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::Engine;
12use crate::cache::{Cache, KvLayer};
13use crate::forward::argmax;
14use crate::hybrid::{FullAttnLayer, HybridModel, LinearAttnLayer, Mixer, MtpHead};
15use cudarc::driver::CudaSlice;
16use std::sync::atomic::{AtomicU64, Ordering};
17
18/// Parse the documented `MEMRA_SPEC_REPLAY=1` rollback seam.
19///
20/// Keep this shared with serving admission so `=0` cannot select replay in one
21/// layer while another layer treats it as disabled.
22pub fn spec_replay_env_on(value: Option<&str>) -> bool {
23 value == Some("1")
24}
25
26pub fn spec_replay_env_enabled() -> bool {
27 let value = std::env::var("MEMRA_SPEC_REPLAY").ok();
28 spec_replay_env_on(value.as_deref())
29}
30
31/// One compact, anchor-bounded DSpark supervision record. `tokens[0]` is the anchor at p and
32/// `hidden` is its predecessor carrier h[p-1], matching the live NextN/DSpark pairing. Target
33/// rows p..p+gamma-1 score tokens p+1..p+gamma. They are the full-target softmax's top-k
34/// entries; `target_tail_probs[j]` is the probability mass outside those rows. All flattened
35/// target arrays are `[gamma, top_k]` in row-major order.
36pub struct DsparkAnchorRecord {
37 pub position: usize,
38 pub hidden: Vec<f32>,
39 pub tokens: Vec<u32>,
40 pub target_top_ids: Vec<u32>,
41 pub target_top_logits: Vec<f32>,
42 pub target_top_probs: Vec<f32>,
43 pub target_tail_probs: Vec<f32>,
44}
45
46fn dspark_sparse_softmax_topk(
47 logits: &[f32],
48 top_k: usize,
49 temperature: f32,
50) -> Result<(Vec<u32>, Vec<f32>, Vec<f32>, f32), Box<dyn std::error::Error>> {
51 if logits.is_empty() || top_k == 0 || top_k > logits.len() || temperature <= 0.0 {
52 return Err("invalid DSpark sparse-softmax shape or temperature".into());
53 }
54 if logits.iter().any(|value| !value.is_finite()) {
55 return Err("DSpark target logits contain a non-finite value".into());
56 }
57 let mut ranked: Vec<(u32, f32)> = logits
58 .iter()
59 .copied()
60 .enumerate()
61 .map(|(index, value)| (index as u32, value))
62 .collect();
63 let compare = |left: &(u32, f32), right: &(u32, f32)| {
64 right.1.total_cmp(&left.1).then(left.0.cmp(&right.0))
65 };
66 ranked.select_nth_unstable_by(top_k - 1, compare);
67 ranked[..top_k].sort_unstable_by(compare);
68
69 let max_logit = logits.iter().copied().fold(f32::NEG_INFINITY, f32::max);
70 let inv_temperature = 1.0f64 / temperature as f64;
71 let denominator: f64 = logits
72 .iter()
73 .map(|value| (((*value - max_logit) as f64) * inv_temperature).exp())
74 .sum();
75 let ids: Vec<u32> = ranked[..top_k].iter().map(|(index, _)| *index).collect();
76 let top_logits: Vec<f32> = ranked[..top_k].iter().map(|(_, value)| *value).collect();
77 let top_probs: Vec<f32> = top_logits
78 .iter()
79 .map(|value| ((((value - max_logit) as f64) * inv_temperature).exp() / denominator) as f32)
80 .collect();
81 let top_mass: f64 = top_probs.iter().map(|value| *value as f64).sum();
82 let tail = (1.0f64 - top_mass).clamp(0.0, 1.0) as f32;
83 Ok((ids, top_logits, top_probs, tail))
84}
85
86fn flatten_dspark_rows<T>(
87 rows: Vec<Option<Vec<T>>>,
88 position: usize,
89 label: &str,
90) -> Result<Vec<T>, Box<dyn std::error::Error>> {
91 let mut flattened = Vec::new();
92 for (slot, row) in rows.into_iter().enumerate() {
93 flattened.extend(
94 row.ok_or_else(|| format!("missing DSpark {label} at {position} slot {slot}"))?,
95 );
96 }
97 Ok(flattened)
98}
99
100/// H-SEED CONVENTION (MEMRA_SPEC_HPOST=1): feed the MTP head the POST-norm hidden — trunk rows
101/// hand over `output_norm(x)` and the draft chain recurrence hands over `shared_head_norm(h_nextn)`
102/// (= final_h) — matching the reference engines: llama.cpp #24025 ("qwen35: use post-norm hidden
103/// state for MTP", t_h_nextn is taken AFTER the final norm in both trunk and MTP graphs) and
104/// SGLang's qwen3_5_mtp (spec_info.hidden_states = the target model's post-norm output). memra's
105/// historical convention (default, MTP-PLAN §A) is PRE-norm x. Draft-quality-only: exactness is
106/// the verify's job either way; acceptance arbitrates. OnceLock: read once, hot-loop safe.
107pub(crate) fn spec_hpost() -> bool {
108 static H: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
109 *H.get_or_init(|| {
110 std::env::var("MEMRA_SPEC_HPOST")
111 .map(|v| v != "0")
112 .unwrap_or(false)
113 })
114}
115
116/// LEAN VERIFY (default ON since 2026-07-08; MEMRA_SPEC_LEAN=0 reverts — close35 lane): the verify m-scaling
117/// probe + nsys diff showed the verify t-path pays ~1.0ms/call at m=1 over eager decode on the
118/// 35B, and the kernels are NOT the cause (dev-MoE identical, kernel-time delta only +179us).
119/// The overhead is (a) ~250 extra cuMemsetD8Async/call from `e.zeros()` on buffers every kernel
120/// fully overwrites (~0.9ms host issue + ~0.35ms GPU) and (b) the t=1 FA rows dispatch (rows_v2 +
121/// combine_rows, +50us vs the eager fa_decode pair). This flag switches (a) fully-overwritten
122/// verify buffers to `e.uninit` (identical bytes: every element is written before read) and
123/// (b) t==1 verify FA to the eager `fa_decode` entry (byte-identical: kernel-check pins the
124/// rows-vs-loop identity and the per-row loop at t=1 IS fa_decode on the same q). Gates arbitrate.
125pub(crate) fn spec_lean() -> bool {
126 static L: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
127 // DEFAULT ON since 2026-07-08 (MEMRA_SPEC_LEAN=0 reverts): bit-identical (buffers fully
128 // overwritten; gates green incl maxdiff-identical run-gen) and measured +2.4% e2e p3 /
129 // +1.5% p2 at the daily 35B config. m=1 verify now costs eager-decode parity.
130 *L.get_or_init(|| {
131 std::env::var("MEMRA_SPEC_LEAN")
132 .map(|v| v != "0")
133 .unwrap_or(true)
134 })
135}
136
137/// SMALL-M BATCHED VERIFY (default ON since 2026-07-09; MEMRA_SPEC_M2=0 reverts — lane/spec-m2): extend the
138/// batched linear-attn verify arm down to t=2 and batch the MoE dev token loop over a
139/// grid.z=token axis at every verify t. The close35 m-scaling probe put the m=2 verify tier at
140/// x1.54 of m=1 (llama x1.14); the per-column linear chain (t<3) and the serial MoE dev token
141/// loop are the two launch-structure causes. Both changes are LAUNCH-STRUCTURE ONLY:
142/// (a) the batched conv's t<pad ring update is pure copies (ssm_conv_ring_rebuild from a cloned
143/// ring — the ring stores raw input columns); every arithmetic kernel is the same one the
144/// t>=3 arm already runs (matmul_decode_exact bit-identical at m=2-4, gdn_scan's internal
145/// t-loop == chained T=1 steps);
146/// (b) the MoE dev-rows twins run the serial loop's per-token warp program with tok-offset
147/// pointers (same sel/w/aq/ad bytes, same dot order, same slot-ordered FMA chain).
148/// Gates arbitrate: run-spec K=1..8 self-consistency (35B+9B), kernel-check, run-gen argmax.
149pub(crate) fn spec_m2() -> bool {
150 static M: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
151 // DEFAULT ON since 2026-07-09 (MEMRA_SPEC_M2=0 reverts): launch-structure only — t=2
152 // batched linear arm (ring-roll copies, zero new FP order) + MoE dev-rows kernels
153 // (grid.z=token, 4 launches/layer at any verify t). Acceptance bit-identical at every K;
154 // 35B p2 +3.4% / p3 +3.6%; the profitable-K plateau widens (new optimum K=3 at 223).
155 *M.get_or_init(|| {
156 std::env::var("MEMRA_SPEC_M2")
157 .map(|v| v != "0")
158 .unwrap_or(true)
159 })
160}
161pub(crate) fn spec_stream() -> bool {
162 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
163 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_STREAM").as_deref() == Ok("1"))
164}
165pub(crate) fn spec_stream_m() -> usize {
166 static M: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
167 *M.get_or_init(|| {
168 std::env::var("MEMRA_SPEC_STREAM_M")
169 .ok()
170 .and_then(|v| v.parse().ok())
171 .unwrap_or(4)
172 })
173}
174pub(crate) fn spec_devacc() -> bool {
175 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
176 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_DEVACC").as_deref() == Ok("1"))
177}
178
179/// GRAMMAR HOOK for constrained spec decode (lane/constrained-full, 2026-08-03). The engine
180/// stays llguidance-agnostic: the server adapts its per-session grammar state behind this
181/// trait. CONTRACT (the verify-side truncation rule — token-identical to constrained plain
182/// greedy decode): the exactness walk runs UNMASKED first; the hook then (a) truncates
183/// acceptance at the first grammar-illegal accepted token, and (b) when the truncation fired
184/// or the bonus is illegal, the engine recomputes that slot as the MASKED argmax of the
185/// target's own verify column (an unmasked argmax that is grammar-legal IS the masked argmax
186/// — masking only removes tokens — so the common case pays nothing). `consume` advances the
187/// state with each EMITTED token in order; EOS handling is the implementor's job (skip).
188pub trait SpecConstraint {
189 /// -inf the current state's banned ids on a HOST logits row (prompt-tail / init-feed
190 /// masked argmax).
191 fn mask_logits(&mut self, logits: &mut [f32]) -> Result<(), String>;
192 /// Packed 32-bit bitset words of the CURRENT state's allowed set (device-mask form).
193 fn mask_words(&mut self) -> Result<Vec<u32>, String>;
194 /// Is `tok` consumable in the CURRENT state?
195 fn is_allowed(&mut self, tok: u32) -> Result<bool, String>;
196 /// Advance the state with an emitted token.
197 fn consume(&mut self, tok: u32) -> Result<(), String>;
198
199 // --- DRAFT-SIDE MASKING (lane/draft-mask, 2026-08-04) ---
200 // The drafter proposed grammar-illegal tokens under tight schemas, so verify-side
201 // truncation cut nearly every round (measured acceptance 0.467-0.513 tight vs 0.62-0.82
202 // loose, research/constrained-full-20260803). These three methods let the engine mask the
203 // DRAFT model's own sampling with the grammar's legal set, so proposals are legal by
204 // construction. The state they walk is a SPECULATIVE CLONE of the session matcher — the
205 // real state is advanced only by `consume` (emitted tokens), so verify-side truncation
206 // stays the correctness backstop and the emitted stream is unchanged by construction
207 // (an accepted draft is the target's unmasked argmax AND grammar-legal, hence the masked
208 // argmax; a cut slot is recomputed as the masked argmax either way).
209 // Default impls = feature OFF (pre-lane behaviour: unmasked drafts).
210
211 /// Is draft-side masking available on this hook? Probed ONCE per burst, before the draft
212 /// graph is captured (the mask is an in-graph node — its presence is a capture-time shape).
213 fn draft_mask_enabled(&self) -> bool {
214 false
215 }
216 /// Start a draft chain: clone the CURRENT (committed) grammar state into the speculative
217 /// slot. Called once per spec round, before the first draft position.
218 fn draft_begin(&mut self) -> Result<(), String> {
219 Ok(())
220 }
221 /// Packed 32-bit bitset words of the SPECULATIVE state's allowed set (target-vocab ids),
222 /// for the draft position about to be sampled. `None` = draft masking off (no-op).
223 fn draft_mask_words(&mut self) -> Result<Option<Vec<u32>>, String> {
224 Ok(None)
225 }
226 /// Advance the SPECULATIVE state with a PROPOSED draft token. `false` = the chain cannot
227 /// continue (EOS proposed, or an unmasked position proposed something illegal) — the
228 /// engine stops drafting; the token already pushed still goes through verify.
229 fn draft_advance(&mut self, _tok: u32) -> Result<bool, String> {
230 Ok(false)
231 }
232}
233
234/// DRAFT-MASK UPLOAD (lane/draft-mask): pull the speculative state's allowed set (TARGET-id
235/// space) from the hook, project it into the DRAFT head's vocab space, and upload it into the
236/// stable device buffer the draft chain reads. Returns false when the chain must stop drafting:
237/// the hook handed out no mask, or NO draft-vocab row is grammar-legal at this position (a
238/// trimmed FR-Spec head genuinely cannot propose a legal token there — masking it would leave
239/// a fully-banned row whose argmax is meaningless, so the round drafts fewer tokens and the
240/// verify emits the masked argmax as usual).
241fn upload_draft_mask(
242 e: &Engine,
243 c: &mut dyn SpecConstraint,
244 dst: &mut CudaSlice<u32>,
245 d2t: Option<&Vec<u32>>,
246 d_vocab: usize,
247 words: usize,
248) -> Result<bool, Box<dyn std::error::Error>> {
249 let Some(tw) = c
250 .draft_mask_words()
251 .map_err(|e2| format!("constraint: {e2}"))?
252 else {
253 return Ok(false);
254 };
255 let bit = |t: usize| -> bool {
256 let w = t >> 5;
257 w < tw.len() && (tw[w] >> (t & 31)) & 1 == 1
258 };
259 let mut buf = vec![0u32; words];
260 match d2t {
261 // TRIMMED draft head: row i proposes target id d2t[i] — permute the mask accordingly.
262 Some(map) => {
263 for (i, &t) in map.iter().enumerate().take(d_vocab) {
264 if bit(t as usize) {
265 buf[i >> 5] |= 1u32 << (i & 31);
266 }
267 }
268 }
269 // UNTRIMMED: draft ids ARE target ids; the packed words transfer verbatim (a short
270 // mask leaves the padded tail zeroed == banned, same rule as constrained::apply_mask).
271 None => {
272 let n = tw.len().min(words);
273 buf[..n].copy_from_slice(&tw[..n]);
274 }
275 }
276 if buf.iter().all(|w| *w == 0) {
277 return Ok(false);
278 }
279 e.htod_u32_into(dst, &buf)?;
280 Ok(true)
281}
282
283/// Keep the full token-embedding table in host memory and upload only the rows needed by each
284/// MTP/verify step. This is an exact memory-capacity seam for very large BF16 vocab tables: host
285/// gather expands the same source bits to f32, and only O(T*n_embd) bytes cross PCIe per step.
286/// CUDA-graph/round-stream draft paths require device token ids and therefore stay disabled.
287pub(crate) fn spec_host_embd() -> bool {
288 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
289 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_HOST_EMBD").as_deref() == Ok("1"))
290}
291
292/// VERIFY-TIER TRUNK LAUNCH-FUSION (default ON since 2026-07-09; MEMRA_SPEC_FUSED_T=0 reverts — lane/close35b): extend
293/// the t=1 fused2/fused3 Q8_0 trunk launches to the batched verify tier (t=2-4, the K=1..3
294/// verify shapes). At t>1 the trunk pairs/triples (35B wqkv+wqkv_gate, wq/wk/wv,
295/// gate_shexp+up_shexp) each run a separate `matmul_decode_exact` — one q8_1 re-quantize of the
296/// SAME activation plus one _b2/_b4 launch per tensor. The fused twins share ONE quantize and
297/// ONE launch per group; per (tensor,token,row) the kernel body is q8_0_mmvq_batched verbatim
298/// with the identical row mapping -> BIT-IDENTICAL by construction (kernel-check pins it,
299/// run-spec K=1..8 + acceptance identity arbitrate e2e).
300pub(crate) fn spec_fused_t() -> bool {
301 static F: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
302 // DEFAULT ON since 2026-07-09 (MEMRA_SPEC_FUSED_T=0 reverts): verify t=2-4 trunk launch-fusion
303 // (fused2/fused3 Q8_0 batched twins, bit-identical by construction — m=1 block-offset split on
304 // the batched body). m=2 marginal token 2117->1762us; 35B daily: p3 +3.7% (crosses llama), p2 +5%.
305 *F.get_or_init(|| {
306 std::env::var("MEMRA_SPEC_FUSED_T")
307 .map(|v| v != "0")
308 .unwrap_or(true)
309 })
310}
311
312/// zeros/uninit switch for verify-path buffers that are FULLY OVERWRITTEN before any read.
313/// Only call this on such buffers — the lean contract is "identical bytes by construction".
314fn vbuf(e: &Engine, n: usize) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
315 if spec_lean() { e.uninit(n) } else { e.zeros(n) }
316}
317
318/// Scratch KV for the MTP block (one full-attn layer).
319///
320/// PERSISTENT MODE (default, 2026-07-03 — the acceptance lever): sized cap = max_ctx and kept in
321/// sync with the COMMITTED sequence — slot p holds the MTP block's K/V for committed token p
322/// (roped p+1, the chain's rope convention), so the draft chain's self-attention sees the FULL
323/// committed history instead of only the current round's 1..K+1 chain tokens (the reference
324/// engine's "mtp_update" design). Entries come from two sources:
325/// - chain appends: accepted positions KEEP their chain-computed entries (embedding exact,
326/// hidden chain-approximate — the reference engine accepts the same);
327/// - `mtp_kv_fill` batches: prompt positions + the last-draft position on full accept, computed
328/// from EXACT trunk hiddens (K/V-only MTP-block pass, no attention/FFN/lm_head).
329/// Rejected drafts / p-min extras / pseudo-seed appends are all discarded by the round-start
330/// `set_len` truncation (the KvLayer len mechanism — §C rollback for the draft side).
331/// Multi-turn spec-decode session (2026-07-05): trunk Cache + persistent MTP draft scratch +
332/// the committed token list, alive across generate_spec_session calls. Turn N+1 primes ONLY its
333/// suffix (chunked continuation prime over the quantized past) and mtp_kv_fill's its suffix rows,
334/// then the round loop runs unchanged. `last_h` carries the pre-output_norm hidden of the last
335/// committed row across turns (the predecessor-pairing seed + fill anchor).
336/// Per-request sampling config for the sampled-spec serve path.
337#[derive(Clone, Copy, Debug)]
338pub struct SpecSampling {
339 pub temp: f32,
340 pub seed: u64,
341 pub top_k: i32, // 0 = off
342 pub top_p: f32, // 1.0 = off
343 pub min_p: f32, // 0.0 = off
344 pub penalty_last_n: usize, // 0 = penalties off
345 pub penalty_repeat: f32,
346 pub penalty_freq: f32,
347 pub penalty_present: f32,
348}
349
350/// Tracked draft positions for [`SpecTelemetry`] (serve K defaults to 3; the run-spec gate
351/// sweeps K=1..8, and MEMRA_SPEC_CAPMAX defaults to 7 — 8 covers every tuned config).
352pub const SPEC_TELEM_POS: usize = 8;
353
354/// Always-on per-draft-position acceptance telemetry (lane/accept-telemetry, 2026-08-05 —
355/// the llama.cpp #26389 / vLLM spec-decode counter schema, upstream-sweeps 2026-08-05).
356/// Lives on the [`SpecSession`] and accumulates across bursts; the serve worker diffs a
357/// stashed copy per burst for its per-model /metrics aggregation and per-request usage.
358/// Same normalization as the `[spec-stats]` line: p-min-discarded chain tokens are counted
359/// in NEITHER drafted nor accepted.
360#[derive(Clone, Copy, Default, Debug)]
361pub struct SpecTelemetry {
362 /// verify rounds completed (a round-stream burst counts each of its M rounds).
363 pub rounds: u64,
364 /// tokens drafted / accepted across all rounds.
365 pub drafted: u64,
366 pub accepted: u64,
367 /// how often draft position j (0-based within a round's chain) was offered / accepted.
368 /// Positions >= SPEC_TELEM_POS are untracked (totals still count them). The opt-in
369 /// round-stream arm (MEMRA_SPEC_STREAM=1) reads back only totals, so under it these
370 /// arrays cover the standard-path rounds only and their sums may undercount the totals.
371 pub pos_drafted: [u64; SPEC_TELEM_POS],
372 pub pos_accepted: [u64; SPEC_TELEM_POS],
373}
374
375impl SpecTelemetry {
376 /// Fieldwise `self - prev` — the worker's per-burst delta off a copy stashed before the
377 /// burst call. Saturating: a caller diffing against the wrong snapshot gets zeros, not
378 /// a wrapped counter.
379 pub fn delta_since(&self, prev: &SpecTelemetry) -> SpecTelemetry {
380 let mut d = SpecTelemetry {
381 rounds: self.rounds.saturating_sub(prev.rounds),
382 drafted: self.drafted.saturating_sub(prev.drafted),
383 accepted: self.accepted.saturating_sub(prev.accepted),
384 ..Default::default()
385 };
386 for j in 0..SPEC_TELEM_POS {
387 d.pos_drafted[j] = self.pos_drafted[j].saturating_sub(prev.pos_drafted[j]);
388 d.pos_accepted[j] = self.pos_accepted[j].saturating_sub(prev.pos_accepted[j]);
389 }
390 d
391 }
392 /// Fieldwise `self += d` — the worker's per-model aggregation.
393 pub fn merge(&mut self, d: &SpecTelemetry) {
394 self.rounds += d.rounds;
395 self.drafted += d.drafted;
396 self.accepted += d.accepted;
397 for j in 0..SPEC_TELEM_POS {
398 self.pos_drafted[j] += d.pos_drafted[j];
399 self.pos_accepted[j] += d.pos_accepted[j];
400 }
401 }
402
403 /// Mean accepted draft-prefix length per verify round (tau).
404 pub fn tau(&self) -> f64 {
405 if self.rounds > 0 {
406 self.accepted as f64 / self.rounds as f64
407 } else {
408 0.0
409 }
410 }
411}
412
413/// Session-lifetime atomic acceptance counters. The verifier records only after the greedy or
414/// rejection-sampling walk has resolved on the host, so these relaxed increments add no GPU
415/// launch, synchronization, allocation, or ordering dependency to the numeric path.
416struct SpecTelemetryCounters {
417 rounds: AtomicU64,
418 drafted: AtomicU64,
419 accepted: AtomicU64,
420 pos_drafted: [AtomicU64; SPEC_TELEM_POS],
421 pos_accepted: [AtomicU64; SPEC_TELEM_POS],
422}
423
424impl Default for SpecTelemetryCounters {
425 fn default() -> Self {
426 Self {
427 rounds: AtomicU64::new(0),
428 drafted: AtomicU64::new(0),
429 accepted: AtomicU64::new(0),
430 pos_drafted: std::array::from_fn(|_| AtomicU64::new(0)),
431 pos_accepted: std::array::from_fn(|_| AtomicU64::new(0)),
432 }
433 }
434}
435
436impl SpecTelemetryCounters {
437 fn record_round(&self, drafted: usize, accepted: usize) {
438 debug_assert!(accepted <= drafted);
439 self.rounds.fetch_add(1, Ordering::Relaxed);
440 self.drafted.fetch_add(drafted as u64, Ordering::Relaxed);
441 self.accepted.fetch_add(accepted as u64, Ordering::Relaxed);
442 for counter in self.pos_drafted.iter().take(drafted) {
443 counter.fetch_add(1, Ordering::Relaxed);
444 }
445 for counter in self.pos_accepted.iter().take(accepted) {
446 counter.fetch_add(1, Ordering::Relaxed);
447 }
448 }
449
450 /// Round-stream keeps each round's accept length on device; retain exact scalar totals while
451 /// leaving the per-position arrays untouched, matching the pre-existing telemetry contract.
452 fn record_totals(&self, rounds: usize, drafted: usize, accepted: usize) {
453 self.rounds.fetch_add(rounds as u64, Ordering::Relaxed);
454 self.drafted.fetch_add(drafted as u64, Ordering::Relaxed);
455 self.accepted.fetch_add(accepted as u64, Ordering::Relaxed);
456 }
457
458 fn snapshot(&self) -> SpecTelemetry {
459 SpecTelemetry {
460 rounds: self.rounds.load(Ordering::Relaxed),
461 drafted: self.drafted.load(Ordering::Relaxed),
462 accepted: self.accepted.load(Ordering::Relaxed),
463 pos_drafted: std::array::from_fn(|j| self.pos_drafted[j].load(Ordering::Relaxed)),
464 pos_accepted: std::array::from_fn(|j| self.pos_accepted[j].load(Ordering::Relaxed)),
465 }
466 }
467}
468
469pub struct SpecSession {
470 pub(crate) cache: Cache,
471 pub(crate) scratch: MtpScratch,
472 /// Every token whose state the caches hold, in order (prompt turns + generated), INCLUDING
473 /// overshoot: spec commits accepted drafts past max_new; those rows are in the caches, so the
474 /// session must count them. Callers render output from this, not from their own echo.
475 pub committed: Vec<u32>,
476 /// Pre-output_norm hidden of the LAST committed row (device). None before the first turn.
477 pub(crate) last_h: Option<CudaSlice<f32>>,
478 /// Greedy argmax predicting the token AFTER committed.last() (from the last turn's final
479 /// logits). Fuels empty-suffix continuation bursts (serve): the next turn emits this token
480 /// first, feeds it, and the round loop resumes without any prime. None before the first turn.
481 pub next_pred: Option<u32>,
482 /// SAMPLED-SPEC stream continuity across bursts: Philox event counters persist here so a
483 /// session's randomness never repeats between generate_spec_session calls. (0,0) at admit.
484 pub sctr: u32,
485 pub uctr: u32,
486 /// PERSISTENT DRAFT-GRAPH CONTEXT (2026-08-01, the serve-burst fixed-cost fix): the captured
487 /// draft graph(s) + every device I/O buffer they bake, carried ACROSS generate_spec_session
488 /// calls. Before this, every serve burst re-captured the draft graph (2 warmup forwards +
489 /// instantiate) — measured ~16ms/burst on H100 q27 (MEMRA_SPEC_BURST sweep,
490 /// research/spec-serving-20260801). None before the first turn; error paths drop it
491 /// (next burst recaptures — serve retires errored sessions anyway).
492 pub(crate) draft_ctx: Option<DraftGraphCtx>,
493 /// PENDING-CARRY across bursts (2026-08-01, the serve burst-boundary fix): the bonus token
494 /// emitted by the last round but NOT committed to the caches. The old tail committed it with
495 /// a solo T=1 trunk pass (+ draft fill), and the next burst's setup fed the stashed next_pred
496 /// with ANOTHER solo pass — 2x ~11.5ms/burst measured on H100 q27 ([spec-setup] trace).
497 /// Carrying it lets the next empty-suffix greedy burst consume it as round-0 verify col 0,
498 /// exactly like a mid-burst full-accept boundary (no solo passes). INVARIANT: when set,
499 /// `committed` (== cache rows) EXCLUDES this token although it was already emitted in the
500 /// last burst's output, and `last_h` holds the hidden of the last COMMITTED row (its
501 /// predecessor — the chain-seed/fill anchor). `next_pred` is None (unknown without the
502 /// commit pass). Non-empty-suffix or sampled turns must flush first (spec_flush_pending);
503 /// generate_spec_session_sampled does this at entry, and serve parks only flushed sessions.
504 pub pending_tok: Option<u32>,
505 /// SESSION-AFFINITY TURN CHECKPOINT (lane/session-affinity, 2026-08-05): the state at this
506 /// turn's PROMPT-END boundary, retained so a later turn can REWIND here. See
507 /// [`SpecCheckpoint`]. Refreshed by every non-empty prime; None until the first one, and on
508 /// a rig too tight to hold it (a failed capture is silent — resume just isn't available).
509 pub(crate) turn_ckpt: Option<SpecCheckpoint>,
510 /// Session-lifetime acceptance telemetry. Relaxed atomics update at the host-side round
511 /// accounting the loop already does — no syncs, no allocation. NOTE a
512 /// pool-resumed session carries the PREVIOUS requests' counts; per-request consumers
513 /// diff with [`SpecTelemetry::delta_since`] around each burst.
514 telem: SpecTelemetryCounters,
515 /// PREFIX-CACHE publication request (lane/spec-prefix-cache): worker sets this to the
516 /// miss-LCP boundary before a cold burst; the prime captures at exactly that split (it must
517 /// coincide with the burst's `prime_split` or no capture happens). One-shot: consumed by the
518 /// prime, result lands in `boundary_capture`.
519 pub capture_at: Option<usize>,
520 /// The capture the last cold prime produced (see [`SpecBoundaryCapture`]). Worker takes it
521 /// post-burst to assemble the prefix entry. A failed capture is silent, like `turn_ckpt` —
522 /// publication just isn't available for that request.
523 pub boundary_capture: Option<SpecBoundaryCapture>,
524}
525impl SpecSession {
526 /// Context capacity of the session's caches (the server's ContextFull guard).
527 pub fn cache_max_ctx(&self) -> usize {
528 self.cache.max_ctx
529 }
530 /// Read access to the live trunk cache (lane/spec-prefix-cache): the worker slices
531 /// full-attn KV rows `[0..capture.pos)` out of it when publishing a boundary capture —
532 /// those rows are append-only for the session's lifetime (rollbacks never truncate below
533 /// the prime boundary), so no copy was taken at prime time.
534 pub fn cache_ref(&self) -> &Cache {
535 &self.cache
536 }
537 /// Read access to the persistent draft-scratch plane (lane/spec-on-cache-hit): the
538 /// worker slices rows `[0..capture.pos)` when publishing a boundary capture, exactly
539 /// like the trunk KV — draft rows below the prompt end are append-only for the
540 /// session's lifetime (the prime fill wrote them once; rollbacks reset `len_d` to the
541 /// committed length, never below the prime boundary, and the true-hidden refresh
542 /// rewrites generated positions only). Returns `(k, v, k_tok_bytes, v_tok_bytes)`.
543 /// None when the scratch is ring-backed (Step35 SWA — physical rows are not
544 /// prefix-addressable; the prefix cache already refuses that class end to end).
545 pub fn draft_plane_ref(&self) -> Option<(&CudaSlice<u8>, &CudaSlice<u8>, usize, usize)> {
546 if self.scratch.kv.ring.is_some() {
547 return None;
548 }
549 Some((
550 &self.scratch.kv.k,
551 &self.scratch.kv.v,
552 self.scratch.kv.k_tok_bytes,
553 self.scratch.kv.v_tok_bytes,
554 ))
555 }
556 /// Snapshot the session's process-local acceptance counters for per-burst diffing.
557 pub fn telemetry(&self) -> SpecTelemetry {
558 self.telem.snapshot()
559 }
560 /// Committed position this session can REWIND to (its retained prompt-end boundary), if any.
561 /// A request whose prompt matches `committed[..pos]` exactly can resume from here — see
562 /// `spec_rewind_to_checkpoint`.
563 pub fn rewind_pos(&self) -> Option<usize> {
564 self.turn_ckpt.as_ref().map(|c| c.pos)
565 }
566 /// Whether every ring-backed trunk/draft row needed by the retained checkpoint is resident.
567 pub fn rewind_is_resident(&self) -> bool {
568 self.turn_ckpt.as_ref().is_some_and(|ckpt| {
569 self.cache.can_rollback(&ckpt.snap, 0) && self.scratch.can_rewind_to(ckpt.pos)
570 })
571 }
572 /// Is this session in the DEMOTION-READY shape (see [`SpecSession::into_demoted`])?
573 /// `false` means a carried pending must be flushed first (`spec_flush_pending`), or the
574 /// session has never run a turn and has no prediction to hand over.
575 pub fn demote_ready(&self) -> bool {
576 self.pending_tok.is_none() && self.next_pred.is_some()
577 }
578 /// Does this session hold a carried pending bonus (flush required before a handoff/park)?
579 pub fn has_pending(&self) -> bool {
580 self.pending_tok.is_some()
581 }
582 /// Committed row count == cache rows (the session invariant), for the caller's own
583 /// `fed`-length cross-check at a handoff boundary.
584 pub fn committed_len(&self) -> usize {
585 self.committed.len()
586 }
587 /// DEMOTION HANDOFF (lane/spec-gate, 2026-08-07): consume this session and hand its trunk
588 /// cache + next-token prediction to the plain batched-decode path.
589 ///
590 /// WHY THIS IS EXACT (greedy). The invariant at a burst boundary is `cache.pos ==
591 /// committed.len()`: every committed row has trunk KV + recurrent state, exactly as a plain
592 /// tokenwise prime of the same `committed` sequence would have left it (that is the
593 /// session-tail contract, and the same property `spec_rewind_to_checkpoint` and the reuse
594 /// pool already rely on). `next_pred` is the argmax of the verify's logits for the LAST
595 /// committed row — and verify-column logits are bit-identical to plain decode's logits at
596 /// that position, because `matmul_decode_exact` bit-identity IS the basis of the greedy
597 /// accept walk. So handing (cache, next_pred) to the batched path continues the stream from
598 /// a state indistinguishable from one the batched path produced itself: the batched tick
599 /// emits `next_pred`, feeds it into this same cache, and decodes on.
600 ///
601 /// `None` when the session is not in the handoff shape — a carried pending (its bonus row is
602 /// NOT in the cache, so `spec_flush_pending` must commit it first) or no `next_pred` yet
603 /// (never bursted). Callers must not force it: a half-committed cache handed to the batched
604 /// path would silently skip a token.
605 ///
606 /// The MTP draft scratch, the persistent draft-graph context and the turn checkpoint are
607 /// DROPPED here (freeing their VRAM): the batched path never drafts, and this handoff is
608 /// one-way by design — there is no cheap symmetric re-promotion (rebuilding the draft KV
609 /// would mean an `mtp_kv_fill` over the whole committed history).
610 pub fn into_demoted(self) -> Option<(Cache, u32)> {
611 if self.pending_tok.is_some() {
612 return None;
613 }
614 let np = self.next_pred?;
615 debug_assert_eq!(
616 self.cache.pos,
617 self.committed.len(),
618 "demotion handoff: cache rows != committed tokens"
619 );
620 Some((self.cache, np))
621 }
622 /// Pool-resume hook (audit Q2): clear the parked draft-graph failure memoization so a
623 /// NEW request resuming this session gets one fresh capture chance — a transient-pressure
624 /// capture failure must not persist for the pool's whole lifetime (the TRT #16072 class).
625 /// Logs once iff a flag was actually set; a no-fallback resume is silent and free.
626 pub fn reset_graph_fallback_on_resume(&mut self) {
627 if let Some(line) = self
628 .draft_ctx
629 .as_mut()
630 .and_then(|c| c.failed.reset_on_resume())
631 {
632 eprintln!("{line}");
633 }
634 }
635}
636
637/// A session's PROMPT-END boundary state, the rewind target for session-affinity resume.
638///
639/// WHY THIS BOUNDARY, AND WHY IT IS THE ONLY ONE WORTH KEEPING. The rewrite class this lane
640/// exists for (a client that strips `<think>` blocks out of prior assistant turns) mutates the
641/// text the session GENERATED, never the prompt it was given. So turn N's prompt agrees with
642/// turn N-1's committed tokens up to almost exactly where turn N-1's generation began — the
643/// prompt-end boundary. Keeping a checkpoint there means the next turn re-primes only its own
644/// delta (the rewritten answer + the new user turn) instead of the whole conversation.
645///
646/// WHAT IT MUST HOLD. Full-attn KV is append-only and position-addressed, so rewinding it is a
647/// `len` truncation (no data). Linear-attn (GDN) conv/ssm state is mutated IN PLACE with no
648/// position index, so it must be a real device COPY — that copy is the entire reason a spec
649/// session could not previously rewind. The MTP draft scratch needs no copy either: its rows
650/// below the boundary were written by this turn's fill and are never revisited (the per-round
651/// true-hidden refresh only rewrites the CURRENT burst's committed positions), so rewinding it
652/// is also just a `len` reset. `last_h` is the hidden of the last row below the boundary — the
653/// predecessor-pairing anchor the next prime's fill reads for its first row.
654///
655/// COST: one `Cache::snapshot` per TURN, on a code path that already takes one per ROUND.
656pub(crate) struct SpecCheckpoint {
657 snap: crate::cache::CacheSnapshot,
658 /// Committed length at the boundary (== cache.pos there, the session invariant).
659 pos: usize,
660 /// Pre-output_norm hidden of row `pos - 1`.
661 last_h: CudaSlice<f32>,
662}
663
664/// PREFIX-CACHE BOUNDARY CAPTURE (lane/spec-prefix-cache, 2026-08-14): the state a spec session
665/// records at its cold-prime split so the WORKER can publish a cross-request prefix entry —
666/// the commit-gated-publication port (research/cache-spec-design-20260814/PORT-PLAN.md item 1).
667/// Only the pieces that are DESTROYED by continuing the prime need copies here: the in-place
668/// GDN conv/ssm states (via `Cache::snapshot`, same mechanism as [`SpecCheckpoint`]) and the
669/// boundary logits. Full-attn KV rows `[0..pos)` and draft-scratch rows `[0..pos)` are
670/// append-only for the session's lifetime (rollbacks never truncate below the prime boundary),
671/// so the worker slices those from the live caches post-burst instead of copying at prime time.
672pub struct SpecBoundaryCapture {
673 pub snap: crate::cache::CacheSnapshot,
674 /// Token boundary (== cache.pos at capture; == the worker's miss-LCP split).
675 pub pos: usize,
676 /// Full-vocab logits after the prefix prime — the entry's boundary logits.
677 pub logits: Vec<f32>,
678 /// Pre-output_norm trunk hidden of row `pos - 1` (lane/spec-on-cache-hit): the
679 /// predecessor-pairing anchor a RESTORED spec session's first suffix-fill row reads
680 /// (the `SpecSession::last_h` convention). Empty = unavailable (capture stays valid;
681 /// the fill's zeros row-0 fallback covers it at a bounded acceptance cost).
682 pub last_h: Vec<f32>,
683}
684
685/// D2H one hidden row out of a `[T, n_embd]` prime hidden stack — the boundary anchor a
686/// spec boundary capture carries for later restored-session fills. Failure is silent
687/// (`turn_ckpt` convention): the capture publishes without an anchor.
688fn capture_boundary_hidden(
689 e: &Engine,
690 h_rows: &CudaSlice<f32>,
691 pos: usize,
692 n_embd: usize,
693) -> Vec<f32> {
694 if pos == 0 || h_rows.len() < pos * n_embd {
695 return Vec::new();
696 }
697 let Ok(mut row) = e.uninit(n_embd) else {
698 return Vec::new();
699 };
700 if e.copy_view_into(
701 &mut row,
702 0,
703 &h_rows.slice((pos - 1) * n_embd..pos * n_embd),
704 n_embd,
705 )
706 .is_err()
707 {
708 return Vec::new();
709 }
710 e.dtoh(&row).unwrap_or_default()
711}
712
713/// ROLLBACK DOOR for sampled BOUNDARY tokens (lane/sampled-spec-quality, 2026-08-19).
714/// Default ON: the token a burst emits at its own boundary is drawn from the request's
715/// sampler. `MEMRA_SPEC_SAMPLED_BOUNDARY=0` restores the pre-lane posture (an ARGMAX at
716/// every boundary) without touching greedy, which is byte-unaffected either way.
717pub fn spec_sampled_boundary_on() -> bool {
718 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
719 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_SAMPLED_BOUNDARY").as_deref() != Ok("0"))
720}
721
722/// ROLLBACK DOOR for SESSION-SPANNING penalty history (lane/sampled-spec-quality).
723/// Default ON: `pen_hist` is seeded from the session's committed tail, so repetition /
724/// frequency / presence penalties see the whole stream. `MEMRA_SPEC_PEN_SESSION=0`
725/// restores the pre-lane posture (each burst restarts the window from its own prompt
726/// slice, i.e. from NOTHING on a continuation burst) — and with the door shut the worker
727/// must keep refusing penalized sampled prefix-cache restores, because the restored
728/// session's continuation burst is handed no prompt slice at all.
729pub fn spec_pen_session_on() -> bool {
730 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
731 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_PEN_SESSION").as_deref() != Ok("0"))
732}
733
734/// ROLLBACK DOOR for extended-entry publication from a RESTORED session
735/// (lane/sampled-spec-quality, Item 3). Default ON: a converted prefix-cache hit that fed a
736/// suffix captures its own prompt-end boundary so the NEXT turn can hit a longer prefix.
737/// `MEMRA_SPEC_RESTORE_REPUBLISH=0` restores the pre-lane posture (a namespace learns exactly
738/// one boundary and never advances it). Whole-entry semantics only — the boundary is the
739/// restored session's own prompt end, so `entry_pos != fed_len` still refuses on the way in.
740pub fn spec_restore_republish_on() -> bool {
741 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
742 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_RESTORE_REPUBLISH").as_deref() != Ok("0"))
743}
744
745/// Diagnostics: name every boundary token on stderr (`MEMRA_SPEC_BOUNDARY_TRACE=1`), with
746/// the argmax the pre-lane code would have emitted from the same row. This is how the
747/// lane MEASURES the boundary rate and the deviation rate instead of estimating them.
748fn spec_boundary_trace() -> bool {
749 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
750 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_BOUNDARY_TRACE").as_deref() == Ok("1"))
751}
752
753/// llama-parity floor for the penalty window when the request does not ask for a bigger
754/// one (`repeat_last_n` default). The serve API arms `penalty_last_n = usize::MAX` for any
755/// non-identity penalty, so this floor only matters to explicit small windows and to the
756/// CLI env path.
757const PEN_WINDOW_FLOOR: usize = 64;
758
759/// CEILING on the penalty window, and it is a COST bound, not a semantic preference.
760/// `penalize_logits_f32` (cu/spec_sample.cu) dedups on device by having thread `i` scan
761/// `hist[0..i]`, so a pass is O(n_hist²) and it runs ~3x per verify round (the q rows, the
762/// p column, the bonus column). The serve API arms `penalty_last_n = usize::MAX` for ANY
763/// non-identity penalty — "the whole context", llama's `repeat_last_n = -1` — so an
764/// uncapped session window would put a 128k-token history through that kernel: ~1.7e10
765/// comparisons per pass, tens of ms per round, i.e. penalties would silently destroy decode
766/// throughput on exactly the long-context requests that most want them. 8192 keeps a pass
767/// at ~7e7 comparisons (tens of microseconds) while still being **128x wider than the
768/// pre-lane effective window** (64 prompt-tail tokens + whatever the current burst had
769/// generated). A request that genuinely needs a window beyond this wants host-side dedup +
770/// counts through a new kernel signature — a follow-up lane, named here rather than hidden.
771const PEN_WINDOW_MAX: usize = 8192;
772
773/// Seed a penalty window over the SESSION, not the burst (lane/sampled-spec-quality,
774/// Item 2). The window is the last `max(penalty_last_n, 64)` tokens of
775/// `session_committed ++ burst_prompt` — for a cold turn-1 burst (`session_committed`
776/// empty, default `penalty_last_n`) that is byte-identically the pre-lane
777/// `prompt.iter().rev().take(64).rev()`; for a continuation burst it is the stream the
778/// client actually asked us to penalize, where the pre-lane code had NOTHING.
779fn pen_window_seed(
780 session_committed: &[u32],
781 burst_prompt: &[u32],
782 penalty_last_n: usize,
783) -> Vec<u32> {
784 let win = penalty_last_n.clamp(PEN_WINDOW_FLOOR, PEN_WINDOW_MAX);
785 let take_prompt = burst_prompt.len().min(win);
786 let take_sess = (win - take_prompt).min(session_committed.len());
787 let mut hist = Vec::with_capacity(take_sess + take_prompt);
788 hist.extend_from_slice(&session_committed[session_committed.len() - take_sess..]);
789 hist.extend_from_slice(&burst_prompt[burst_prompt.len() - take_prompt..]);
790 hist
791}
792
793/// Draw a BOUNDARY token from the target distribution the request asked for
794/// (lane/sampled-spec-quality, Item 1) — the fix for "sampled spec emits an ARGMAX token at
795/// every burst boundary".
796///
797/// WHY THIS EXISTS. A spec burst's first emitted token is not produced by the accept walk:
798/// it comes off a logits row that already exists (the prime's last row on a cold burst; the
799/// row after the last committed token on a continuation burst; the prefix-cache entry's
800/// boundary row on a restored one). Pre-lane that token was `argmax` in BOTH sampling
801/// regimes, so a sampled stream took a greedy token once per burst — measured, not
802/// estimated, in research/spec-cache-20260818/SAMPLED-QUALITY.md. At temperature > 0 the
803/// customer asked for a sampled token, so this draws one.
804///
805/// THE PROGRAM IS THE FULL-ACCEPT BONUS'S PROGRAM, deliberately: penalize the row (over the
806/// session's window), take this row's OWN filter stats (the sampfix-20260805 law — stats
807/// from a neighbour row mis-scale every `e0` and can wipe the row to token 0), gumbel-perturb
808/// with the session's Philox stream at `*sctr`, argmax the perturbed row. Reusing the bonus's
809/// composition means `sample_check`'s distributional oracle covers this draw too, and the
810/// boundary token is drawn from the same filtered/penalized `p` the accept walk targets.
811///
812/// THE STREAM IS THE SESSION'S, NOT A FRESH ONE. `sctr` is the caller's live counter and is
813/// advanced by exactly one, so a boundary draw consumes the next value in the same Philox
814/// stream the accept walk uses — never a second, independently seeded stream (which would be
815/// a new distributional bug: two streams from one seed correlate wherever their counters
816/// collide). That also makes a restored session's boundary draw at `sctr == 0` bit-identical
817/// to the cold session's own first draw from the same logits row, which is what preserves the
818/// sampled-hit lane's per-seed hit==cold byte identity.
819#[allow(clippy::too_many_arguments)]
820pub fn sample_boundary_token_dev(
821 e: &Engine,
822 logits: &CudaSlice<f32>,
823 n_vocab: usize,
824 sp: &SpecSampling,
825 pen_hist: &[u32],
826 sctr: &mut u32,
827 site: &str,
828) -> Result<u32, Box<dyn std::error::Error>> {
829 debug_assert!(
830 sp.temp > 0.0,
831 "boundary sampling is the sampled regime only"
832 );
833 // Own copy: penalize_logits mutates in place and the caller's row is live state
834 // (prime_logits back the constrained recompute; last_col_logits backs round 0's accept).
835 let mut col = e.zeros(n_vocab)?;
836 e.copy_into(&mut col, 0, logits, n_vocab)?;
837 let pen_on = sp.penalty_last_n > 0
838 && (sp.penalty_repeat != 1.0 || sp.penalty_freq != 0.0 || sp.penalty_present != 0.0);
839 if pen_on && !pen_hist.is_empty() {
840 // window trim mirrors the round loop's own upload (`pen_hist[w0..]`), cap included.
841 let w0 = pen_hist
842 .len()
843 .saturating_sub(sp.penalty_last_n.min(PEN_WINDOW_MAX));
844 let hist = &pen_hist[w0..];
845 let hd = e.htod_u32_v(hist)?;
846 e.penalize_logits(
847 &mut col,
848 &hd,
849 hist.len(),
850 sp.penalty_repeat,
851 sp.penalty_freq,
852 sp.penalty_present,
853 n_vocab,
854 )?;
855 }
856 let rows0 = e.htod_i32(&[0])?;
857 let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
858 e.filter_stats(
859 &col, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1, sp.temp, sp.top_k,
860 sp.top_p, sp.min_p,
861 )?;
862 let (th, mx) = (e.dtoh(&th_d)?[0], e.dtoh(&mx_d)?[0]);
863 let mut perturb = e.zeros(n_vocab)?;
864 e.gumbel_perturb_filtered(&col, &mut perturb, n_vocab, sp.seed, *sctr, sp.temp, mx, th)?;
865 *sctr = sctr.wrapping_add(1);
866 let td = e.argmax_token_device(&perturb, n_vocab)?;
867 let tok = e.dtoh_u32_one(&td)?;
868 if spec_boundary_trace() {
869 // the pre-lane token, from the SAME row, so the deviation rate is measurable.
870 let raw = e.argmax_token_device(logits, n_vocab)?;
871 let greedy = e.dtoh_u32_one(&raw)?;
872 eprintln!(
873 "[spec-boundary] site={site} sampled={tok} argmax={greedy} \
874 deviates={} temp={} sctr={}",
875 (tok != greedy) as u8,
876 sp.temp,
877 sctr.wrapping_sub(1),
878 );
879 }
880 Ok(tok)
881}
882
883/// Host-row twin of [`sample_boundary_token_dev`] (the prime / feed / entry rows arrive as
884/// host `Vec<f32>`).
885#[allow(clippy::too_many_arguments)]
886pub fn sample_boundary_token(
887 e: &Engine,
888 logits: &[f32],
889 sp: &SpecSampling,
890 pen_hist: &[u32],
891 sctr: &mut u32,
892 site: &str,
893) -> Result<u32, Box<dyn std::error::Error>> {
894 let n_vocab = logits.len();
895 let d = e.htod(logits)?;
896 sample_boundary_token_dev(e, &d, n_vocab, sp, pen_hist, sctr, site)
897}
898
899struct SpecPipeTraceClock {
900 pair: usize,
901 started: std::time::Instant,
902}
903
904#[derive(Clone)]
905struct SpecPipeTraceCtx {
906 clock: std::sync::Arc<SpecPipeTraceClock>,
907 round: usize,
908 lane: usize,
909}
910
911struct SpecPipeTraceMarker {
912 trace: SpecPipeTraceCtx,
913 phase: &'static str,
914 edge: &'static str,
915 slot: Option<usize>,
916}
917
918unsafe extern "C" fn spec_pipe_trace_marker(raw: *mut std::ffi::c_void) {
919 let marker = unsafe { Box::from_raw(raw.cast::<SpecPipeTraceMarker>()) };
920 let lane = if marker.trace.lane == 0 { "A" } else { "B" };
921 let slot = marker
922 .slot
923 .map(|v| v.to_string())
924 .unwrap_or_else(|| "-".into());
925 let t_ms = marker.trace.clock.started.elapsed().as_secs_f64() * 1e3;
926 use std::io::Write as _;
927 let stderr = std::io::stderr();
928 let mut stderr = stderr.lock();
929 let _ = writeln!(
930 stderr,
931 "[spec-pipe-timeline] pair={} round={} lane={lane} phase={} edge={} \
932 slot={slot} t_ms={t_ms:.3}",
933 marker.trace.clock.pair, marker.trace.round, marker.phase, marker.edge,
934 );
935}
936
937fn enqueue_spec_pipe_trace_marker(
938 stream: &cudarc::driver::CudaStream,
939 trace: Option<&SpecPipeTraceCtx>,
940 phase: &'static str,
941 edge: &'static str,
942 slot: Option<usize>,
943) -> Result<(), Box<dyn std::error::Error>> {
944 let Some(trace) = trace else {
945 return Ok(());
946 };
947 let marker = Box::new(SpecPipeTraceMarker {
948 trace: trace.clone(),
949 phase,
950 edge,
951 slot,
952 });
953 let raw = Box::into_raw(marker);
954 let result = unsafe {
955 cudarc::driver::result::stream::launch_host_function(
956 stream.cu_stream(),
957 spec_pipe_trace_marker,
958 raw.cast(),
959 )
960 };
961 if let Err(err) = result {
962 unsafe {
963 drop(Box::from_raw(raw));
964 }
965 return Err(err.into());
966 }
967 Ok(())
968}
969
970#[derive(Default)]
971struct SpecPipeProgress {
972 setup_done: [bool; 2],
973 draft_done: [usize; 2],
974 stage0_done: [usize; 2],
975 verify_done: [usize; 2],
976 accept_done: [usize; 2],
977 finished: [bool; 2],
978 aborted: bool,
979}
980
981/// Host-side issue coordinator for the reduced two-session speculative pipeline. Each session
982/// keeps its existing call stack and round locals; this object only orders phase entry. The
983/// primary mutex spans whole draft/accept/tail issue regions so Engine's single-stream scratch
984/// cannot be interleaved by the two host threads.
985struct SpecPipeSync {
986 progress: std::sync::Mutex<SpecPipeProgress>,
987 changed: std::sync::Condvar,
988 primary: std::sync::Mutex<()>,
989 trace: Option<std::sync::Arc<SpecPipeTraceClock>>,
990}
991
992impl SpecPipeSync {
993 fn new() -> Self {
994 static TRACE_PAIR: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
995 let trace = (std::env::var("MEMRA_SPEC_PIPE_TRACE").as_deref() == Ok("1")).then(|| {
996 std::sync::Arc::new(SpecPipeTraceClock {
997 pair: TRACE_PAIR.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1,
998 started: std::time::Instant::now(),
999 })
1000 });
1001 Self {
1002 progress: std::sync::Mutex::new(SpecPipeProgress::default()),
1003 changed: std::sync::Condvar::new(),
1004 primary: std::sync::Mutex::new(()),
1005 trace,
1006 }
1007 }
1008}
1009
1010#[derive(Clone)]
1011struct SpecPipeLane {
1012 sync: std::sync::Arc<SpecPipeSync>,
1013 lane: usize,
1014}
1015
1016impl SpecPipeLane {
1017 fn peer(&self) -> usize {
1018 1 - self.lane
1019 }
1020
1021 fn aborted() -> Box<dyn std::error::Error> {
1022 "paired speculative peer aborted".into()
1023 }
1024
1025 fn trace(&self, round: usize) -> Option<SpecPipeTraceCtx> {
1026 self.sync.trace.as_ref().map(|clock| SpecPipeTraceCtx {
1027 clock: clock.clone(),
1028 round,
1029 lane: self.lane,
1030 })
1031 }
1032
1033 fn setup_begin(&self) -> Result<(), Box<dyn std::error::Error>> {
1034 let mut p = self.sync.progress.lock().unwrap();
1035 while !p.aborted && self.lane == 1 && !p.setup_done[0] && !p.finished[0] {
1036 p = self.sync.changed.wait(p).unwrap();
1037 }
1038 if p.aborted {
1039 Err(Self::aborted())
1040 } else {
1041 Ok(())
1042 }
1043 }
1044
1045 fn setup_end(&self) {
1046 let mut p = self.sync.progress.lock().unwrap();
1047 p.setup_done[self.lane] = true;
1048 self.sync.changed.notify_all();
1049 }
1050
1051 fn draft_begin(
1052 &self,
1053 round: usize,
1054 ) -> Result<std::sync::MutexGuard<'_, ()>, Box<dyn std::error::Error>> {
1055 let peer = self.peer();
1056 let mut p = self.sync.progress.lock().unwrap();
1057 loop {
1058 if p.aborted {
1059 return Err(Self::aborted());
1060 }
1061 let setup_ready =
1062 (p.setup_done[0] || p.finished[0]) && (p.setup_done[1] || p.finished[1]);
1063 let prior_ready = p.accept_done[self.lane] >= round
1064 && (p.accept_done[peer] >= round || p.finished[peer]);
1065 let turn_ready = if self.lane == 0 {
1066 true
1067 } else {
1068 p.draft_done[0] > round || p.finished[0]
1069 };
1070 if setup_ready && prior_ready && turn_ready {
1071 break;
1072 }
1073 p = self.sync.changed.wait(p).unwrap();
1074 }
1075 drop(p);
1076 Ok(self.sync.primary.lock().unwrap())
1077 }
1078
1079 fn draft_end(&self, round: usize) {
1080 let mut p = self.sync.progress.lock().unwrap();
1081 p.draft_done[self.lane] = round + 1;
1082 self.sync.changed.notify_all();
1083 }
1084
1085 /// Admit stage 0 and return whether this lane owns the interval's one reverse fence.
1086 /// Lane B releases as soon as lane A has issued its boundary TX, not after A's full body.
1087 fn stage0_begin(&self, round: usize) -> Result<bool, Box<dyn std::error::Error>> {
1088 let peer = self.peer();
1089 let mut p = self.sync.progress.lock().unwrap();
1090 loop {
1091 if p.aborted {
1092 return Err(Self::aborted());
1093 }
1094 let ready = if self.lane == 0 {
1095 p.draft_done[0] > round && (p.draft_done[1] > round || p.finished[1])
1096 } else {
1097 p.draft_done[1] > round && (p.stage0_done[0] > round || p.finished[0])
1098 };
1099 if ready {
1100 return Ok(self.lane == 0 || p.finished[peer]);
1101 }
1102 p = self.sync.changed.wait(p).unwrap();
1103 }
1104 }
1105
1106 fn stage0_end(&self, round: usize) {
1107 let mut p = self.sync.progress.lock().unwrap();
1108 p.stage0_done[self.lane] = round + 1;
1109 self.sync.changed.notify_all();
1110 }
1111
1112 /// Stage 1 is single-owner per engine. A proceeds immediately after its own ticket; B waits
1113 /// for A's full stage1/head issue so only A.S1 and B.S0 can overlap.
1114 fn stage1_begin(&self, round: usize) -> Result<(), Box<dyn std::error::Error>> {
1115 let mut p = self.sync.progress.lock().unwrap();
1116 while !p.aborted
1117 && !(p.stage0_done[self.lane] > round
1118 && (self.lane == 0 || p.verify_done[0] > round || p.finished[0]))
1119 {
1120 p = self.sync.changed.wait(p).unwrap();
1121 }
1122 if p.aborted {
1123 Err(Self::aborted())
1124 } else {
1125 Ok(())
1126 }
1127 }
1128
1129 fn verify_end(&self, round: usize) {
1130 let mut p = self.sync.progress.lock().unwrap();
1131 p.verify_done[self.lane] = round + 1;
1132 self.sync.changed.notify_all();
1133 }
1134
1135 fn accept_begin(
1136 &self,
1137 round: usize,
1138 ) -> Result<std::sync::MutexGuard<'_, ()>, Box<dyn std::error::Error>> {
1139 let mut p = self.sync.progress.lock().unwrap();
1140 loop {
1141 if p.aborted {
1142 return Err(Self::aborted());
1143 }
1144 let ready = if self.lane == 0 {
1145 p.verify_done[0] > round && (p.verify_done[1] > round || p.finished[1])
1146 } else {
1147 p.verify_done[1] > round && (p.accept_done[0] > round || p.finished[0])
1148 };
1149 if ready {
1150 break;
1151 }
1152 p = self.sync.changed.wait(p).unwrap();
1153 }
1154 drop(p);
1155 Ok(self.sync.primary.lock().unwrap())
1156 }
1157
1158 fn accept_end(&self, round: usize) {
1159 let mut p = self.sync.progress.lock().unwrap();
1160 p.accept_done[self.lane] = round + 1;
1161 self.sync.changed.notify_all();
1162 }
1163
1164 fn primary(&self) -> std::sync::MutexGuard<'_, ()> {
1165 self.sync.primary.lock().unwrap()
1166 }
1167
1168 fn finish(&self, failed: bool) {
1169 let mut p = self.sync.progress.lock().unwrap();
1170 p.finished[self.lane] = true;
1171 p.aborted |= failed;
1172 self.sync.changed.notify_all();
1173 }
1174}
1175
1176struct SpecPipeFinish<'a> {
1177 lane: &'a SpecPipeLane,
1178 closed: bool,
1179}
1180
1181impl<'a> SpecPipeFinish<'a> {
1182 fn new(lane: &'a SpecPipeLane) -> Self {
1183 Self {
1184 lane,
1185 closed: false,
1186 }
1187 }
1188
1189 fn close(&mut self, failed: bool) {
1190 self.lane.finish(failed);
1191 self.closed = true;
1192 }
1193}
1194
1195impl Drop for SpecPipeFinish<'_> {
1196 fn drop(&mut self) {
1197 if !self.closed {
1198 self.lane.finish(true);
1199 }
1200 }
1201}
1202
1203/// Scoped transfer of one exclusively-borrowed session to the second host issue thread.
1204/// `CudaGraph` is not marked Send by cudarc because its raw driver handles carry no automatic
1205/// trait. CUDA driver graph handles are context-scoped rather than OS-thread-affine; the caller
1206/// binds that context before touching the session, joins before returning, and never aliases the
1207/// pointer. Keep this exception local to the experimental pair call instead of marking the public
1208/// session type Send.
1209struct SpecPipeSessionPtr(*mut SpecSession);
1210
1211unsafe impl Send for SpecPipeSessionPtr {}
1212
1213impl SpecPipeSessionPtr {
1214 unsafe fn get_mut(&mut self) -> &mut SpecSession {
1215 unsafe { &mut *self.0 }
1216 }
1217}
1218
1219/// Per-session persistent draft-graph context: the captured CUDA graph(s) plus the device
1220/// buffers whose POINTERS the capture bakes. Reuse legality: the greedy capture bakes only
1221/// session-stable pointers (the session's own MtpScratch KV — allocated once, never realloc'd;
1222/// the model's resident embedding; the process-wide OnceLock p_min) and the g_* buffers held
1223/// HERE — so one capture serves the session's whole lifetime. The sampled capture additionally
1224/// bakes (seed, temp) as capture-time constants and needs k q-slots — keyed by `s_key`, dropped
1225/// and recaptured when a pool-resumed request changes them. `*_failed` memoizes a failed capture
1226/// so the eager fallback doesn't pay a doomed capture attempt every burst.
1227pub(crate) struct DraftGraphCtx {
1228 g_tok: CudaSlice<u32>,
1229 g_pos: CudaSlice<i32>,
1230 g_seed: CudaSlice<f32>,
1231 g_p: CudaSlice<f32>,
1232 g_ctr: CudaSlice<u32>,
1233 g_q: CudaSlice<f32>,
1234 g_perturb: CudaSlice<f32>,
1235 q_slots: Vec<CudaSlice<f32>>,
1236 /// DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): packed allowed-set words over the DRAFT
1237 /// head's vocab, at a STABLE address so the captured draft graph's mask node reads the
1238 /// per-position contents the host re-uploads before each replay (the graph-promote
1239 /// pattern from decode.rs). Empty unless the session drafts under a grammar.
1240 g_dmask: CudaSlice<u32>,
1241 /// was `graph` captured WITH the mask node? A parked graph of the wrong shape is dropped.
1242 graph_masked: bool,
1243 graph: Option<cudarc::driver::CudaGraph>,
1244 graph_s: Option<cudarc::driver::CudaGraph>,
1245 /// Failed-capture memoization for both graphs — LOUD on flip, cleared on pool resume
1246 /// (audit Q2, the TRT #16072 silent-permanent-coverage-loss class).
1247 failed: DraftGraphFallback,
1248 /// (seed, temp.to_bits(), k) baked into graph_s at its capture.
1249 s_key: Option<(u64, u32, usize)>,
1250 /// CAPTURE-RETAIN keepers (#68 root cause, 2026-08-04): the warmup-run transients whose
1251 /// pool addresses the captured graph(s) bake. Without these, the transients return to the
1252 /// pool at capture-body exit and later work (burst-boundary prime/fill/commit passes, or a
1253 /// co-served session in the worker) reuses those addresses — the persisted graph's replay
1254 /// then reads/writes live unrelated buffers (exactness corruption, first seen as the ST
1255 /// serve-spec 4B graph-arm corruption; one-shot CLI calls never re-shuffled the pool, which
1256 /// is why run-spec K=1..8 passed on the same checkpoint). Same fix class as
1257 /// capture_graph_retained's gemma/decode.rs sites — hold as long as the graph replays.
1258 keeper: Vec<Box<dyn std::any::Any + Send>>,
1259 keeper_s: Vec<Box<dyn std::any::Any + Send>>,
1260}
1261
1262/// Failed-capture memoization for the two draft graphs (audit Q2, 2026-08-05 — the
1263/// TRT #16072 trap class: pressure-triggered, silent, long-lived coverage loss).
1264///
1265/// Three contracts:
1266/// - LOUD FLIP: `mark_*` returns the warn line exactly on the false→true transition
1267/// (returned, not printed, so the once-per-flip contract is unit-testable); the caller
1268/// `eprintln!`s it UNCONDITIONALLY — a dropped draft graph is never silent. Re-marking
1269/// an already-failed graph returns None (the per-burst memoization that keeps the eager
1270/// fallback from paying a doomed capture attempt every burst).
1271/// - RESET ON RESUME: `reset_on_resume` clears both flags — a parked session resumed by a
1272/// NEW request gets one fresh capture chance instead of carrying a transient-pressure
1273/// failure for the pool's whole lifetime. Returns the note line only when a flag was
1274/// actually set (quiet on the common clean-resume path).
1275/// - Shape-change clears (`clear_*`) stay silent, exactly as before: they precede a fresh
1276/// capture attempt whose own failure would re-flip loudly.
1277#[derive(Default)]
1278pub(crate) struct DraftGraphFallback {
1279 greedy: bool,
1280 sampled: bool,
1281}
1282impl DraftGraphFallback {
1283 fn mark_greedy(&mut self, reason: &str) -> Option<String> {
1284 if self.greedy {
1285 return None;
1286 }
1287 self.greedy = true;
1288 Some(format!(
1289 "[spec] WARN: draft-graph capture failed ({reason}); eager fallback until session resume"
1290 ))
1291 }
1292 fn mark_sampled(&mut self, reason: &str) -> Option<String> {
1293 if self.sampled {
1294 return None;
1295 }
1296 self.sampled = true;
1297 Some(format!(
1298 "[spec] WARN: sampled draft-graph capture failed ({reason}); eager fallback until session resume"
1299 ))
1300 }
1301 fn greedy_failed(&self) -> bool {
1302 self.greedy
1303 }
1304 fn sampled_failed(&self) -> bool {
1305 self.sampled
1306 }
1307 fn clear_greedy(&mut self) {
1308 self.greedy = false;
1309 }
1310 fn clear_sampled(&mut self) {
1311 self.sampled = false;
1312 }
1313 /// Pool-resume reset: both graphs get a fresh capture chance. Some(note) iff any flag
1314 /// was set (so clean resumes stay quiet).
1315 pub(crate) fn reset_on_resume(&mut self) -> Option<String> {
1316 if !self.greedy && !self.sampled {
1317 return None;
1318 }
1319 let which = match (self.greedy, self.sampled) {
1320 (true, true) => "greedy+sampled",
1321 (true, false) => "greedy",
1322 _ => "sampled",
1323 };
1324 self.greedy = false;
1325 self.sampled = false;
1326 Some(format!(
1327 "[spec] draft-graph fallback reset on session resume ({which}); recapture eligible"
1328 ))
1329 }
1330}
1331
1332impl DraftGraphCtx {
1333 fn new(e: &Engine, n_embd: usize, qlen: usize) -> Result<Self, Box<dyn std::error::Error>> {
1334 Ok(DraftGraphCtx {
1335 g_tok: e.alloc_u32_zeroed(1)?,
1336 g_pos: e.htod_i32(&[0])?,
1337 g_seed: e.zeros(n_embd)?,
1338 g_p: e.zeros(1)?,
1339 g_ctr: e.alloc_u32_zeroed(1)?,
1340 g_q: e.zeros(qlen)?,
1341 g_perturb: e.zeros(qlen)?,
1342 q_slots: Vec::new(),
1343 g_dmask: e.alloc_u32_zeroed(1)?,
1344 graph_masked: false,
1345 graph: None,
1346 graph_s: None,
1347 failed: DraftGraphFallback::default(),
1348 s_key: None,
1349 keeper: Vec::new(),
1350 keeper_s: Vec::new(),
1351 })
1352 }
1353}
1354
1355pub(crate) struct MtpScratch {
1356 kv: KvLayer,
1357 /// Logical row capacity. On the graph/DC draft path it also doubles as fa_decode_dc's
1358 /// bucket_max: n_splits is sized from it ONCE, so the graph captured at round 0 stays valid
1359 /// for every later t_kv. Step35 refuses that path and may back this logical extent with the
1360 /// smaller host-indexed SWA ring instead.
1361 cap: usize,
1362}
1363
1364fn mtp_scratch_layout(
1365 cfg: &memra_gguf::config::ModelConfig,
1366 geom: Option<&crate::hybrid::DraftGeom>,
1367) -> (usize, usize, usize, usize) {
1368 // Student draft heads carry fewer KV heads (head_dim unchanged) -> smaller scratch rows.
1369 let n_head_kv = geom.map(|g| g.n_head_kv).unwrap_or(cfg.n_head_kv as usize);
1370 let head_dim_k = cfg.head_dim_k as usize;
1371 let head_dim_v = cfg.head_dim_v as usize;
1372 assert!(
1373 head_dim_k % 32 == 0 && head_dim_v % 32 == 0,
1374 "KVQUANT requires head_dim%32==0 (MTP scratch)"
1375 );
1376 let kv_dim_k = head_dim_k * n_head_kv;
1377 let kv_dim_v = head_dim_v * n_head_kv;
1378 // The fp8-KV arm deliberately does not reach the draft scratch; keep the exact format
1379 // policy shared with `MtpScratch::new` so admission scales the same allocation.
1380 let (kbb, vbb) = crate::kv_blk_bytes();
1381 let k_tok_bytes = (kv_dim_k / 32) * kbb;
1382 let v_tok_bytes = (kv_dim_v / 32) * vbb;
1383 (kv_dim_k, kv_dim_v, k_tok_bytes, v_tok_bytes)
1384}
1385
1386impl MtpScratch {
1387 fn new(
1388 e: &Engine,
1389 cfg: &memra_gguf::config::ModelConfig,
1390 cap: usize,
1391 geom: Option<&crate::hybrid::DraftGeom>,
1392 ) -> Result<Self, Box<dyn std::error::Error>> {
1393 // env-selected KV formats (default 34/24). The fp8-KV arm (MEMRA_KV_FP8) deliberately
1394 // does NOT reach the draft scratch: fp8 drafts drifted acceptance 69-88% -> 46%
1395 // (2026-07-12 A/B); the scratch is tiny, so it keeps baseline q8_0/q5_1 numerics
1396 // while the TRUNK cache carries the fp8 depth win. Scratch append/fa pass g=false.
1397 let (kv_dim_k, kv_dim_v, k_tok_bytes, v_tok_bytes) = mtp_scratch_layout(cfg, geom);
1398 let ring = if crate::cache::swa_ring_on() && cfg.arch.is_step35() {
1399 let window = cfg.step35.as_ref().unwrap().sliding_window as usize;
1400 Some(crate::cache::KvRing::new(
1401 crate::cache::swa_ring_rows(window, cap),
1402 window,
1403 ))
1404 } else {
1405 None
1406 };
1407 let alloc_rows = ring.as_ref().map(crate::cache::KvRing::rows).unwrap_or(cap);
1408 Ok(MtpScratch {
1409 kv: KvLayer {
1410 k: e.alloc_u8(alloc_rows * k_tok_bytes)?,
1411 v: e.alloc_u8(alloc_rows * v_tok_bytes)?,
1412 kv_dim_k,
1413 kv_dim_v,
1414 k_tok_bytes,
1415 v_tok_bytes,
1416 len: 0,
1417 ring,
1418 len_d: e.htod_i32(&[0])?,
1419 },
1420 cap,
1421 })
1422 }
1423 /// Set BOTH length counters: the host mirror AND the device len_d the captured append/fa read
1424 /// (a 4-byte in-place htod — the counter pointer is baked into the graph, never realloc'd).
1425 /// This is the ONLY truncation/rollback mechanism the persistent draft KV needs.
1426 fn set_len(&mut self, e: &Engine, n: usize) -> Result<(), Box<dyn std::error::Error>> {
1427 if self
1428 .kv
1429 .ring
1430 .as_ref()
1431 .is_some_and(|ring| !ring.can_rewind_to(n))
1432 {
1433 return Err("SWA ring MTP checkpoint has been lapped; full re-prime required".into());
1434 }
1435 self.kv.len = n;
1436 e.set_i32_one(&mut self.kv.len_d, n as i32)
1437 }
1438
1439 fn can_rewind_to(&self, n: usize) -> bool {
1440 self.kv
1441 .ring
1442 .as_ref()
1443 .is_none_or(|ring| ring.can_rewind_to(n))
1444 }
1445}
1446
1447/// Retained verify intermediates for the REPLAY-FREE partial accept (2026-07-03, the profiled
1448/// #1 spec cost at long ctx: the partial-accept replay was a DUPLICATE trunk pass — ~0.54 extra
1449/// full weight reads per round — recomputing columns the verify had already produced
1450/// bit-identically). Holds, per linear layer, everything needed to rebuild its recurrent state
1451/// to "after the first j verify columns" WITHOUT re-running the trunk:
1452/// - BATCHED-path layers (`gdn`): the exact token-major inputs the round's ONE gdn_scan
1453/// consumed. A prefix re-run of the SAME kernel (t=j) from the snapshot state is bit-identical
1454/// to the first j iterations of the verify's scan — the kernel's t-loop carries state in
1455/// registers and iteration t never depends on T. `qkv_mixed` (the conv input) feeds the
1456/// pure-copy ring rebuild.
1457/// - PER-COLUMN-path layers (`cols`): dtod clones of (conv_state, ssm_state) taken after each
1458/// column 0..t-2 — pure copies of the actual chain states (the last column is never a rebuild
1459/// target: j <= t-1).
1460/// Full-attn layers need nothing: their verify KV rows are bit-identical to eager's (the
1461/// decode-exact contract; verify-probe pins it), so rollback = len truncation.
1462struct GdnStash {
1463 qkv_mixed: CudaSlice<f32>, // [t, conv_dim] token-major (conv input)
1464 q_l2: CudaSlice<f32>,
1465 k_l2: CudaSlice<f32>,
1466 v_g: CudaSlice<f32>, // [t, num_v, d_state]
1467 g_log: CudaSlice<f32>,
1468 beta: CudaSlice<f32>, // [t, num_v]
1469}
1470struct VerifyCkpt {
1471 gdn: Vec<Option<GdnStash>>, // [n_layer], Some iff batched linear path ran
1472 cols: Vec<Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>>>, // [n_layer][col] = (conv, ssm) after col
1473}
1474/// Opaque handle for the dspark round (dflash.rs) — VerifyCkpt stays spec-private.
1475pub(crate) struct DsparkVerifyCkpt(VerifyCkpt);
1476
1477impl VerifyCkpt {
1478 fn new(n_layer: usize) -> Self {
1479 VerifyCkpt {
1480 gdn: (0..n_layer).map(|_| None).collect(),
1481 cols: (0..n_layer).map(|_| None).collect(),
1482 }
1483 }
1484}
1485
1486/// The stage-0/TX half of one PP verify. The boundary slot is the ownership token: stage 1
1487/// consumes exactly the slot selected by `tx()` / `tx_pipelined()`, never a slot inferred from
1488/// a logical round number.
1489struct VerifyBoundaryTicket {
1490 rt: &'static crate::pp::PpNRt,
1491 caller_stream: std::sync::Arc<cudarc::driver::CudaStream>,
1492 slot: usize,
1493 pos0: usize,
1494 t: usize,
1495 payload: usize,
1496 n_st: usize,
1497 pipelined: bool,
1498 pp_anatomy: bool,
1499 pp_started: std::time::Instant,
1500 reverse_ms: f64,
1501 stage0_ms: f64,
1502 tx_ms: f64,
1503 trace: Option<SpecPipeTraceCtx>,
1504}
1505
1506/// Explicit OPTIPIPE diagnostic control. Forced modes are set only by `optipipe-gate`; the
1507/// increment-2 controller can also be armed by the server's fresh-process research door.
1508#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1509pub enum OptiForkGateMode {
1510 Disabled,
1511 Hit,
1512 Miss,
1513 Alternate,
1514 Abort,
1515 Controller,
1516}
1517
1518static OPTI_FORK_GATE_MODE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
1519static OPTI_CONTROLLER_THRESHOLD: std::sync::atomic::AtomicU32 =
1520 std::sync::atomic::AtomicU32::new(0);
1521static OPTI_FORK_ATTEMPTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1522static OPTI_FORK_HITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1523static OPTI_FORK_MISSES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1524static OPTI_FORK_ABORT_DRAINS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1525static OPTI_FORK_REFUSALS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1526static OPTI_GATE_CHECKS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1527static OPTI_GATE_ADMITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1528static OPTI_GATE_REJECTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1529static OPTI_RECONCILES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1530static OPTI_WASTED_DRAFT_TOKENS: std::sync::atomic::AtomicU64 =
1531 std::sync::atomic::AtomicU64::new(0);
1532static OPTI_SHADOW_DRAFT_TOKENS: std::sync::atomic::AtomicU64 =
1533 std::sync::atomic::AtomicU64::new(0);
1534static OPTI_BREAKER_TRIPS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1535
1536impl OptiForkGateMode {
1537 fn code(self) -> u8 {
1538 match self {
1539 Self::Disabled => 0,
1540 Self::Hit => 1,
1541 Self::Miss => 2,
1542 Self::Alternate => 3,
1543 Self::Abort => 4,
1544 Self::Controller => 5,
1545 }
1546 }
1547
1548 fn configured() -> Self {
1549 match OPTI_FORK_GATE_MODE.load(std::sync::atomic::Ordering::Relaxed) {
1550 1 => Self::Hit,
1551 2 => Self::Miss,
1552 3 => Self::Alternate,
1553 4 => Self::Abort,
1554 5 => Self::Controller,
1555 _ => Self::Disabled,
1556 }
1557 }
1558
1559 fn action(self, generation: u64) -> OptiForkAction {
1560 match self {
1561 Self::Hit => OptiForkAction::Hit,
1562 Self::Miss => OptiForkAction::Miss,
1563 Self::Alternate if generation & 1 == 0 => OptiForkAction::Hit,
1564 Self::Alternate => OptiForkAction::Miss,
1565 Self::Abort => OptiForkAction::Abort,
1566 Self::Disabled | Self::Controller => {
1567 unreachable!("non-forced mode cannot choose a forced fork action")
1568 }
1569 }
1570 }
1571
1572 fn is_forced(self) -> bool {
1573 matches!(self, Self::Hit | Self::Miss | Self::Alternate | Self::Abort)
1574 }
1575}
1576
1577/// Arm or disarm the forced harness. Serving uses only `set_optipipe_controller_threshold`.
1578pub fn set_optipipe_gate_mode(mode: OptiForkGateMode) {
1579 OPTI_FORK_GATE_MODE.store(mode.code(), std::sync::atomic::Ordering::Relaxed);
1580}
1581
1582/// Arm the increment-2 diagnostic controller. The threshold applies to the uncalibrated
1583/// two-token draft-probability product. Serving can call this only through its explicit
1584/// fresh-process research door; the absent-door default remains byte-for-byte disabled.
1585pub fn set_optipipe_controller_threshold(threshold: f32) {
1586 assert!(threshold.is_finite() && (0.0..=1.0).contains(&threshold));
1587 OPTI_CONTROLLER_THRESHOLD.store(threshold.to_bits(), std::sync::atomic::Ordering::Relaxed);
1588 set_optipipe_gate_mode(OptiForkGateMode::Controller);
1589}
1590
1591#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1592pub struct OptiForkGateStats {
1593 pub attempts: u64,
1594 pub hits: u64,
1595 pub misses: u64,
1596 pub abort_drains: u64,
1597 pub refusals: u64,
1598 pub gate_checks: u64,
1599 pub gate_admits: u64,
1600 pub gate_rejects: u64,
1601 pub reconciles: u64,
1602 pub wasted_draft_tokens: u64,
1603 pub shadow_draft_tokens: u64,
1604 pub breaker_trips: u64,
1605}
1606
1607#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1608pub struct OptiForkStateIdentity {
1609 pub trunk_kv_bytes: usize,
1610 pub recurrent_bytes: usize,
1611 pub scratch_kv_bytes: usize,
1612 pub hidden_bytes: usize,
1613}
1614
1615pub fn reset_optipipe_gate_stats() {
1616 for counter in [
1617 &OPTI_FORK_ATTEMPTS,
1618 &OPTI_FORK_HITS,
1619 &OPTI_FORK_MISSES,
1620 &OPTI_FORK_ABORT_DRAINS,
1621 &OPTI_FORK_REFUSALS,
1622 &OPTI_GATE_CHECKS,
1623 &OPTI_GATE_ADMITS,
1624 &OPTI_GATE_REJECTS,
1625 &OPTI_RECONCILES,
1626 &OPTI_WASTED_DRAFT_TOKENS,
1627 &OPTI_SHADOW_DRAFT_TOKENS,
1628 &OPTI_BREAKER_TRIPS,
1629 ] {
1630 counter.store(0, std::sync::atomic::Ordering::Relaxed);
1631 }
1632}
1633
1634pub fn optipipe_gate_stats() -> OptiForkGateStats {
1635 let load = |v: &std::sync::atomic::AtomicU64| v.load(std::sync::atomic::Ordering::Relaxed);
1636 OptiForkGateStats {
1637 attempts: load(&OPTI_FORK_ATTEMPTS),
1638 hits: load(&OPTI_FORK_HITS),
1639 misses: load(&OPTI_FORK_MISSES),
1640 abort_drains: load(&OPTI_FORK_ABORT_DRAINS),
1641 refusals: load(&OPTI_FORK_REFUSALS),
1642 gate_checks: load(&OPTI_GATE_CHECKS),
1643 gate_admits: load(&OPTI_GATE_ADMITS),
1644 gate_rejects: load(&OPTI_GATE_REJECTS),
1645 reconciles: load(&OPTI_RECONCILES),
1646 wasted_draft_tokens: load(&OPTI_WASTED_DRAFT_TOKENS),
1647 shadow_draft_tokens: load(&OPTI_SHADOW_DRAFT_TOKENS),
1648 breaker_trips: load(&OPTI_BREAKER_TRIPS),
1649 }
1650}
1651
1652#[derive(Clone, Copy, Debug)]
1653struct OptiControllerPolicy {
1654 threshold: f32,
1655 consecutive_misses: u8,
1656 breaker_tripped: bool,
1657}
1658
1659impl OptiControllerPolicy {
1660 fn configured() -> Self {
1661 Self {
1662 threshold: f32::from_bits(
1663 OPTI_CONTROLLER_THRESHOLD.load(std::sync::atomic::Ordering::Relaxed),
1664 ),
1665 consecutive_misses: 0,
1666 breaker_tripped: false,
1667 }
1668 }
1669
1670 fn admit(&self, q_proxy: f32) -> bool {
1671 q_proxy.is_finite()
1672 && (0.0..=1.0).contains(&q_proxy)
1673 && (self.threshold == 0.0 || (!self.breaker_tripped && q_proxy >= self.threshold))
1674 }
1675
1676 /// Returns true exactly when this resolution newly trips the three-miss breaker.
1677 fn resolve(&mut self, hit: bool) -> bool {
1678 // q*=0 is the lane's explicit unconditional measurement arm. Its purpose is to price
1679 // every optimistic opportunity, so the safety breaker is measured separately and must
1680 // not silently turn this arm into "three attempts then serial".
1681 if self.threshold == 0.0 {
1682 self.consecutive_misses = 0;
1683 return false;
1684 }
1685 if hit {
1686 self.consecutive_misses = 0;
1687 return false;
1688 }
1689 self.consecutive_misses = self.consecutive_misses.saturating_add(1);
1690 if !self.breaker_tripped && self.consecutive_misses >= 3 {
1691 self.breaker_tripped = true;
1692 return true;
1693 }
1694 false
1695 }
1696}
1697
1698#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1699enum OptiForkAction {
1700 Hit,
1701 Miss,
1702 Abort,
1703}
1704
1705#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1706struct OptiForkGeneration {
1707 id: u64,
1708 slot: usize,
1709}
1710
1711#[derive(Default)]
1712struct OptiForkGenerationTracker {
1713 next: u64,
1714 live: [Option<u64>; 2],
1715}
1716
1717impl OptiForkGenerationTracker {
1718 fn reserve(&mut self) -> Result<OptiForkGeneration, Box<dyn std::error::Error>> {
1719 let generation = OptiForkGeneration {
1720 id: self.next,
1721 slot: (self.next & 1) as usize,
1722 };
1723 if let Some(live) = self.live[generation.slot] {
1724 return Err(format!(
1725 "optipipe snapshot slot {} still owns generation {live}; refusing to overwrite it",
1726 generation.slot,
1727 )
1728 .into());
1729 }
1730 self.next += 1;
1731 self.live[generation.slot] = Some(generation.id);
1732 Ok(generation)
1733 }
1734
1735 fn retire(&mut self, generation: OptiForkGeneration) -> Result<(), Box<dyn std::error::Error>> {
1736 match self.live[generation.slot] {
1737 Some(id) if id == generation.id => {
1738 self.live[generation.slot] = None;
1739 Ok(())
1740 }
1741 other => Err(format!(
1742 "optipipe generation teardown mismatch: ticket={} slot={} live={other:?}",
1743 generation.id, generation.slot,
1744 )
1745 .into()),
1746 }
1747 }
1748}
1749
1750struct OptiForkSeedGeneration {
1751 h_seed: CudaSlice<f32>,
1752 fill_prev: CudaSlice<f32>,
1753 scratch_len: usize,
1754}
1755
1756/// Allocate or refresh one full checkpoint through the engine that owns each PP stage. The
1757/// generic cache helper accepts one device and therefore cannot copy GDN state split across
1758/// devices. KV lengths and position stay host metadata; only recurrent buffers need stage-local
1759/// device ownership.
1760fn opti_snapshot_stage_owned(
1761 e: &Engine,
1762 cache: &Cache,
1763 rt: &'static crate::pp::PpNRt,
1764 fence: &[usize],
1765) -> Result<crate::cache::CacheSnapshot, Box<dyn std::error::Error>> {
1766 let n = cache.kv.len();
1767 let mut snapshot = crate::cache::CacheSnapshot {
1768 kv_len: vec![None; n],
1769 conv: (0..n).map(|_| None).collect(),
1770 ssm: (0..n).map(|_| None).collect(),
1771 pos: cache.pos,
1772 };
1773 opti_snapshot_stage_owned_into(e, cache, rt, fence, &mut snapshot)?;
1774 Ok(snapshot)
1775}
1776
1777fn opti_snapshot_stage_owned_into(
1778 e: &Engine,
1779 cache: &Cache,
1780 rt: &'static crate::pp::PpNRt,
1781 fence: &[usize],
1782 snapshot: &mut crate::cache::CacheSnapshot,
1783) -> Result<(), Box<dyn std::error::Error>> {
1784 if fence.len() != rt.n_stages() + 1 || snapshot.kv_len.len() != cache.kv.len() {
1785 return Err("optipipe stage-owned snapshot shape mismatch".into());
1786 }
1787 for stage in 0..rt.n_stages() {
1788 opti_snapshot_one_stage_owned_into(e, cache, rt, fence, stage, snapshot)?;
1789 }
1790 snapshot.pos = cache.pos;
1791 Ok(())
1792}
1793
1794/// Refresh one PP stage of a checkpoint. Increment 2 uses this split form so stage 0's
1795/// optimistic post-N state is captured before N+1 stage 0 is queued, while stage 1's matching
1796/// post-N state is captured only after N stage 1 is enqueued. Calling the all-stage helper at
1797/// either point would capture one side of the fork at the wrong generation.
1798fn opti_snapshot_one_stage_owned_into(
1799 e: &Engine,
1800 cache: &Cache,
1801 rt: &'static crate::pp::PpNRt,
1802 fence: &[usize],
1803 stage: usize,
1804 snapshot: &mut crate::cache::CacheSnapshot,
1805) -> Result<(), Box<dyn std::error::Error>> {
1806 if fence.len() != rt.n_stages() + 1
1807 || snapshot.kv_len.len() != cache.kv.len()
1808 || stage >= rt.n_stages()
1809 {
1810 return Err("optipipe single-stage snapshot shape mismatch".into());
1811 }
1812 let _scope = rt.enter(stage);
1813 let owner = rt.engine(stage, e);
1814 for il in fence[stage]..fence[stage + 1] {
1815 snapshot.kv_len[il] = cache.kv[il].as_ref().map(|kv| kv.len);
1816 match &cache.recur[il] {
1817 Some(recur) => {
1818 match snapshot.conv[il].as_mut() {
1819 Some(dst) => {
1820 owner.copy_into(dst, 0, &recur.conv_state, recur.conv_state.len())?
1821 }
1822 None => snapshot.conv[il] = Some(owner.clone_dtod(&recur.conv_state)?),
1823 }
1824 match snapshot.ssm[il].as_mut() {
1825 Some(dst) => {
1826 owner.copy_into(dst, 0, &recur.ssm_state, recur.ssm_state.len())?
1827 }
1828 None => snapshot.ssm[il] = Some(owner.clone_dtod(&recur.ssm_state)?),
1829 }
1830 }
1831 None if snapshot.conv[il].is_some() || snapshot.ssm[il].is_some() => {
1832 return Err(
1833 format!("optipipe stage-owned snapshot layer {il} changed shape").into(),
1834 );
1835 }
1836 None => {}
1837 }
1838 }
1839 snapshot.pos = cache.pos;
1840 Ok(())
1841}
1842
1843/// Increment-1 persistent fork state. Exactly two snapshot/seed slots alternate; a live ticket
1844/// names its generation and keeps teardown fail-closed. Only stage 0 is allowed to mutate before
1845/// resolve, so the reconcile tables and conditional restores are stage-local.
1846struct OptiForkState {
1847 mode: OptiForkGateMode,
1848 controller: Option<OptiControllerPolicy>,
1849 generations: OptiForkGenerationTracker,
1850 active_snapshot_slot: usize,
1851 alternate_snapshot: crate::cache::CacheSnapshot,
1852 seeds: [OptiForkSeedGeneration; 2],
1853 rt: &'static crate::pp::PpNRt,
1854 fence: [usize; 3],
1855 split: usize,
1856 len_ptrs: CudaSlice<u64>,
1857 saved_lens: CudaSlice<i32>,
1858 forced_acc: CudaSlice<u32>,
1859 valid: CudaSlice<u32>,
1860 stage0_stream: std::sync::Arc<cudarc::driver::CudaStream>,
1861 logical_payload_bytes: [usize; 2],
1862}
1863
1864struct OptiForkTicket {
1865 generation: OptiForkGeneration,
1866 boundary: Option<VerifyBoundaryTicket>,
1867 drain: std::sync::Arc<cudarc::driver::CudaStream>,
1868 settled: bool,
1869}
1870
1871struct OptiControllerTicket {
1872 generation: OptiForkGeneration,
1873 boundary: Option<VerifyBoundaryTicket>,
1874 ckpt: Option<VerifyCkpt>,
1875 verify_tokens: [u32; 2],
1876 draft_prob: f32,
1877 eager_seed: Option<CudaSlice<f32>>,
1878 q_proxy: f32,
1879 scratch_len: usize,
1880 issued_at: std::time::Instant,
1881 drain: std::sync::Arc<cudarc::driver::CudaStream>,
1882 settled: bool,
1883}
1884
1885struct OptiControllerPrepared {
1886 verify_tokens: [u32; 2],
1887 draft_prob: f32,
1888 eager_seed: Option<CudaSlice<f32>>,
1889 q_proxy: f32,
1890 scratch_len: usize,
1891}
1892
1893impl OptiControllerTicket {
1894 fn take_boundary(&mut self) -> VerifyBoundaryTicket {
1895 self.boundary
1896 .take()
1897 .expect("controller boundary ticket already consumed")
1898 }
1899
1900 fn take_ckpt(&mut self) -> VerifyCkpt {
1901 self.ckpt
1902 .take()
1903 .expect("controller verify checkpoint already consumed")
1904 }
1905
1906 fn take_eager_seed(&mut self) -> Option<CudaSlice<f32>> {
1907 self.eager_seed.take()
1908 }
1909
1910 fn settle(&mut self) {
1911 self.settled = true;
1912 }
1913}
1914
1915impl Drop for OptiControllerTicket {
1916 fn drop(&mut self) {
1917 if !self.settled {
1918 let _ = self.drain.synchronize();
1919 OPTI_FORK_ABORT_DRAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1920 }
1921 }
1922}
1923
1924impl OptiForkTicket {
1925 fn take_boundary(&mut self) -> VerifyBoundaryTicket {
1926 self.boundary
1927 .take()
1928 .expect("fork ticket boundary already consumed")
1929 }
1930
1931 fn settle(&mut self) {
1932 self.settled = true;
1933 }
1934}
1935
1936impl Drop for OptiForkTicket {
1937 fn drop(&mut self) {
1938 if !self.settled {
1939 let _ = self.drain.synchronize();
1940 OPTI_FORK_ABORT_DRAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1941 }
1942 }
1943}
1944
1945impl OptiForkState {
1946 #[allow(clippy::too_many_arguments)]
1947 fn new(
1948 e: &Engine,
1949 cache: &Cache,
1950 mode: OptiForkGateMode,
1951 alternate_snapshot: crate::cache::CacheSnapshot,
1952 h_seed: &CudaSlice<f32>,
1953 fill_prev: &CudaSlice<f32>,
1954 rt: &'static crate::pp::PpNRt,
1955 split: usize,
1956 n_layer: usize,
1957 ) -> Result<Self, Box<dyn std::error::Error>> {
1958 let fence = [0, split, n_layer];
1959 let mut logical_payload_bytes = [0usize; 2];
1960 for stage in 0..2 {
1961 for il in fence[stage]..fence[stage + 1] {
1962 logical_payload_bytes[stage] += alternate_snapshot.conv[il]
1963 .as_ref()
1964 .map_or(0, |v| v.len() * std::mem::size_of::<f32>());
1965 logical_payload_bytes[stage] += alternate_snapshot.ssm[il]
1966 .as_ref()
1967 .map_or(0, |v| v.len() * std::mem::size_of::<f32>());
1968 }
1969 }
1970 let seeds = [
1971 OptiForkSeedGeneration {
1972 h_seed: e.clone_dtod(h_seed)?,
1973 fill_prev: e.clone_dtod(fill_prev)?,
1974 scratch_len: 0,
1975 },
1976 OptiForkSeedGeneration {
1977 h_seed: e.clone_dtod(h_seed)?,
1978 fill_prev: e.clone_dtod(fill_prev)?,
1979 scratch_len: 0,
1980 },
1981 ];
1982 let (len_ptrs, saved_lens, forced_acc, valid, stage0_stream) = {
1983 let _stage = rt.enter(0);
1984 let e0 = rt.engine(0, e);
1985 (
1986 crate::round_stream::kv_len_ptr_table_range(e0, cache, 0..split, None)?,
1987 e0.htod_i32(&vec![0; split])?,
1988 e0.alloc_u32_zeroed(2)?,
1989 e0.alloc_u32_zeroed(1)?,
1990 e0.stream(),
1991 )
1992 };
1993 logical_payload_bytes[0] += seeds
1994 .iter()
1995 .map(|seed| (seed.h_seed.len() + seed.fill_prev.len()) * std::mem::size_of::<f32>())
1996 .sum::<usize>();
1997 logical_payload_bytes[0] += len_ptrs.len() * std::mem::size_of::<u64>()
1998 + saved_lens.len() * std::mem::size_of::<i32>()
1999 + forced_acc.len() * std::mem::size_of::<u32>()
2000 + valid.len() * std::mem::size_of::<u32>();
2001 Ok(Self {
2002 mode,
2003 controller: (mode == OptiForkGateMode::Controller)
2004 .then(OptiControllerPolicy::configured),
2005 generations: OptiForkGenerationTracker::default(),
2006 active_snapshot_slot: 0,
2007 alternate_snapshot,
2008 seeds,
2009 rt,
2010 fence,
2011 split,
2012 len_ptrs,
2013 saved_lens,
2014 forced_acc,
2015 valid,
2016 stage0_stream,
2017 logical_payload_bytes,
2018 })
2019 }
2020
2021 fn reserve(
2022 &mut self,
2023 current_snapshot: &mut crate::cache::CacheSnapshot,
2024 ) -> Result<OptiForkGeneration, Box<dyn std::error::Error>> {
2025 let generation = self.generations.reserve()?;
2026 if generation.slot != self.active_snapshot_slot {
2027 std::mem::swap(current_snapshot, &mut self.alternate_snapshot);
2028 self.active_snapshot_slot = generation.slot;
2029 }
2030 Ok(generation)
2031 }
2032
2033 fn capture_seed(
2034 &mut self,
2035 e: &Engine,
2036 generation: OptiForkGeneration,
2037 h_seed: &CudaSlice<f32>,
2038 fill_prev: &CudaSlice<f32>,
2039 scratch_len: usize,
2040 ) -> Result<(), Box<dyn std::error::Error>> {
2041 let seed = &mut self.seeds[generation.slot];
2042 e.copy_into(&mut seed.h_seed, 0, h_seed, h_seed.len())?;
2043 e.copy_into(&mut seed.fill_prev, 0, fill_prev, fill_prev.len())?;
2044 seed.scratch_len = scratch_len;
2045 Ok(())
2046 }
2047
2048 fn ticket(
2049 &self,
2050 generation: OptiForkGeneration,
2051 boundary: VerifyBoundaryTicket,
2052 ) -> OptiForkTicket {
2053 OptiForkTicket {
2054 generation,
2055 boundary: Some(boundary),
2056 drain: self.stage0_stream.clone(),
2057 settled: false,
2058 }
2059 }
2060
2061 #[allow(clippy::too_many_arguments)]
2062 fn controller_ticket(
2063 &self,
2064 generation: OptiForkGeneration,
2065 boundary: VerifyBoundaryTicket,
2066 ckpt: VerifyCkpt,
2067 verify_tokens: [u32; 2],
2068 draft_prob: f32,
2069 eager_seed: Option<CudaSlice<f32>>,
2070 q_proxy: f32,
2071 scratch_len: usize,
2072 ) -> OptiControllerTicket {
2073 OptiControllerTicket {
2074 generation,
2075 boundary: Some(boundary),
2076 ckpt: Some(ckpt),
2077 verify_tokens,
2078 draft_prob,
2079 eager_seed,
2080 q_proxy,
2081 scratch_len,
2082 issued_at: std::time::Instant::now(),
2083 drain: self.stage0_stream.clone(),
2084 settled: false,
2085 }
2086 }
2087
2088 fn reserve_successor(&mut self) -> Result<OptiForkGeneration, Box<dyn std::error::Error>> {
2089 self.generations.reserve()
2090 }
2091
2092 fn successor_snapshot_mut(&mut self) -> &mut crate::cache::CacheSnapshot {
2093 &mut self.alternate_snapshot
2094 }
2095
2096 fn promote_successor_snapshot(
2097 &mut self,
2098 current_snapshot: &mut crate::cache::CacheSnapshot,
2099 generation: OptiForkGeneration,
2100 ) {
2101 std::mem::swap(current_snapshot, &mut self.alternate_snapshot);
2102 self.active_snapshot_slot = generation.slot;
2103 }
2104
2105 fn queue_actual_reconcile(
2106 &mut self,
2107 e: &Engine,
2108 snapshot: &crate::cache::CacheSnapshot,
2109 acc: &CudaSlice<u32>,
2110 optimistic_pending: u32,
2111 base: usize,
2112 ) -> Result<(), Box<dyn std::error::Error>> {
2113 let saved: Vec<i32> = (0..self.split)
2114 .map(|il| snapshot.kv_len[il].map(|v| v as i32).unwrap_or(0))
2115 .collect();
2116 // Serving keeps the caller/accept walk on the head (stage-1) device. Record the accept
2117 // decision point there and append a wait to stage 0 after its optimistic successor/TX;
2118 // the validity/reconcile kernels must never peer-read acc before it is written. The
2119 // increment-1 harness uses primary stage 0, where stream order already provides this.
2120 if self.rt.engine(0, e).ctx().ordinal() != e.ctx().ordinal() {
2121 self.rt.fence_stages_behind(&e.stream())?;
2122 }
2123 let _stage = self.rt.enter(0);
2124 let e0 = self.rt.engine(0, e);
2125 e0.htod_i32_into(&mut self.saved_lens, &saved)?;
2126 e0.spec_fork_valid(acc, optimistic_pending, &mut self.valid)?;
2127 e0.spec_fork_reconcile_kv(
2128 &self.len_ptrs,
2129 &self.saved_lens,
2130 acc,
2131 &self.valid,
2132 base,
2133 self.split,
2134 )
2135 }
2136
2137 fn finish_actual_reconcile(
2138 &mut self,
2139 e: &Engine,
2140 cache: &mut Cache,
2141 snapshot: &crate::cache::CacheSnapshot,
2142 n_acc: usize,
2143 base: usize,
2144 hit: bool,
2145 ) -> Result<(), Box<dyn std::error::Error>> {
2146 if hit {
2147 return Ok(());
2148 }
2149 let len_delta = base + n_acc;
2150 for il in 0..self.split {
2151 if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
2152 kv.len = saved + len_delta;
2153 }
2154 }
2155 {
2156 let _stage = self.rt.enter(1);
2157 let e1 = self.rt.engine(1, e);
2158 for il in self.split..self.fence[2] {
2159 if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
2160 kv.len = saved + len_delta;
2161 e1.set_i32_one(&mut kv.len_d, kv.len as i32)?;
2162 }
2163 }
2164 }
2165 self.rt.publish_to(0, &e.stream())?;
2166 Ok(())
2167 }
2168
2169 fn cancel_controller_ticket(
2170 &mut self,
2171 e: &Engine,
2172 cache: &mut Cache,
2173 scratch: &mut MtpScratch,
2174 snapshot: &crate::cache::CacheSnapshot,
2175 ticket: &mut OptiControllerTicket,
2176 ) -> Result<(), Box<dyn std::error::Error>> {
2177 {
2178 let _stage = self.rt.enter(0);
2179 let e0 = self.rt.engine(0, e);
2180 for il in 0..self.split {
2181 if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
2182 kv.len = saved;
2183 e0.set_i32_one(&mut kv.len_d, saved as i32)?;
2184 }
2185 }
2186 }
2187 scratch.set_len(e, snapshot.pos)?;
2188 ticket.settle();
2189 self.generations.retire(ticket.generation)?;
2190 OPTI_FORK_ABORT_DRAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2191 OPTI_WASTED_DRAFT_TOKENS.fetch_add(2, std::sync::atomic::Ordering::Relaxed);
2192 eprintln!(
2193 "[opti-controller] tail-drain generation={} slot={}",
2194 ticket.generation.id, ticket.generation.slot,
2195 );
2196 Ok(())
2197 }
2198
2199 #[allow(clippy::too_many_arguments)]
2200 fn reconcile(
2201 &mut self,
2202 e: &Engine,
2203 cache: &mut Cache,
2204 scratch: &mut MtpScratch,
2205 snapshot: &crate::cache::CacheSnapshot,
2206 h_seed: &mut CudaSlice<f32>,
2207 fill_prev: &mut CudaSlice<f32>,
2208 generation: OptiForkGeneration,
2209 action: OptiForkAction,
2210 optimistic_pending: u32,
2211 ) -> Result<(), Box<dyn std::error::Error>> {
2212 debug_assert!(action != OptiForkAction::Abort);
2213 let miss_started = std::time::Instant::now();
2214 let keep = action == OptiForkAction::Hit;
2215 let saved: Vec<i32> = (0..self.split)
2216 .map(|il| snapshot.kv_len[il].map(|v| v as i32).unwrap_or(0))
2217 .collect();
2218 let seed = &self.seeds[generation.slot];
2219 {
2220 let _stage = self.rt.enter(0);
2221 let e0 = self.rt.engine(0, e);
2222 e0.htod_i32_into(&mut self.saved_lens, &saved)?;
2223 let forced = if keep {
2224 [1u32, optimistic_pending]
2225 } else {
2226 [0u32, optimistic_pending]
2227 };
2228 e0.htod_u32_into(&mut self.forced_acc, &forced)?;
2229 e0.spec_fork_valid(&self.forced_acc, optimistic_pending, &mut self.valid)?;
2230 e0.spec_fork_reconcile_kv(
2231 &self.len_ptrs,
2232 &self.saved_lens,
2233 &self.forced_acc,
2234 &self.valid,
2235 0,
2236 self.split,
2237 )?;
2238 for il in 0..self.split {
2239 if let Some(recur) = cache.recur[il].as_mut() {
2240 let conv = snapshot.conv[il]
2241 .as_ref()
2242 .ok_or("optipipe stage0 snapshot missing conv state")?;
2243 let ssm = snapshot.ssm[il]
2244 .as_ref()
2245 .ok_or("optipipe stage0 snapshot missing ssm state")?;
2246 e0.spec_fork_restore_f32(conv, &mut recur.conv_state, &self.valid)?;
2247 e0.spec_fork_restore_f32(ssm, &mut recur.ssm_state, &self.valid)?;
2248 }
2249 }
2250 e0.spec_fork_restore_f32(&seed.h_seed, h_seed, &self.valid)?;
2251 e0.spec_fork_restore_f32(&seed.fill_prev, fill_prev, &self.valid)?;
2252 }
2253
2254 if keep {
2255 OPTI_FORK_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2256 return Ok(());
2257 }
2258
2259 for il in 0..self.split {
2260 if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
2261 kv.len = saved;
2262 }
2263 }
2264 scratch.set_len(e, seed.scratch_len)?;
2265 // Targeted E_restart: publish only stage 0's reconcile to the caller, then bound the
2266 // forced diagnostic so the retained number is the actual miss cost, not enqueue time.
2267 let caller = e.stream();
2268 self.rt.publish_to(0, &caller)?;
2269 caller.synchronize()?;
2270 let miss_ms = miss_started.elapsed().as_secs_f64() * 1e3;
2271 eprintln!(
2272 "[opti-fork-reconcile] generation={} slot={} miss_ms={miss_ms:.3}",
2273 generation.id, generation.slot,
2274 );
2275 OPTI_FORK_MISSES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2276 Ok(())
2277 }
2278
2279 fn retire(&mut self, generation: OptiForkGeneration) -> Result<(), Box<dyn std::error::Error>> {
2280 self.generations.retire(generation)
2281 }
2282}
2283
2284impl HybridModel {
2285 fn opti_graph_draft_step(
2286 &self,
2287 e: &Engine,
2288 mtp: &MtpHead,
2289 dctx: &mut DraftGraphCtx,
2290 scratch: &mut MtpScratch,
2291 d_vocab: usize,
2292 ) -> Result<(u32, f32), Box<dyn std::error::Error>> {
2293 dctx.graph
2294 .as_ref()
2295 .ok_or("optipipe controller requires the greedy draft graph")?
2296 .launch()?;
2297 scratch.kv.len += 1;
2298 let idx = e.dtoh_u32_one(&dctx.g_tok)?;
2299 if (idx as usize) >= d_vocab {
2300 return Err(
2301 format!("optipipe draft argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab}").into(),
2302 );
2303 }
2304 let probability = e.dtoh(&dctx.g_p)?[0];
2305 if !probability.is_finite() || !(0.0..=1.0).contains(&probability) {
2306 return Err(format!("optipipe draft probability is invalid: {probability}").into());
2307 }
2308 let token = match &mtp.d2t {
2309 Some(map) => map[idx as usize],
2310 None => idx,
2311 };
2312 if token != idx {
2313 e.set_u32_one(&mut dctx.g_tok, token)?;
2314 }
2315 Ok((token, probability))
2316 }
2317
2318 #[allow(clippy::too_many_arguments)]
2319 fn opti_controller_draft_step(
2320 &self,
2321 e: &Engine,
2322 mtp: &MtpHead,
2323 dctx: &mut DraftGraphCtx,
2324 scratch: &mut MtpScratch,
2325 d_vocab: usize,
2326 eager_state: &mut Option<(u32, CudaSlice<f32>)>,
2327 eager_pos: usize,
2328 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
2329 ) -> Result<(u32, f32), Box<dyn std::error::Error>> {
2330 if dctx.graph.is_some() {
2331 return self.opti_graph_draft_step(e, mtp, dctx, scratch, d_vocab);
2332 }
2333 let (input_token, input_seed) = eager_state
2334 .take()
2335 .ok_or("optipipe eager continuation seed is unavailable")?;
2336 let (logits, next_seed) = self.mtp_head_forward_dev(
2337 e,
2338 mtp,
2339 input_token,
2340 &input_seed,
2341 scratch,
2342 eager_pos,
2343 embd_dev,
2344 None,
2345 )?;
2346 let token_d = e.argmax_token_device(&logits, d_vocab)?;
2347 let idx = e.dtoh_u32_one(&token_d)?;
2348 if (idx as usize) >= d_vocab {
2349 return Err(format!(
2350 "optipipe eager draft argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab}"
2351 )
2352 .into());
2353 }
2354 let probability_d = e.prob_of_token_device(&logits, &token_d, d_vocab)?;
2355 let probability = e.dtoh(&probability_d)?[0];
2356 if !probability.is_finite() || !(0.0..=1.0).contains(&probability) {
2357 return Err(
2358 format!("optipipe eager draft probability is invalid: {probability}").into(),
2359 );
2360 }
2361 let token = match &mtp.d2t {
2362 Some(map) => map[idx as usize],
2363 None => idx,
2364 };
2365 *eager_state = Some((token, next_seed));
2366 Ok((token, probability))
2367 }
2368
2369 /// NextN head forward for ONE draft token (§A ops 1-13, T=1).
2370 /// Inputs: `e_tok` = the token to predict FROM (last committed / previous draft); `h_seed` =
2371 /// the trunk's pre-output_norm hidden of that token (§A op 2 input). `mtp_pos` = absolute
2372 /// position of the token being predicted from. Returns (draft_logits[n_vocab] host, h_nextn dev).
2373 /// `h_nextn` (§A op 10) becomes `h_seed` for the next autoregressive draft step.
2374 /// Device-resident: returns draft logits ON DEVICE (no [n_vocab] dtoh). The greedy draft
2375 /// loop only needs argmax — paired with `argmax_token_device` this cuts the ~600KB logits
2376 /// transfer + host argmax per draft token from the K-token draft chain.
2377 #[allow(clippy::too_many_arguments)]
2378 fn mtp_head_forward_dev(
2379 &self,
2380 e: &Engine,
2381 mtp: &MtpHead,
2382 e_tok: u32,
2383 h_seed: &CudaSlice<f32>,
2384 scratch: &mut MtpScratch,
2385 mtp_pos: usize,
2386 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
2387 // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): (packed draft-vocab allowed set, words).
2388 // Applied to the head logits BEFORE they are returned, so every consumer (argmax,
2389 // gumbel draw, p-min prob) sees the grammar-legal row. None = unmasked (pre-lane).
2390 mask: Option<(&CudaSlice<u32>, usize)>,
2391 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
2392 let cfg = &self.cfg;
2393 let n_embd = cfg.n_embd as usize;
2394 // Distilled-student geometry: the block runs at the INNER width `di` (eh_proj out /
2395 // attn / ffn); the n_embd interface (embed, norms in, carrier out, head in) is unchanged.
2396 let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
2397 let eps = cfg.rms_eps;
2398 let pos_d = e.htod_i32(&[mtp_pos as i32])?;
2399
2400 // op A: a resident table transfers one 4B token id. The exact host-row capacity path
2401 // expands this one row on CPU and transfers n_embd f32 values instead.
2402 let e_emb = match embd_dev {
2403 Some((g, qt, rb)) => e.embed_gather_device_t(g, &[e_tok], n_embd, qt, rb)?,
2404 None => e.htod(&self.embd.gather(n_embd, &[e_tok]))?,
2405 };
2406
2407 // op 1/2: e_norm = RMSNorm(e, enorm); h_norm = RMSNorm(h_seed, hnorm)
2408 let mut e_norm = e.zeros(n_embd)?;
2409 e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, 1, eps)?;
2410 let mut h_norm = e.zeros(n_embd)?;
2411 e.rms_norm(h_seed, mtp.hnorm.float_data(), &mut h_norm, n_embd, 1, eps)?;
2412
2413 // op 3: concat = [e_norm ; h_norm] -> [2*n_embd], e_norm in [0,n_embd), h_norm in [n_embd,2n_embd)
2414 let mut concat = e.zeros(2 * n_embd)?;
2415 e.copy_into(&mut concat, 0, &e_norm, n_embd)?;
2416 e.copy_into(&mut concat, n_embd, &h_norm, n_embd)?;
2417
2418 // op 4: inpSA = eh_proj @ concat (eh_proj [2*n_embd, n_embd]) -> [n_embd]
2419 let inp_sa = e.matmul(&mtp.eh_proj, &concat, 1)?;
2420
2421 // op 5: a_norm = RMSNorm(inpSA, attn_norm)
2422 let mut a_norm = e.zeros(di)?;
2423 e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, 1, eps)?;
2424
2425 // op 6: attention on the scratch KV. SAME dc launcher as the graph path (bucket_max =
2426 // scratch.cap, length from the device len_d) so eager drafts match graph drafts
2427 // bit-for-bit at any t_kv (the parity gate). Host len mirrored here (the dc append
2428 // advances only the device counter).
2429 let attn_out = match (&mtp.mixer, mtp.step35.as_ref()) {
2430 // step35 MTP block: PER-LAYER geometry + a separate head-wise gate + an SWA window,
2431 // none of which the dc launcher can express (see `mtp_step35_attn`). Host-len arm.
2432 // Advances BOTH the host len and the device counter itself (unlike the dc arm,
2433 // whose host-side mirror the caller does).
2434 (Mixer::Full(fa), Some(g)) => {
2435 self.mtp_step35_attn(e, fa, g, &a_norm, &pos_d, scratch)?
2436 }
2437 (Mixer::Full(fa), None) => {
2438 let out =
2439 self.mtp_full_attn_dc(e, fa, &a_norm, &pos_d, scratch, mtp.geom.as_ref())?;
2440 scratch.kv.len += 1;
2441 out
2442 }
2443 (Mixer::Linear(_), _) => {
2444 panic!("MTP block is full-attn in qwen35; linear MTP not supported")
2445 }
2446 (Mixer::Mla(_), _) => crate::hybrid::mla_forward_unimplemented(),
2447 };
2448
2449 // op 7: x1 = inpSA + attn_out
2450 let mut x1 = e.zeros(di)?;
2451 e.add(&inp_sa, &attn_out, &mut x1, di)?;
2452
2453 // op 8: z = RMSNorm(x1, post_attn_norm) (pre-FFN norm)
2454 let mut z = e.zeros(di)?;
2455 e.rms_norm(&x1, mtp.post_attn_norm.float_data(), &mut z, di, 1, eps)?;
2456
2457 // op 9: FFN (Dense or MoE) — same as the trunk decode FFN
2458 let ffn_out = match &mtp.ffn {
2459 crate::hybrid::Ffn::Dense {
2460 ffn_gate,
2461 ffn_up,
2462 ffn_down,
2463 } => {
2464 let n_ff = ffn_gate.out_features();
2465 let (gate, up) = if e.uses_q8_1_fast(ffn_gate) && e.uses_q8_1_fast(ffn_up) {
2466 let (zq, zd) = e.quantize_q8_1(&z, 1, di)?;
2467 (
2468 e.matmul_pre(ffn_gate, &zq, &zd, &z, 1)?,
2469 e.matmul_pre(ffn_up, &zq, &zd, &z, 1)?,
2470 )
2471 } else {
2472 (e.matmul(ffn_gate, &z, 1)?, e.matmul(ffn_up, &z, 1)?)
2473 };
2474 let mut act = e.zeros(n_ff)?;
2475 // step35: a DENSE FFN reads the per-layer SHEXP clamp (upstream's one `build_ffn`
2476 // serves the dense MLP and the shared expert off `swiglu_clamp_shexp` —
2477 // llama-graph.cpp:1751), resolved for the MTP block's OWN index. Every other arch
2478 // passes None, which is `ffn_act`'s dispatch verbatim.
2479 Self::ffn_act_lim(
2480 e,
2481 &self.cfg,
2482 &gate,
2483 &up,
2484 1.0,
2485 1.0,
2486 mtp.step35.as_ref().and_then(|s| s.clamp_shexp),
2487 &mut act,
2488 n_ff,
2489 )?;
2490 e.matmul(ffn_down, &act, 1)?
2491 }
2492 // MTP head is a distinct block — key its experts under a separate layer index (u16::MAX)
2493 // so they never alias trunk layer 0's cache keys.
2494 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, 1, u16::MAX)?,
2495 };
2496
2497 // op 10: h_nextn = x1 + ffn_out (at di)
2498 let mut h_inner = e.zeros(di)?;
2499 e.add(&x1, &ffn_out, &mut h_inner, di)?;
2500
2501 // op 10.5 (student): up-project the inner hidden back to n_embd — training semantics:
2502 // the chain carrier AND the head input are out_up(h_inner) (pre-final-norm).
2503 let h_nextn = match mtp.geom.as_ref() {
2504 Some(g) => e.matmul(&g.out_up, &h_inner, 1)?,
2505 None => h_inner,
2506 };
2507
2508 // op 11: final = RMSNorm(h_nextn, shared_head_norm OR output_norm)
2509 let final_norm = mtp.shared_head_norm.as_ref().unwrap_or(&self.output_norm);
2510 let mut final_h = e.zeros(n_embd)?;
2511 e.rms_norm(
2512 &h_nextn,
2513 final_norm.float_data(),
2514 &mut final_h,
2515 n_embd,
2516 1,
2517 eps,
2518 )?;
2519
2520 // op 12: draft_logits = (shared_head_head OR output) @ final — stays ON DEVICE.
2521 let head = mtp.shared_head_head.as_ref().unwrap_or(&self.output);
2522 let mut logits = e.matmul(head, &final_h, 1)?;
2523 // op 12b (lane/draft-mask): grammar mask over the DRAFT vocab, applied here so the
2524 // caller's argmax / gumbel draw / p-min prob all read the grammar-legal row.
2525 if let Some((mask_d, mw)) = mask {
2526 let d_vocab = head.out_features();
2527 e.mask_logits_col(&mut logits, mask_d, 0, d_vocab, mw)?;
2528 }
2529 // Chain recurrence hand-over: pre-norm h_nextn (default) or post-norm final_h
2530 // (MEMRA_SPEC_HPOST — llama.cpp #24025's t_h_nextn is taken AFTER the head norm).
2531 Ok((logits, if spec_hpost() { final_h } else { h_nextn }))
2532 }
2533
2534 /// step35 MTP-block attention, T=1, on the scratch KV — the EAGER-ONLY twin of
2535 /// `mtp_full_attn_dc`. Three things force a separate arm rather than a geometry parameter on
2536 /// the dc path, and all three are properties of this arch's MTP block:
2537 ///
2538 /// 1. **The SWA window.** Block 45 is an SWA-type block (`sliding_window_pattern[45]=true`,
2539 /// window 512). Windowed decode in memra is a token-aligned VIEW OFFSET into the quantized
2540 /// cache (the gemma4 R6 / `step35_decode_attn` pattern: keys carry absolute rope and the
2541 /// mask is purely positional, so one query at `len-1` attending the last `win` rows IS the
2542 /// windowed result). `fa_decode_dc` takes the key count from a DEVICE counter and always
2543 /// starts at row 0 — it cannot express a nonzero offset, so a windowed dc arm would need a
2544 /// new kernel. That is deliberately not built here: see the CUDA-graph note below.
2545 /// 2. **Per-layer head count.** 96 q heads over 8 KV (GQA 12) at this block, vs the trunk's 64
2546 /// on its full-attn layers. The trunk cfg's `n_head` scalar is the MAX over layers, and the
2547 /// trunk ARTIFACT's per-layer arrays stop at index 44 — so the count must come from the
2548 /// resolved `Step35MtpGeom`, never from `cfg`.
2549 /// 3. **The separate head-wise gate.** `blk.45.attn_gate.weight [n_embd, 96]` produces one
2550 /// sigmoid scalar per head (broadcast over head_dim) — `attn_head_gate`, not the qwen35
2551 /// fused-into-wq `q_gate_split` form the dc arm handles.
2552 ///
2553 /// WHY EAGER-ONLY IS NOT A GAP TODAY: `graph_draft` requires `trunk_dense`, and this SKU's
2554 /// trunk is a 288-expert MoE, so the graph draft is already off for every step35 model — the
2555 /// eager chain IS the served path. `mtp_head_forward_cap` refuses step35 explicitly rather
2556 /// than silently capturing a window-less (wrong past `win` draft rows) graph.
2557 ///
2558 /// Unlike the dc arm this advances BOTH the host `kv.len` and the device counter, so the
2559 /// caller must not mirror.
2560 fn mtp_step35_attn(
2561 &self,
2562 e: &Engine,
2563 fa: &FullAttnLayer,
2564 g: &crate::hybrid::Step35MtpGeom,
2565 h: &CudaSlice<f32>,
2566 pos_d: &CudaSlice<i32>,
2567 scratch: &mut MtpScratch,
2568 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2569 let (nh, nkv, hd) = (g.n_head, g.n_head_kv, self.cfg.head_dim_k as usize);
2570 let eps = self.cfg.rms_eps;
2571 let scale = 1.0 / (hd as f32).sqrt(); // step35.cpp:255 kq_scale
2572 let n_embd = self.cfg.n_embd as usize;
2573 let gw = fa
2574 .attn_gate
2575 .as_ref()
2576 .ok_or("step35 MTP block is missing attn_gate.weight (head-wise attention gate)")?;
2577
2578 let (q0, k0, v0, gt) = if e.uses_q8_1_fast(&fa.wq)
2579 && e.uses_q8_1_fast(&fa.wk)
2580 && e.uses_q8_1_fast(&fa.wv)
2581 && e.uses_q8_1_fast(gw)
2582 {
2583 let (hq, hdq) = e.quantize_q8_1(h, 1, n_embd)?;
2584 let (a, b, c) = match e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, &hq, &hdq)? {
2585 Some(t3) => t3,
2586 None => (
2587 e.matmul_pre(&fa.wq, &hq, &hdq, h, 1)?,
2588 e.matmul_pre(&fa.wk, &hq, &hdq, h, 1)?,
2589 e.matmul_pre(&fa.wv, &hq, &hdq, h, 1)?,
2590 ),
2591 };
2592 (a, b, c, e.matmul_pre(gw, &hq, &hdq, h, 1)?)
2593 } else {
2594 (
2595 e.matmul(&fa.wq, h, 1)?,
2596 e.matmul(&fa.wk, h, 1)?,
2597 e.matmul(&fa.wv, h, 1)?,
2598 e.matmul(gw, h, 1)?,
2599 )
2600 };
2601
2602 let mut q = e.uninit(nh * hd)?;
2603 e.rms_norm(&q0, fa.q_norm.float_data(), &mut q, hd, nh, eps)?;
2604 let mut k = e.uninit(nkv * hd)?;
2605 e.rms_norm(&k0, fa.k_norm.float_data(), &mut k, hd, nkv, eps)?;
2606 // `rope_freqs.weight` (llama3 factors) applies to the FULL-attn layers ONLY; SWA passes
2607 // null (llama-hparams / step35.cpp). Block 45 is SWA, so `ff` is None there — but read
2608 // the resolved flag, not the constant, so an all-full sibling stays correct.
2609 let ff = if g.swa {
2610 None
2611 } else {
2612 self.step35_aux.as_ref().and_then(|a| a.rope_freqs(e))
2613 };
2614 #[cfg(debug_assertions)]
2615 if let Some(ff) = ff {
2616 crate::debug_assert_tensor_stream_device(ff, &e.stream(), "mtp_step35_attn.rope_freqs");
2617 }
2618 e.rope_neox2(
2619 &mut q,
2620 &mut k,
2621 pos_d,
2622 hd,
2623 g.n_rot,
2624 nh,
2625 nkv,
2626 1,
2627 g.rope_base,
2628 1.0,
2629 ff,
2630 )?;
2631
2632 // Append at the HOST slot, then re-stamp the device counter: the eager chain has the
2633 // length on the host anyway, and the windowed view below needs it there to compute the
2634 // offset. The device counter is kept in lockstep so `mtp_kv_fill`'s `set_i32_one` and any
2635 // dc-family consumer of this scratch still agree.
2636 let kv = &mut scratch.kv;
2637 assert!(
2638 kv.len < scratch.cap,
2639 "step35 MTP scratch overflow ({} >= {})",
2640 kv.len,
2641 scratch.cap
2642 );
2643 let next_len = kv.len + 1;
2644 let (off, t_kv) = if g.swa && next_len > g.window {
2645 (next_len - g.window, g.window)
2646 } else {
2647 (0, next_len)
2648 };
2649 let write_row = e.prepare_kv_append(kv, off & !31usize, 1)?;
2650 e.append_kv_quantized(
2651 &k,
2652 &v0,
2653 &mut kv.k,
2654 &mut kv.v,
2655 write_row,
2656 kv.kv_dim_k,
2657 kv.kv_dim_v,
2658 kv.k_tok_bytes,
2659 kv.v_tok_bytes,
2660 false,
2661 )?;
2662 kv.len = next_len;
2663 e.set_i32_one(&mut kv.len_d, kv.len as i32)?;
2664 // SWA view offset (see note 1). The draft chain is short (k+2 rows), but the scratch is
2665 // PERSISTENT across rounds — `mtp_kv_fill` leaves one row per committed token behind, so
2666 // `kv.len` tracks absolute position and crosses 512 in any real generation. The window is
2667 // therefore live, not theoretical.
2668 let physical = kv.physical_rows(off, off + t_kv)?;
2669 let k_view = e.view_u8_range(
2670 &kv.k,
2671 physical.start * kv.k_tok_bytes,
2672 physical.end * kv.k_tok_bytes,
2673 );
2674 let v_view = e.view_u8_range(
2675 &kv.v,
2676 physical.start * kv.v_tok_bytes,
2677 physical.end * kv.v_tok_bytes,
2678 );
2679 let mut attn = e.uninit(nh * hd)?;
2680 e.fa_decode_kvmod(
2681 &q,
2682 &k_view,
2683 &v_view,
2684 &mut attn,
2685 hd,
2686 nh,
2687 nkv,
2688 t_kv,
2689 scale,
2690 kv.k_tok_bytes,
2691 kv.v_tok_bytes,
2692 false,
2693 )?;
2694
2695 let mut ag = e.uninit(nh * hd)?;
2696 e.attn_head_gate(&attn, >, &mut ag, None, hd, nh, 1)?;
2697 Ok(e.matmul(&fa.wo, &ag, 1)?)
2698 }
2699
2700 /// MTP-block full attention, T=1, on the scratch KV (BOTH draft paths — eager and graph):
2701 /// the scratch write slot and the attention bound come from `scratch.kv.len_d` (device i32[1])
2702 /// so the launch args are FIXED across draft steps — ONE captured graph serves the whole
2703 /// chain, and replays keep seeing KV growth through the device counter (no recapture).
2704 /// Geometry contract: n_splits is sized from `scratch.cap` (the persistent capacity); splits
2705 /// whose key range lies beyond the device t_kv exit empty and the shared combine skips them
2706 /// (fa_decode_dc bit-correct-for-any-t_kv<=bucket_max contract). The eager path uses the SAME
2707 /// launcher with the SAME bucket_max -> identical dispatch -> bit-identical draft tokens (the
2708 /// graph-vs-eager parity gate). Host len is NOT advanced here (graph contract); callers mirror.
2709 fn mtp_full_attn_dc(
2710 &self,
2711 e: &Engine,
2712 fa: &FullAttnLayer,
2713 h: &CudaSlice<f32>,
2714 pos_d: &CudaSlice<i32>,
2715 scratch: &mut MtpScratch,
2716 geom: Option<&crate::hybrid::DraftGeom>,
2717 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2718 let cfg = &self.cfg;
2719 let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
2720 let geometry = cfg.full_attention_geometry_at(mtp_il);
2721 let n_head = geom.map(|g| g.n_head).unwrap_or(geometry.n_head as usize);
2722 let n_head_kv = geom
2723 .map(|g| g.n_head_kv)
2724 .unwrap_or(geometry.n_head_kv as usize);
2725 let head_dim = geometry.head_dim_k as usize;
2726 let eps = cfg.rms_eps;
2727 let scale = geometry.attention_scale();
2728 let n_embd = geom.map(|g| g.d_inner).unwrap_or(cfg.n_embd as usize);
2729 let bucket_max = scratch.cap; // < 96 guaranteed by the graph_draft eligibility gate
2730
2731 let (qf, mut k, v) =
2732 if e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk) && e.uses_q8_1_fast(&fa.wv) {
2733 let (hq, hd) = e.quantize_q8_1(h, 1, n_embd)?;
2734 (
2735 e.matmul_pre(&fa.wq, &hq, &hd, h, 1)?,
2736 e.matmul_pre(&fa.wk, &hq, &hd, h, 1)?,
2737 e.matmul_pre(&fa.wv, &hq, &hd, h, 1)?,
2738 )
2739 } else {
2740 (
2741 e.matmul(&fa.wq, h, 1)?,
2742 e.matmul(&fa.wk, h, 1)?,
2743 e.matmul(&fa.wv, h, 1)?,
2744 )
2745 };
2746 // M3/Hy3 have no attention output gate — wq out is exactly q; skip the split.
2747 let gated = geometry.attention_gate == memra_gguf::config::AttentionGateKind::FusedQ;
2748 let (mut q, gate) = if gated {
2749 let mut q = e.zeros(n_head * head_dim)?;
2750 let mut gate = e.zeros(n_head * head_dim)?;
2751 e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, 1)?;
2752 (q, Some(gate))
2753 } else {
2754 (qf, None)
2755 };
2756
2757 let mut qn = e.zeros(n_head * head_dim)?;
2758 e.rms_norm(&q, fa.q_norm.float_data(), &mut qn, head_dim, n_head, eps)?;
2759 q = qn;
2760 let mut kn = e.zeros(n_head_kv * head_dim)?;
2761 e.rms_norm(
2762 &k,
2763 fa.k_norm.float_data(),
2764 &mut kn,
2765 head_dim,
2766 n_head_kv,
2767 eps,
2768 )?;
2769 k = kn;
2770 let rope_dims = geometry.n_rot as usize;
2771 e.rope_neox(
2772 &mut q,
2773 pos_d,
2774 head_dim,
2775 rope_dims,
2776 n_head,
2777 1,
2778 geometry.rope_base,
2779 1.0,
2780 )?;
2781 e.rope_neox(
2782 &mut k,
2783 pos_d,
2784 head_dim,
2785 rope_dims,
2786 n_head_kv,
2787 1,
2788 geometry.rope_base,
2789 1.0,
2790 )?;
2791
2792 let kv = &mut scratch.kv;
2793 // append at the DEVICE slot (kv.len_d == old len), then advance the counter in-graph.
2794 e.append_kv_quantized_dc(
2795 &k,
2796 &v,
2797 &mut kv.k,
2798 &mut kv.v,
2799 &kv.len_d,
2800 kv.kv_dim_k,
2801 kv.kv_dim_v,
2802 kv.k_tok_bytes,
2803 kv.v_tok_bytes,
2804 false,
2805 )?;
2806 e.inc_seqlen(&mut kv.len_d)?;
2807 // full-buffer views (any in-round t_kv stays in range on replay); the kernel bounds the
2808 // key range from the device counter.
2809 let k_view = e.view_u8(&kv.k, kv.k.len());
2810 let v_view = e.view_u8(&kv.v, kv.v.len());
2811 let (ktb, vtb) = (kv.k_tok_bytes, kv.v_tok_bytes);
2812 let mut attn = e.zeros(n_head * head_dim)?;
2813 e.fa_decode_dc(
2814 &q, &k_view, &v_view, &mut attn, head_dim, n_head, n_head_kv, &kv.len_d, bucket_max,
2815 scale, ktb, vtb, false,
2816 )?;
2817
2818 let attn_g = match &gate {
2819 Some(gate) => {
2820 let mut gsig = e.zeros(n_head * head_dim)?;
2821 e.sigmoid(gate, &mut gsig, n_head * head_dim)?;
2822 let mut ag = e.zeros(n_head * head_dim)?;
2823 e.mul(&attn, &gsig, &mut ag, n_head * head_dim)?;
2824 ag
2825 }
2826 None => attn,
2827 };
2828 Ok(e.matmul(&fa.wo, &attn_g, 1)?)
2829 }
2830
2831 /// PERSISTENT-DRAFT-KV fill (the reference engine's "mtp_update" analogue): compute the MTP
2832 /// block's K/V for `tokens` (committed tokens at positions pos0..pos0+T) from their EXACT
2833 /// trunk hiddens `h` ([T, n_embd] token-major, pre-output_norm) and append at slots pos0.. of
2834 /// the scratch KV. K/V-ONLY — ops A/1-5 plus the K-side of op 6 (wk/wv + k_norm + rope +
2835 /// quantized append); no wq/attention/FFN/lm_head, so per-token cost ~= eh_proj + wk/wv (a
2836 /// small fraction of one trunk layer), T-batched. Rope follows the chain convention
2837 /// rope(token@p) = p+1. Runs at round boundaries OUTSIDE the captured graph in BOTH draft
2838 /// modes -> draft parity by construction. Caller must have scratch.kv.len == pos0.
2839 #[allow(clippy::too_many_arguments)]
2840 fn mtp_kv_fill(
2841 &self,
2842 e: &Engine,
2843 mtp: &MtpHead,
2844 tokens: &[u32],
2845 h: &CudaSlice<f32>,
2846 pos0: usize,
2847 scratch: &mut MtpScratch,
2848 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
2849 ) -> Result<(), Box<dyn std::error::Error>> {
2850 let cfg = &self.cfg;
2851 let n_embd = cfg.n_embd as usize;
2852 let eps = cfg.rms_eps;
2853 let t = tokens.len();
2854 assert_eq!(scratch.kv.len, pos0, "mtp_kv_fill: append slot mismatch");
2855 assert!(pos0 + t <= scratch.cap, "mtp_kv_fill: scratch overflow");
2856 let Mixer::Full(fa) = &mtp.mixer else {
2857 panic!("MTP block is full-attn in qwen35; linear MTP not supported")
2858 };
2859 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i + 1) as i32).collect();
2860 let pos_d = e.htod_i32(&pos_vec)?;
2861
2862 // ops A/1/2: embed + the two input norms, T-wide.
2863 let e_emb = match embd_dev {
2864 Some((g, qt, rb)) => e.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
2865 None => e.htod(&self.embd.gather(n_embd, tokens))?,
2866 };
2867 let mut e_norm = e.zeros(t * n_embd)?;
2868 e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, t, eps)?;
2869 let mut h_norm = e.zeros(t * n_embd)?;
2870 e.rms_norm(h, mtp.hnorm.float_data(), &mut h_norm, n_embd, t, eps)?;
2871
2872 // op 3: per-row [e_norm ; h_norm] concat, token-major [T, 2*n_embd].
2873 let mut concat = e.zeros(t * 2 * n_embd)?;
2874 for i in 0..t {
2875 e.copy_view_into(
2876 &mut concat,
2877 i * 2 * n_embd,
2878 &e_norm.slice(i * n_embd..(i + 1) * n_embd),
2879 n_embd,
2880 )?;
2881 e.copy_view_into(
2882 &mut concat,
2883 i * 2 * n_embd + n_embd,
2884 &h_norm.slice(i * n_embd..(i + 1) * n_embd),
2885 n_embd,
2886 )?;
2887 }
2888
2889 // ops 4/5: eh_proj + attn_norm, T-wide (at the student inner width when geom is set).
2890 let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
2891 let inp_sa = e.matmul(&mtp.eh_proj, &concat, t)?;
2892 let mut a_norm = e.zeros(t * di)?;
2893 e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, t, eps)?;
2894
2895 // op 6 (K/V half): wk/wv + k_norm + rope + per-row quantized append. No wq/attention —
2896 // the fill only has to leave correct K/V rows behind for later chains to attend over.
2897 let n_head_kv = mtp
2898 .geom
2899 .as_ref()
2900 .map(|g| g.n_head_kv)
2901 .or(mtp.step35.as_ref().map(|s| s.n_head_kv))
2902 .unwrap_or_else(|| {
2903 let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
2904 cfg.full_attention_geometry_at(mtp_il).n_head_kv as usize
2905 });
2906 let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
2907 let geometry = cfg.full_attention_geometry_at(mtp_il);
2908 let head_dim = geometry.head_dim_k as usize;
2909 let mut k = e.matmul(&fa.wk, &a_norm, t)?;
2910 let v = e.matmul(&fa.wv, &a_norm, t)?;
2911 let mut kn = e.zeros(t * n_head_kv * head_dim)?;
2912 e.rms_norm(
2913 &k,
2914 fa.k_norm.float_data(),
2915 &mut kn,
2916 head_dim,
2917 n_head_kv * t,
2918 eps,
2919 )?;
2920 k = kn;
2921 // step35: rotary width AND base are per-layer, and the MTP block's values come from the
2922 // resolved `Step35MtpGeom` — NOT from `cfg.rope_dim_count`/`cfg.rope_freq_base`, which
2923 // carry the arch defaults (128 / 5e6, i.e. the FULL-attn layers' base). Getting this wrong
2924 // writes K rows the attention arm then re-derives at a different theta: correct-looking
2925 // output with dead acceptance, invisible to the exactness gates.
2926 let (rope_dims, rope_base, ff) = match mtp.step35.as_ref() {
2927 Some(s) => (
2928 s.n_rot,
2929 s.rope_base,
2930 if s.swa {
2931 None
2932 } else {
2933 self.step35_aux.as_ref().and_then(|a| a.rope_freqs(e))
2934 },
2935 ),
2936 None => (geometry.n_rot as usize, geometry.rope_base, None),
2937 };
2938 #[cfg(debug_assertions)]
2939 if let Some(ff) = ff {
2940 crate::debug_assert_tensor_stream_device(ff, &e.stream(), "mtp_kv_fill.rope_freqs");
2941 }
2942 match ff {
2943 Some(f) => e.rope_neox_ff(
2944 &mut k, &pos_d, head_dim, rope_dims, n_head_kv, t, rope_base, 1.0, f,
2945 )?,
2946 None => e.rope_neox(
2947 &mut k, &pos_d, head_dim, rope_dims, n_head_kv, t, rope_base, 1.0,
2948 )?,
2949 }
2950
2951 let kv = &mut scratch.kv;
2952 // Match the trunk prime contract: a chunk may need the aligned window immediately before
2953 // its first row, so preserve that prefix when the physical tail rebases at wrap.
2954 let retain_from = kv
2955 .ring
2956 .as_ref()
2957 .map(|ring| pos0.saturating_sub(ring.window() - 1) & !31usize)
2958 .unwrap_or(0);
2959 let write_row = e.prepare_kv_append(kv, retain_from, t)?;
2960 for i in 0..t {
2961 let k_row = k.slice(i * kv.kv_dim_k..(i + 1) * kv.kv_dim_k);
2962 let v_row = v.slice(i * kv.kv_dim_v..(i + 1) * kv.kv_dim_v);
2963 e.append_kv_quantized_view(
2964 &k_row,
2965 &v_row,
2966 &mut kv.k,
2967 &mut kv.v,
2968 write_row + i,
2969 kv.kv_dim_k,
2970 kv.kv_dim_v,
2971 kv.k_tok_bytes,
2972 kv.v_tok_bytes,
2973 false,
2974 )?;
2975 }
2976 kv.len = pos0 + t;
2977 e.set_i32_one(&mut kv.len_d, kv.len as i32)?;
2978 Ok(())
2979 }
2980
2981 /// CAPTURE body for the GRAPH DRAFT (stage 2 of graph-grade spec): ONE MTP head forward with
2982 /// every varying input device-resident —
2983 /// - token id from the persistent `tok_d` (the previous replay's in-graph argmax wrote it,
2984 /// so the chain feeds itself; the host reads the same 4 bytes for the draft list),
2985 /// - h_seed from the persistent `h_seed_d` (h_nextn is copied BACK into it at the end),
2986 /// - rope pos from the persistent `pos_d` counter (inc'd in-graph),
2987 /// - scratch KV slot/bound from `scratch.kv.len_d` (see mtp_full_attn_dc).
2988 /// The p-min confidence lands in the persistent `p_d` iff `with_prob` (env is fixed per run).
2989 /// Same kernels, same dispatch as the eager mtp_head_forward_dev chain -> same draft tokens
2990 /// (exactness never depends on drafts — the verify arbitrates — but acceptance parity does).
2991 /// `with_head=false` captures the HEAD-LESS twin for the pseudo-seed replay (2026-07-03):
2992 /// the pseudo pass only needs h_nextn (op 10) + the scratch append — the lm_head read
2993 /// (~1.06ms q6_K on the 9B), argmax and prob are dead weight there. h_nextn's inputs are
2994 /// untouched, so the seed value is identical; round-start resets overwrite tok_d/p_d anyway.
2995 /// `sampled_cap` = Some((ctr_d, perturb_d, q_out_d, seed, temp)) captures the SAMPLED twin
2996 /// (step 3 of the sampled-spec arc): head logits are retained in the persistent `q_out_d`
2997 /// (host D2Ds them to the round's q slot after each replay), the DEVICE event counter is
2998 /// bumped in-graph, and the argmax reads GUMBEL-PERTURBED logits — one categorical draw per
2999 /// replay, bit-identical to the eager arm's gumbel_perturb at the same (seed, sctr, temp).
3000 /// seed/temp are capture-time constants (fixed per generate call, like p_min).
3001 #[allow(clippy::too_many_arguments)]
3002 fn mtp_head_forward_cap(
3003 &self,
3004 e: &Engine,
3005 mtp: &MtpHead,
3006 tok_d: &mut CudaSlice<u32>,
3007 pos_d: &mut CudaSlice<i32>,
3008 h_seed_d: &mut CudaSlice<f32>,
3009 p_d: &mut CudaSlice<f32>,
3010 scratch: &mut MtpScratch,
3011 with_prob: bool,
3012 with_head: bool,
3013 embd_gpu: &CudaSlice<u8>,
3014 embd_qt: i32,
3015 embd_rb: usize,
3016 d_vocab: usize,
3017 sampled_cap: Option<(
3018 &mut CudaSlice<u32>,
3019 &mut CudaSlice<f32>,
3020 &mut CudaSlice<f32>,
3021 u64,
3022 f32,
3023 )>,
3024 stream_pack: Option<(&mut CudaSlice<u32>, usize, Option<&CudaSlice<u32>>)>,
3025 // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): (packed draft-vocab allowed-set buffer,
3026 // word count). Captured as ONE mask_logits_f32 node between the head matmul and the
3027 // in-graph argmax; the buffer address is baked, its CONTENTS are re-uploaded by the
3028 // host before every replay (the decode.rs graph-mask pattern). All-ones contents = a
3029 // no-op ban, so a position the grammar cannot constrain costs one pass over the row.
3030 mask_cap: Option<(&CudaSlice<u32>, usize)>,
3031 ) -> Result<(), Box<dyn std::error::Error>> {
3032 let cfg = &self.cfg;
3033 let n_embd = cfg.n_embd as usize;
3034 // step35 REFUSAL (deliberate, named): the graph body's attention is `mtp_full_attn_dc`,
3035 // whose device-counter key bound always starts at row 0 — it cannot express this block's
3036 // SWA view offset, so a captured chain would silently attend OUTSIDE the window once the
3037 // persistent scratch passes 512 rows. Nothing is lost today: `graph_draft` also requires
3038 // `trunk_dense`, and step35's trunk is a 288-expert MoE, so the eager chain
3039 // (`mtp_head_forward_dev` -> `mtp_step35_attn`) is the served path. Returning Err (not a
3040 // panic) is what the two capture sites and the round-stream capture already handle by
3041 // degrading to eager / stream-off.
3042 if mtp.step35.is_some() {
3043 return Err(
3044 "step35 has no captured draft chain (fa_decode_dc cannot express the MTP \
3045 block's SWA view offset; same root cause as the dc decode refusal) — the \
3046 eager draft chain serves this arch"
3047 .into(),
3048 );
3049 }
3050 // student inner width (see mtp_head_forward_dev) — interface dims stay n_embd.
3051 let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
3052 let eps = cfg.rms_eps;
3053 let e_emb = e.embed_gather_device(embd_gpu, tok_d, n_embd, embd_qt, embd_rb)?;
3054 let mut e_norm = e.zeros(n_embd)?;
3055 e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, 1, eps)?;
3056 let mut h_norm = e.zeros(n_embd)?;
3057 e.rms_norm(
3058 &*h_seed_d,
3059 mtp.hnorm.float_data(),
3060 &mut h_norm,
3061 n_embd,
3062 1,
3063 eps,
3064 )?;
3065 let mut concat = e.zeros(2 * n_embd)?;
3066 e.copy_into(&mut concat, 0, &e_norm, n_embd)?;
3067 e.copy_into(&mut concat, n_embd, &h_norm, n_embd)?;
3068 let inp_sa = e.matmul(&mtp.eh_proj, &concat, 1)?;
3069 let mut a_norm = e.zeros(di)?;
3070 e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, 1, eps)?;
3071 let attn_out = match &mtp.mixer {
3072 Mixer::Full(fa) => {
3073 self.mtp_full_attn_dc(e, fa, &a_norm, pos_d, scratch, mtp.geom.as_ref())?
3074 }
3075 Mixer::Linear(_) => {
3076 panic!("MTP block is full-attn in qwen35; linear MTP not supported")
3077 }
3078 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
3079 };
3080 let mut x1 = e.zeros(di)?;
3081 e.add(&inp_sa, &attn_out, &mut x1, di)?;
3082 let mut z = e.zeros(di)?;
3083 e.rms_norm(&x1, mtp.post_attn_norm.float_data(), &mut z, di, 1, eps)?;
3084 let ffn_out = match &mtp.ffn {
3085 crate::hybrid::Ffn::Dense {
3086 ffn_gate,
3087 ffn_up,
3088 ffn_down,
3089 } => {
3090 let n_ff = ffn_gate.out_features();
3091 let (gate, up) = if e.uses_q8_1_fast(ffn_gate) && e.uses_q8_1_fast(ffn_up) {
3092 let (zq, zd) = e.quantize_q8_1(&z, 1, di)?;
3093 (
3094 e.matmul_pre(ffn_gate, &zq, &zd, &z, 1)?,
3095 e.matmul_pre(ffn_up, &zq, &zd, &z, 1)?,
3096 )
3097 } else {
3098 (e.matmul(ffn_gate, &z, 1)?, e.matmul(ffn_up, &z, 1)?)
3099 };
3100 let mut act = e.zeros(n_ff)?;
3101 Self::ffn_act(e, &self.cfg, &gate, &up, &mut act, n_ff)?;
3102 e.matmul(ffn_down, &act, 1)?
3103 }
3104 // ROUND-STREAM: the 35B NextN block carries a MoE FFN. With RESIDENT experts the
3105 // dev path is pure device launches (device top-k + rows kernels, ZERO-DtoH by
3106 // design) — capture-legal. Non-resident (SLRU-lock) stays rejected: the capture
3107 // error arm degrades the caller to eager/stream-off.
3108 crate::hybrid::Ffn::Moe(m) if m.dev_exps.is_some() => {
3109 self.moe_ffn_il(e, m, &z, 1, u16::MAX)?
3110 }
3111 crate::hybrid::Ffn::Moe(_) => {
3112 return Err("graph draft requires a Dense (or resident-MoE) MTP FFN".into());
3113 }
3114 };
3115 let mut h_inner = e.zeros(di)?;
3116 e.add(&x1, &ffn_out, &mut h_inner, di)?;
3117 // student: up-project back to n_embd (carrier + head input; see mtp_head_forward_dev).
3118 let h_nextn = match mtp.geom.as_ref() {
3119 Some(g) => e.matmul(&g.out_up, &h_inner, 1)?,
3120 None => h_inner,
3121 };
3122 // MEMRA_SPEC_HPOST needs final_h even head-less (it IS the next seed under that convention).
3123 let final_h = if with_head || spec_hpost() {
3124 let final_norm = mtp.shared_head_norm.as_ref().unwrap_or(&self.output_norm);
3125 let mut fh = e.zeros(n_embd)?;
3126 e.rms_norm(&h_nextn, final_norm.float_data(), &mut fh, n_embd, 1, eps)?;
3127 Some(fh)
3128 } else {
3129 None
3130 };
3131 if with_head {
3132 let head = mtp.shared_head_head.as_ref().unwrap_or(&self.output);
3133 let mut logits = e.matmul(head, final_h.as_ref().unwrap(), 1)?;
3134 // DRAFT-SIDE GRAMMAR MASK: ban the grammar-illegal draft ids IN the captured chain,
3135 // before the argmax — proposals become legal by construction. Contents-only
3136 // per-replay upload keeps the capture valid.
3137 if let Some((mask_d, mw)) = mask_cap {
3138 e.mask_logits_col(&mut logits, mask_d, 0, d_vocab, mw)?;
3139 }
3140 if let Some((ctr_d, perturb_d, q_out_d, seed, temp)) = sampled_cap {
3141 // SAMPLED chain: retain q (raw head logits -> persistent q_out_d; the matmul's
3142 // own buffer is pool-recycled after the capture body returns, so it can't be the
3143 // retention target), bump the device event counter, gumbel-perturb reading it,
3144 // and argmax the PERTURBED logits into tok_d — the in-graph categorical draw.
3145 e.copy_into(q_out_d, 0, &logits, d_vocab)?;
3146 e.sctr_inc(ctr_d)?;
3147 e.gumbel_perturb_ctr(&logits, perturb_d, d_vocab, seed, ctr_d, temp)?;
3148 e.argmax_token_device_into(perturb_d, tok_d, d_vocab)?;
3149 // p-min prob = the head's RAW softmax confidence in the SAMPLED pick — same
3150 // semantics as the eager sampled arm's prob_of_token_device(dl_d, tok_d).
3151 if with_prob {
3152 e.prob_of_token_device_into(&logits, tok_d, p_d, d_vocab)?;
3153 }
3154 } else {
3155 // draft token -> persistent tok_d (next replay's embed reads it; host reads the 4 bytes).
3156 e.argmax_token_device_into(&logits, tok_d, d_vocab)?;
3157 // p-min under a draft mask reads the MASKED row: confidence relative to the
3158 // grammar-LEGAL alternatives (illegal ids leave the softmax denominator), which
3159 // is the right semantics for "does the drafter know what comes next here" and
3160 // the same row the pick came from. Draft-quality only — verify arbitrates.
3161 if with_prob {
3162 e.prob_of_token_device_into(&logits, tok_d, p_d, d_vocab)?;
3163 }
3164 }
3165 }
3166 // ROUND-STREAM K-chain: pack (tok, p) into slot j, then remap tok through d2t so the
3167 // NEXT chained body's embed reads the TARGET id — zero host involvement per step.
3168 if let Some((out, slot, d2t)) = stream_pack {
3169 e.pack_tok_p(tok_d, p_d, out, slot)?;
3170 if let Some(map) = d2t {
3171 e.tok_map_u32(tok_d, map)?;
3172 }
3173 }
3174 // Next draft step's h_seed: pre-norm h_nextn (default) or post-norm final_h (HPOST).
3175 if spec_hpost() {
3176 e.copy_into(h_seed_d, 0, final_h.as_ref().unwrap(), n_embd)?;
3177 } else {
3178 e.copy_into(h_seed_d, 0, &h_nextn, n_embd)?;
3179 }
3180 // advance the draft rope position in-graph.
3181 e.inc_seqlen(pos_d)?;
3182 Ok(())
3183 }
3184
3185 /// Batched target verify forward over `tokens` at positions `pos0..pos0+T` (§D.3, T=K+1).
3186 /// Returns ALL T logit columns (host f32, [T*n_vocab]); appends T cols to every full-attn KV
3187 /// and advances every linear-attn recur state by T steps (the recur steps are SEQUENTIAL T=1).
3188 /// Advances `cache.pos` by T.
3189 pub fn decode_step_t(
3190 &self,
3191 e: &Engine,
3192 tokens: &[u32],
3193 pos0: usize,
3194 cache: &mut Cache,
3195 ) -> Result<Vec<f32>, Box<dyn std::error::Error>> {
3196 if self.is_gemma4_e4b() {
3197 return Ok(self.gemma4_e4b_decode_step_t_h(e, tokens, pos0, cache)?.0);
3198 }
3199 if self.cfg.gemma4.is_some() {
3200 return self.gemma4_decode_step_t(e, tokens, pos0, cache);
3201 }
3202 Ok(self.decode_step_t_h(e, tokens, pos0, cache)?.0)
3203 }
3204
3205 /// Like `decode_step_t` but ALSO returns the LAST column's pre-output_norm hidden (h_seed for
3206 /// the next draft round). This lets partial-accept replay run as ONE batched T=(n_acc+1) forward
3207 /// (single weight read) instead of n_acc+1 separate T=1 decode_steps (n_acc+1 weight reads).
3208 /// At batch=1 decode is bandwidth-bound, so batching the replay is THE MTP profitability lever.
3209 pub fn decode_step_t_h(
3210 &self,
3211 e: &Engine,
3212 tokens: &[u32],
3213 pos0: usize,
3214 cache: &mut Cache,
3215 ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3216 self.decode_step_t_h_emb(e, tokens, pos0, cache, None)
3217 }
3218
3219 /// Like `decode_step_t_h` with an optional RESIDENT embed table (spec hot loop): device
3220 /// gather instead of host dequant + [T, n_embd] f32 htod. Bit-identical rows.
3221 pub fn decode_step_t_h_emb(
3222 &self,
3223 e: &Engine,
3224 tokens: &[u32],
3225 pos0: usize,
3226 cache: &mut Cache,
3227 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3228 ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3229 let (logits_d, h_seed) = self.decode_step_t_h_emb_dev(e, tokens, pos0, cache, embd_dev)?;
3230 Ok((e.dtoh(&logits_d)?, h_seed))
3231 }
3232
3233 /// DEVICE-LOGITS verify forward (spec device-argmax lever): identical kernel chain to
3234 /// `decode_step_t_h_emb` but returns the [T, n_vocab] logits ON DEVICE — the accept walk
3235 /// argmaxes each column on-device and reads back ONE [T] u32 instead of dtoh'ing the full
3236 /// T x n_vocab f32 block (~1-4 MB + T host argmaxes, every round). Kernel dispatch is
3237 /// UNCHANGED (same decode-exact kernels); only the post-logits transfer moves.
3238 pub fn decode_step_t_h_emb_dev(
3239 &self,
3240 e: &Engine,
3241 tokens: &[u32],
3242 pos0: usize,
3243 cache: &mut Cache,
3244 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3245 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3246 let n_embd = self.cfg.n_embd as usize;
3247 let t = tokens.len();
3248 let (logits, x) = self.decode_step_t_core(e, tokens, pos0, cache, embd_dev, None)?;
3249 // h_seed for the next round = LAST column's pre-output_norm hidden ([n_embd]).
3250 let mut hs = vbuf(e, n_embd)?; // fully written by copy_view_into below
3251 e.copy_view_into(&mut hs, 0, &x.slice((t - 1) * n_embd..t * n_embd), n_embd)?;
3252 Ok((logits, hs))
3253 }
3254
3255 /// CORE verify forward: the `decode_step_t_h_emb_dev` kernel chain, returning the FULL
3256 /// pre-output_norm hidden stack x ([T, n_embd], any column extractable) and optionally
3257 /// filling a `VerifyCkpt` (retained per-layer state-rebuild inputs) for the REPLAY-FREE
3258 /// partial accept. `ckpt: None` => byte-for-byte the old behavior (the ckpt writes are pure
3259 /// retains/copies — they never change what any kernel computes).
3260 fn decode_step_t_core(
3261 &self,
3262 e: &Engine,
3263 tokens: &[u32],
3264 pos0: usize,
3265 cache: &mut Cache,
3266 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3267 mut ckpt: Option<&mut VerifyCkpt>,
3268 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3269 self.decode_step_t_core_stream(e, tokens, pos0, cache, embd_dev, ckpt.take(), None, None)
3270 }
3271
3272 /// Increment-0 two-session PP seam: release the peer after this lane's stage-0 boundary TX.
3273 /// The two independent sessions keep their own cache/checkpoint state; only issue order moves.
3274 fn decode_step_t_core_pipelined(
3275 &self,
3276 e: &Engine,
3277 tokens: &[u32],
3278 pos0: usize,
3279 cache: &mut Cache,
3280 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3281 mut ckpt: Option<&mut VerifyCkpt>,
3282 pipe: &SpecPipeLane,
3283 round: usize,
3284 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3285 let fence = crate::pp::pp_cuts(self.layers.len())
3286 .ok_or("two-session speculative pipeline requires a PP stage cut")?;
3287 if crate::pp::pp2_streams_off() || !crate::pp::spec_pp_on() {
3288 return Err("two-session speculative pipeline requires the PP verify split".into());
3289 }
3290 let interval_fence = pipe.stage0_begin(round)?;
3291 let ticket = self.verify_stage0_issue(
3292 e,
3293 tokens,
3294 pos0,
3295 cache,
3296 embd_dev,
3297 ckpt.as_deref_mut(),
3298 None,
3299 &fence,
3300 Some(interval_fence),
3301 pipe.trace(round),
3302 )?;
3303 pipe.stage0_end(round);
3304 pipe.stage1_begin(round)?;
3305 let result = self.verify_stage1_finish(e, ticket, cache, ckpt, None, &fence, true)?;
3306 pipe.verify_end(round);
3307 Ok(result)
3308 }
3309
3310 /// ROUND-STREAM stage (c) 4: `stream` = (device verify tokens [t], device pos counter) —
3311 /// when Some, rope positions come from pos_iota over the counter, the embed gathers the
3312 /// device tokens, and full_attn_verify routes appends/FA through the _dc twins reading the
3313 /// SAME counter (every layer's kvl.len == cache.pos, one counter drives all three). The
3314 /// host `tokens`/`pos0` args still size buffers (t is FIXED K+1 in stream mode).
3315 #[allow(clippy::too_many_arguments)]
3316 fn decode_step_t_core_stream(
3317 &self,
3318 e: &Engine,
3319 tokens: &[u32],
3320 pos0: usize,
3321 cache: &mut Cache,
3322 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3323 mut ckpt: Option<&mut VerifyCkpt>,
3324 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
3325 pp_pipe: Option<bool>,
3326 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3327 // PP DOOR (lane/pp2-spec 2026-08-06): the verify trunk now takes its OWN stage split,
3328 // exactly as the eager and batched steps do. This is the single funnel every verify
3329 // forward reaches (decode_step_t / _h / _h_emb / _h_emb_dev / _core all land here), so
3330 // wiring it here wires the whole spec surface — the draft/accept/commit machinery above
3331 // is untouched.
3332 //
3333 // History: pp2-hardening (2026-08-06) made this funnel FAIL CLOSED, because its trunk
3334 // walk was unsplit on one stream and a sharded cross-device placement peer-read every
3335 // remote layer's weights on every spec round (measured 13.9-28x on the batched twin).
3336 // The refusal below survives to cover the residue — MEMRA_SPEC_PP=0, MEMRA_PP_STREAMS=0,
3337 // or a placement whose PpNRt fails to build — so a config that would still walk the
3338 // whole trunk on one stream refuses instead of regressing 28x.
3339 if let Some(fence) = crate::pp::pp_cuts(self.layers.len()) {
3340 if !crate::pp::pp2_streams_off() && crate::pp::spec_pp_on() {
3341 return self.decode_step_t_core_ppn(
3342 e,
3343 tokens,
3344 pos0,
3345 cache,
3346 embd_dev,
3347 ckpt.take(),
3348 stream,
3349 &fence,
3350 pp_pipe,
3351 );
3352 }
3353 }
3354 crate::pp::refuse_unsplit_if_remote(
3355 "decode_step_t (spec verify)",
3356 "drop MEMRA_SPEC_PP=0 / MEMRA_PP_STREAMS=0 so the verify trunk takes its OWN stage \
3357 split (decode_step_t_core_ppn); or run spec on one device",
3358 )?;
3359 let cfg = &self.cfg;
3360 let n_embd = cfg.n_embd as usize;
3361 let eps = cfg.rms_eps;
3362 let t = tokens.len();
3363 let pos_d = match stream {
3364 Some((_, ctr)) => {
3365 let mut p = e.alloc_uninit::<i32>(t)?;
3366 e.pos_iota(ctr, &mut p, t)?;
3367 p
3368 }
3369 None => {
3370 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
3371 e.htod_i32(&pos_vec)?
3372 }
3373 };
3374
3375 // embed T tokens -> [T, n_embd] token-major (device gather on the spec hot loop)
3376 let x = match (stream, embd_dev) {
3377 (Some((vtok, _)), Some((g, qt, rb))) => {
3378 e.embed_gather_device_td(g, vtok, t, n_embd, qt, rb)?
3379 }
3380 (None, Some((g, qt, rb))) => e.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
3381 _ => e.htod(&self.embd.gather(n_embd, tokens))?,
3382 };
3383
3384 // TRUNK WALK: layers [0, n_layers) through the SAME range-scoped subgraph the PP-N
3385 // stage split calls per stage (`verify_layers`) — one code path, so the split cannot
3386 // drift from the unsplit dispatch mirroring. lane/pp2-spec 2026-08-06.
3387 let x = self.verify_layers(
3388 e,
3389 x,
3390 0,
3391 self.layers.len(),
3392 &pos_d,
3393 pos0,
3394 t,
3395 cache,
3396 ckpt.take(),
3397 stream,
3398 )?;
3399
3400 let mut hn = vbuf(e, t * n_embd)?;
3401 let serving_head = self.cfg.step35.is_some() || self.qwen35_serving_class();
3402 let logits = if serving_head {
3403 // Step35 and the qwen35 family (MoE 2026-08-14 AM, dense-hybrid same day PM — the
3404 // Q3.8 bring-up reproduced the identical near-tie class on dense: eager-class verify
3405 // vs batched-class live serving, ULP drift amplified through the GDN recurrence)
3406 // serve one batched numeric class at every live width, including B=1. Keep the
3407 // verify head in that same class; other generic families retain the decode-exact
3408 // head that their run-spec contract pins.
3409 e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
3410 e.matmul(&self.output, &hn, t)?
3411 } else {
3412 e.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
3413 e.matmul_decode_exact(&self.output, &hn, t)?
3414 };
3415 // stream: the device pos counter owns position; host mirror reconciles at drain.
3416 if stream.is_none() {
3417 cache.pos += t;
3418 }
3419 // Hidden stack for seeds/refresh-fills: pre-norm x (default) or post-norm hn (HPOST).
3420 Ok((logits, if spec_hpost() { hn } else { x }))
3421 }
3422
3423 /// THE VERIFY TRUNK OVER PP-N (lane/pp2-spec 2026-08-06): `decode_step_t_core_stream`'s walk
3424 /// as N stage subgraphs, each on its own engine/stream (and, under `MEMRA_PP_DEVICES`, its own
3425 /// device), with a `[T, n_embd]` boundary transfer between them. T = K+1 (the verify batch),
3426 /// so this is the batched-boundary shape the pp2-batch lane's grow-only slots already handle
3427 /// (`tx(b, x, t*n_embd)`; the slot grows to the high-water T and the transport moves exactly
3428 /// the payload).
3429 ///
3430 /// Structure is `decode_step_batch_ppn`'s, which is `decode_step_h_ppn`'s. FOUR THINGS ARE
3431 /// PER-STAGE and each for a measured reason (see `decode_step_batch_ppn`'s header for the
3432 /// receipts):
3433 ///
3434 /// 1. THE ENGINE (`rt.engine(s, e)`) — `Engine` owns lazily-grown stable-pointer scratch
3435 /// (`fa_part_pool`, `fa_vf16_scratch`, `argmax_partials`) that is single-stream-safe BY
3436 /// DESIGN. Two stage streams through one Engine is the 2026-08-02 shared-scratch race
3437 /// (35% flake, nondeterministic all-logits divergence). `PpNRt::build` gives every stage
3438 /// s>0 its own Engine even on the primary device; honouring it here is what scopes the
3439 /// pools. The verify path allocates MORE of that scratch than eager decode does (FA at
3440 /// m=T, and the per-layer `GdnStash` retains), so this is load-bearing, not inherited.
3441 ///
3442 /// 2. `pos_d` — each stage uploads its OWN copy of the T rope positions on ITS stream, so the
3443 /// buffer is allocated, consumed and freed on one stream. In `stream` mode that means each
3444 /// stage runs its own `pos_iota` over the SHARED device counter (`pos_ctr`): the counter is
3445 /// read-only during the forward (the round's `inc`/`copy_add` happen outside it), so every
3446 /// stage derives the identical iota, and each stage's own output buffer is stream-local.
3447 ///
3448 /// 3. THE EMBED lives with stage 0 (`self.embd` / `embd_gpu` are host/primary-side; the
3449 /// sharded loader leaves the table with stage 0 by construction).
3450 ///
3451 /// 4. THE HEAD (`output_norm` + `output`) runs on the LAST stage — the sharded loader uploaded
3452 /// both through that stage's engine (`hybrid.rs`: `e_head = layer_engine(e, n_trunk,
3453 /// n_trunk-1)`), so reading them anywhere else is a peer read of the biggest tensor in the
3454 /// model, every round.
3455 ///
3456 /// WHAT STAYS ON THE PRIMARY, deliberately: the returned logits and hidden stack `x`. Both are
3457 /// last-stage-allocated device buffers, and every consumer (the device argmax walk, the accept
3458 /// kernels, `spec_seed_gather`, the ckpt rebuild in `commit_verified_prefix`) reads them
3459 /// through the primary context by UVA — the same read the batched serving epilogue's
3460 /// `last_logits_dev` park does. Those consumers are per-round O(T x n_vocab) and O(n_embd),
3461 /// not per-layer, so they are not the 28x class; splitting them is a separate lane.
3462 ///
3463 /// The MTP HEAD (draft side) is NOT split: it is one block, it lives wherever the loader put
3464 /// it (`load_mtp` uses the primary engine), and it is ~1-2 GB against the trunk's tens. Draft
3465 /// placement is measured, not assumed — see `research/pp2-spec-20260806`.
3466 ///
3467 /// EXACTNESS: PP-N adds ZERO deviation. Each stage runs the SAME kernels on the SAME bytes in
3468 /// the same order via the SAME `verify_layers` the unsplit body calls; the only change is
3469 /// where the residual is materialized, and the boundary is a straight f32 copy (dtod
3470 /// same-device / `cudaMemcpyPeerAsync` cross-device, no conversion). So the split MUST be
3471 /// BIT-IDENTICAL to the unsplit verify at the same T, in both placement orders. Gate:
3472 /// `decode-batch-gate --mode ppspec`. Acceptance counts are a DERIVED consequence — greedy
3473 /// accept argmaxes these logits, so bit-identical logits force identical accept walks; the
3474 /// `run-spec` K=1..8 arm checks that end-to-end rather than trusting the implication.
3475 #[allow(clippy::too_many_arguments)]
3476 fn decode_step_t_core_ppn(
3477 &self,
3478 e: &Engine,
3479 tokens: &[u32],
3480 pos0: usize,
3481 cache: &mut Cache,
3482 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3483 mut ckpt: Option<&mut VerifyCkpt>,
3484 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
3485 fence: &[usize],
3486 pp_pipe: Option<bool>,
3487 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3488 let ticket = self.verify_stage0_issue(
3489 e,
3490 tokens,
3491 pos0,
3492 cache,
3493 embd_dev,
3494 ckpt.as_deref_mut(),
3495 stream,
3496 fence,
3497 pp_pipe,
3498 None,
3499 )?;
3500 self.verify_stage1_finish(e, ticket, cache, ckpt, stream, fence, true)
3501 }
3502
3503 /// Enqueue embed, stage 0, and the first boundary TX, then return the actual boundary slot.
3504 /// The ordinary PP verify wrapper calls `verify_stage1_finish` immediately after this return.
3505 #[allow(clippy::too_many_arguments)]
3506 fn verify_stage0_issue(
3507 &self,
3508 e: &Engine,
3509 tokens: &[u32],
3510 pos0: usize,
3511 cache: &mut Cache,
3512 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3513 mut ckpt: Option<&mut VerifyCkpt>,
3514 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
3515 fence: &[usize],
3516 pp_pipe: Option<bool>,
3517 trace: Option<SpecPipeTraceCtx>,
3518 ) -> Result<VerifyBoundaryTicket, Box<dyn std::error::Error>> {
3519 assert!(
3520 !self.is_gemma4_e4b() && self.cfg.gemma4.is_none(),
3521 "decode_step_t_core_ppn covers the hybrid non-gemma4 verify trunk only \
3522 (the gemma4 arms have their own decode_step_t twins)"
3523 );
3524 if crate::pp::pp_host_bounce_active() && (stream.is_some() || embd_dev.is_some()) {
3525 return Err(
3526 "decode_step_t_core_ppn: refused with MEMRA_PP_HOST_BOUNCE=1 — the trunk \
3527 boundary itself is host-staged, but device-resident verify still peer-reads \
3528 primary-device token/position/embedding buffers from stage 0. Run plain PP \
3529 serving on this host class; spec requires local per-stage inputs first."
3530 .into(),
3531 );
3532 }
3533 let rt = crate::pp::PpNRt::get(e)?;
3534 let n_st = fence.len() - 1;
3535 assert_eq!(
3536 rt.n_stages(),
3537 n_st,
3538 "PpNRt stage count {} != fence stages {n_st}",
3539 rt.n_stages()
3540 );
3541 let n_embd = self.cfg.n_embd as usize;
3542 let t = tokens.len();
3543 let payload = t * n_embd;
3544 if pp_pipe.is_some() {
3545 assert_eq!(n_st, 2, "spec pipeline requires exactly two PP stages");
3546 }
3547 // One-shot lane diagnostic: force natural PP-2 boundaries to completion so the server
3548 // log can price stage 0, the peer hop, the RX copy, and stage 1 + head separately without
3549 // nsys. The ordinary path keeps every enqueue asynchronous. N>2 is deliberately excluded:
3550 // the report below names exactly two stages and must never imply it measured middle ones.
3551 let pp_anatomy = n_st == 2 && std::env::var("MEMRA_SPEC_PP_ANATOMY").as_deref() == Ok("1");
3552 let pp_started = std::time::Instant::now();
3553 let (mut reverse_ms, mut stage0_ms, mut tx_ms) = (0.0f64, 0.0f64, 0.0f64);
3554 // The CALLER's ambient stream, captured BEFORE any `rt.enter()` pushes a stage stream:
3555 // this body returns DEVICE-RESIDENT buffers (the device-argmax accept walk's contract),
3556 // so the exit needs the same publication the boundaries get — see `PpNRt::publish_to`.
3557 // Taken here, not at the end, because inside the last-stage scope `e.stream()` IS the
3558 // stage stream and the wait would self-order into a no-op.
3559 let caller_stream = e.stream();
3560 // #87 ROOT-CAUSE FENCE (lane/pp2spec-crash): the PREVIOUS round's stage-allocated
3561 // outputs (logits/hidden/ckpt stashes) freed stream-ordered on the STAGE streams while
3562 // the primary stream still holds queued reads of them — with event tracking elided,
3563 // nothing stops the pool from reusing those blocks for THIS round's stage allocations,
3564 // whose writes then race the queued reads (measured: 13/4096-NaN random-bits garbage in
3565 // the spec round seed; the full anatomy is on `PpNRt::fence_stages_behind`). Order every
3566 // stage stream behind the caller before enqueueing new stage work.
3567 let reverse_started = std::time::Instant::now();
3568 if pp_pipe != Some(false) {
3569 rt.fence_stages_behind(&caller_stream)?;
3570 }
3571 if pp_pipe == Some(true) {
3572 // Both session verifies must alternate boundary slots even when the ordinary
3573 // decode overlap experiment is off. Prewarm before A's stage 0 so B cannot grow
3574 // slot 1 by synchronizing the RX stream while A's stage 1 is in flight.
3575 rt.prepare_overlap_slots(0, payload)?;
3576 }
3577 if pp_anatomy {
3578 // Drain the reverse-publication dependency before timing stage 0 itself. At c=1 this
3579 // prices any primary-stream rollback/refresh tail inherited from the prior round.
3580 for s in 0..n_st {
3581 let _st = rt.enter(s);
3582 rt.engine(s, e).stream().synchronize()?;
3583 }
3584 reverse_ms = reverse_started.elapsed().as_secs_f64() * 1e3;
3585 }
3586
3587 // Per-stage rope positions: in host mode the same [T] iota each stage uploads itself; in
3588 // stream mode each stage's own `pos_iota` over the shared read-only device counter.
3589 let stage_pos = |es: &Engine| -> Result<CudaSlice<i32>, Box<dyn std::error::Error>> {
3590 match stream {
3591 Some((_, ctr)) => {
3592 let mut p = es.alloc_uninit::<i32>(t)?;
3593 es.pos_iota(ctr, &mut p, t)?;
3594 Ok(p)
3595 }
3596 None => {
3597 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
3598 es.htod_i32(&pos_vec)
3599 }
3600 }
3601 };
3602
3603 // ---- STAGE 0: embed (the table lives with stage 0) + layers [0, fence[1]) + TX ----
3604 let slot = {
3605 let _st0 = rt.enter(0);
3606 let e0 = rt.engine(0, e);
3607 enqueue_spec_pipe_trace_marker(&e0.stream(), trace.as_ref(), "S0", "start", None)?;
3608 let stage0_started = std::time::Instant::now();
3609 let pos_d = stage_pos(e0)?;
3610 let x = match (stream, embd_dev) {
3611 (Some((vtok, _)), Some((g, qt, rb))) => {
3612 e0.embed_gather_device_td(g, vtok, t, n_embd, qt, rb)?
3613 }
3614 (None, Some((g, qt, rb))) => e0.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
3615 _ => e0.htod(&self.embd.gather(n_embd, tokens))?,
3616 };
3617 let x = self.verify_layers(
3618 e0,
3619 x,
3620 fence[0],
3621 fence[1],
3622 &pos_d,
3623 pos0,
3624 t,
3625 cache,
3626 ckpt.as_deref_mut(),
3627 stream,
3628 )?;
3629 if pp_anatomy {
3630 e0.stream().synchronize()?;
3631 stage0_ms = stage0_started.elapsed().as_secs_f64() * 1e3;
3632 }
3633 let tx_started = std::time::Instant::now();
3634 let slot = if pp_pipe.is_some() {
3635 rt.tx_pipelined(0, &x, payload)?
3636 } else {
3637 rt.tx(0, &x, payload)?
3638 };
3639 enqueue_spec_pipe_trace_marker(&e0.stream(), trace.as_ref(), "S0", "end", Some(slot))?;
3640 if pp_anatomy {
3641 e0.stream().synchronize()?;
3642 tx_ms = tx_started.elapsed().as_secs_f64() * 1e3;
3643 }
3644 slot
3645 // x + pos_d drop here: freed stream-ordered on stage-0's stream after use.
3646 };
3647
3648 Ok(VerifyBoundaryTicket {
3649 rt,
3650 caller_stream,
3651 slot,
3652 pos0,
3653 t,
3654 payload,
3655 n_st,
3656 pipelined: pp_pipe.is_some(),
3657 pp_anatomy,
3658 pp_started,
3659 reverse_ms,
3660 stage0_ms,
3661 tx_ms,
3662 trace,
3663 })
3664 }
3665
3666 /// Consume a stage-0 boundary ticket and enqueue the remaining PP stages plus the head.
3667 /// On PP-2 this is exactly stage 1; PP-N keeps its pre-existing middle-stage walk here.
3668 #[allow(clippy::too_many_arguments)]
3669 fn verify_stage1_finish(
3670 &self,
3671 e: &Engine,
3672 ticket: VerifyBoundaryTicket,
3673 cache: &mut Cache,
3674 mut ckpt: Option<&mut VerifyCkpt>,
3675 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
3676 fence: &[usize],
3677 publish_to_caller: bool,
3678 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3679 let VerifyBoundaryTicket {
3680 rt,
3681 caller_stream,
3682 slot,
3683 pos0,
3684 t,
3685 payload,
3686 n_st,
3687 pipelined,
3688 pp_anatomy,
3689 pp_started,
3690 reverse_ms,
3691 stage0_ms,
3692 tx_ms,
3693 trace,
3694 } = ticket;
3695 let n_embd = self.cfg.n_embd as usize;
3696 let eps = self.cfg.rms_eps;
3697 let mut slot = slot;
3698 let (mut rx_ms, mut stage1_ms) = (0.0f64, 0.0f64);
3699 let stage_pos = |es: &Engine| -> Result<CudaSlice<i32>, Box<dyn std::error::Error>> {
3700 match stream {
3701 Some((_, ctr)) => {
3702 let mut p = es.alloc_uninit::<i32>(t)?;
3703 es.pos_iota(ctr, &mut p, t)?;
3704 Ok(p)
3705 }
3706 None => {
3707 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
3708 es.htod_i32(&pos_vec)
3709 }
3710 }
3711 };
3712
3713 // ---- MIDDLE STAGES: RX boundary s-1 -> range -> TX boundary s ----
3714 for s in 1..n_st - 1 {
3715 let _st = rt.enter(s);
3716 let es = rt.engine(s, e);
3717 let pos_d = stage_pos(es)?;
3718 let x = rt.rx(s - 1, slot, payload)?;
3719 let x = self.verify_layers(
3720 es,
3721 x,
3722 fence[s],
3723 fence[s + 1],
3724 &pos_d,
3725 pos0,
3726 t,
3727 cache,
3728 ckpt.as_deref_mut(),
3729 stream,
3730 )?;
3731 slot = if pipelined {
3732 rt.tx_pipelined(s, &x, payload)?
3733 } else {
3734 rt.tx(s, &x, payload)?
3735 };
3736 }
3737
3738 // ---- LAST STAGE: RX + final range + output_norm + lm head ----
3739 let _stl = rt.enter(n_st - 1);
3740 let el = rt.engine(n_st - 1, e);
3741 let pos_d = stage_pos(el)?;
3742 let rx_started = std::time::Instant::now();
3743 let x = rt.rx(n_st - 2, slot, payload)?;
3744 if pp_anatomy {
3745 el.stream().synchronize()?;
3746 rx_ms = rx_started.elapsed().as_secs_f64() * 1e3;
3747 }
3748 enqueue_spec_pipe_trace_marker(&el.stream(), trace.as_ref(), "S1", "start", Some(slot))?;
3749 let stage1_started = std::time::Instant::now();
3750 let x = self.verify_layers(
3751 el,
3752 x,
3753 fence[n_st - 1],
3754 fence[n_st],
3755 &pos_d,
3756 pos0,
3757 t,
3758 cache,
3759 ckpt.as_deref_mut(),
3760 stream,
3761 )?;
3762
3763 let mut hn = vbuf(el, payload)?;
3764 let logits = if self.cfg.step35.is_some() {
3765 // The PP Step35 serving path uses rms_norm + matmul for B=1 as well as B>1.
3766 // Verify must not switch numeric class merely because the same session speculates.
3767 el.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
3768 el.matmul(&self.output, &hn, t)?
3769 } else {
3770 el.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
3771 el.matmul_decode_exact(&self.output, &hn, t)?
3772 };
3773 enqueue_spec_pipe_trace_marker(&el.stream(), trace.as_ref(), "S1", "end", Some(slot))?;
3774 if pp_anatomy {
3775 el.stream().synchronize()?;
3776 stage1_ms = stage1_started.elapsed().as_secs_f64() * 1e3;
3777 }
3778 // EXIT PUBLICATION: both returned buffers are still being produced on the last stage's
3779 // stream. Order the caller's stream behind that work before the buffers escape this
3780 // scope (the 2026-08-06 same-device ppspec find: without it the caller's primary-stream
3781 // consumer read unwritten logits — nondeterministic, one-device-only, and it poisoned
3782 // the following arm's KV in the same process).
3783 if publish_to_caller {
3784 rt.publish_to(n_st - 1, &caller_stream)?;
3785 }
3786 if pp_anatomy {
3787 if publish_to_caller {
3788 caller_stream.synchronize()?;
3789 }
3790 eprintln!(
3791 "[spec-pp-anatomy] t={t} reverse={reverse_ms:.3}ms stage0={stage0_ms:.3}ms \
3792 tx={tx_ms:.3}ms rx={rx_ms:.3}ms stage1-head={stage1_ms:.3}ms total={:.3}ms",
3793 pp_started.elapsed().as_secs_f64() * 1e3,
3794 );
3795 }
3796 // stream: the device pos counter owns position; host mirror reconciles at drain.
3797 if stream.is_none() {
3798 cache.pos += t;
3799 }
3800 Ok((logits, if spec_hpost() { hn } else { x }))
3801 }
3802
3803 /// Step3.5/Step3.7 verify trunk in the serving batched numeric class.
3804 ///
3805 /// `step35_decode_batch_layers` is now authoritative at every live serving width, including
3806 /// B=1 (lane/cx-b1fix). The older verify walk deliberately mirrored the eager T=1 class:
3807 /// it replayed `step35_decode_attn` per row and used the eager/decode-exact FFN dispatch.
3808 /// Those classes are individually stable, but a near-tie prompt can choose different greedy
3809 /// bytes when a request moves from batched plain serving into speculative verify. Run the
3810 /// same authoritative B=1 stage subgraph for each verify row here. Rows still advance
3811 /// layer-by-layer, so every layer sees the preceding verify rows in its attention cache while
3812 /// every norm/projection/FFN uses exactly the live serving dispatch.
3813 #[allow(clippy::too_many_arguments)]
3814 fn step35_verify_batch_layers(
3815 &self,
3816 e: &Engine,
3817 mut x: CudaSlice<f32>,
3818 lo: usize,
3819 hi: usize,
3820 pos0: usize,
3821 t: usize,
3822 cache: &mut Cache,
3823 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3824 let n_embd = self.cfg.n_embd as usize;
3825 self.cfg
3826 .step35
3827 .as_ref()
3828 .ok_or("step35 verify batch requires step35 cfg")?;
3829 let mut ph_last = std::time::Instant::now();
3830 for il in lo..hi {
3831 let mut next = e.uninit(t * n_embd)?;
3832 for r in 0..t {
3833 let mut row = e.uninit(n_embd)?;
3834 e.dtod_copy_view(&x.slice(r * n_embd..(r + 1) * n_embd), &mut row)?;
3835 // The caller owns this verify's position. During controller overlap, cache.pos
3836 // still describes generation N while this stage-0 walk belongs to N+1.
3837 let row_pos = e.htod_i32(&[(pos0 + r) as i32])?;
3838 let mut one = [&mut *cache];
3839 let out = self.step35_decode_batch_layers(
3840 e,
3841 row,
3842 &mut one,
3843 &row_pos,
3844 il,
3845 il + 1,
3846 &mut ph_last,
3847 )?;
3848 e.dtod_copy_into(&out, &mut next, r * n_embd)?;
3849 }
3850 self.dflash_tap(e, cache, il, &next, t)?;
3851 x = next;
3852 }
3853 Ok(x)
3854 }
3855
3856 /// DSpark drafter verify (lane/dspark-q38-recover): one t-row forward through the
3857 /// SERVING-CLASS verify funnel (`decode_step_t_core_stream` — the same numeric class
3858 /// MTP verify rides, GDN state advanced in place), returning per-row argmax tokens.
3859 /// Advances `cache.pos += t`; the caller owns snapshot/rollback (block acceptance is
3860 /// prefix-keep, not all-or-nothing).
3861 pub(crate) fn dspark_verify_t_am(
3862 &self,
3863 e: &Engine,
3864 tokens: &[u32],
3865 pos0: usize,
3866 cache: &mut Cache,
3867 ) -> Result<Vec<u32>, Box<dyn std::error::Error>> {
3868 let (logits, _hn) =
3869 self.decode_step_t_core_stream(e, tokens, pos0, cache, None, None, None, None)?;
3870 let t = tokens.len();
3871 let v = self.output.out_features();
3872 let mut am_d = e.stream().alloc_zeros::<u32>(t)?;
3873 for r in 0..t {
3874 e.argmax_token_device_col(&logits, r, v, &mut am_d, r)?;
3875 }
3876 Ok(e.dtoh_u32(&am_d)?)
3877 }
3878
3879 /// DSpark verify with the MTP column-stash armed: identical forward to
3880 /// `dspark_verify_t_am`, but fills a `VerifyCkpt` so a partial accept can restore
3881 /// column state directly (`dspark_commit_prefix`) instead of snapshot-replay.
3882 /// The ckpt type is opaque outside spec.rs (newtype) — dflash.rs threads it through.
3883 pub(crate) fn dspark_verify_t_am_ckpt(
3884 &self,
3885 e: &Engine,
3886 tokens: &[u32],
3887 pos0: usize,
3888 cache: &mut Cache,
3889 ) -> Result<(Vec<u32>, DsparkVerifyCkpt), Box<dyn std::error::Error>> {
3890 let mut ck = VerifyCkpt::new(self.layers.len());
3891 let (logits, _hn) = self.decode_step_t_core_stream(
3892 e,
3893 tokens,
3894 pos0,
3895 cache,
3896 None,
3897 Some(&mut ck),
3898 None,
3899 None,
3900 )?;
3901 let t = tokens.len();
3902 let v = self.output.out_features();
3903 let mut am_d = e.stream().alloc_zeros::<u32>(t)?;
3904 for r in 0..t {
3905 e.argmax_token_device_col(&logits, r, v, &mut am_d, r)?;
3906 }
3907 Ok((e.dtoh_u32(&am_d)?, DsparkVerifyCkpt(ck)))
3908 }
3909
3910 /// Restore the round to `keep` accepted columns from the verify stash: KV lens and
3911 /// pos from the pre-verify snapshot + keep, GDN conv/ssm from the stashed column
3912 /// state — no replay forward. The exact `commit_verified_prefix` the MTP path ships.
3913 pub(crate) fn dspark_commit_prefix(
3914 &self,
3915 e: &Engine,
3916 cache: &mut Cache,
3917 snap: &crate::cache::CacheSnapshot,
3918 ckpt: &DsparkVerifyCkpt,
3919 keep: usize,
3920 ) -> Result<(), Box<dyn std::error::Error>> {
3921 self.commit_verified_prefix(e, cache, snap, &ckpt.0, keep, false, None)
3922 }
3923
3924 /// Qwen35-family verify trunk in the live serving numeric class.
3925 ///
3926 /// Serving intentionally keeps this architecture in the generic batched program even at
3927 /// B=1. The older verify walk used its own mirrored dispatch and can flip near-tie argmaxes.
3928 ///
3929 /// Two arms, one numeric class:
3930 /// - DENSE (`Arch::Qwen35`, t<=16): `qwen35_verify_tparallel` — the weight ops (norms,
3931 /// projections, FFN) hoist to m=T through the exact-tier batched kernels whose per-row
3932 /// program IS the m=1 program (`matmul_pre == fused2 per (tensor,row); _bN mmvq per-row
3933 /// == m=1` — decode_batch.rs v2 note), while the state ops (conv ring, gdn scan, KV
3934 /// append, fa decode) stay a per-row loop running the b_n=1 serving kernels with each
3935 /// row's own t_kv-driven arm pick (the straddle law: every row executes the exact
3936 /// program its isolated serving step would). One weight read per layer per round
3937 /// instead of T — this is what makes MTP profitable in the exact class (the per-row
3938 /// walk measured verify(K+1) ~= (K+1) plain steps: 69 -> 44 tok/s served, 2026-08-15).
3939 /// - MoE / t>16 / `MEMRA_SPEC_VERIFY_ROWWISE=1`: the per-row replay of the authoritative
3940 /// serving layer body, preserving single-session autoregressive cache order (the
3941 /// correctness reference; also the rollback seam for the t-parallel arm).
3942 ///
3943 /// Bit-identity of the t-parallel arm vs the rowwise arm is gated by spec-serve-gate
3944 /// (zero differing logits at T=1..4, K arms) + the 8-prompt ON/OFF canary before ship.
3945 #[allow(clippy::too_many_arguments)]
3946 fn qwen35_verify_batch_layers(
3947 &self,
3948 e: &Engine,
3949 x: CudaSlice<f32>,
3950 lo: usize,
3951 hi: usize,
3952 pos0: usize,
3953 t: usize,
3954 cache: &mut Cache,
3955 ckpt: Option<&mut VerifyCkpt>,
3956 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3957 let rowwise = std::env::var("MEMRA_SPEC_VERIFY_ROWWISE").as_deref() == Ok("1")
3958 || !matches!(self.cfg.arch, memra_gguf::config::Arch::Qwen35)
3959 || t > 16;
3960 if rowwise {
3961 self.qwen35_verify_rowwise(e, x, lo, hi, pos0, t, cache, ckpt)
3962 } else {
3963 self.qwen35_verify_tparallel(e, x, lo, hi, pos0, t, cache, ckpt)
3964 }
3965 }
3966
3967 /// The per-row correctness reference: replay each verify row through the authoritative
3968 /// serving layer body (`decode_batch_layers` at b_n=1). T full weight reads per layer.
3969 #[allow(clippy::too_many_arguments)]
3970 fn qwen35_verify_rowwise(
3971 &self,
3972 e: &Engine,
3973 mut x: CudaSlice<f32>,
3974 lo: usize,
3975 hi: usize,
3976 pos0: usize,
3977 t: usize,
3978 cache: &mut Cache,
3979 mut ckpt: Option<&mut VerifyCkpt>,
3980 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3981 let n_embd = self.cfg.n_embd as usize;
3982 let saved_pos = cache.pos;
3983 let mut ph_last = std::time::Instant::now();
3984 for il in lo..hi {
3985 let mut next = e.uninit(t * n_embd)?;
3986 let mut col_states: Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>> =
3987 if ckpt.is_some() && t >= 2 && matches!(self.layers[il].mixer, Mixer::Linear(_)) {
3988 Some(Vec::with_capacity(t - 1))
3989 } else {
3990 None
3991 };
3992 for r in 0..t {
3993 cache.pos = pos0 + r;
3994 let mut row = e.uninit(n_embd)?;
3995 e.dtod_copy_view(&x.slice(r * n_embd..(r + 1) * n_embd), &mut row)?;
3996 let row_pos = e.htod_i32(&[(pos0 + r) as i32])?;
3997 let mut one = [&mut *cache];
3998 let ctx = self.batch_layer_ctx(e, &one, il, il + 1)?;
3999 let out = match self.decode_batch_layers(
4000 e,
4001 row,
4002 &mut one,
4003 &ctx,
4004 &row_pos,
4005 &mut ph_last,
4006 ) {
4007 Ok(out) => out,
4008 Err(error) => {
4009 cache.pos = saved_pos;
4010 return Err(error);
4011 }
4012 };
4013 e.dtod_copy_into(&out, &mut next, r * n_embd)?;
4014 if r + 1 < t {
4015 if let Some(states) = col_states.as_mut() {
4016 let recur = cache.recur[il]
4017 .as_ref()
4018 .ok_or("Qwen35-MoE linear verify layer has no recurrent state")?;
4019 states.push((
4020 e.clone_dtod(&recur.conv_state)?,
4021 e.clone_dtod(&recur.ssm_state)?,
4022 ));
4023 }
4024 }
4025 }
4026 if let (Some(checkpoint), Some(states)) = (ckpt.as_deref_mut(), col_states) {
4027 checkpoint.cols[il] = Some(states);
4028 }
4029 x = next;
4030 }
4031 cache.pos = saved_pos;
4032 Ok(x)
4033 }
4034
4035 /// T-PARALLEL VERIFY IN THE SERVING NUMERIC CLASS (lane/tparallel-verify, 2026-08-15).
4036 ///
4037 /// The weight ops run ONCE per layer at m=T; the state ops run per row through the same
4038 /// b_n=1 serving kernels the rowwise replay uses. Per-row bit-identity rests on the two
4039 /// pins the serving batch tier already carries:
4040 /// * `matmul_pre` / `_bN` mmvq: per-row program == m=1 program (decode_batch.rs v2 note,
4041 /// kernel-check pinned) — so a [T, n_embd] projection row equals the row projected
4042 /// alone;
4043 /// * row-indexed norms/elementwise (`rms_norm`, `quantize_q8_1`, `add_rms_norm`,
4044 /// `gated_rmsnorm[_q8_1]`, `silu_mul`, `rope_neox` with per-row positions): the T-row
4045 /// launch is the per-row program (same pin the generic verify's fused norms rely on).
4046 /// The sequential dependencies keep their exact serving order: the conv ring / gdn scan
4047 /// chain state row -> row through the `_b` kernels at b_n=1 (ping-pong via a 6-entry
4048 /// alternating pointer table, host handles swapped per row so VerifyCkpt clones the
4049 /// canonical state exactly as the rowwise arm does), and each row's KV append + fa decode
4050 /// picks its arm from ITS OWN t_kv (append: format-only; fa: `fa_seqs_eligible` + its own
4051 /// `fa_split_keys` rung at b_n=1) — the straddle law per row, so every row executes the
4052 /// program its isolated B=1 serving step would.
4053 ///
4054 /// Cost: 1 weight read per layer per round + T state micro-launches, vs the rowwise arm's
4055 /// T weight reads. Gated bit-identical vs the rowwise arm by spec-serve-gate + canary.
4056 #[allow(clippy::too_many_arguments)]
4057 fn qwen35_verify_tparallel(
4058 &self,
4059 e: &Engine,
4060 mut x: CudaSlice<f32>,
4061 lo: usize,
4062 hi: usize,
4063 pos0: usize,
4064 t: usize,
4065 cache: &mut Cache,
4066 mut ckpt: Option<&mut VerifyCkpt>,
4067 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
4068 use cudarc::driver::DevicePtr;
4069 let cfg = &self.cfg;
4070 let n_embd = cfg.n_embd as usize;
4071 let eps = cfg.rms_eps;
4072 let head_dim_global = cfg.head_dim_k as usize;
4073 let pos_host: Vec<i32> = (0..t).map(|r| (pos0 + r) as i32).collect();
4074 let pos_d = e.htod_i32(&pos_host)?;
4075 // Per-row 1-element position buffers, built ONCE per verify (the append/fa wrappers
4076 // take owned pos slices; building these inside the layer x row loops cost 16xT H2Ds).
4077 let pos_rows: Vec<CudaSlice<i32>> = (0..t)
4078 .map(|r| e.htod_i32(&[(pos0 + r) as i32]))
4079 .collect::<Result<_, _>>()?;
4080 let seqs_append =
4081 std::env::var("MEMRA_BATCH_APPEND").as_deref() != Ok("0") && !Engine::kv_fp8_on();
4082 let batch_fa_on = std::env::var("MEMRA_BATCH_FA").as_deref() != Ok("0");
4083
4084 for il in lo..hi {
4085 let layer = &self.layers[il];
4086 // ---- attn_norm + q8_1 quantize at m=T (row-indexed == per-row) ----
4087 let anorm = layer.attn_norm.float_data();
4088 let mut xn = e.uninit(t * n_embd)?;
4089 e.rms_norm(&x, anorm, &mut xn, n_embd, t, eps)?;
4090 let (hq, hd) = e.quantize_q8_1(&xn, t, n_embd)?;
4091
4092 let mixed: CudaSlice<f32> = match &layer.mixer {
4093 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
4094 Mixer::Full(fa) => {
4095 let geometry = cfg.full_attention_geometry_at(il as u32);
4096 let n_head = geometry.n_head as usize;
4097 let n_head_kv = geometry.n_head_kv as usize;
4098 let head_dim = geometry.head_dim_k as usize;
4099 let rope_dims = geometry.n_rot as usize;
4100 let rope_base = geometry.rope_base;
4101 let scale = geometry.attention_scale();
4102 // Batched projections: one weight read serves all T rows.
4103 let qf = e.matmul_pre(&fa.wq, &hq, &hd, &xn, t)?;
4104 let mut k = e.matmul_pre(&fa.wk, &hq, &hd, &xn, t)?;
4105 let v = e.matmul_pre(&fa.wv, &hq, &hd, &xn, t)?;
4106 let gated =
4107 geometry.attention_gate == memra_gguf::config::AttentionGateKind::FusedQ;
4108 let (mut q, gate) = if gated {
4109 let mut qs = e.uninit(t * n_head * head_dim)?;
4110 let mut gs = e.uninit(t * n_head * head_dim)?;
4111 e.q_gate_split(&qf, &mut qs, &mut gs, head_dim, n_head, t)?;
4112 (qs, Some(gs))
4113 } else {
4114 (qf, None)
4115 };
4116 let mut qn = e.uninit(t * n_head * head_dim)?;
4117 e.rms_norm(
4118 &q,
4119 fa.q_norm.float_data(),
4120 &mut qn,
4121 head_dim,
4122 t * n_head,
4123 eps,
4124 )?;
4125 q = qn;
4126 let mut kn = e.uninit(t * n_head_kv * head_dim)?;
4127 e.rms_norm(
4128 &k,
4129 fa.k_norm.float_data(),
4130 &mut kn,
4131 head_dim,
4132 t * n_head_kv,
4133 eps,
4134 )?;
4135 k = kn;
4136 e.rope_neox(
4137 &mut q, &pos_d, head_dim, rope_dims, n_head, t, rope_base, 1.0,
4138 )?;
4139 e.rope_neox(
4140 &mut k, &pos_d, head_dim, rope_dims, n_head_kv, t, rope_base, 1.0,
4141 )?;
4142
4143 // Per-row append + attend: row r sees rows 0..r in KV (causal within the
4144 // draft), each through the b_n=1 serving kernels at its own t_kv.
4145 let q_dim = n_head * head_dim;
4146 let kv_dim = n_head_kv * head_dim;
4147 let mut attn = e.uninit(t * q_dim)?;
4148 let (kdk, kdv, ktb, vtb, kv_view) = {
4149 let kvl = cache.kv[il].as_ref().unwrap();
4150 let s = &e.gpu.stream();
4151 let (pk, _g) = kvl.k.device_ptr(s);
4152 let (pv, _g2) = kvl.v.device_ptr(s);
4153 (
4154 kvl.kv_dim_k,
4155 kvl.kv_dim_v,
4156 kvl.k_tok_bytes,
4157 kvl.v_tok_bytes,
4158 e.htod_u64(&[pk as u64, pv as u64])?,
4159 )
4160 };
4161 for r in 0..t {
4162 // Owned per-row scratch: the b_n=1 kernels take packed batch buffers
4163 // whose row 0 is this row (arithmetic-free materialization copies,
4164 // same as decode's per-seq fallback arm).
4165 let mut k_row = e.uninit(kv_dim)?;
4166 e.dtod_copy_view(&k.slice(r * kv_dim..(r + 1) * kv_dim), &mut k_row)?;
4167 let mut v_row = e.uninit(kv_dim)?;
4168 e.dtod_copy_view(&v.slice(r * kv_dim..(r + 1) * kv_dim), &mut v_row)?;
4169 let pos_row = &pos_rows[r];
4170 let kvl = cache.kv[il].as_mut().unwrap();
4171 if seqs_append {
4172 e.append_kv_quantized_seqs(
4173 &k_row,
4174 &v_row,
4175 &kv_view.slice(0..2),
4176 pos_row,
4177 1,
4178 kdk,
4179 kdv,
4180 ktb,
4181 vtb,
4182 )?;
4183 kvl.len += 1;
4184 } else {
4185 e.append_kv_quantized_view(
4186 &k_row.slice(0..kv_dim),
4187 &v_row.slice(0..kv_dim),
4188 &mut kvl.k,
4189 &mut kvl.v,
4190 kvl.len,
4191 kvl.kv_dim_k,
4192 kvl.kv_dim_v,
4193 kvl.k_tok_bytes,
4194 kvl.v_tok_bytes,
4195 Engine::kv_fp8_on(),
4196 )?;
4197 kvl.len += 1;
4198 }
4199 let t_kv = kvl.len;
4200 let mut q_row = e.uninit(q_dim)?;
4201 e.dtod_copy_view(&q.slice(r * q_dim..(r + 1) * q_dim), &mut q_row)?;
4202 let mut a_row = e.uninit(q_dim)?;
4203 if batch_fa_on && crate::fa_seqs_eligible(t_kv, head_dim_global) {
4204 let sp0_r = crate::fa_split_keys(t_kv, cfg.n_head_kv as usize);
4205 e.fa_decode_batch_seqs_v4(
4206 &q_row,
4207 &kv_view.slice(0..2),
4208 pos_row,
4209 &mut a_row,
4210 head_dim,
4211 n_head,
4212 n_head_kv,
4213 1,
4214 t_kv,
4215 scale,
4216 sp0_r,
4217 ktb,
4218 vtb,
4219 )?;
4220 } else {
4221 let k_view = e.view_u8(&kvl.k, t_kv * kvl.k_tok_bytes);
4222 let v_view = e.view_u8(&kvl.v, t_kv * kvl.v_tok_bytes);
4223 let mut a_view = a_row.slice_mut(0..q_dim);
4224 e.fa_decode_kvmod_view(
4225 &q_row.slice(0..q_dim),
4226 &k_view,
4227 &v_view,
4228 &mut a_view,
4229 head_dim,
4230 n_head,
4231 n_head_kv,
4232 t_kv,
4233 scale,
4234 kvl.k_tok_bytes,
4235 kvl.v_tok_bytes,
4236 Engine::kv_fp8_on(),
4237 )?;
4238 }
4239 e.dtod_copy_into(&a_row, &mut attn, r * q_dim)?;
4240 }
4241
4242 // Output gate (element-wise) + o-proj at m=T.
4243 let attn_g = match &gate {
4244 Some(g) => {
4245 let n = t * q_dim;
4246 let mut gsig = e.uninit(n)?;
4247 e.sigmoid(g, &mut gsig, n)?;
4248 let mut ag = e.uninit(n)?;
4249 e.mul(&attn, &gsig, &mut ag, n)?;
4250 ag
4251 }
4252 None => attn,
4253 };
4254 e.matmul(&fa.wo, &attn_g, t)?
4255 }
4256 Mixer::Linear(la) => {
4257 let ssm = cfg.ssm.as_ref().expect("linear mixer requires ssm cfg");
4258 let d_state = ssm.state_size as usize;
4259 let num_k = ssm.group_count as usize;
4260 let num_v = ssm.time_step_rank as usize;
4261 let d_conv = ssm.conv_kernel as usize;
4262 let key_dim = d_state * num_k;
4263 let value_dim = d_state * num_v;
4264 let conv_dim = key_dim * 2 + value_dim;
4265 let gdn_scale = 1.0 / (d_state as f32).sqrt();
4266
4267 // ---- batched projections: one weight read for all T rows ----
4268 let qkv_mixed = e.matmul_pre(&la.wqkv, &hq, &hd, &xn, t)?;
4269 let z = e.matmul_pre(&la.wqkv_gate, &hq, &hd, &xn, t)?;
4270 let beta_raw = e.matmul_pre(&la.ssm_beta, &hq, &hd, &xn, t)?;
4271 let alpha = e.matmul_pre(&la.ssm_alpha, &hq, &hd, &xn, t)?;
4272 let beta_w = la.ssm_beta.out_features();
4273 let alpha_w = la.ssm_alpha.out_features();
4274 let qkv_w = la.wqkv.out_features();
4275
4276 // ---- per-row state chain through the b_n=1 serving kernels ----
4277 // 6-entry alternating pointer table expresses the ping-pong without a
4278 // rebuild per row: even rows scan s0 -> s1, odd rows s1 -> s0. Host
4279 // handles swap per row so ckpt clones the canonical state (and the
4280 // post-verify canonical handle matches the last write), exactly as the
4281 // rowwise arm leaves them.
4282 let table = {
4283 let rl = cache.recur[il].as_ref().unwrap();
4284 let s = &e.gpu.stream();
4285 let (pc, _g0) = rl.conv_state.device_ptr(s);
4286 let (p0, _g1) = rl.ssm_state.device_ptr(s);
4287 let (p1, _g2) = rl.ssm_state_alt.device_ptr(s);
4288 e.htod_u64(&[
4289 pc as u64, p0 as u64, p1 as u64, pc as u64, p1 as u64, p0 as u64,
4290 ])?
4291 };
4292 let mut o_all = e.uninit(t * value_dim)?;
4293 let mut col_states: Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>> =
4294 if ckpt.is_some() && t >= 2 {
4295 Some(Vec::with_capacity(t - 1))
4296 } else {
4297 None
4298 };
4299 // Per-row scratch reused across rows (uninit is cheap but not free at
4300 // 48 layers x T rows); row inputs/outputs pass as VIEWS into the packed
4301 // [T, ...] buffers — zero arithmetic-free copies in this loop.
4302 let mut conv_out = e.uninit(conv_dim)?;
4303 let mut q_l2 = e.uninit(value_dim)?;
4304 let mut k_l2 = e.uninit(value_dim)?;
4305 let mut v_gd = e.uninit(value_dim)?;
4306 let mut beta_b = e.uninit(num_v)?;
4307 let mut g_log = e.uninit(num_v)?;
4308 for r in 0..t {
4309 let base = if r % 2 == 0 { 0 } else { 3 };
4310 let conv_view = table.slice(base..base + 1);
4311 let in_view = table.slice(base + 1..base + 2);
4312 let out_view = table.slice(base + 2..base + 3);
4313 e.ssm_conv1d_fused_decode_b_view(
4314 &qkv_mixed.slice(r * qkv_w..(r + 1) * qkv_w),
4315 &conv_view,
4316 la.ssm_conv1d.float_data(),
4317 &mut conv_out,
4318 conv_dim,
4319 d_conv,
4320 1,
4321 )?;
4322 e.gdn_prep_decode_b_view(
4323 &conv_out,
4324 &beta_raw.slice(r * beta_w..(r + 1) * beta_w),
4325 &alpha.slice(r * alpha_w..(r + 1) * alpha_w),
4326 la.ssm_dt.float_data(),
4327 la.ssm_a.float_data(),
4328 &mut q_l2,
4329 &mut k_l2,
4330 &mut v_gd,
4331 &mut beta_b,
4332 &mut g_log,
4333 d_state,
4334 num_v,
4335 num_k,
4336 key_dim,
4337 eps,
4338 conv_dim,
4339 1,
4340 )?;
4341 let mut o_row = o_all.slice_mut(r * value_dim..(r + 1) * value_dim);
4342 e.gdn_scan_s128_batched_view(
4343 &q_l2, &k_l2, &v_gd, &g_log, &beta_b, &in_view, &out_view, &mut o_row,
4344 num_v, 1, gdn_scale,
4345 )?;
4346 {
4347 let rl = cache.recur[il].as_mut().unwrap();
4348 std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
4349 }
4350 if r + 1 < t {
4351 if let Some(states) = col_states.as_mut() {
4352 let recur = cache.recur[il]
4353 .as_ref()
4354 .ok_or("qwen35 linear verify layer has no recurrent state")?;
4355 states.push((
4356 e.clone_dtod(&recur.conv_state)?,
4357 e.clone_dtod(&recur.ssm_state)?,
4358 ));
4359 }
4360 }
4361 }
4362 if let (Some(checkpoint), Some(states)) = (ckpt.as_deref_mut(), col_states) {
4363 checkpoint.cols[il] = Some(states);
4364 }
4365
4366 // ---- batched gated norm + out-projection at m=T ----
4367 if e.uses_q8_1_fast(&la.ssm_out) {
4368 let (gq, gd) = e.gated_rmsnorm_q8_1(
4369 &o_all,
4370 la.ssm_norm.float_data(),
4371 &z,
4372 d_state,
4373 t * num_v,
4374 eps,
4375 )?;
4376 let g0 = e.zeros(0)?;
4377 e.matmul_pre(&la.ssm_out, &gq, &gd, &g0, t)?
4378 } else {
4379 let mut gn = e.uninit(t * value_dim)?;
4380 e.gated_rmsnorm(
4381 &o_all,
4382 la.ssm_norm.float_data(),
4383 &z,
4384 &mut gn,
4385 d_state,
4386 t * num_v,
4387 eps,
4388 )?;
4389 e.matmul(&la.ssm_out, &gn, t)?
4390 }
4391 }
4392 };
4393
4394 // ---- residual add + post_attn_norm + FFN at m=T (serving dispatch verbatim) ----
4395 let pnorm = layer.post_attn_norm.float_data();
4396 let mut x1 = e.uninit(t * n_embd)?;
4397 let mut zn = e.uninit(t * n_embd)?;
4398 e.add_rms_norm(&x, &mixed, pnorm, &mut x1, &mut zn, n_embd, t, eps)?;
4399 let ffn_out = match &layer.ffn {
4400 crate::hybrid::Ffn::Dense {
4401 ffn_gate,
4402 ffn_up,
4403 ffn_down,
4404 } => {
4405 assert!(
4406 self.cfg.m3.is_none(),
4407 "qwen35 t-parallel verify: M3 swigluoai FFN not yet batched"
4408 );
4409 let n_ff = ffn_gate.out_features();
4410 let (zq, zd) = e.quantize_q8_1(&zn, t, n_embd)?;
4411 let g = e.matmul_pre(ffn_gate, &zq, &zd, &zn, t)?;
4412 let u = e.matmul_pre(ffn_up, &zq, &zd, &zn, t)?;
4413 let mut act = e.uninit(t * n_ff)?;
4414 e.silu_mul(&g, &u, &mut act, t * n_ff)?;
4415 let (aq, ad) = e.quantize_q8_1(&act, t, n_ff)?;
4416 e.matmul_pre(ffn_down, &aq, &ad, &act, t)?
4417 }
4418 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il_zq8(e, m, &zn, None, t, il as u16)?,
4419 };
4420 let mut x2 = e.uninit(t * n_embd)?;
4421 e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
4422 // dspark drafter tap (no-op when no sink armed): post-layer residual verify rows
4423 self.dflash_tap(e, cache, il, &x2, t)?;
4424 x = x2;
4425 }
4426 Ok(x)
4427 }
4428
4429 /// PP-N STAGE SUBGRAPH of the verify trunk: layers `[lo, hi)` of `decode_step_t_core_stream`'s
4430 /// walk, verbatim. Enters with a MATERIALIZED `[T, n_embd]` residual (no pending fusion pair
4431 /// carried in from outside the range) and exits with the range's final residual materialized
4432 /// (the trailing add executed) — exactly the `decode_layers_eager(lo, hi)` contract, T rows
4433 /// instead of one.
4434 ///
4435 /// EXTRACTED (lane/pp2-spec 2026-08-06) rather than duplicated: `decode_step_t_core_stream` IS
4436 /// the single funnel every verify forward reaches, and its per-layer dispatch MIRRORING (norm
4437 /// fusion per layer, the t>=3/spec_m2 batched-linear window, the fused-q8 FFN chain, the
4438 /// decode-exact projections) is what makes verify bit-identical to eager decode. A second copy
4439 /// for the split arm is how those mirrors drift apart on the next lever. The unsplit body now
4440 /// calls this with `(0, n_layers)`, so the whole-trunk path and every stage range run the SAME
4441 /// code — there is no "split version" of the verify math.
4442 ///
4443 /// Bit-identity of a cut rests on the same kernel-check-pinned identity the eager arm's cut
4444 /// does — `add_rms_norm_q8_1 == add then rms_norm_q8_1` at nrows=T — because the ONLY thing a
4445 /// fence changes is that the cross-layer fusion carry breaks at `hi-1` and is re-materialized
4446 /// as an explicit `add`. `decode-batch-gate --mode ppspec` verifies end-to-end on real weights.
4447 #[allow(clippy::too_many_arguments)]
4448 fn verify_layers(
4449 &self,
4450 e: &Engine,
4451 mut x: CudaSlice<f32>,
4452 lo: usize,
4453 hi: usize,
4454 pos_d: &CudaSlice<i32>,
4455 pos0: usize,
4456 t: usize,
4457 cache: &mut Cache,
4458 mut ckpt: Option<&mut VerifyCkpt>,
4459 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
4460 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
4461 if self.cfg.step35.is_some() {
4462 if stream.is_some() {
4463 return Err(
4464 "step35 has no ROUND-STREAM verify arm (the device-counter _dc twins \
4465 cannot express the SWA offset KV view)"
4466 .into(),
4467 );
4468 }
4469 return self.step35_verify_batch_layers(e, x, lo, hi, pos0, t, cache);
4470 }
4471 if self.qwen35_serving_class() {
4472 if stream.is_some() {
4473 return Err("qwen35-family serving-class verify has no ROUND-STREAM arm".into());
4474 }
4475 return self.qwen35_verify_batch_layers(e, x, lo, hi, pos0, t, cache, ckpt.take());
4476 }
4477 let n_embd = self.cfg.n_embd as usize;
4478 let eps = self.cfg.rms_eps;
4479 // CROSS-LAYER ADD+NORM FUSION (lane/vt-fixes fix 2, mirroring decode_step_h's
4480 // launch-arc form): layer il's post-FFN residual add (x2 = x1 + ffn_out) and layer
4481 // il+1's attn_norm(+quantize) are consecutive row-wise ops — ONE add_rms_norm_q8_1
4482 // launch at nrows=t does all three (bit-identity pinned by the T-row kernel-check
4483 // arms). Carry the un-added (x1, ffn_out) pair; the fused launch materializes x2 (the
4484 // residual the next layer needs) as its `res` output. Falls back to the separate add
4485 // when the next layer is off the fused-q8 path.
4486 let mut pending: Option<(CudaSlice<f32>, CudaSlice<f32>)> = None;
4487 for il in lo..hi {
4488 let layer = &self.layers[il];
4489 // DISPATCH-MIRRORED attn-input RMSNorm (FP-order lesson #8): eager decode fuses the
4490 // 1024-thread rms_norm_q8_1 ONLY when every mixer projection is q8_1-fast; layers with
4491 // Float projections (ssm_beta/ssm_alpha on layers 1/2/4 of the 9B NVFP4 GGUF) take the
4492 // UNFUSED 256-thread rms_norm. The verify norm must mirror that PER-LAYER choice —
4493 // blockDim changes the sum-of-squares reduce order, and the ULP shift amplifies through
4494 // the GDN recurrence into argmax flips (measured: 9B text prompt, 1 ULP at layer 2 ->
4495 // 2.3e-1 logit maxdiff at the head -> K=1..8 divergence at a 0.03-margin token).
4496 let mixer_fast = self.mixer_in_q8_1_fast(e, &layer.mixer);
4497 let norm_fused = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err() && mixer_fast;
4498 // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2, 2026-08-03): when the norm is
4499 // dispatch-fused AND every consumer of `h` reads only its q8_1 form (Full mixer:
4500 // projections only; Linear mixer: the batched arm — the per-column fallback needs
4501 // f32 h), emit the attn-input norm DIRECTLY as q8_1 via `rms_norm_q8_1` at nrows=t
4502 // (row-indexed kernel — the T-row launch is the per-row m=1 program, kernel-check
4503 // pins bit-identity vs rms_norm_decode -> quantize_q8_1). Kills the standalone
4504 // quantize launch(es) + the f32 h HBM round-trip that decode never pays.
4505 // step35 (Full mixer) is the third case that needs f32 `h`: its verify arm is a
4506 // per-ROW replay of the eager decode mixer, whose `pre_q` contract is a single row —
4507 // a T-row q8_1 pair cannot be handed to it, and re-deriving per-row q8_1 from the f32
4508 // rows is exactly the dispatch being mirrored. Keep step35 on the unfused arm.
4509 let lin_q8_only = match &layer.mixer {
4510 Mixer::Linear(la) => {
4511 (t >= 3 || (t == 2 && spec_m2())) && e.uses_q8_1_fast(&la.ssm_out)
4512 }
4513 Mixer::Full(_) if self.cfg.step35.is_some() => false,
4514 _ => true,
4515 };
4516 // NOTE decode.rs's take()-first lesson: take the pending pair BEFORE branching so
4517 // a non-fused layer still performs the residual add.
4518 let taken = pending.take();
4519 let (h, h_q8) = if norm_fused && lin_q8_only {
4520 let pair = match taken {
4521 // fused add + attn_norm + q8_1: ONE launch resolves the carried residual
4522 // AND emits this layer's mixer input pre-quantized. res -> x2 (= new x).
4523 Some((x1p, f1p)) => {
4524 let mut x2 = vbuf(e, t * n_embd)?; // fully written (res output)
4525 let p = e.add_rms_norm_q8_1(
4526 &x1p,
4527 &f1p,
4528 layer.attn_norm.float_data(),
4529 &mut x2,
4530 n_embd,
4531 t,
4532 eps,
4533 )?;
4534 x = x2;
4535 p
4536 }
4537 None => e.rms_norm_q8_1(&x, layer.attn_norm.float_data(), n_embd, t, eps)?,
4538 };
4539 (e.zeros(0)?, Some(pair)) // h unused on this path (q8-only consumers)
4540 } else {
4541 if let Some((x1p, f1p)) = taken {
4542 let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
4543 e.add(&x1p, &f1p, &mut x2, t * n_embd)?;
4544 x = x2;
4545 }
4546 let mut h = vbuf(e, t * n_embd)?; // fully written by either rms_norm arm
4547 if norm_fused {
4548 e.rms_norm_decode(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
4549 } else {
4550 e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
4551 }
4552 (h, None)
4553 };
4554 let h_q8_ref = h_q8.as_ref().map(|(q, d)| (q, d));
4555
4556 let mixed = match &layer.mixer {
4557 Mixer::Full(fa) => self.full_attn_verify(
4558 e,
4559 fa,
4560 &h,
4561 h_q8_ref,
4562 pos_d,
4563 t,
4564 cache,
4565 il,
4566 stream.map(|(_, c)| c),
4567 )?,
4568 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
4569 Mixer::Linear(la) => {
4570 // BATCHED linear verify (2026-07-03, the MTP-profit lever): one T-token pass —
4571 // batched projections (weight read ONCE, hits the m=2-4 weight-resident matvec),
4572 // carried-state conv (ssm_conv1d_tm_state), GDN prep on the prefill kernels, and
4573 // ONE gdn_scan whose internal sequential t-loop is the SAME recurrence as T
4574 // chained T=1 steps (bit-identical). Falls back to the sequential per-column
4575 // chain when T < d_conv-1 (conv ring update needs T >= pad) — or when ANY
4576 // projection is off the q8_1 fast path: matmul_decode_exact would route a Float
4577 // tensor to cuBLAS at m=t (different FP accumulation than eager's per-token
4578 // GEMV), so mixed-dtype layers stay on the eager-identical per-column chain.
4579 // MEMRA_SPEC_M2 (lane/spec-m2): the t==2 batch rides the same arm — the conv
4580 // wrapper handles t<pad with a pure-copy ring rebuild; see spec_m2() header.
4581 if (t >= 3 || (t == 2 && spec_m2()))
4582 && mixer_fast
4583 && e.uses_q8_1_fast(&la.ssm_out)
4584 {
4585 let want = ckpt.is_some();
4586 let (out, stash) =
4587 self.linear_attn_verify_t(e, la, &h, h_q8_ref, t, cache, il, want)?;
4588 if let (Some(ck), Some(st)) = (ckpt.as_deref_mut(), stash) {
4589 ck.gdn[il] = Some(st);
4590 }
4591 out
4592 } else {
4593 let mut out = vbuf(e, t * n_embd)?; // every col written by copy_into
4594 let mut col_states: Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>> =
4595 if ckpt.is_some() && t >= 2 {
4596 Some(Vec::with_capacity(t - 1))
4597 } else {
4598 None
4599 };
4600 for col in 0..t {
4601 let mut h_col = vbuf(e, n_embd)?; // fully written by copy_view_into
4602 let src = h.slice(col * n_embd..(col + 1) * n_embd);
4603 e.copy_view_into(&mut h_col, 0, &src, n_embd)?;
4604 let m_col = self.linear_attn_decode(e, la, &h_col, cache, il)?;
4605 e.copy_into(&mut out, col * n_embd, &m_col, n_embd)?;
4606 // REPLAY-FREE ckpt: clone the chain's ACTUAL state after this column
4607 // (pure dtod — cannot change any computed value). Last column skipped:
4608 // rebuild targets are j <= t-1 columns.
4609 if let Some(cs) = col_states.as_mut() {
4610 if col + 1 < t {
4611 let rl = cache.recur[il].as_ref().unwrap();
4612 cs.push((
4613 e.clone_dtod(&rl.conv_state)?,
4614 e.clone_dtod(&rl.ssm_state)?,
4615 ));
4616 }
4617 }
4618 }
4619 if let (Some(ck), Some(cs)) = (ckpt.as_deref_mut(), col_states) {
4620 // ReplaySSM-assessment instrumentation (2026-07-30): the
4621 // per-column clones are the only true state snapshots left in
4622 // the verify (the batched path stashes INPUTS and replays).
4623 if std::env::var("MEMRA_SPEC_STATS").as_deref() == Ok("1") {
4624 static ONCE: std::sync::Once = std::sync::Once::new();
4625 let bytes: usize =
4626 cs.iter().map(|(c, s)| (c.len() + s.len()) * 4).sum();
4627 ONCE.call_once(|| eprintln!(
4628 "[verify-ckpt] per-column layer il={il}: {} clones, {:.2} MB/layer/round",
4629 cs.len(), bytes as f64 / 1e6));
4630 }
4631 ck.cols[il] = Some(cs);
4632 }
4633 out
4634 }
4635 }
4636 };
4637
4638 // DISPATCH-MIRRORED post-attn norm: eager residual_norm_ffn fuses add+norm+quant
4639 // (1024-thread add_rms_norm_q8_1) only for Dense FFNs whose gate+up are q8_1-fast;
4640 // otherwise (and for MoE) it runs the 256-thread fused add_rms_norm. Mirror per layer.
4641 let ffn_fuse = match &layer.ffn {
4642 crate::hybrid::Ffn::Dense {
4643 ffn_gate, ffn_up, ..
4644 } => {
4645 std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
4646 && e.uses_q8_1_fast(ffn_gate)
4647 && e.uses_q8_1_fast(ffn_up)
4648 }
4649 crate::hybrid::Ffn::Moe(_) => false,
4650 };
4651 // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): on the ffn_fuse path (Dense,
4652 // gate+up q8_1-fast, non-M3) the FFN input is emitted DIRECTLY as q8_1 by ONE
4653 // add_rms_norm_q8_1 launch at nrows=t (row-indexed kernel: the T-row launch is the
4654 // per-row m=1 program; kernel-check pins bit-identity vs the unfused
4655 // add_f32 -> rms_norm_decode -> quantize_q8_1 chain at T=2/4/5/8) — replacing the
4656 // add + rms_norm_decode launches AND the dual/singles' internal re-quantize.
4657 // M3's swigluoai must keep the f32 chain (the fused SwiGLU epilogue encodes plain
4658 // SiLU), mirroring residual_norm_ffn's m3 guard on the decode path.
4659 // step35: same guard per LAYER. A dense FFN's clamp is the SHEXP array (upstream's
4660 // one build_ffn serves dense + shared expert, llama-graph.cpp:1751), and verify MUST
4661 // mirror decode's dispatch or spec self-consistency fails.
4662 let dense_lim = self.cfg.clamp_shexp_at(il as u32);
4663 let fuse_q8 = ffn_fuse && self.cfg.m3.is_none() && dense_lim.is_none();
4664 let mut x1 = vbuf(e, t * n_embd)?; // fully written by add / add_rms_norm*
4665 let mut z = e.zeros(0)?; // replaced below on the unfused arms
4666 let z_q8 = if fuse_q8 {
4667 Some(e.add_rms_norm_q8_1(
4668 &x,
4669 &mixed,
4670 layer.post_attn_norm.float_data(),
4671 &mut x1,
4672 n_embd,
4673 t,
4674 eps,
4675 )?)
4676 } else {
4677 let mut zf = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode / add_rms_norm
4678 if ffn_fuse {
4679 e.add(&x, &mixed, &mut x1, t * n_embd)?;
4680 e.rms_norm_decode(
4681 &x1,
4682 layer.post_attn_norm.float_data(),
4683 &mut zf,
4684 n_embd,
4685 t,
4686 eps,
4687 )?;
4688 } else {
4689 e.add_rms_norm(
4690 &x,
4691 &mixed,
4692 layer.post_attn_norm.float_data(),
4693 &mut x1,
4694 &mut zf,
4695 n_embd,
4696 t,
4697 eps,
4698 )?;
4699 }
4700 z = zf;
4701 None
4702 };
4703 // DECODE-EXACT FFN projections: force MMVQ for gate/up/down at any T to match the
4704 // T=1 decode FP accumulation order. At T>=5 the generic matmul/matmul_pre falls to dp4a
4705 // (128-thread, different FP sum order). At T=2-4 the batched MMVQ is already bit-identical.
4706 let ffn_out = match &layer.ffn {
4707 crate::hybrid::Ffn::Dense {
4708 ffn_gate,
4709 ffn_up,
4710 ffn_down,
4711 } => {
4712 let n_ff = ffn_gate.out_features();
4713 if let Some((zq, zd)) = z_q8.as_ref() {
4714 // FUSED CHAIN (fix 2): pre-quantized z feeds the projections; the SwiGLU
4715 // epilogue emits act pre-quantized for ffn_down (silu_mul_scaled_q8_1,
4716 // bit-identical to silu_mul + quantize — kernel-check-pinned) with the
4717 // NVFP4 macro-scales folded (deferred-scale dual: y*s inline == the
4718 // scale_inplace store, value-exact) — the exact m=1 decode epilogue
4719 // structure at nrows=t.
4720 let pair =
4721 match e.matmul_decode_exact_dual_pre(ffn_gate, ffn_up, zq, zd, t)? {
4722 Some(((g, gs), (u, us))) => Some((g, gs, u, us)),
4723 None => None,
4724 };
4725 let (gate, gs, up, us) = match pair {
4726 Some(x4) => x4,
4727 None => (
4728 e.matmul_decode_exact_pre(ffn_gate, zq, zd, t)?,
4729 1.0, // scale already applied inside _pre
4730 e.matmul_decode_exact_pre(ffn_up, zq, zd, t)?,
4731 1.0,
4732 ),
4733 };
4734 if e.uses_q8_1_fast(ffn_down) {
4735 let (aq, ad) = e.silu_mul_scaled_q8_1(&gate, &up, gs, us, t * n_ff)?;
4736 e.matmul_decode_exact_pre(ffn_down, &aq, &ad, t)?
4737 } else {
4738 let mut act = vbuf(e, t * n_ff)?;
4739 e.silu_mul_scaled(&gate, &up, gs, us, &mut act, t * n_ff)?;
4740 e.matmul_decode_exact(ffn_down, &act, t)?
4741 }
4742 } else {
4743 // UNFUSED (pre-fix) chain — MoE-adjacent/M3/off-fast layers, unchanged.
4744 // DUAL gate+up batched twin (lane/verify-economics, 2026-08-02): one launch
4745 // for the pair at t=2..8 — bit-identical per (tensor,token,row) to the two
4746 // singles (kernel-check pins bitwise; MEMRA_SPEC_DUAL_T=0 reverts). None
4747 // (non-NVFP4 / t outside the tier / seam off) -> the two singles, unchanged.
4748 let (gate, up) =
4749 match e.matmul_decode_exact_dual(ffn_gate, ffn_up, &z, t)? {
4750 Some(pair) => pair,
4751 None => (
4752 e.matmul_decode_exact(ffn_gate, &z, t)?,
4753 e.matmul_decode_exact(ffn_up, &z, t)?,
4754 ),
4755 };
4756 let mut act = vbuf(e, t * n_ff)?; // fully written by ffn_act_lim
4757 Self::ffn_act_lim(
4758 e,
4759 &self.cfg,
4760 &gate,
4761 &up,
4762 1.0,
4763 1.0,
4764 dense_lim,
4765 &mut act,
4766 t * n_ff,
4767 )?;
4768 e.matmul_decode_exact(ffn_down, &act, t)?
4769 }
4770 }
4771 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, t, il as u16)?,
4772 };
4773 // CROSS-LAYER fusion: defer this layer's post-FFN residual add — the next layer's
4774 // fused-q8 attn norm folds it in (add_rms_norm_q8_1 == add; rms_norm; quantize,
4775 // kernel-check-pinned at nrows=T). Non-fused next layers add explicitly above.
4776 pending = Some((x1, ffn_out));
4777 }
4778 // RANGE's final add (no next norm INSIDE the range to fuse with; for the
4779 // whole-trunk call that is the last layer, whose next norm is output_norm — f32-out).
4780 if let Some((x1p, f1p)) = pending.take() {
4781 let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
4782 e.add(&x1p, &f1p, &mut x2, t * n_embd)?;
4783 x = x2;
4784 }
4785 Ok(x)
4786 }
4787 /// BATCHED linear-attn verify (T=K+1): the whole layer in ~10 launches instead of T x the
4788 /// T=1 decode chain (T x ~12 launches + T weight reads of the four projections). The GDN
4789 /// recurrence itself is inherently sequential — gdn_scan_s128 runs its internal t-loop with
4790 /// the SAME per-token math as chained T=1 calls (bit-identical state evolution); everything
4791 /// around it (projections, conv, prep, gated norm, out-proj) batches. Advances conv ring +
4792 /// ssm state exactly like T sequential decode steps.
4793 /// `want_stash`: additionally RETAIN the gdn-scan inputs (pure buffer keep-alives, zero extra
4794 /// kernels) so a partial accept can rebuild the state after any column prefix (REPLAY-FREE).
4795 #[allow(clippy::too_many_arguments)]
4796 fn linear_attn_verify_t(
4797 &self,
4798 e: &Engine,
4799 la: &LinearAttnLayer,
4800 h: &CudaSlice<f32>,
4801 h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
4802 t: usize,
4803 cache: &mut Cache,
4804 il: usize,
4805 want_stash: bool,
4806 ) -> Result<(CudaSlice<f32>, Option<GdnStash>), Box<dyn std::error::Error>> {
4807 let cfg = &self.cfg;
4808 let ssm = cfg.ssm.as_ref().unwrap();
4809 let d_state = ssm.state_size as usize;
4810 let num_k = ssm.group_count as usize;
4811 let num_v = ssm.time_step_rank as usize;
4812 let d_conv = ssm.conv_kernel as usize;
4813 let key_dim = d_state * num_k;
4814 let conv_dim = key_dim * 2 + d_state * num_v;
4815 let eps = cfg.rms_eps;
4816 let scale = 1.0 / (d_state as f32).sqrt();
4817
4818 // DECODE-EXACT projections: matmul_decode_exact forces the MMVQ (warp-per-row, 32-thread)
4819 // accumulation order for EVERY m, matching the T=1 decode path bit-for-bit. The generic
4820 // `matmul` at m>=5 falls to dp4a (128-thread, two-level reduce) which has a different FP
4821 // sum order — ULP differences propagate through gdn_scan and flip argmax on the 27B.
4822 // Q8 TRUNK-FUSION at T=1 (35B: wqkv+wqkv_gate both Q8_0): one fused2 launch, bit-identical
4823 // per (tensor,row) to the two m=1 MMVQ dispatches below — decode-exact contract holds.
4824 // VERIFY-TIER TRUNK FUSION (MEMRA_SPEC_FUSED_T, t=2-4): quantize h ONCE for every
4825 // fused-eligible same-input Q8_0 pair of this layer (35B wqkv+wqkv_gate; 9B
4826 // ssm_beta+ssm_alpha) — each fused2 batched launch then replaces two decode-exact
4827 // calls (each of which re-quantizes the same h + runs its own _b2/_b4 launch).
4828 // Bit-identical per (tensor,token,row) — see spec_fused_t().
4829 // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): `h_q8` = the attn-input norm emitted
4830 // directly as q8_1 by the caller's fused rms_norm_q8_1 (bit-identical to the unfused
4831 // chain, kernel-check-pinned). When present it REPLACES the standalone quantize below
4832 // and feeds every projection; the caller guaranteed all four input projections are
4833 // q8_1-fast. When absent, the old shared-quantize (fused-t window) stands.
4834 let h_q8_t = if h_q8.is_none()
4835 && spec_fused_t()
4836 && (2..=4).contains(&t)
4837 && ((e.uses_q8_1_fast(&la.wqkv) && e.uses_q8_1_fast(&la.wqkv_gate))
4838 || (e.uses_q8_1_fast(&la.ssm_beta) && e.uses_q8_1_fast(&la.ssm_alpha)))
4839 {
4840 Some(e.quantize_q8_1(h, t, cfg.n_embd as usize)?)
4841 } else {
4842 None
4843 };
4844 // one view: the caller's fused-norm q8 or this fn's own shared quantize.
4845 let hq8_any: Option<(&CudaSlice<i8>, &CudaSlice<f32>)> =
4846 h_q8.or(h_q8_t.as_ref().map(|(q, d)| (q, d)));
4847 let (qkv_mixed, z) = {
4848 let mut fused = None;
4849 if t == 1 && e.uses_q8_1_fast(&la.wqkv) && e.uses_q8_1_fast(&la.wqkv_gate) {
4850 let (hq, hd) = e.quantize_q8_1(h, 1, cfg.n_embd as usize)?;
4851 fused = e.matmul_q8_fused2(&la.wqkv, &la.wqkv_gate, &hq, &hd)?;
4852 } else if let Some((hq, hd)) = hq8_any {
4853 if spec_fused_t() && (2..=4).contains(&t) {
4854 fused = e.matmul_q8_fused2_t(&la.wqkv, &la.wqkv_gate, hq, hd, t)?;
4855 }
4856 }
4857 match (fused, hq8_any) {
4858 (Some(pair), _) => pair,
4859 (None, Some((hq, hd))) if h_q8.is_some() => (
4860 e.matmul_decode_exact_pre(&la.wqkv, hq, hd, t)?,
4861 e.matmul_decode_exact_pre(&la.wqkv_gate, hq, hd, t)?,
4862 ),
4863 (None, _) => (
4864 e.matmul_decode_exact(&la.wqkv, h, t)?,
4865 e.matmul_decode_exact(&la.wqkv_gate, h, t)?,
4866 ),
4867 }
4868 };
4869 // beta+alpha DUAL at T=1 (75% of p3 rounds run T=1 verify — p-min chain cuts): the dual
4870 // mr2 kernel is bit-identical per element to the m=1 MMVQ matmul_decode_exact dispatches
4871 // (same warp-per-row body, blockIdx.y picks the weight), so the decode-exact contract
4872 // holds; the run-spec battery is the arbiter. T>1 keeps the per-tensor decode-exact path.
4873 let (beta_raw, alpha) = if t == 1 {
4874 let (hq, hd) = e.quantize_q8_1(h, 1, cfg.n_embd as usize)?;
4875 match e.matmul_pre_dual_noscale(&la.ssm_beta, &la.ssm_alpha, &hq, &hd, 1)? {
4876 Some(((mut b, bs), (mut a, as_))) => {
4877 if bs != 1.0 {
4878 e.scale_inplace(&mut b, bs, la.ssm_beta.out_features())?;
4879 }
4880 if as_ != 1.0 {
4881 e.scale_inplace(&mut a, as_, la.ssm_alpha.out_features())?;
4882 }
4883 (b, a)
4884 }
4885 // Q8_0 fused2 twin (9B stores beta/alpha as Q8_0): DISPATCH-MIRRORS the eager
4886 // decode's beta_alpha closure — the fused body is qmatvec_q8_0_mmvq verbatim,
4887 // bit-identical per row (kernel-check rel=0.00e0 gate), so decode==verify holds.
4888 None => match e.matmul_q8_fused2(&la.ssm_beta, &la.ssm_alpha, &hq, &hd)? {
4889 Some((b, a)) => (b, a),
4890 None => (
4891 e.matmul_decode_exact(&la.ssm_beta, h, 1)?,
4892 e.matmul_decode_exact(&la.ssm_alpha, h, 1)?,
4893 ),
4894 },
4895 }
4896 } else {
4897 // fused-t twin (9B stores beta/alpha as Q8_0): same shared-quantize + one launch
4898 // contract as the wqkv pair above; 35B beta/alpha are Float -> None -> fallback.
4899 let mut nvfp4_fused = None;
4900 let mut q8_fused = None;
4901 if let Some((hq, hd)) = hq8_any {
4902 if t == 3 && std::env::var("MEMRA_NVFP4_AUX_DUAL").as_deref() != Ok("0") {
4903 nvfp4_fused =
4904 e.matmul_decode_exact_dual_pre(&la.ssm_beta, &la.ssm_alpha, hq, hd, t)?;
4905 if nvfp4_fused.is_some() && std::env::var("MEMRA_DEBUG").is_ok() {
4906 static ONCE: std::sync::Once = std::sync::Once::new();
4907 ONCE.call_once(|| {
4908 eprintln!("[memra] NVFP4 beta+alpha batched aux dual ENGAGED (t={t})")
4909 });
4910 }
4911 }
4912 if nvfp4_fused.is_none() && spec_fused_t() && (2..=4).contains(&t) {
4913 q8_fused = e.matmul_q8_fused2_t(&la.ssm_beta, &la.ssm_alpha, hq, hd, t)?;
4914 }
4915 }
4916 if let Some(((mut b, bs), (mut a, as_))) = nvfp4_fused {
4917 if bs != 1.0 {
4918 e.scale_inplace(&mut b, bs, t * la.ssm_beta.out_features())?;
4919 }
4920 if as_ != 1.0 {
4921 e.scale_inplace(&mut a, as_, t * la.ssm_alpha.out_features())?;
4922 }
4923 (b, a)
4924 } else if let Some(pair) = q8_fused {
4925 pair
4926 } else {
4927 match hq8_any {
4928 Some((hq, hd)) if h_q8.is_some() => (
4929 e.matmul_decode_exact_pre(&la.ssm_beta, hq, hd, t)?,
4930 e.matmul_decode_exact_pre(&la.ssm_alpha, hq, hd, t)?,
4931 ),
4932 _ => (
4933 e.matmul_decode_exact(&la.ssm_beta, h, t)?,
4934 e.matmul_decode_exact(&la.ssm_alpha, h, t)?,
4935 ),
4936 }
4937 }
4938 };
4939
4940 // conv with CARRIED state + ring roll (T >= pad rides the input-column update kernel;
4941 // T < pad — the MEMRA_SPEC_M2 t=2 arm — rolls via the pure-copy ring rebuild).
4942 let rl = cache.recur[il].as_mut().unwrap();
4943 let mut conv_out = e.uninit(conv_dim * t)?;
4944 e.ssm_conv1d_tm_state(
4945 &qkv_mixed,
4946 &mut rl.conv_state,
4947 la.ssm_conv1d.float_data(),
4948 &mut conv_out,
4949 conv_dim,
4950 t,
4951 d_conv,
4952 )?;
4953
4954 // GDN prep via the prefill kernels (repack + L2 + sigmoid + glog), T-wide.
4955 let mut q_g = e.uninit(d_state * num_v * t)?;
4956 let mut k_g = e.uninit(d_state * num_v * t)?;
4957 let mut v_g = e.uninit(d_state * num_v * t)?;
4958 e.qkv_to_gdn_repack(
4959 &conv_out, &mut q_g, &mut k_g, &mut v_g, d_state, num_v, num_k, key_dim, t,
4960 )?;
4961 let mut q_l2 = e.uninit(d_state * num_v * t)?;
4962 e.l2_norm_decode(&q_g, &mut q_l2, d_state, num_v * t, eps)?;
4963 let mut k_l2 = e.uninit(d_state * num_v * t)?;
4964 e.l2_norm_decode(&k_g, &mut k_l2, d_state, num_v * t, eps)?;
4965 let mut beta = e.uninit(t * num_v)?;
4966 e.sigmoid(&beta_raw, &mut beta, t * num_v)?;
4967 let mut g_log = e.uninit(t * num_v)?;
4968 e.gdn_glog(
4969 &alpha,
4970 la.ssm_dt.float_data(),
4971 la.ssm_a.float_data(),
4972 &mut g_log,
4973 num_v,
4974 t,
4975 )?;
4976
4977 // ONE gdn_scan over T tokens from the carried state (internal sequential loop ==
4978 // T chained T=1 steps). Ping-pong the resident buffers like eager decode.
4979 let mut o = e.uninit(d_state * num_v * t)?;
4980 {
4981 let crate::cache::RecurLayer {
4982 ssm_state,
4983 ssm_state_alt,
4984 ..
4985 } = rl;
4986 e.gdn_scan_s128(
4987 &q_l2,
4988 &k_l2,
4989 &v_g,
4990 &g_log,
4991 &beta,
4992 ssm_state,
4993 ssm_state_alt,
4994 &mut o,
4995 num_v,
4996 t,
4997 scale,
4998 )?;
4999 }
5000 std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
5001
5002 // gated RMSNorm + out projection, T-wide. FUSED-QUANTIZE ARM (lane/vt-fixes fix 2,
5003 // mirroring the T=1 decode's launch-arc form): when ssm_out rides the q8_1 fast path,
5004 // emit q8_1 straight from the gated norm at nrows=num_v*t (row-indexed kernel, the
5005 // T-wide launch is the per-row program; kernel-check pins bit-identity vs
5006 // gated_rmsnorm -> quantize_q8_1 at T=1 and T=5) and feed the decode-exact dispatch
5007 // pre-quantized — one launch replaces norm + quantize. Fallback = the f32 chain.
5008 let out = if e.uses_q8_1_fast(&la.ssm_out) {
5009 let (gq, gd) =
5010 e.gated_rmsnorm_q8_1(&o, la.ssm_norm.float_data(), &z, d_state, num_v * t, eps)?;
5011 e.matmul_decode_exact_pre(&la.ssm_out, &gq, &gd, t)?
5012 } else {
5013 let mut gn = e.uninit(d_state * num_v * t)?;
5014 e.gated_rmsnorm(
5015 &o,
5016 la.ssm_norm.float_data(),
5017 &z,
5018 &mut gn,
5019 d_state,
5020 num_v * t,
5021 eps,
5022 )?;
5023 // DECODE-EXACT out-projection: same MMVQ path as the T=1 decode (ssm_out at m>=5
5024 // would fall to dp4a with a different FP reduction order — same class of bug as
5025 // the input projs).
5026 e.matmul_decode_exact(&la.ssm_out, &gn, t)?
5027 };
5028 let stash = if want_stash {
5029 Some(GdnStash {
5030 qkv_mixed,
5031 q_l2,
5032 k_l2,
5033 v_g,
5034 g_log,
5035 beta,
5036 })
5037 } else {
5038 None
5039 };
5040 Ok((out, stash))
5041 }
5042
5043 /// REPLAY-FREE partial-accept commit (2026-07-03): make the cache state == "committed through
5044 /// the first `j` verify columns" WITHOUT the legacy rollback + duplicate trunk replay.
5045 /// - Full-attn KV: truncate len to snapshot + j. The verify's appended rows for those columns
5046 /// are bit-identical to what an eager T=1 chain writes (the decode-exact contract the
5047 /// verify-probe gates), so keeping them == replaying them.
5048 /// - Linear layers, batched path: rebuild the conv ring by PURE COPIES (ring holds raw input
5049 /// columns) and the ssm state by a prefix re-run of the SAME gdn_scan kernel (t=j) from the
5050 /// snapshot state over the stash's identical inputs — the kernel's t-loop carries state in
5051 /// registers and writes it once at the end, so iterations 0..j-1 are independent of T:
5052 /// bit-identical to the verify's own state after j tokens == the eager chain state.
5053 /// - Linear layers, per-column path: restore the cloned actual state after column j-1.
5054 /// Caller guarantees 1 <= j <= t-1 (j==0 rounds take the legacy rollback; j==t is full accept).
5055 fn commit_verified_prefix(
5056 &self,
5057 e: &Engine,
5058 cache: &mut Cache,
5059 snap: &crate::cache::CacheSnapshot,
5060 ckpt: &VerifyCkpt,
5061 j: usize,
5062 kv_lens_done: bool,
5063 dev_j: Option<(&CudaSlice<u32>, usize, usize)>,
5064 ) -> Result<(), Box<dyn std::error::Error>> {
5065 let cfg = &self.cfg;
5066 let ssm = cfg.ssm.as_ref().unwrap();
5067 let d_state = ssm.state_size as usize;
5068 let num_k = ssm.group_count as usize;
5069 let num_v = ssm.time_step_rank as usize;
5070 let d_conv = ssm.conv_kernel as usize;
5071 let conv_dim = d_state * num_k * 2 + d_state * num_v;
5072 let scale = 1.0 / (d_state as f32).sqrt();
5073 for il in 0..self.layers.len() {
5074 if let (Some(kvl), Some(saved)) = (cache.kv[il].as_mut(), snap.kv_len[il]) {
5075 kvl.len = saved + j;
5076 // devacc 3a: spec_rollback_kv already wrote len_d on-device (same value).
5077 if !kv_lens_done {
5078 e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
5079 }
5080 }
5081 if let Some(rl) = cache.recur[il].as_mut() {
5082 if let Some(st) = &ckpt.gdn[il] {
5083 let ring_old = snap.conv[il].as_ref().expect("snapshot missing conv");
5084 let state_in = snap.ssm[il].as_ref().expect("snapshot missing ssm");
5085 if let Some((acc, base, t_v)) = dev_j {
5086 // 3b: j read on-device (_dc twins, same bodies; full accept early-exits).
5087 e.ssm_conv_ring_rebuild_dc(
5088 &st.qkv_mixed,
5089 ring_old,
5090 &mut rl.conv_state,
5091 conv_dim,
5092 acc,
5093 base,
5094 t_v,
5095 d_conv,
5096 )?;
5097 let mut o = e.uninit(d_state * num_v * j.max(1))?;
5098 e.gdn_scan_s128_dc(
5099 &st.q_l2,
5100 &st.k_l2,
5101 &st.v_g,
5102 &st.g_log,
5103 &st.beta,
5104 state_in,
5105 &mut rl.ssm_state,
5106 &mut o,
5107 num_v,
5108 acc,
5109 base,
5110 t_v,
5111 scale,
5112 )?;
5113 } else {
5114 e.ssm_conv_ring_rebuild(
5115 &st.qkv_mixed,
5116 ring_old,
5117 &mut rl.conv_state,
5118 conv_dim,
5119 j,
5120 d_conv,
5121 )?;
5122 let mut o = e.uninit(d_state * num_v * j)?; // scan output, discarded
5123 e.gdn_scan_s128(
5124 &st.q_l2,
5125 &st.k_l2,
5126 &st.v_g,
5127 &st.g_log,
5128 &st.beta,
5129 state_in,
5130 &mut rl.ssm_state,
5131 &mut o,
5132 num_v,
5133 j,
5134 scale,
5135 )?;
5136 }
5137 } else if let Some(cols) = &ckpt.cols[il] {
5138 let (c, s) = &cols[j - 1];
5139 e.copy_into(&mut rl.conv_state, 0, c, c.len())?;
5140 e.copy_into(&mut rl.ssm_state, 0, s, s.len())?;
5141 } else {
5142 return Err(
5143 "commit_verified_prefix: verify ckpt missing for linear layer".into(),
5144 );
5145 }
5146 }
5147 }
5148 cache.pos = snap.pos + j;
5149 Ok(())
5150 }
5151
5152 /// ROUND-STREAM: recur restore with device-j (the _dc twins; full accept early-exits
5153 /// in-kernel). Requires the batched-linear stash on every linear layer (stream gate).
5154 fn commit_verified_prefix_stream(
5155 &self,
5156 e: &Engine,
5157 cache: &mut Cache,
5158 snap: &crate::cache::CacheSnapshot,
5159 ckpt: &VerifyCkpt,
5160 acc: &CudaSlice<u32>,
5161 base: usize,
5162 t_v: usize,
5163 ) -> Result<(), Box<dyn std::error::Error>> {
5164 let cfg = &self.cfg;
5165 let ssm = cfg.ssm.as_ref().unwrap();
5166 let d_state = ssm.state_size as usize;
5167 let num_k = ssm.group_count as usize;
5168 let num_v = ssm.time_step_rank as usize;
5169 let d_conv = ssm.conv_kernel as usize;
5170 let conv_dim = d_state * num_k * 2 + d_state * num_v;
5171 let scale = 1.0 / (d_state as f32).sqrt();
5172 for il in 0..self.layers.len() {
5173 if let Some(rl) = cache.recur[il].as_mut() {
5174 let st = ckpt.gdn[il]
5175 .as_ref()
5176 .ok_or("stream restore: batched-linear stash missing")?;
5177 let ring_old = snap.conv[il].as_ref().expect("snapshot missing conv");
5178 let state_in = snap.ssm[il].as_ref().expect("snapshot missing ssm");
5179 e.ssm_conv_ring_rebuild_dc(
5180 &st.qkv_mixed,
5181 ring_old,
5182 &mut rl.conv_state,
5183 conv_dim,
5184 acc,
5185 base,
5186 t_v,
5187 d_conv,
5188 )?;
5189 let mut o = e.uninit(d_state * num_v * t_v)?;
5190 e.gdn_scan_s128_dc(
5191 &st.q_l2,
5192 &st.k_l2,
5193 &st.v_g,
5194 &st.g_log,
5195 &st.beta,
5196 state_in,
5197 &mut rl.ssm_state,
5198 &mut o,
5199 num_v,
5200 acc,
5201 base,
5202 t_v,
5203 scale,
5204 )?;
5205 }
5206 }
5207 Ok(())
5208 }
5209
5210 /// EAGLE3 aux-capturing verify forward over `tokens` (T) — mirrors `decode_step_t_h` exactly
5211 /// (same KV append, same causal verify, same recur advance) but ALSO clones the aux residual-
5212 /// stream hiddens (blocks in `aux_layers`) for TWO columns: the LAST column (always) and the
5213 /// optional `pred_col` (the EAGLE seed = bonus's predecessor). Returns
5214 /// (all_T_logits host, last_col_aux, pred_col_aux?). Used by the EAGLE3 orchestrator's commit.
5215 pub fn decode_step_t_aux2(
5216 &self,
5217 e: &Engine,
5218 tokens: &[u32],
5219 pos0: usize,
5220 cache: &mut Cache,
5221 aux_layers: &[usize],
5222 pred_col: Option<usize>,
5223 ) -> Result<
5224 (Vec<f32>, Vec<CudaSlice<f32>>, Option<Vec<CudaSlice<f32>>>),
5225 Box<dyn std::error::Error>,
5226 > {
5227 let cfg = &self.cfg;
5228 let n_embd = cfg.n_embd as usize;
5229 let eps = cfg.rms_eps;
5230 let t = tokens.len();
5231 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
5232 let pos_d = e.htod_i32(&pos_vec)?;
5233 let mut x = e.htod(&self.embd.gather(n_embd, tokens))?;
5234 let mut aux_last: Vec<CudaSlice<f32>> = Vec::with_capacity(aux_layers.len());
5235 let mut aux_pred: Vec<CudaSlice<f32>> = Vec::new();
5236 let want_pred = pred_col.is_some();
5237
5238 for (il, layer) in self.layers.iter().enumerate() {
5239 // DISPATCH-MIRRORED norms (FP-order lesson #8) — see decode_step_t_h_emb.
5240 let mixer_fast = self.mixer_in_q8_1_fast(e, &layer.mixer);
5241 let norm_fused = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err() && mixer_fast;
5242 let mut h = vbuf(e, t * n_embd)?; // fully written by either rms_norm arm
5243 if norm_fused {
5244 e.rms_norm_decode(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
5245 } else {
5246 e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
5247 }
5248 let mixed = match &layer.mixer {
5249 Mixer::Full(fa) => {
5250 self.full_attn_verify(e, fa, &h, None, &pos_d, t, cache, il, None)?
5251 }
5252 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
5253 Mixer::Linear(la) => {
5254 let mut out = e.zeros(t * n_embd)?;
5255 for col in 0..t {
5256 let mut h_col = e.zeros(n_embd)?;
5257 let src = h.slice(col * n_embd..(col + 1) * n_embd);
5258 e.copy_view_into(&mut h_col, 0, &src, n_embd)?;
5259 let m_col = self.linear_attn_decode(e, la, &h_col, cache, il)?;
5260 e.copy_into(&mut out, col * n_embd, &m_col, n_embd)?;
5261 }
5262 out
5263 }
5264 };
5265 let ffn_fuse = match &layer.ffn {
5266 crate::hybrid::Ffn::Dense {
5267 ffn_gate, ffn_up, ..
5268 } => {
5269 std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
5270 && e.uses_q8_1_fast(ffn_gate)
5271 && e.uses_q8_1_fast(ffn_up)
5272 }
5273 crate::hybrid::Ffn::Moe(_) => false,
5274 };
5275 let mut x1 = vbuf(e, t * n_embd)?; // fully written by add / add_rms_norm
5276 let mut z = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode / add_rms_norm
5277 if ffn_fuse {
5278 e.add(&x, &mixed, &mut x1, t * n_embd)?;
5279 e.rms_norm_decode(
5280 &x1,
5281 layer.post_attn_norm.float_data(),
5282 &mut z,
5283 n_embd,
5284 t,
5285 eps,
5286 )?;
5287 } else {
5288 e.add_rms_norm(
5289 &x,
5290 &mixed,
5291 layer.post_attn_norm.float_data(),
5292 &mut x1,
5293 &mut z,
5294 n_embd,
5295 t,
5296 eps,
5297 )?;
5298 }
5299 let ffn_out = match &layer.ffn {
5300 crate::hybrid::Ffn::Dense {
5301 ffn_gate,
5302 ffn_up,
5303 ffn_down,
5304 } => {
5305 let n_ff = ffn_gate.out_features();
5306 let gate = e.matmul_decode_exact(ffn_gate, &z, t)?;
5307 let up = e.matmul_decode_exact(ffn_up, &z, t)?;
5308 let mut act = vbuf(e, t * n_ff)?; // fully written by ffn_act_lim
5309 // dense FFN clamp = the SHEXP array (upstream build_ffn serves both).
5310 Self::ffn_act_lim(
5311 e,
5312 &self.cfg,
5313 &gate,
5314 &up,
5315 1.0,
5316 1.0,
5317 self.cfg.clamp_shexp_at(il as u32),
5318 &mut act,
5319 t * n_ff,
5320 )?;
5321 e.matmul_decode_exact(ffn_down, &act, t)?
5322 }
5323 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, t, il as u16)?,
5324 };
5325 let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
5326 e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
5327 if aux_layers.contains(&il) {
5328 let mut a = e.zeros(n_embd)?;
5329 e.copy_view_into(&mut a, 0, &x2.slice((t - 1) * n_embd..t * n_embd), n_embd)?;
5330 aux_last.push(a);
5331 if let Some(pc) = pred_col {
5332 let mut ap = e.zeros(n_embd)?;
5333 e.copy_view_into(
5334 &mut ap,
5335 0,
5336 &x2.slice(pc * n_embd..(pc + 1) * n_embd),
5337 n_embd,
5338 )?;
5339 aux_pred.push(ap);
5340 }
5341 }
5342 x = x2;
5343 }
5344 let mut hn = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode
5345 e.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
5346 let logits = e.matmul_decode_exact(&self.output, &hn, t)?;
5347 let host = e.dtoh(&logits)?;
5348 cache.pos += t;
5349 Ok((
5350 host,
5351 aux_last,
5352 if want_pred { Some(aux_pred) } else { None },
5353 ))
5354 }
5355
5356 /// step35 SPEC-VERIFY attention over T query tokens — a per-row REPLAY of the eager
5357 /// `step35_decode_attn`.
5358 ///
5359 /// WHY A REPLAY AND NOT A BATCHED TWIN. The verify's whole job is to be bit-identical to what
5360 /// the eager decode would have computed for the same tokens; that is what makes greedy spec
5361 /// decode exact (run-spec asserts token identity for K=1..8). Every other verify arm in this
5362 /// file earns that identity by carefully mirroring dispatch (`matmul_decode_exact` to force
5363 /// MMVQ at any m, per-layer `ffn_fuse` mirroring, per-row `fa_decode` key bounds). step35
5364 /// stacks FOUR more per-layer degrees of freedom on top of that — per-layer `n_head`
5365 /// (64 full / 96 SWA), per-layer rotary width (64 full / 128 SWA), per-layer rope base, and a
5366 /// SEPARATE `attn_gate` tensor whose projection shares the attn-normed input — and its SWA
5367 /// layers attend through a token-OFFSET view whose offset is a function of the ABSOLUTE
5368 /// position of each query row. A batched twin would have to reproduce all of that AND the
5369 /// per-row offset in one launch; the offset alone rules out the existing rows kernels (they
5370 /// take one `base_len`, not a per-row offset).
5371 ///
5372 /// So this arm calls the eager path itself, once per row, on the same cache. Identity is then
5373 /// true BY CONSTRUCTION rather than by mirroring: row r runs exactly the kernel sequence that
5374 /// eager decode step r runs (same projections, same q8_1 fusion decision, same append, same
5375 /// view arithmetic, same `fa_decode_kvmod`, same gate), because it IS that code. Cost: T x the
5376 /// eager decode mixer instead of one batched pass — the same trade the generic arm's `else`
5377 /// per-row loop already accepts when `fa_rows_eligible` says no. Correctness first; a batched
5378 /// step35 twin is a perf lane's job and must be gated against this arm.
5379 ///
5380 /// The `h_q8` pre-quantized pair from the caller's fused norm is NOT forwarded: it is a
5381 /// T-row buffer and `step35_decode_attn`'s `pre_q` contract is one row. Instead each row's
5382 /// f32 `h` slice is handed over and the callee re-derives its own q8_1 exactly as eager decode
5383 /// does (`quantize_q8_1(h, 1, n_embd)`) — which is the dispatch being mirrored. Callers that
5384 /// took the fused arm therefore MUST still pass a live `h`; `step35_verify` asserts that.
5385 #[allow(clippy::too_many_arguments)]
5386 fn step35_verify(
5387 &self,
5388 e: &Engine,
5389 fa: &FullAttnLayer,
5390 h: &CudaSlice<f32>,
5391 h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
5392 t: usize,
5393 cache: &mut Cache,
5394 il: usize,
5395 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5396 let n_embd = self.cfg.n_embd as usize;
5397 // The fused (h-less) attn-norm arm hands `h` as a zero-length placeholder. This arm needs
5398 // the f32 rows, so the caller must not take that lever for step35 — enforced at the call
5399 // site by the `Mixer::Full(_) if self.cfg.step35.is_some() => false` arm of
5400 // `lin_q8_only` in `decode_step_t_core_stream`, and asserted here so a future caller
5401 // cannot regress it into silently reading an empty buffer.
5402 assert_eq!(
5403 h.len(),
5404 t * n_embd,
5405 "step35_verify needs the f32 attn-normed rows ([t*n_embd]); the caller took the \
5406 fused q8-only norm arm (h_q8={}) — step35 must stay on the unfused arm",
5407 h_q8.is_some()
5408 );
5409 // ROW WIDTH IS n_embd, NOT n_head*head_dim: `step35_decode_attn` returns the mixer output
5410 // AFTER `wo`, so a row is [n_embd] — the same contract the generic arm's
5411 // `matmul_decode_exact(&fa.wo, &attn_g, t)` return has. Sizing this buffer from the
5412 // per-layer head geometry (8192 on full-attn, 12288 on SWA) instead overran the row on the
5413 // FIRST copy and panicked inside `copy_into`'s `CudaView::slice` unwrap
5414 // (raw/mtp-bt-20260806T212127Z.log frames 12-13).
5415 let mut out = vbuf(e, t * n_embd)?; // each row fully written by the copy below
5416 for r in 0..t {
5417 // Absolute position of this query row. `cache.pos` is the committed length at round
5418 // start and every row before r has already been appended by this loop, so the r-th
5419 // verify token sits at cache.pos + r — the same position eager decode would give it.
5420 let pos_d = e.htod_i32(&[(cache.pos + r) as i32])?;
5421 let mut h_row = vbuf(e, n_embd)?; // fully written by copy_view_into
5422 e.copy_view_into(
5423 &mut h_row,
5424 0,
5425 &h.slice(r * n_embd..(r + 1) * n_embd),
5426 n_embd,
5427 )?;
5428 // THE eager decode mixer: appends this row's K/V at kvl.len, advances it, then
5429 // attends over the (SWA-offset) view. Post-`wo`, same contract as this fn returns.
5430 let o = self.step35_decode_attn(e, fa, il, &h_row, None, &pos_d, cache)?;
5431 debug_assert_eq!(
5432 o.len(),
5433 n_embd,
5434 "step35_decode_attn returns post-wo [n_embd]"
5435 );
5436 e.copy_into(&mut out, r * n_embd, &o, n_embd)?;
5437 }
5438 Ok(out)
5439 }
5440
5441 /// Full-attention mixer over T query tokens with a GROWING resident KV (verify path, §D.3).
5442 /// Appends the T new K/V columns to cache.kv[il] then attends causally over [0..len) via
5443 /// fa_prefill. Token-major [T, kv_dim] projection layout == cache row layout (single copy).
5444 #[allow(clippy::too_many_arguments)]
5445 fn full_attn_verify(
5446 &self,
5447 e: &Engine,
5448 fa: &FullAttnLayer,
5449 h: &CudaSlice<f32>,
5450 h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
5451 pos_d: &CudaSlice<i32>,
5452 t: usize,
5453 cache: &mut Cache,
5454 il: usize,
5455 stream_ctr: Option<&CudaSlice<i32>>,
5456 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5457 // step35: the generic geometry below is wrong for this arch (per-layer n_head, partial
5458 // per-layer rope, the SWA offset view, and a SEPARATE head-wise gate tensor), so it takes
5459 // its own arm. A verify that silently computes different attention than decode defeats the
5460 // whole self-consistency gate, so the arm is a per-row REPLAY of `step35_decode_attn`
5461 // rather than a batched twin — see `step35_verify` for why that is the exactness-correct
5462 // shape and not laziness.
5463 if self.cfg.step35.is_some() {
5464 if stream_ctr.is_some() {
5465 return Err(
5466 "step35 has no ROUND-STREAM verify arm (the device-counter _dc twins \
5467 cannot express the SWA offset KV view; same root cause as the dc \
5468 decode refusal) — run spec without the stream arm"
5469 .into(),
5470 );
5471 }
5472 return self.step35_verify(e, fa, h, h_q8, t, cache, il);
5473 }
5474 let cfg = &self.cfg;
5475 let geometry = cfg.full_attention_geometry_at(il as u32);
5476 let n_head = geometry.n_head as usize;
5477 let n_head_kv = geometry.n_head_kv as usize;
5478 let head_dim = geometry.head_dim_k as usize;
5479 let eps = cfg.rms_eps;
5480 let scale = geometry.attention_scale();
5481 let n_embd = cfg.n_embd as usize;
5482
5483 // DECODE-EXACT Q/K/V projections: matmul_decode_exact forces the MMVQ (warp-per-row) path
5484 // for every m, matching the T=1 decode's FP accumulation order. matmul_pre at m>=5 would
5485 // fall to dp4a (128-thread, two-level reduce) with a different FP sum order.
5486 // Q8 TRUNK-FUSION at T=1: DISPATCH-MIRRORS the eager decode's fused3 (bit-identical body).
5487 // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): `h_q8` = the attn-input norm's q8_1
5488 // form emitted by the fused rms_norm_q8_1 (bit-identical to rms_norm_decode ->
5489 // quantize_q8_1, kernel-check-pinned). When present (caller checked mixer q8_1-fast),
5490 // every projection consumes it — `h` may be a zero-len placeholder and must not be read.
5491 let (qf, mut k, v) = {
5492 let mut fused = None;
5493 let qkv_fast =
5494 e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk) && e.uses_q8_1_fast(&fa.wv);
5495 if t == 1 && qkv_fast {
5496 let (hq_o, hd_o);
5497 let (hq, hd): (&CudaSlice<i8>, &CudaSlice<f32>) = match h_q8 {
5498 Some(p) => p,
5499 None => {
5500 (hq_o, hd_o) = e.quantize_q8_1(h, 1, n_embd)?;
5501 (&hq_o, &hd_o)
5502 }
5503 };
5504 fused = e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, hq, hd)?;
5505 } else if spec_fused_t() && (2..=4).contains(&t) && qkv_fast {
5506 // VERIFY-TIER TRUNK FUSION (MEMRA_SPEC_FUSED_T): one shared quantize + one
5507 // fused3 batched launch replaces three decode-exact calls (3 re-quantizes of
5508 // the same h + 3 _b2/_b4 launches). Bit-identical per (tensor,token,row).
5509 let (hq_o, hd_o);
5510 let (hq, hd): (&CudaSlice<i8>, &CudaSlice<f32>) = match h_q8 {
5511 Some(p) => p,
5512 None => {
5513 (hq_o, hd_o) = e.quantize_q8_1(h, t, n_embd)?;
5514 (&hq_o, &hd_o)
5515 }
5516 };
5517 fused = e.matmul_q8_fused3_t(&fa.wq, &fa.wk, &fa.wv, hq, hd, t)?;
5518 }
5519 match (fused, h_q8) {
5520 (Some(triple), _) => triple,
5521 // shared pre-quantized activation (q8_1-fast guaranteed by the caller): the
5522 // decode-exact dispatch consumes (hq, hd) instead of re-quantizing 3x.
5523 (None, Some((hq, hd))) if qkv_fast => (
5524 e.matmul_decode_exact_pre(&fa.wq, hq, hd, t)?,
5525 e.matmul_decode_exact_pre(&fa.wk, hq, hd, t)?,
5526 e.matmul_decode_exact_pre(&fa.wv, hq, hd, t)?,
5527 ),
5528 (None, _) => (
5529 e.matmul_decode_exact(&fa.wq, h, t)?,
5530 e.matmul_decode_exact(&fa.wk, h, t)?,
5531 e.matmul_decode_exact(&fa.wv, h, t)?,
5532 ),
5533 }
5534 };
5535 // M3/Hy3 have no attention output gate — wq out is exactly q; skip the split.
5536 let gated = geometry.attention_gate == memra_gguf::config::AttentionGateKind::FusedQ;
5537 let (mut q, gate) = if gated {
5538 let mut q = vbuf(e, t * n_head * head_dim)?; // fully written by q_gate_split
5539 let mut gate = vbuf(e, t * n_head * head_dim)?; // fully written by q_gate_split
5540 e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, t)?;
5541 (q, Some(gate))
5542 } else {
5543 (qf, None)
5544 };
5545
5546 let mut qn = vbuf(e, t * n_head * head_dim)?; // fully written by rms_norm
5547 e.rms_norm(
5548 &q,
5549 fa.q_norm.float_data(),
5550 &mut qn,
5551 head_dim,
5552 n_head * t,
5553 eps,
5554 )?;
5555 q = qn;
5556 let mut kn = vbuf(e, t * n_head_kv * head_dim)?; // fully written by rms_norm
5557 e.rms_norm(
5558 &k,
5559 fa.k_norm.float_data(),
5560 &mut kn,
5561 head_dim,
5562 n_head_kv * t,
5563 eps,
5564 )?;
5565 k = kn;
5566 let rope_dims = geometry.n_rot as usize;
5567 e.rope_neox(
5568 &mut q,
5569 pos_d,
5570 head_dim,
5571 rope_dims,
5572 n_head,
5573 t,
5574 geometry.rope_base,
5575 1.0,
5576 )?;
5577 e.rope_neox(
5578 &mut k,
5579 pos_d,
5580 head_dim,
5581 rope_dims,
5582 n_head_kv,
5583 t,
5584 geometry.rope_base,
5585 1.0,
5586 )?;
5587
5588 // append T new K/V columns to the resident QUANTIZED cache. k/v are token-major [T, kv_dim]
5589 // f32; append-quantize each of the T token rows into the byte cache (q8_0 K / q5_1 V).
5590 let kvl = cache.kv[il].as_mut().unwrap();
5591 let (kv_dim_k, kv_dim_v, ktb, vtb) =
5592 (kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes, kvl.v_tok_bytes);
5593 if let Some(ctr) = stream_ctr {
5594 // stream: ONE batched append at the device counter (rows kernel = the per-view warp
5595 // math on a (block, token) grid, documented byte-identical); host len is a stale
5596 // LOWER BOUND under pre-issue (drain reconciles it).
5597 e.append_kv_quantized_rows_dc(
5598 &k,
5599 &v,
5600 &mut kvl.k,
5601 &mut kvl.v,
5602 ctr,
5603 t,
5604 kv_dim_k,
5605 kv_dim_v,
5606 ktb,
5607 vtb,
5608 crate::Engine::kv_fp8_on(),
5609 )?;
5610 } else {
5611 for i in 0..t {
5612 let k_row = k.slice(i * kv_dim_k..(i + 1) * kv_dim_k);
5613 let v_row = v.slice(i * kv_dim_v..(i + 1) * kv_dim_v);
5614 e.append_kv_quantized_view(
5615 &k_row,
5616 &v_row,
5617 &mut kvl.k,
5618 &mut kvl.v,
5619 kvl.len + i,
5620 kv_dim_k,
5621 kv_dim_v,
5622 ktb,
5623 vtb,
5624 crate::Engine::kv_fp8_on(),
5625 )?;
5626 }
5627 kvl.len += t;
5628 }
5629
5630 // BIT-IDENTICAL VERIFY ATTENTION (spec-exactness fix): the FP accumulation order must be
5631 // byte-for-byte identical to the eager decode path. fa_prefill uses a different tile size
5632 // (BLOCK_Q=64, BK=32) and online-softmax structure than fa_decode's split-K + combine,
5633 // which changes FP summation order and can flip argmax at tight logit margins. Query row r
5634 // attends to keys [0..base_len+r+1) — each successive row sees one more key (the causal
5635 // property). This matches eager: decode appends k at len, then fa_decode sees t_kv = len+1
5636 // keys. The verify appends all T tokens first but bounds the key range per row.
5637 //
5638 // MULTI-ROW FUSED PATH (the long-ctx spec fix, 2026-07-03): when every row takes the vec
5639 // kernel (base_len+1 >= FA_VEC_MIN_TKV), ONE fa_decode_rows launch executes the exact
5640 // per-row program for all T rows (grid.z = row, per-row n_splits from the same
5641 // fa_split_keys formula) — replacing T x (2 launches + 2 dtod copies + 5 partial allocs)
5642 // and multiplying resident CTAs by T on a latency-bound kernel. Bit-identical per row by
5643 // construction; kernel-check pins rows-vs-loop byte identity, run-spec is the end gate.
5644 // Short ctx (any row below the vec crossover) and MEMRA_NO_FA_VEC/MEMRA_FA_ROWS_OFF keep the
5645 // per-row loop (whose fa_decode picks scalar/vec per row exactly like eager decode).
5646 let mut attn = vbuf(e, t * n_head * head_dim)?; // fully written by every FA arm below
5647 let base_len = kvl.len - t; // KV len BEFORE this round's T tokens were appended
5648 // T=1 INCLUDED (2026-07-05): p-min cuts the draft to 1 in ~75% of rounds on hard
5649 // (agentic) content — the old t>1 gate sent those rounds to the per-row loop (262us/row
5650 // + q-row copy + per-row allocs vs 93us/row through the fused kernel at grid.z=1, same
5651 // program). nsys accounting: 1088 of 1456 verify FA launches were T=1 escapees.
5652 // LEAN T=1 ARM (MEMRA_SPEC_LEAN, close35): at t==1, q IS one row and fa_decode on it is
5653 // the EXACT eager decode dispatch (vec_q_v2 + combine_f32; the rows pair measured +50us
5654 // at m=1). Byte-identical: kernel-check pins rows-vs-loop identity, and the per-row loop
5655 // at t=1 is fa_decode on the same q with zero-offset copies. Gates arbitrate.
5656 if let Some(ctr) = stream_ctr {
5657 // STREAM ARM: causal base from the device counter; host kvl.len is a stale lower
5658 // bound used only for the split-sizing upper bound (+64 slack covers M pre-issued
5659 // rounds at K<=8). Views span the bound; per-row limits derive in-kernel.
5660 let upper = kvl.len + t + 64;
5661 let k_view = e.view_u8(&kvl.k, (upper.min(cache.max_ctx)) * ktb);
5662 let v_view = e.view_u8(&kvl.v, (upper.min(cache.max_ctx)) * vtb);
5663 e.fa_decode_rows_dc(
5664 &q,
5665 &k_view,
5666 &v_view,
5667 &mut attn,
5668 head_dim,
5669 n_head,
5670 n_head_kv,
5671 ctr,
5672 upper.min(cache.max_ctx),
5673 t,
5674 scale,
5675 ktb,
5676 vtb,
5677 0,
5678 false,
5679 )?;
5680 } else if spec_lean() && t == 1 {
5681 let t_kv = base_len + 1;
5682 let k_view = e.view_u8(&kvl.k, t_kv * ktb);
5683 let v_view = e.view_u8(&kvl.v, t_kv * vtb);
5684 e.fa_decode_kvmod(
5685 &q,
5686 &k_view,
5687 &v_view,
5688 &mut attn,
5689 head_dim,
5690 n_head,
5691 n_head_kv,
5692 t_kv,
5693 scale,
5694 ktb,
5695 vtb,
5696 crate::Engine::kv_fp8_on(),
5697 )?;
5698 } else if e.fa_rows_eligible(base_len, head_dim) {
5699 let k_view = e.view_u8(&kvl.k, (base_len + t) * ktb);
5700 let v_view = e.view_u8(&kvl.v, (base_len + t) * vtb);
5701 e.fa_decode_rows(
5702 &q,
5703 &k_view,
5704 &v_view,
5705 &mut attn,
5706 head_dim,
5707 n_head,
5708 n_head_kv,
5709 base_len,
5710 t,
5711 scale,
5712 ktb,
5713 vtb,
5714 None,
5715 false,
5716 crate::Engine::kv_fp8_on(),
5717 None,
5718 )?;
5719 } else {
5720 for r in 0..t {
5721 let t_kv_r = base_len + r + 1; // this row sees keys [0..t_kv_r)
5722 let k_view_r = e.view_u8(&kvl.k, t_kv_r * ktb);
5723 let v_view_r = e.view_u8(&kvl.v, t_kv_r * vtb);
5724 // copy q row into an owned buffer (fa_decode takes &CudaSlice, not CudaView)
5725 let mut q_row = vbuf(e, n_head * head_dim)?; // fully written by copy_view_into
5726 let q_src = q.slice(r * n_head * head_dim..(r + 1) * n_head * head_dim);
5727 e.copy_view_into(&mut q_row, 0, &q_src, n_head * head_dim)?;
5728 let mut attn_row = vbuf(e, n_head * head_dim)?; // fully written by fa_decode
5729 e.fa_decode_kvmod(
5730 &q_row,
5731 &k_view_r,
5732 &v_view_r,
5733 &mut attn_row,
5734 head_dim,
5735 n_head,
5736 n_head_kv,
5737 t_kv_r,
5738 scale,
5739 ktb,
5740 vtb,
5741 crate::Engine::kv_fp8_on(),
5742 )?;
5743 e.copy_into(
5744 &mut attn,
5745 r * n_head * head_dim,
5746 &attn_row,
5747 n_head * head_dim,
5748 )?;
5749 }
5750 }
5751
5752 let attn_g = match &gate {
5753 Some(gate) => {
5754 let mut gsig = vbuf(e, t * n_head * head_dim)?; // fully written by sigmoid
5755 e.sigmoid(gate, &mut gsig, t * n_head * head_dim)?;
5756 let mut ag = vbuf(e, t * n_head * head_dim)?; // fully written by mul
5757 e.mul(&attn, &gsig, &mut ag, t * n_head * head_dim)?;
5758 ag
5759 }
5760 None => attn,
5761 };
5762 // DECODE-EXACT wo projection: at m>=5 (K=4+ with pending) the generic matmul would use dp4a
5763 // (128-thread, different FP sum order than MMVQ). Force MMVQ for bit-identity with decode.
5764 Ok(e.matmul_decode_exact(&fa.wo, &attn_g, t)?)
5765 }
5766
5767 /// Context-linear bytes for a plain serving session's trunk cache.
5768 pub fn plain_session_kv_bytes_per_token(&self) -> usize {
5769 crate::cache::cache_bytes_per_token(&self.cfg)
5770 }
5771
5772 /// `(logical bytes/token, ring-capped bytes/token, ring row cap)` for exact admission.
5773 pub fn plain_session_kv_shape(&self) -> (usize, usize, usize) {
5774 (
5775 self.plain_session_kv_bytes_per_token(),
5776 crate::cache::cache_ring_bytes_per_token(&self.cfg),
5777 crate::cache::cache_ring_row_cap(&self.cfg),
5778 )
5779 }
5780
5781 /// Context-linear bytes for a speculative serving session: trunk cache plus persistent MTP
5782 /// scratch. With no MTP head this equals the plain coefficient.
5783 pub fn spec_session_kv_bytes_per_token(&self) -> usize {
5784 let scratch = self
5785 .mtp
5786 .as_ref()
5787 .map(|mtp| {
5788 let (_, _, k, v) = mtp_scratch_layout(&self.cfg, mtp.geom.as_ref());
5789 k + v
5790 })
5791 .unwrap_or(0);
5792 self.plain_session_kv_bytes_per_token()
5793 .saturating_add(scratch)
5794 }
5795
5796 /// Spec twin of [`HybridModel::plain_session_kv_shape`]; Step35's persistent MTP scratch is
5797 /// capped by the same SWA ring rows as the trunk.
5798 pub fn spec_session_kv_shape(&self) -> (usize, usize, usize) {
5799 let total = self.spec_session_kv_bytes_per_token();
5800 let (_, mut ring, rows) = self.plain_session_kv_shape();
5801 if rows > 0 {
5802 ring = ring.saturating_add(
5803 self.mtp
5804 .as_ref()
5805 .map(|mtp| {
5806 let (_, _, k, v) = mtp_scratch_layout(&self.cfg, mtp.geom.as_ref());
5807 k + v
5808 })
5809 .unwrap_or(0),
5810 );
5811 }
5812 (total, ring, rows)
5813 }
5814
5815 /// Greedy MTP speculative decode (§B). Token-identical to `generate(prompt, max_new)` but uses
5816 /// the NextN head to draft K tokens then verifies them in one batched target forward.
5817 /// Returns (generated tokens, total_drafted, total_accepted) so the caller can report
5818 /// acceptance rate. `k` = draft length per round.
5819 ///
5820 /// GRAPH DRAFT (stage 2 of graph-grade spec): when the model is all-Dense and the MTP head is
5821 /// Dense (no MoE host readbacks), the fixed-shape T=1 MTP forward is CUDA-graph-captured ONCE
5822 /// and replayed per draft step — the ~40 eager launches per drafted token collapse into one
5823 /// graph dispatch; only the 4-byte token id (and 4-byte p-min confidence) round-trip per step.
5824 /// Event tracking is disabled for the whole call (generate_graph pattern) so every buffer the
5825 /// captured graph references is event-free; the spec loop is strictly single-stream.
5826 /// MEMRA_SPEC_NOGRAPH=1 forces the eager draft chain.
5827 /// SAMPLED mode (MEMRA_SPEC_TEMP>0) has its OWN capture (gumbel-perturbed in-graph argmax,
5828 /// device Philox event counter, persistent q retention) — graph-vs-eager sampled streams are
5829 /// bit-identical for the same (seed, prompt, K, temp); see the sampled-graph setup in
5830 /// generate_spec_inner2.
5831 /// Multi-turn session: trunk cache + MTP draft scratch persist across generate calls, so
5832 /// turn N+1 primes ONLY its new suffix (the 124k-conversation daily pattern — re-priming a
5833 /// 32k history costs ~54s; a suffix prime costs seconds). APPEND-ONLY by construction: the
5834 /// hybrid linear-attn states are in-place (no position index), so a session can extend but
5835 /// never rewind — `committed` is the exact token list whose state the caches hold (includes
5836 /// any overshoot tokens past max_new; the caller renders from `committed`, not its own echo).
5837 pub fn new_session(
5838 &self,
5839 e: &Engine,
5840 max_ctx: usize,
5841 ) -> Result<SpecSession, Box<dyn std::error::Error>> {
5842 Ok(SpecSession {
5843 // STAGE-OWNED KV (lane/pp2-spec 2026-08-06): `pp::new_cache`, not `Cache::new`. This
5844 // is the SERVING spec-session path, and with the ppN door open across two cards a
5845 // primary-homed cache makes every remote stage peer-read its OWN KV on every verify
5846 // round — the wrong-card class already fixed on the two batched serving paths
5847 // (worker.rs 2483 / 2837). With the door shut `new_cache` IS `Cache::new` (same
5848 // branch, same allocations), so single-device behavior is byte-unchanged.
5849 cache: crate::pp::new_cache(e, &self.cfg, max_ctx)?,
5850 scratch: MtpScratch::new(
5851 e,
5852 &self.cfg,
5853 max_ctx,
5854 self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
5855 )?,
5856 committed: Vec::new(),
5857 last_h: None,
5858 next_pred: None,
5859 sctr: 0,
5860 uctr: 0,
5861 draft_ctx: None,
5862 pending_tok: None,
5863 turn_ckpt: None,
5864 telem: SpecTelemetryCounters::default(),
5865 capture_at: None,
5866 boundary_capture: None,
5867 })
5868 }
5869
5870 /// SPEC-ON-CACHE-HIT restore (lane/spec-on-cache-hit, 2026-08-18 — PORT-PLAN item 3,
5871 /// research/cache-spec-design-20260814, scoped to WHOLE-ENTRY restores only): build a
5872 /// SpecSession around a trunk cache the worker already restored from a prefix-cache
5873 /// entry, re-installing the entry's published draft plane as the MTP scratch rows
5874 /// `[0..prefix.len())` and the entry's boundary hidden as `last_h`, then feeding the
5875 /// prompt SUFFIX here — through EXACTLY the plain path's program selection — so the
5876 /// worker always receives a fully-warm continuation session (committed = whole
5877 /// prompt, `next_pred` + `last_h` set; caller sets `next_pred` from the entry's
5878 /// boundary logits on the empty-suffix shape).
5879 ///
5880 /// PROGRAM LAW (the splitiso two-programs class, learned AGAIN in this lane's own
5881 /// gate): the identity target for a converted hit is the PLAIN hit serving the same
5882 /// request, and plain feeds a carried suffix via eager `decode_step` below
5883 /// PRIME_MIN_T and via `prime_cache` at/above it (prefill_tick's arms). The generate
5884 /// path's tokenwise arm routes qwen35-class through the BATCHED T=1 program
5885 /// (`spec_target_step_h`) instead — ULP-different suffix rows, and the gate measured
5886 /// the near-tie flip at generated token ~8 (research/spec-cache-20260818, qwen r3).
5887 /// So the suffix is fed HERE, mirroring prefill_tick arm-for-arm, not handed to the
5888 /// burst prime.
5889 ///
5890 /// SEED RULE (both sampling regimes; lane/sampled-hit-spec 2026-08-19, sampled draw
5891 /// added by lane/sampled-spec-quality 2026-08-19). The boundary token is produced by
5892 /// EXACTLY the rule the cold burst entry applies to its own first token from the same
5893 /// logits row: `argmax` when greedy, and a `sample_boundary_token` draw at Philox
5894 /// counter 0 when sampled. Both shapes are covered — the entry's boundary logits on a
5895 /// full-cover (empty-suffix) hit, this feed's own boundary logits on a suffix hit.
5896 /// That is what keeps a restored session seed-identical to a cold one PER SEED: the
5897 /// cold session draws from the identical row at counter 0 and then runs its rounds from
5898 /// counter 1, so the restored session admits with `sctr = 1` after its own draw.
5899 /// The WORKER owns the one refusal this constructor cannot see — a constrained request.
5900 /// (The penalized-sampled refusal was LIFTED once the burst's penalty window learned to
5901 /// span the session: `committed` here is the WHOLE prompt, so the restored session's
5902 /// window is the cold session's window. It comes back if `MEMRA_SPEC_PEN_SESSION=0`.)
5903 ///
5904 /// NOT the rolled-back partial-restore hazard: the caller restores at exactly the
5905 /// entry's captured endpoint (`e.pos`) through the shipping whole-entry path;
5906 /// mid-entry (`at < e.pos`) trunk restores stay behind MEMRA_PREFIX_PARTIAL_RESTORE
5907 /// and are never routed here.
5908 ///
5909 /// Failure contract: `Err((Some(cache), why))` before any trunk mutation — the
5910 /// worker rebuilds the plain carrier and the hit serves plain, byte-unchanged.
5911 /// `Err((None, why))` after the suffix feed began — the carrier is part-fed and
5912 /// UNUSABLE; the worker serves the request cold-plain (correct, slower) and the
5913 /// entry stays published for the next request.
5914 #[allow(clippy::too_many_arguments)]
5915 pub fn spec_session_from_restored(
5916 &self,
5917 e: &Engine,
5918 mut cache: Cache,
5919 prefix: Vec<u32>,
5920 suffix: &[u32],
5921 draft_k: &CudaSlice<u8>,
5922 draft_v: &CudaSlice<u8>,
5923 draft_k_tok_bytes: usize,
5924 draft_v_tok_bytes: usize,
5925 draft_len: usize,
5926 last_h: &[f32],
5927 // The ENTRY's boundary logits row (the full-cover shape's seed source). May be empty
5928 // when a suffix follows — the feed's own logits are the boundary then.
5929 boundary_logits: &[f32],
5930 // The request's sampler, or None for greedy. Owned here so the seed rule lives in
5931 // ONE place instead of being half-applied by the worker.
5932 sampling: Option<SpecSampling>,
5933 require_anchor: bool,
5934 max_ctx: usize,
5935 ) -> Result<SpecSession, (Option<Cache>, String)> {
5936 let pos = prefix.len();
5937 let fail = |cache: Cache, msg: String| -> Result<SpecSession, (Option<Cache>, String)> {
5938 Err((Some(cache), msg))
5939 };
5940 if self.mtp.is_none() {
5941 return fail(cache, "no MTP head attached (nothing to draft with)".into());
5942 }
5943 if pos == 0 {
5944 return fail(cache, "empty committed prefix".into());
5945 }
5946 if cache.pos != pos {
5947 let msg = format!(
5948 "restored cache pos {} != restored prefix len {pos}",
5949 cache.pos
5950 );
5951 return fail(cache, msg);
5952 }
5953 if draft_len != pos {
5954 return fail(
5955 cache,
5956 format!("draft plane len {draft_len} != restored prefix len {pos}"),
5957 );
5958 }
5959 if pos + suffix.len() >= max_ctx {
5960 return fail(
5961 cache,
5962 format!(
5963 "prompt {} + suffix would not leave generation room in ctx {max_ctx}",
5964 pos + suffix.len(),
5965 ),
5966 );
5967 }
5968 let mut scratch = match MtpScratch::new(
5969 e,
5970 &self.cfg,
5971 max_ctx,
5972 self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
5973 ) {
5974 Ok(s) => s,
5975 Err(err) => return fail(cache, format!("draft scratch alloc failed: {err}")),
5976 };
5977 if scratch.kv.ring.is_some() {
5978 return fail(
5979 cache,
5980 "ring-backed draft scratch (Step35 SWA) cannot take a flat prefix restore".into(),
5981 );
5982 }
5983 if scratch.kv.k_tok_bytes != draft_k_tok_bytes
5984 || scratch.kv.v_tok_bytes != draft_v_tok_bytes
5985 {
5986 return fail(
5987 cache,
5988 format!(
5989 "draft plane layout {draft_k_tok_bytes}/{draft_v_tok_bytes} != scratch \
5990 {}/{} bytes/token (stale entry across a format change)",
5991 scratch.kv.k_tok_bytes, scratch.kv.v_tok_bytes,
5992 ),
5993 );
5994 }
5995 if pos > scratch.cap {
5996 return fail(
5997 cache,
5998 format!(
5999 "draft plane rows {pos} exceed scratch capacity {}",
6000 scratch.cap
6001 ),
6002 );
6003 }
6004 let kb = pos * draft_k_tok_bytes;
6005 let vb = pos * draft_v_tok_bytes;
6006 if draft_k.len() < kb || draft_v.len() < vb {
6007 return fail(
6008 cache,
6009 format!(
6010 "truncated draft plane: K {} < {kb} or V {} < {vb} bytes",
6011 draft_k.len(),
6012 draft_v.len(),
6013 ),
6014 );
6015 }
6016 if kb > 0 {
6017 if let Err(err) = e.copy_u8_into(&mut scratch.kv.k, 0, draft_k, kb) {
6018 return fail(cache, format!("draft K restore copy failed: {err}"));
6019 }
6020 }
6021 if vb > 0 {
6022 if let Err(err) = e.copy_u8_into(&mut scratch.kv.v, 0, draft_v, vb) {
6023 return fail(cache, format!("draft V restore copy failed: {err}"));
6024 }
6025 }
6026 if let Err(err) = scratch.set_len(e, pos) {
6027 return fail(cache, format!("draft scratch len set failed: {err}"));
6028 }
6029 let mut last_h_dev = if last_h.len() == self.cfg.n_embd as usize {
6030 // anchor upload failure is acceptance-only when a suffix feed follows (fill
6031 // row-0 falls back to zeros) but FATAL for an empty-suffix continuation (the
6032 // burst entry asserts committed + last_h + next_pred) — the caller says which.
6033 e.htod(last_h).ok()
6034 } else {
6035 None
6036 };
6037 if require_anchor && last_h_dev.is_none() {
6038 return fail(
6039 cache,
6040 "empty-suffix continuation requires the entry's boundary hidden anchor".into(),
6041 );
6042 }
6043 let mut committed = prefix;
6044 // Set on BOTH shapes below (suffix-fed and full-cover) — never left None, which is
6045 // what the empty-suffix continuation assert in the burst entry requires.
6046 let next_pred;
6047 // Philox: (0,0) at admit exactly like a fresh session; a sampled boundary draw below
6048 // consumes counter 0 and leaves 1, which is the state a cold session reaches after
6049 // drawing its own first token from the same row.
6050 let mut sctr = 0u32;
6051 let sampled = sampling.is_some_and(|s| s.temp > 0.0) && spec_sampled_boundary_on();
6052 // Penalty window for the boundary draw: the last `penalty_last_n` tokens of the WHOLE
6053 // prompt, which is what the cold session's own burst sees (Item 2's window). Built
6054 // after the suffix joins `committed` below.
6055 let mut boundary_capture: Option<SpecBoundaryCapture> = None;
6056 if !suffix.is_empty() {
6057 // ---- SUFFIX FEED, mirroring prefill_tick's program selection exactly ----
6058 // From here on the trunk cache mutates: failures return Err((None, _)) and
6059 // the worker serves the request cold-plain instead of reusing the carrier.
6060 let dirty =
6061 |msg: String| -> Result<SpecSession, (Option<Cache>, String)> { Err((None, msg)) };
6062 let n_embd = self.cfg.n_embd as usize;
6063 let t = suffix.len();
6064 let mut h_rows = match e.uninit(t * n_embd) {
6065 Ok(b) => b,
6066 Err(err) => return fail(cache, format!("suffix hidden buffer alloc: {err}")),
6067 };
6068 let mut feed_logits = Vec::new();
6069 let batched = t >= crate::hybrid_forward::PRIME_MIN_T
6070 && std::env::var("MEMRA_PRIME_TOKENWISE").is_err()
6071 && !e.frozen_cpu_experts_prefer_tokenwise_prime();
6072 if batched {
6073 // prefill_tick's prime arm: one request-level prime_cache call.
6074 match self.prime_cache(e, suffix, &mut cache, 0) {
6075 Ok((l, _h_seed, hiddens)) => {
6076 if let Err(err) = e.copy_into(&mut h_rows, 0, &hiddens, t * n_embd) {
6077 return dirty(format!("suffix hidden copy: {err}"));
6078 }
6079 feed_logits = l;
6080 }
6081 Err(err) => return dirty(format!("suffix prime failed: {err}")),
6082 }
6083 } else {
6084 // prefill_tick's tokenwise arm: eager decode_step, one token at a time.
6085 for (i, &tok) in suffix.iter().enumerate() {
6086 match self.decode_step_h(e, tok, &mut cache) {
6087 Ok((l, h)) => {
6088 if let Err(err) = e.copy_into(&mut h_rows, i * n_embd, &h, n_embd) {
6089 return dirty(format!("suffix hidden copy: {err}"));
6090 }
6091 feed_logits = l;
6092 }
6093 Err(err) => return dirty(format!("suffix decode_step failed: {err}")),
6094 }
6095 }
6096 }
6097 // Draft-scratch fill for the suffix rows, predecessor-paired: row `pos` reads
6098 // the entry's boundary anchor (zeros fallback — acceptance-only), row `pos+i`
6099 // reads h_rows[i-1]. Chunked like the generate path's fill (transients scale
6100 // with T). Fill failures are acceptance-only — truncate to the restored rows
6101 // and continue; the burst's own set_len keeps the invariant.
6102 let mtp = self.mtp.as_ref().expect("mtp checked above");
6103 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
6104 let embd_gpu = if spec_host_embd() {
6105 None
6106 } else {
6107 Some(
6108 self.embd_gpu
6109 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
6110 )
6111 };
6112 let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
6113 let fill_chunk = 4096usize;
6114 let mut filled = true;
6115 let mut start = 0usize;
6116 'fill: while start < t {
6117 let end = (start + fill_chunk).min(t);
6118 let tc = end - start;
6119 let Ok(mut phs) = e.zeros(tc * n_embd) else {
6120 filled = false;
6121 break 'fill;
6122 };
6123 let (src_lo, dst_off, n_copy) = if start == 0 {
6124 (0, n_embd, (tc - 1) * n_embd)
6125 } else {
6126 ((start - 1) * n_embd, 0, tc * n_embd)
6127 };
6128 if start == 0 {
6129 if let Some(lh) = last_h_dev.as_ref() {
6130 if e.copy_into(&mut phs, 0, lh, n_embd).is_err() {
6131 filled = false;
6132 break 'fill;
6133 }
6134 }
6135 }
6136 if n_copy > 0
6137 && e.copy_view_into(
6138 &mut phs,
6139 dst_off,
6140 &h_rows.slice(src_lo..src_lo + n_copy),
6141 n_copy,
6142 )
6143 .is_err()
6144 {
6145 filled = false;
6146 break 'fill;
6147 }
6148 if self
6149 .mtp_kv_fill(
6150 e,
6151 mtp,
6152 &suffix[start..end],
6153 &phs,
6154 pos + start,
6155 &mut scratch,
6156 embd_dev,
6157 )
6158 .is_err()
6159 {
6160 filled = false;
6161 break 'fill;
6162 }
6163 start = end;
6164 }
6165 if !filled {
6166 // acceptance-only: drafts over missing suffix rows are cheap and wrong,
6167 // so keep only the restored rows resident and let verify arbitrate.
6168 if let Err(err) = scratch.set_len(e, pos) {
6169 return dirty(format!("scratch truncation after failed fill: {err}"));
6170 }
6171 }
6172 // EXTENDED-ENTRY PUBLICATION (lane/sampled-spec-quality, Item 3 — the fix for
6173 // "a restored spec session never publishes an extended entry", SAMPLED-HIT.md
6174 // finding (d)). Pre-lane, publication was armed only for COLD sessions
6175 // (`spec_resumed == 0` in the worker) and both engine capture sites require a
6176 // non-continuation burst — but a converted hit's first burst IS a continuation,
6177 // so a growing conversation learned exactly ONE boundary and turn 3 could never
6178 // hit a longer prefix than turn 2 did.
6179 //
6180 // WHERE, and why it is safe here: `cache.pos == prefix + suffix` at this exact
6181 // line — the trunk is primed over the whole prompt, nothing is generated, and the
6182 // draft plane rows [0..prompt) are filled just above. That is a complete
6183 // whole-entry boundary (`pos == fed_len`), the same shape the cold seed capture
6184 // publishes; the worker's existing publication sweep picks it up because it is
6185 // keyed on `boundary_capture.is_some()` and is sampler- and resume-independent.
6186 // NOT the partial-restore hazard: the boundary is this session's own prompt END,
6187 // never mid-entry, so `entry_pos != fed_len` still refuses on the way back in.
6188 // Failure is SILENT by design (the turn_ckpt / boundary-capture convention):
6189 // publication is an optimization, never a correctness dependency.
6190 if spec_restore_republish_on() {
6191 debug_assert_eq!(
6192 cache.pos,
6193 pos + t,
6194 "extended-entry capture must sit at the restored session's prompt end",
6195 );
6196 if let Ok(snap) = cache.snapshot(e) {
6197 boundary_capture = Some(SpecBoundaryCapture {
6198 snap,
6199 pos: pos + t,
6200 logits: feed_logits.clone(),
6201 last_h: capture_boundary_hidden(e, &h_rows, t, n_embd),
6202 });
6203 }
6204 }
6205 // continuation seed: the feed's boundary logits ARE the plain path's boundary
6206 // logits (same program), so greedy's argmax here is plain's first emitted token,
6207 // and the sampled draw is the cold sampled session's own first token.
6208 next_pred = Some(if sampled {
6209 let sp = sampling.expect("sampled implies a sampler");
6210 // `committed` is still the restored prefix here; the suffix joins it below —
6211 // so this is the last-N window over the WHOLE prompt, exactly the cold
6212 // session's own window at its first token.
6213 let hist = pen_window_seed(&committed, suffix, sp.penalty_last_n);
6214 match sample_boundary_token(
6215 e,
6216 &feed_logits,
6217 &sp,
6218 &hist,
6219 &mut sctr,
6220 "restore-suffix-feed",
6221 ) {
6222 Ok(t) => t,
6223 // the trunk is already fed: hand nothing back, the worker serves the
6224 // request cold-plain. Never fall back to an argmax — that would put a
6225 // greedy token in a sampled stream to save a slow path.
6226 Err(err) => {
6227 return dirty(format!("boundary token draw failed: {err}"));
6228 }
6229 }
6230 } else {
6231 argmax(&feed_logits) as u32
6232 });
6233 let mut lh = match e.uninit(n_embd) {
6234 Ok(b) => b,
6235 Err(err) => return dirty(format!("boundary hidden alloc: {err}")),
6236 };
6237 if let Err(err) = e.copy_view_into(
6238 &mut lh,
6239 0,
6240 &h_rows.slice((t - 1) * n_embd..t * n_embd),
6241 n_embd,
6242 ) {
6243 return dirty(format!("boundary hidden copy: {err}"));
6244 }
6245 last_h_dev = Some(lh);
6246 committed.extend_from_slice(suffix);
6247 } else {
6248 // FULL-COVER shape (empty suffix — the identical-repeat / agent-loop shape): the
6249 // ENTRY's boundary logits are the boundary row, and this is the token the cold
6250 // session emits from that same row. Owned here rather than in the worker so the
6251 // sampled draw cannot be half-applied on one shape (the worker used to argmax it).
6252 if boundary_logits.is_empty() {
6253 return fail(
6254 cache,
6255 "full-cover restore without the entry's boundary logits".into(),
6256 );
6257 }
6258 next_pred = Some(if sampled {
6259 let sp = sampling.expect("sampled implies a sampler");
6260 let hist = pen_window_seed(&committed, &[], sp.penalty_last_n);
6261 match sample_boundary_token(
6262 e,
6263 boundary_logits,
6264 &sp,
6265 &hist,
6266 &mut sctr,
6267 "restore-full-cover",
6268 ) {
6269 Ok(t) => t,
6270 // nothing has been mutated on this shape — hand the carrier back and let
6271 // the hit serve PLAIN (the banked pre-lane path).
6272 Err(err) => {
6273 return fail(cache, format!("boundary token draw failed: {err}"));
6274 }
6275 }
6276 } else {
6277 argmax(boundary_logits) as u32
6278 });
6279 }
6280 Ok(SpecSession {
6281 cache,
6282 scratch,
6283 committed,
6284 last_h: last_h_dev,
6285 next_pred,
6286 sctr,
6287 uctr: 0,
6288 draft_ctx: None,
6289 pending_tok: None,
6290 turn_ckpt: None,
6291 telem: SpecTelemetryCounters::default(),
6292 capture_at: None,
6293 boundary_capture,
6294 })
6295 }
6296
6297 /// Forced-gate exact state comparison. This intentionally reads the real live prefixes from
6298 /// their owning PP devices: matching emitted ids alone would miss a stale `len_d`, recurrent
6299 /// snapshot, or draft-KV row that only corrupts the following round.
6300 pub fn optipipe_compare_session_state(
6301 &self,
6302 e: &Engine,
6303 reference: &SpecSession,
6304 candidate: &SpecSession,
6305 ) -> Result<OptiForkStateIdentity, Box<dyn std::error::Error>> {
6306 fn fail(what: &str) -> Box<dyn std::error::Error> {
6307 format!("optipipe state mismatch: {what}").into()
6308 }
6309 fn same_f32(a: &[f32], b: &[f32]) -> bool {
6310 a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.to_bits() == y.to_bits())
6311 }
6312 fn compare_layers(
6313 es: &Engine,
6314 range: std::ops::Range<usize>,
6315 reference: &SpecSession,
6316 candidate: &SpecSession,
6317 report: &mut OptiForkStateIdentity,
6318 ) -> Result<(), Box<dyn std::error::Error>> {
6319 for il in range {
6320 match (&reference.cache.kv[il], &candidate.cache.kv[il]) {
6321 (Some(a), Some(b)) => {
6322 if a.len != b.len {
6323 return Err(fail(&format!(
6324 "layer {il} host KV len {} != {}",
6325 a.len, b.len
6326 )));
6327 }
6328 let ad = es.dtoh_i32(&a.len_d)?;
6329 let bd = es.dtoh_i32(&b.len_d)?;
6330 if ad != bd || ad.first().copied() != Some(a.len as i32) {
6331 return Err(fail(&format!(
6332 "layer {il} device KV len {ad:?} != {bd:?} (host={})",
6333 a.len,
6334 )));
6335 }
6336 let kb = a.len * a.k_tok_bytes;
6337 let vb = a.len * a.v_tok_bytes;
6338 if kb > 0 {
6339 let ak = es.dtoh_u8_view(&a.k.slice(0..kb))?;
6340 let bk = es.dtoh_u8_view(&b.k.slice(0..kb))?;
6341 if ak != bk {
6342 let at = ak.iter().zip(&bk).position(|(x, y)| x != y).unwrap();
6343 return Err(fail(&format!(
6344 "layer {il} K bytes at byte {at} row {} offset {}: {} != {}",
6345 at / a.k_tok_bytes,
6346 at % a.k_tok_bytes,
6347 ak[at],
6348 bk[at],
6349 )));
6350 }
6351 }
6352 if vb > 0 {
6353 let av = es.dtoh_u8_view(&a.v.slice(0..vb))?;
6354 let bv = es.dtoh_u8_view(&b.v.slice(0..vb))?;
6355 if av != bv {
6356 let at = av.iter().zip(&bv).position(|(x, y)| x != y).unwrap();
6357 return Err(fail(&format!(
6358 "layer {il} V bytes at byte {at} row {} offset {}: {} != {}",
6359 at / a.v_tok_bytes,
6360 at % a.v_tok_bytes,
6361 av[at],
6362 bv[at],
6363 )));
6364 }
6365 }
6366 report.trunk_kv_bytes += kb + vb;
6367 }
6368 (None, None) => {}
6369 _ => return Err(fail(&format!("layer {il} KV presence"))),
6370 }
6371 match (&reference.cache.recur[il], &candidate.cache.recur[il]) {
6372 (Some(a), Some(b)) => {
6373 let ac = es.dtoh(&a.conv_state)?;
6374 let bc = es.dtoh(&b.conv_state)?;
6375 if !same_f32(&ac, &bc) {
6376 return Err(fail(&format!("layer {il} conv state")));
6377 }
6378 let as_ = es.dtoh(&a.ssm_state)?;
6379 let bs = es.dtoh(&b.ssm_state)?;
6380 if !same_f32(&as_, &bs) {
6381 return Err(fail(&format!("layer {il} SSM state")));
6382 }
6383 report.recurrent_bytes += (ac.len() + as_.len()) * 4;
6384 }
6385 (None, None) => {}
6386 _ => return Err(fail(&format!("layer {il} recurrent presence"))),
6387 }
6388 }
6389 Ok(())
6390 }
6391
6392 if reference.committed != candidate.committed {
6393 return Err(fail("committed token ids"));
6394 }
6395 if reference.cache.pos != candidate.cache.pos
6396 || reference.cache.max_ctx != candidate.cache.max_ctx
6397 {
6398 return Err(fail("cache pos/capacity"));
6399 }
6400 if reference.pending_tok != candidate.pending_tok
6401 || reference.next_pred != candidate.next_pred
6402 || reference.sctr != candidate.sctr
6403 || reference.uctr != candidate.uctr
6404 {
6405 return Err(fail("pending/prediction/counter tail"));
6406 }
6407
6408 let mut report = OptiForkStateIdentity::default();
6409 if let Some(fence) = crate::pp::pp_cuts(self.layers.len()) {
6410 let rt = crate::pp::PpNRt::get(e)?;
6411 for stage in 0..rt.n_stages() {
6412 let _scope = rt.enter(stage);
6413 compare_layers(
6414 rt.engine(stage, e),
6415 fence[stage]..fence[stage + 1],
6416 reference,
6417 candidate,
6418 &mut report,
6419 )?;
6420 }
6421 } else {
6422 compare_layers(e, 0..self.layers.len(), reference, candidate, &mut report)?;
6423 }
6424
6425 let (a, b) = (&reference.scratch.kv, &candidate.scratch.kv);
6426 if a.len != b.len || e.dtoh_i32(&a.len_d)? != e.dtoh_i32(&b.len_d)? {
6427 return Err(fail("draft scratch length"));
6428 }
6429 let kb = a.len * a.k_tok_bytes;
6430 let vb = a.len * a.v_tok_bytes;
6431 if kb > 0 && e.dtoh_u8_view(&a.k.slice(0..kb))? != e.dtoh_u8_view(&b.k.slice(0..kb))? {
6432 return Err(fail("draft scratch K bytes"));
6433 }
6434 if vb > 0 && e.dtoh_u8_view(&a.v.slice(0..vb))? != e.dtoh_u8_view(&b.v.slice(0..vb))? {
6435 return Err(fail("draft scratch V bytes"));
6436 }
6437 report.scratch_kv_bytes = kb + vb;
6438
6439 match (&reference.last_h, &candidate.last_h) {
6440 (Some(a), Some(b)) => {
6441 let ah = e.dtoh(a)?;
6442 let bh = e.dtoh(b)?;
6443 if !same_f32(&ah, &bh) {
6444 return Err(fail("last hidden/seed bytes"));
6445 }
6446 report.hidden_bytes = ah.len() * 4;
6447 }
6448 (None, None) => {}
6449 _ => return Err(fail("last hidden/seed presence")),
6450 }
6451 Ok(report)
6452 }
6453
6454 /// SESSION-AFFINITY REWIND (lane/session-affinity, 2026-08-05): roll `sess` back to its
6455 /// retained prompt-end checkpoint, so a request whose prompt matches
6456 /// `committed[..rewind_pos()]` exactly can resume there and prime only its own delta.
6457 ///
6458 /// EXACTNESS. After this returns, the session is byte-for-byte the state it was in AT that
6459 /// boundary: full-attn KV truncated to it (append-only, position-addressed), GDN conv/ssm
6460 /// restored from the device copy taken there, draft scratch length reset, `committed`
6461 /// truncated, `last_h` = the boundary's predecessor anchor. That is precisely the state a
6462 /// fresh prime of `committed[..pos]` would have produced, so the following suffix prime and
6463 /// every burst after it are identical to a cold run of the same token stream — the
6464 /// committed-tokens-authoritative contract.
6465 ///
6466 /// `next_pred` and `pending_tok` are CLEARED: both describe generation past the boundary,
6467 /// which the rewind discards. The caller therefore must supply a non-empty suffix (a
6468 /// rewound session cannot serve an empty-suffix continuation burst — there is nothing to
6469 /// continue). The persistent draft graph survives: it bakes only session-stable pointers
6470 /// (the scratch KV, the resident embedding), none of which the rewind moves.
6471 ///
6472 /// The checkpoint is CONSUMED (`turn_ckpt` taken): its snapshot buffers are freed here, and
6473 /// this turn's own prime installs a fresh one at the new prompt end. Returns the position
6474 /// rewound to, or `None` when the session holds no checkpoint (caller: full re-prime).
6475 pub fn spec_rewind_to_checkpoint(
6476 &self,
6477 e: &Engine,
6478 sess: &mut SpecSession,
6479 ) -> Result<Option<usize>, Box<dyn std::error::Error>> {
6480 if sess.turn_ckpt.as_ref().is_some_and(|ckpt| {
6481 !sess.cache.can_rollback(&ckpt.snap, 0) || !sess.scratch.can_rewind_to(ckpt.pos)
6482 }) {
6483 return Err(
6484 "SWA ring rewind checkpoint has been lapped; full re-prime required".into(),
6485 );
6486 }
6487 let Some(ckpt) = sess.turn_ckpt.take() else {
6488 return Ok(None);
6489 };
6490 assert!(
6491 ckpt.pos <= sess.committed.len(),
6492 "checkpoint past committed ({} > {})",
6493 ckpt.pos,
6494 sess.committed.len()
6495 );
6496 // Restore through each layer's owning engine. A single primary-engine rollback is not
6497 // sufficient when the serving cache is stage-owned under cross-device PP.
6498 crate::pp::restore_cache_checkpoint(e, &self.cfg, None, &mut sess.cache, &ckpt.snap)?;
6499 debug_assert_eq!(
6500 sess.cache.pos, ckpt.pos,
6501 "rollback landed off the checkpoint"
6502 );
6503 sess.scratch.set_len(e, ckpt.pos)?;
6504 sess.committed.truncate(ckpt.pos);
6505 sess.last_h = Some(ckpt.last_h);
6506 sess.next_pred = None;
6507 sess.pending_tok = None;
6508 Ok(Some(ckpt.pos))
6509 }
6510
6511 /// Grow a parked speculative session to `target_cap` and rewind it to its retained turn
6512 /// checkpoint without re-priming the checkpoint prefix.
6513 ///
6514 /// The trunk cache is restored exactly like a plain grown cache: append-only full-attention
6515 /// KV rows come from the parked cache, while recurrent state comes from the checkpoint's
6516 /// owned snapshot. The MTP scratch is also context-linear and its rows below the checkpoint
6517 /// remain authoritative, so they are copied into a fresh larger scratch before its length is
6518 /// truncated. Pointer-baking draft graphs are dropped and recaptured on the next burst.
6519 ///
6520 /// All fallible work completes before `sess` is mutated. A failed allocation or copy leaves
6521 /// the parked session intact, allowing the caller one reclaim-and-retry attempt.
6522 pub fn spec_grow_and_rewind_to_checkpoint(
6523 &self,
6524 e: &Engine,
6525 sess: &mut SpecSession,
6526 target_cap: usize,
6527 ) -> Result<Option<usize>, Box<dyn std::error::Error>> {
6528 if target_cap <= sess.cache.max_ctx {
6529 return self.spec_rewind_to_checkpoint(e, sess);
6530 }
6531 let Some(ckpt) = sess.turn_ckpt.as_ref() else {
6532 return Ok(None);
6533 };
6534 if ckpt.pos == 0 || ckpt.pos > sess.committed.len() {
6535 return Err(format!(
6536 "checkpoint pos {} outside committed length {}",
6537 ckpt.pos,
6538 sess.committed.len(),
6539 )
6540 .into());
6541 }
6542 if ckpt.pos > target_cap {
6543 return Err(format!(
6544 "checkpoint pos {} exceeds grown capacity {target_cap}",
6545 ckpt.pos,
6546 )
6547 .into());
6548 }
6549
6550 let mut grown_cache = crate::pp::new_cache(e, &self.cfg, target_cap)?;
6551 let mut grown_scratch = MtpScratch::new(
6552 e,
6553 &self.cfg,
6554 target_cap,
6555 self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
6556 )?;
6557 crate::pp::restore_cache_checkpoint(
6558 e,
6559 &self.cfg,
6560 Some(&sess.cache),
6561 &mut grown_cache,
6562 &ckpt.snap,
6563 )?;
6564
6565 let src = &sess.scratch.kv;
6566 let dst = &mut grown_scratch.kv;
6567 if ckpt.pos > src.len
6568 || src.kv_dim_k != dst.kv_dim_k
6569 || src.kv_dim_v != dst.kv_dim_v
6570 || src.k_tok_bytes != dst.k_tok_bytes
6571 || src.v_tok_bytes != dst.v_tok_bytes
6572 {
6573 return Err(format!(
6574 "checkpoint draft layout mismatch (pos {}, source len {})",
6575 ckpt.pos, src.len,
6576 )
6577 .into());
6578 }
6579 let kb = ckpt.pos * src.k_tok_bytes;
6580 let vb = ckpt.pos * src.v_tok_bytes;
6581 if kb > 0 {
6582 e.copy_u8_into(&mut dst.k, 0, &src.k, kb)?;
6583 }
6584 if vb > 0 {
6585 e.copy_u8_into(&mut dst.v, 0, &src.v, vb)?;
6586 }
6587 grown_scratch.set_len(e, ckpt.pos)?;
6588 // The old scratch is dropped immediately after publication below. Bound its D2D reads
6589 // first; growth happens once per rewritten turn, outside the decode hot loop.
6590 e.stream().synchronize()?;
6591
6592 let ckpt = sess
6593 .turn_ckpt
6594 .take()
6595 .expect("checkpoint remained present through transactional grow");
6596 let pos = ckpt.pos;
6597 sess.cache = grown_cache;
6598 sess.scratch = grown_scratch;
6599 sess.committed.truncate(pos);
6600 sess.last_h = Some(ckpt.last_h);
6601 sess.next_pred = None;
6602 sess.pending_tok = None;
6603 sess.draft_ctx = None;
6604 debug_assert_eq!(sess.cache.pos, pos, "grown rewind landed off checkpoint");
6605 debug_assert_eq!(
6606 sess.scratch.kv.len, pos,
6607 "grown draft rewind landed off checkpoint"
6608 );
6609 Ok(Some(pos))
6610 }
6611
6612 /// Commit a carried pending bonus (see SpecSession::pending_tok): one T=1 trunk pass
6613 /// (its logits' argmax becomes next_pred) + the draft-KV fill at the carried anchor —
6614 /// byte-identical to the pre-carry session tail. Required before a non-empty-suffix
6615 /// prime, a sampled turn, or parking a session for pool reuse. No-op without a pending.
6616 /// `sampling` is the sampler of the request that will CONSUME the resulting `next_pred`
6617 /// (lane/sampled-spec-quality): this is a boundary site like any other, so a sampled
6618 /// consumer must get a DRAWN token, not an argmax. Pass `None` from the park/demote
6619 /// callers — a pending only ever exists on the GREEDY tail, and the consumer of a
6620 /// park-time flush is a future request whose sampler is not knowable here (residual
6621 /// named at the pool-resume probe in worker.rs and in SAMPLED-QUALITY.md).
6622 pub fn spec_flush_pending(
6623 &self,
6624 e: &Engine,
6625 sess: &mut SpecSession,
6626 sampling: Option<SpecSampling>,
6627 ) -> Result<(), Box<dyn std::error::Error>> {
6628 let Some(b) = sess.pending_tok.take() else {
6629 return Ok(());
6630 };
6631 let mtp = self
6632 .mtp
6633 .as_ref()
6634 .expect("pending carry requires an MTP head");
6635 let n_embd = self.cfg.n_embd as usize;
6636 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
6637 let embd_gpu = if spec_host_embd() {
6638 None
6639 } else {
6640 Some(
6641 self.embd_gpu
6642 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
6643 )
6644 };
6645 let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
6646 let pos_b = sess.cache.pos;
6647 sess.scratch.set_len(e, pos_b)?;
6648 let (lg_b, hb) = self.spec_target_step_h(e, b, &mut sess.cache)?;
6649 sess.next_pred = Some(match sampling {
6650 Some(sp) if sp.temp > 0.0 && spec_sampled_boundary_on() => {
6651 // window includes `b` itself: it is committed by this pass, and the pre-lane
6652 // code never counted a boundary token in the penalty history at all.
6653 let hist = pen_window_seed(&sess.committed, &[b], sp.penalty_last_n);
6654 sample_boundary_token(e, &lg_b, &sp, &hist, &mut sess.sctr, "flush-pending")?
6655 }
6656 _ => argmax(&lg_b) as u32,
6657 });
6658 let anchor = sess
6659 .last_h
6660 .as_ref()
6661 .expect("pending carry requires last_h (the predecessor-row anchor)");
6662 self.mtp_kv_fill(e, mtp, &[b], anchor, pos_b, &mut sess.scratch, embd_dev)?;
6663 sess.last_h = Some(hb);
6664 sess.committed.push(b);
6665 Ok(())
6666 }
6667
6668 /// Solo target feed used only at speculative round boundaries. Step35 serving made its
6669 /// staged batched B=1 graph authoritative, so a speculative session must enter and leave
6670 /// rounds through that same graph. Other model families keep their eager T=1 contract.
6671 fn spec_target_step_h(
6672 &self,
6673 e: &Engine,
6674 token: u32,
6675 cache: &mut Cache,
6676 ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
6677 if self.cfg.step35.is_none() && !self.qwen35_serving_class() {
6678 return self.decode_step_h(e, token, cache);
6679 }
6680 let pos0 = cache.pos;
6681 let (logits, hidden) = self.decode_step_t_core(e, &[token], pos0, cache, None, None)?;
6682 Ok((e.dtoh(&logits)?, hidden))
6683 }
6684
6685 /// The archs whose LIVE B=1 serving runs the generic BATCHED numeric class (decode_step_batch
6686 /// walk + batched head), so their spec verify must run the SAME class. MoE learned this
6687 /// 2026-08-14 AM (4b777ccc5); the dense hybrid reproduced the identical near-tie flip class
6688 /// the same day on Qwen3.8-27B — eager-class verify logits drift from batched-class serving
6689 /// logits ("1 ULP at layer 2 → 2.3e-1 logit maxdiff at the head"), and the GDN recurrence
6690 /// carries the drift until a near-tie flips deep in generation. One predicate so the five
6691 /// dispatch sites cannot drift apart again.
6692 fn qwen35_serving_class(&self) -> bool {
6693 matches!(
6694 self.cfg.arch,
6695 memra_gguf::config::Arch::Qwen35 | memra_gguf::config::Arch::Qwen35Moe
6696 )
6697 }
6698
6699 /// Reduced-matrix admission for increment 1. This deliberately does not change the PP-2
6700 /// serving policy: the worker calls it only after `MEMRA_SPEC_PIPE=1` and an explicit spec
6701 /// session already exist.
6702 pub fn spec_pipe_available(&self, e: &Engine) -> bool {
6703 if std::env::var("MEMRA_SPEC_PIPE").as_deref() != Ok("1")
6704 || !spec_devacc()
6705 || spec_replay_env_enabled()
6706 || spec_stream()
6707 || std::env::var("MEMRA_SPEC_ADAPT").as_deref() == Ok("1")
6708 || std::env::var("MEMRA_SPEC_PMIN0").as_deref() == Ok("1")
6709 || std::env::var("MEMRA_SPEC_PP_ANATOMY").as_deref() == Ok("1")
6710 || std::env::var("MEMRA_SPEC_PMIN")
6711 .ok()
6712 .and_then(|v| v.parse::<f32>().ok())
6713 .unwrap_or(0.0)
6714 > 0.0
6715 || self.is_gemma4_e4b()
6716 || self.cfg.gemma4.is_some()
6717 || self.mtp.is_none()
6718 {
6719 return false;
6720 }
6721 let Some(cuts) = crate::pp::pp_cuts(self.layers.len()) else {
6722 return false;
6723 };
6724 if cuts.len() != 3 || crate::pp::pp2_streams_off() || !crate::pp::spec_pp_on() {
6725 return false;
6726 }
6727 crate::pp::PpNRt::get(e)
6728 .map(|rt| rt.n_stages() == 2 && rt.cross_device())
6729 .unwrap_or(false)
6730 }
6731
6732 /// Two warm greedy continuation bursts over one PP-2 interval coordinator. The two existing
6733 /// `generate_spec_inner2` call stacks own all per-session round locals; only phase issue order
6734 /// changes. No callback is accepted in increment 1 — the worker publishes each completed burst.
6735 #[allow(clippy::too_many_arguments)]
6736 pub fn generate_spec_session_pair(
6737 &self,
6738 e: &Engine,
6739 sess_a: &mut SpecSession,
6740 max_new_a: usize,
6741 k_a: usize,
6742 sess_b: &mut SpecSession,
6743 max_new_b: usize,
6744 k_b: usize,
6745 ) -> Result<((Vec<u32>, usize, usize), (Vec<u32>, usize, usize)), Box<dyn std::error::Error>>
6746 {
6747 if !self.spec_pipe_available(e) {
6748 return Err("two-session speculative pipeline is outside its reduced matrix".into());
6749 }
6750 if max_new_a == 0 || max_new_b == 0 || k_a == 0 || k_b == 0 {
6751 return Err(
6752 "two-session speculative pipeline requires non-empty positive-K bursts".into(),
6753 );
6754 }
6755 for sess in [&*sess_a, &*sess_b] {
6756 if sess.committed.is_empty()
6757 || sess.last_h.is_none()
6758 || (sess.next_pred.is_none() && sess.pending_tok.is_none())
6759 {
6760 return Err("two-session speculative pipeline requires warm continuations".into());
6761 }
6762 }
6763
6764 let mtp_dense = self
6765 .mtp
6766 .as_ref()
6767 .map(|m| matches!(m.ffn, crate::hybrid::Ffn::Dense { .. }))
6768 .unwrap_or(false);
6769 let trunk_dense = self
6770 .layers
6771 .iter()
6772 .all(|l| matches!(l.ffn, crate::hybrid::Ffn::Dense { .. }));
6773 let graph_ok = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
6774 && !spec_host_embd()
6775 && mtp_dense
6776 && trunk_dense
6777 && !crate::model::full_prec_enabled();
6778 let graph_a = graph_ok && k_a + 2 < 96;
6779 let graph_b = graph_ok && k_b + 2 < 96;
6780 let was_tracking = e.ctx().is_event_tracking();
6781 if (graph_a || graph_b) && was_tracking {
6782 unsafe {
6783 e.ctx().disable_event_tracking();
6784 }
6785 }
6786
6787 static LOGGED: std::sync::Once = std::sync::Once::new();
6788 LOGGED.call_once(|| {
6789 eprintln!("[spec-pipe] two-session PP-2 continuation pipeline engaged");
6790 });
6791 let sync = std::sync::Arc::new(SpecPipeSync::new());
6792 let lane_a = SpecPipeLane {
6793 sync: sync.clone(),
6794 lane: 0,
6795 };
6796 let lane_b = SpecPipeLane { sync, lane: 1 };
6797 let mut sess_b_ptr = SpecPipeSessionPtr(sess_b as *mut SpecSession);
6798 let (result_a, result_b) = std::thread::scope(|scope| {
6799 let b = scope.spawn(move || {
6800 let mut finish = SpecPipeFinish::new(&lane_b);
6801 let sess_b = unsafe { sess_b_ptr.get_mut() };
6802 let result = e
6803 .ctx()
6804 .bind_to_thread()
6805 .map_err(|err| err.to_string())
6806 .and_then(|_| {
6807 self.generate_spec_inner2(
6808 e,
6809 &[],
6810 max_new_b,
6811 k_b,
6812 graph_b,
6813 Some(sess_b),
6814 None,
6815 None,
6816 None,
6817 None,
6818 Some(&lane_b),
6819 )
6820 .map_err(|err| err.to_string())
6821 });
6822 finish.close(result.is_err());
6823 result
6824 });
6825 let mut finish = SpecPipeFinish::new(&lane_a);
6826 let result_a = self.generate_spec_inner2(
6827 e,
6828 &[],
6829 max_new_a,
6830 k_a,
6831 graph_a,
6832 Some(sess_a),
6833 None,
6834 None,
6835 None,
6836 None,
6837 Some(&lane_a),
6838 );
6839 finish.close(result_a.is_err());
6840 let result_b = b
6841 .join()
6842 .map_err(|_| "paired speculative session B panicked".to_string())
6843 .and_then(|r| r);
6844 (result_a, result_b)
6845 });
6846
6847 if (graph_a || graph_b) && was_tracking {
6848 unsafe {
6849 e.ctx().enable_event_tracking();
6850 }
6851 }
6852 let result_a = result_a?;
6853 let result_b = result_b.map_err(|err| -> Box<dyn std::error::Error> { err.into() })?;
6854 Ok((result_a, result_b))
6855 }
6856
6857 /// One spec-decode turn on a live session. `suffix` = the NEW tokens only (turn N+1's user
6858 /// message rendered through the chat template continuation). Returns (new tokens emitted,
6859 /// drafted, accepted); session.committed grows by suffix + emitted.
6860 pub fn generate_spec_session(
6861 &self,
6862 e: &Engine,
6863 sess: &mut SpecSession,
6864 suffix: &[u32],
6865 max_new: usize,
6866 k: usize,
6867 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
6868 self.generate_spec_session_sampled(e, sess, suffix, max_new, k, None, None)
6869 }
6870
6871 /// Serve-path sampled spec: routes the burst through the rejection-sampling verify with
6872 /// per-SESSION Philox continuity (sess.sctr/uctr). None = env-driven (CLI) or greedy.
6873 /// Filters (top-k/p/min-p) apply SYMMETRICALLY to draft q and verify p — distribution-exact
6874 /// for the filtered target (feat/filtered-spec).
6875 ///
6876 /// `on_commit` (sse-cadence, 2026-08-05): called with each newly-emitted slice of the
6877 /// output — once right after the prime's first token, then once per round commit — so a
6878 /// streaming caller can flush text at round cadence instead of once per burst. The slices
6879 /// are disjoint, in order, and concatenate to exactly the returned token vec. Emission-
6880 /// timing only: token bytes, session state, and exactness are untouched.
6881 ///
6882 /// The returned bool is a CONTINUE-VERDICT (admission yield, 2026-08-06): `false` ends
6883 /// the burst at the current round boundary, exactly as if `max_new` had been reached —
6884 /// the caller's scheduler regains control without waiting the burst out. Burst size is
6885 /// content-neutral (spec-levers battery), so an early exit moves WHEN the burst returns,
6886 /// never what tokens say. The slice may be EMPTY (a poll-only boundary — round-stream
6887 /// drains and the defensive tail flush can land with nothing new committed).
6888 #[allow(clippy::too_many_arguments)]
6889 pub fn generate_spec_session_sampled(
6890 &self,
6891 e: &Engine,
6892 sess: &mut SpecSession,
6893 suffix: &[u32],
6894 max_new: usize,
6895 k: usize,
6896 sampling: Option<SpecSampling>,
6897 on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
6898 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
6899 self.generate_spec_session_sampled_prime_split(
6900 e, sess, suffix, max_new, k, sampling, None, on_commit,
6901 )
6902 }
6903
6904 /// Serve-only cold-prime segmentation twin. `prime_split` is the same stable boundary the
6905 /// plain worker would honor before entering its sub-floor tokenwise tail; warm continuations
6906 /// pass `None` and stay on the existing zero-prime path.
6907 #[allow(clippy::too_many_arguments)]
6908 pub fn generate_spec_session_sampled_prime_split(
6909 &self,
6910 e: &Engine,
6911 sess: &mut SpecSession,
6912 suffix: &[u32],
6913 max_new: usize,
6914 k: usize,
6915 sampling: Option<SpecSampling>,
6916 prime_split: Option<usize>,
6917 on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
6918 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
6919 self.generate_spec_session_constrained_prime_split(
6920 e,
6921 sess,
6922 suffix,
6923 max_new,
6924 k,
6925 sampling,
6926 None,
6927 prime_split,
6928 on_commit,
6929 )
6930 }
6931
6932 /// `generate_spec_session_sampled` + GRAMMAR (constrained decoding, 2026-08-03): the
6933 /// hook truncates acceptance at the first grammar-illegal token AFTER the exactness
6934 /// verify (grammar is an extra rejection rule, ordering like the batched-verify twins)
6935 /// and replaces an illegal bonus with the MASKED argmax of the target's own verify
6936 /// column — token-identical to constrained plain greedy decode. GREEDY only (the
6937 /// worker routes sampled constrained to plain decode). Acceptance under tight grammars
6938 /// may drop (drafter is unconstrained); that is measured, not hidden.
6939 #[allow(clippy::too_many_arguments)]
6940 pub fn generate_spec_session_constrained(
6941 &self,
6942 e: &Engine,
6943 sess: &mut SpecSession,
6944 suffix: &[u32],
6945 max_new: usize,
6946 k: usize,
6947 sampling: Option<SpecSampling>,
6948 constraint: Option<&mut dyn SpecConstraint>,
6949 on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
6950 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
6951 self.generate_spec_session_constrained_prime_split(
6952 e, sess, suffix, max_new, k, sampling, constraint, None, on_commit,
6953 )
6954 }
6955
6956 #[allow(clippy::too_many_arguments)]
6957 pub fn generate_spec_session_constrained_prime_split(
6958 &self,
6959 e: &Engine,
6960 sess: &mut SpecSession,
6961 suffix: &[u32],
6962 max_new: usize,
6963 k: usize,
6964 sampling: Option<SpecSampling>,
6965 constraint: Option<&mut dyn SpecConstraint>,
6966 prime_split: Option<usize>,
6967 on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
6968 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
6969 if constraint.is_some() && sampling.is_some_and(|s| s.temp > 0.0) {
6970 return Err(
6971 "constrained spec decode is greedy-only (worker routes sampled \
6972 constrained to plain decode)"
6973 .into(),
6974 );
6975 }
6976 // PENDING-CARRY entry flush: a carried bonus precedes any new suffix in the sequence,
6977 // so it must commit BEFORE the suffix primes; the sampled path doesn't carry (its
6978 // round-0 accept needs the commit pass's logits). Empty-suffix greedy bursts — the
6979 // serve continuation case — consume the carry in-loop with zero solo passes.
6980 if sess.pending_tok.is_some()
6981 && (!suffix.is_empty() || sampling.map_or(false, |s| s.temp > 0.0))
6982 {
6983 self.spec_flush_pending(e, sess, sampling)?;
6984 }
6985 let mtp_dense = self
6986 .mtp
6987 .as_ref()
6988 .map(|m| matches!(m.ffn, crate::hybrid::Ffn::Dense { .. }))
6989 .unwrap_or(false);
6990 let trunk_dense = self
6991 .layers
6992 .iter()
6993 .all(|l| matches!(l.ffn, crate::hybrid::Ffn::Dense { .. }));
6994 // FULL_PREC forces the EAGER draft: the graph capture would enclose cuBLASLt f32 GEMV
6995 // (the FloatBf16 else-branches) and a bf16_to_f32 dequant alloc — neither is stream-capture
6996 // safe. Eager rides matmul/matmul_decode_exact, which dequant FloatBf16 on use. (§item 2.)
6997 let graph_draft = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
6998 && !spec_host_embd()
6999 && mtp_dense
7000 && trunk_dense
7001 && k + 2 < 96
7002 && !crate::model::full_prec_enabled();
7003 let was_tracking = e.ctx().is_event_tracking();
7004 if graph_draft && was_tracking {
7005 unsafe {
7006 e.ctx().disable_event_tracking();
7007 }
7008 }
7009 let r = self.generate_spec_inner2(
7010 e,
7011 suffix,
7012 max_new,
7013 k,
7014 graph_draft,
7015 Some(sess),
7016 sampling,
7017 constraint,
7018 on_commit,
7019 prime_split,
7020 None,
7021 );
7022 if graph_draft && was_tracking {
7023 unsafe {
7024 e.ctx().enable_event_tracking();
7025 }
7026 }
7027 let (out, d, a) = r?;
7028 Ok((out, d, a))
7029 }
7030
7031 pub fn generate_spec(
7032 &self,
7033 e: &Engine,
7034 prompt: &[u32],
7035 max_new: usize,
7036 k: usize,
7037 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
7038 let mtp_dense = self
7039 .mtp
7040 .as_ref()
7041 .map(|m| matches!(m.ffn, crate::hybrid::Ffn::Dense { .. }))
7042 .unwrap_or(false);
7043 let trunk_dense = self
7044 .layers
7045 .iter()
7046 .all(|l| matches!(l.ffn, crate::hybrid::Ffn::Dense { .. }));
7047 // FULL_PREC forces eager (see generate_spec_session note): CUDA graph capture cannot
7048 // enclose cuBLASLt f32 GEMV or the bf16_to_f32 dequant alloc the FloatBf16 path needs.
7049 let graph_draft = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
7050 && !spec_host_embd()
7051 && mtp_dense
7052 && trunk_dense
7053 && k + 2 < 96
7054 && !crate::model::full_prec_enabled();
7055 if !graph_draft {
7056 return self.generate_spec_inner2(
7057 e, prompt, max_new, k, false, None, None, None, None, None, None,
7058 );
7059 }
7060 let was_tracking = e.ctx().is_event_tracking();
7061 if was_tracking {
7062 unsafe {
7063 e.ctx().disable_event_tracking();
7064 }
7065 }
7066 let r = self.generate_spec_inner2(
7067 e, prompt, max_new, k, true, None, None, None, None, None, None,
7068 );
7069 if was_tracking {
7070 unsafe {
7071 e.ctx().enable_event_tracking();
7072 }
7073 }
7074 r
7075 }
7076
7077 fn generate_spec_inner2(
7078 &self,
7079 e: &Engine,
7080 prompt: &[u32],
7081 max_new: usize,
7082 k: usize,
7083 graph_draft: bool,
7084 mut sess: Option<&mut SpecSession>,
7085 sampling: Option<SpecSampling>,
7086 mut constraint: Option<&mut dyn SpecConstraint>,
7087 mut on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
7088 prime_split: Option<usize>,
7089 pipe: Option<&SpecPipeLane>,
7090 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
7091 assert!(k >= 1, "k must be >= 1");
7092 if let Some(p) = pipe {
7093 p.setup_begin()?;
7094 }
7095 // sse-cadence flush cursor: everything in out[..flushed] has been handed to on_commit.
7096 let mut flushed = 0usize;
7097 // admission yield (2026-08-06): on_commit's continue-verdict; false = end the burst
7098 // at the next round boundary (same exit as max_new reached — the session tail runs).
7099 // Initialized by the unconditional post-prime flush below.
7100 let mut keep_going;
7101 let mtp = self
7102 .mtp
7103 .as_ref()
7104 .expect("generate_spec requires an MTP head (nextn_predict_layers>0)");
7105 let n_vocab = self.output.out_features();
7106 // FR-Spec: the draft head may be TRIMMED (fewer rows than n_vocab); the draft argmax runs
7107 // over the draft vocab and the winning index maps through d2t to a TARGET token id.
7108 // Everything downstream (verify/accept/commit) sees target ids only — exactness unchanged.
7109 let d_vocab = mtp
7110 .shared_head_head
7111 .as_ref()
7112 .unwrap_or(&self.output)
7113 .out_features();
7114 let n_embd = self.cfg.n_embd as usize;
7115 // SESSION MODE: reuse the live cache/scratch, prime only the suffix. `base` = tokens
7116 // already committed (their state is in the caches); 0 = fresh single-shot call.
7117 let session_mode = sess.is_some();
7118 let max_ctx = match sess.as_ref() {
7119 Some(s) => s.cache.max_ctx,
7120 None => prompt.len() + max_new + k + 8,
7121 };
7122 let mut own_cache;
7123 let mut own_scratch;
7124 // PREFIX-CACHE capture request threaded out of the session (lane/spec-prefix-cache):
7125 // (requested split, destination slot). Single-shot per burst; fresh calls have none.
7126 let mut sess_capture: Option<(Option<usize>, &mut Option<SpecBoundaryCapture>)> = None;
7127 let (
7128 cache,
7129 scratch,
7130 mut sess_tail,
7131 mut sess_draft_slot,
7132 mut sess_pending_slot,
7133 sess_ckpt_slot,
7134 sess_telem,
7135 ): (
7136 &mut Cache,
7137 &mut MtpScratch,
7138 Option<(
7139 &mut Vec<u32>,
7140 &mut Option<CudaSlice<f32>>,
7141 &mut Option<u32>,
7142 &mut u32,
7143 &mut u32,
7144 )>,
7145 Option<&mut Option<DraftGraphCtx>>,
7146 Option<&mut Option<u32>>,
7147 Option<&mut Option<SpecCheckpoint>>,
7148 Option<&SpecTelemetryCounters>,
7149 ) = match sess.take() {
7150 Some(sr) => {
7151 let SpecSession {
7152 cache,
7153 scratch,
7154 committed,
7155 last_h,
7156 next_pred,
7157 sctr: s_sctr,
7158 uctr: s_uctr,
7159 draft_ctx,
7160 pending_tok,
7161 turn_ckpt,
7162 telem,
7163 capture_at,
7164 boundary_capture,
7165 } = sr;
7166 sess_capture = Some((capture_at.take(), boundary_capture));
7167 (
7168 cache,
7169 scratch,
7170 Some((committed, last_h, next_pred, s_sctr, s_uctr)),
7171 Some(draft_ctx),
7172 Some(pending_tok),
7173 Some(turn_ckpt),
7174 Some(telem),
7175 )
7176 }
7177 None => {
7178 // STAGE-OWNED KV (lane/pp2-spec 2026-08-06) — see `new_session`. Door shut =
7179 // `Cache::new` verbatim.
7180 own_cache = crate::pp::new_cache(e, &self.cfg, max_ctx)?;
7181 // Persistent scratch = max_ctx rows (~2KB/token quantized).
7182 own_scratch = MtpScratch::new(
7183 e,
7184 &self.cfg,
7185 max_ctx,
7186 self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
7187 )?;
7188 (
7189 &mut own_cache,
7190 &mut own_scratch,
7191 None,
7192 None,
7193 None,
7194 None,
7195 None,
7196 )
7197 }
7198 };
7199 let base = cache.pos;
7200 // PENDING-CARRY consume (2026-08-01): a carried bonus reaches here only on the
7201 // empty-suffix GREEDY continuation path (generate_spec_session_sampled flushed every
7202 // other case). It enters the round loop as round-0's pending — verify col 0 — exactly
7203 // like a mid-burst full-accept boundary: no init feed, no tail commit pass.
7204 let carried_pending: Option<u32> = sess_pending_slot.as_mut().and_then(|s| s.take());
7205 // PERSISTENT DRAFT KV (the only mode since 2026-07-08 — the legacy round-local scratch,
7206 // MEMRA_SPEC_KVLOCAL, measured -35 acceptance pts on the 27B p3 sweep and was removed;
7207 // acceptance-only — exactness is verify's job either way).
7208 // HIDDEN-PAIRING CONVENTION (DEFAULT = predecessor-row, 2026-07-04 — the 27B acceptance
7209 // unlock, +16pts): the MTP head is TRAINED on rows pairing token x_p with the trunk
7210 // hidden of its PREDECESSOR h_{p-1} (the reference engine's mtp_update shifts the target
7211 // hiddens right by one; its draft step 0 feeds (id_last, TRUE hidden of the row id_last
7212 // was sampled from)). memra's historical convention paired SAME-ROW (x_p, h_p) in the fill
7213 // and seeded chain step 0 through an extra MTP pass on a duplicated token (the
7214 // pseudo-seed) — measured 27B p2 K=3 acceptance 0.569 vs 0.731, p3 0.445 vs 0.63+, and
7215 // the chain steps j>=1 were already predecessor-shaped, so ONLY the fill + step-0 seed
7216 // move. The fill shifts by one and the chain seeds from the predecessor's true hidden
7217 // DIRECTLY (vh_seed / vx[j-1]) — the pseudo pass disappears (one MTP-block pass saved
7218 // per round on top of the acceptance win). Draft-quality-only: exactness stays the
7219 // verify's job either way. (The legacy same-row pairing seam, MEMRA_SPEC_HSAME, and its
7220 // pseudo-seed passes were removed 2026-07-08 — predecessor pairing won by +16 acc pts;
7221 // the legacy round-local scratch, MEMRA_SPEC_KVLOCAL, went with it.)
7222 // REPLAY-FREE PARTIAL ACCEPT (default, 2026-07-03): partial rounds keep the verify's own
7223 // bit-identical committed-prefix state (KV truncate + recur rebuild from the VerifyCkpt)
7224 // and leave the bonus PENDING — no duplicate trunk pass (profiled ~0.54 extra full weight
7225 // reads/round at long ctx). MEMRA_SPEC_REPLAY=1 restores the legacy rollback+replay (A/B
7226 // + fallback seam).
7227 // Qwen35-MoE stays on the correctness reference path until its retained verify-state
7228 // commit is proven equivalent to sequential serving on the long-prompt gate. Replaying
7229 // every accepted round through the serving-class verifier is slower, but prevents a
7230 // numerically exact verify result from carrying a drifted recurrent cache into the next
7231 // round. DENSE qwen35 runs replay-free: its verify already executes the serving batched
7232 // class (qwen35_verify_batch_layers), and the serving-class replay loop below steps
7233 // per-row T=1 (replay.len() full weight reads/round — measured 69 -> 30 tok/s on
7234 // Qwen3.8-27B, 2026-08-15); the replay-free VerifyCkpt commit is gated bit-identical by
7235 // the spec-serve battery before release.
7236 let spec_replay = spec_replay_env_enabled()
7237 || matches!(self.cfg.arch, memra_gguf::config::Arch::Qwen35Moe);
7238 if constraint.is_some() && spec_replay {
7239 return Err(
7240 "constrained spec decode does not support MEMRA_SPEC_REPLAY=1 \
7241 (legacy replay commits an unmasked bonus)"
7242 .into(),
7243 );
7244 }
7245 // TRUE-HIDDEN REFRESH (default in persistent-draft-KV mode): every round overwrites the
7246 // committed positions' scratch entries from the verify's exact hiddens (mtp_kv_fill batch)
7247 // instead of keeping chain-approximate entries. MEMRA_SPEC_NOREFRESH=1 = legacy (A/B seam).
7248 let refresh = std::env::var("MEMRA_SPEC_NOREFRESH").is_err();
7249
7250 // prime: BATCHED cache prime (prime_cache — the measured #1 e2e gap: tokenwise primed at
7251 // ~102/38 tok/s vs the engine's ~2000-5900 tok/s batched prefill). prime_cache returns the
7252 // full pre-output_norm hidden stack [T, n_embd], which IS prompt_h (the persistent-draft-KV
7253 // mtp_kv_fill input) — no per-token collection needed. Prompts below PRIME_MIN_T, and
7254 // MEMRA_PRIME_TOKENWISE=1, and frozen Hy3 CPU/GPU expert splits take the tokenwise
7255 // decode_step_h loop. The latter avoids transient GPU staging of the spilled expert bank.
7256 // EMPTY-SUFFIX CONTINUATION (serve bursts): a session turn with NO new tokens resumes
7257 // generation exactly where the last turn stopped — no prime at all. The stashed
7258 // `next_pred` plays prime_logits' role: it is the token produced from the logits after
7259 // committed.last() by the same rule this entry applies to a cold prime's last row —
7260 // an argmax when greedy, a `sample_boundary_token` draw when sampled (the burst tail,
7261 // or `spec_session_from_restored` for a converted prefix-cache hit, did the drawing
7262 // where the sampler and the session's Philox counters were live). `last_h` seeds the
7263 // predecessor pairing below. Fresh calls and non-empty suffixes take the normal path.
7264 let continuation = prompt.is_empty();
7265 if continuation {
7266 assert!(session_mode, "empty prompt requires a session");
7267 assert!(
7268 sess_tail
7269 .as_ref()
7270 .map_or(false, |(c, lh, np, _, _)| !c.is_empty()
7271 && lh.is_some()
7272 && (np.is_some() || carried_pending.is_some())),
7273 "empty-suffix continuation needs a primed session (committed + last_h + next_pred|pending)"
7274 );
7275 }
7276 let mut prime_logits;
7277 let mut prompt_h: Option<CudaSlice<f32>> = None;
7278 let t_prime = std::time::Instant::now();
7279 let batched_prime = !continuation
7280 && prompt.len() >= crate::hybrid_forward::PRIME_MIN_T
7281 && std::env::var("MEMRA_PRIME_TOKENWISE").is_err()
7282 && !e.frozen_cpu_experts_prefer_tokenwise_prime();
7283 let prime_split = prime_split.filter(|&split| split > 0 && split < prompt.len());
7284 if prime_split.is_some() && (continuation || base != 0) {
7285 return Err("spec prime split is cold-session-only".into());
7286 }
7287 if continuation {
7288 prime_logits = Vec::new();
7289 } else if let Some(split) = prime_split {
7290 if split < crate::hybrid_forward::PRIME_MIN_T {
7291 return Err(format!(
7292 "spec prime split {split} is below PRIME_MIN_T {}",
7293 crate::hybrid_forward::PRIME_MIN_T,
7294 )
7295 .into());
7296 }
7297 // Mirror the plain worker's affinity boundary exactly. The prefix is a request-level
7298 // prime (`queued_after` keeps Step35 arm selection independent of this stop); a tail
7299 // below PRIME_MIN_T then takes the same eager tokenwise continuation as prefill_tick.
7300 // Retain every hidden row so the draft scratch fill remains one coherent prompt.
7301 let mut h_all = e.uninit(prompt.len() * n_embd)?;
7302 let (l, _, h_prefix) =
7303 self.prime_cache(e, &prompt[..split], &mut *cache, prompt.len() - split)?;
7304 e.copy_into(&mut h_all, 0, &h_prefix, split * n_embd)?;
7305 prime_logits = l;
7306 // PREFIX-CACHE BOUNDARY CAPTURE (lane/spec-prefix-cache): the GDN conv/ssm states
7307 // are about to be advanced in place by the tail prime, so this is the ONLY moment
7308 // the boundary's recurrent state exists. Capture iff the worker requested exactly
7309 // this split. cache.pos == split here (the prefix prime just finished). A failed
7310 // snapshot is silent (turn_ckpt convention) — publication is an optimization,
7311 // never a correctness dependency.
7312 if let Some((requested, slot)) = sess_capture.as_mut() {
7313 if *requested == Some(split) {
7314 debug_assert_eq!(cache.pos, split, "boundary capture off the prime split");
7315 if let Ok(snap) = cache.snapshot(e) {
7316 **slot = Some(SpecBoundaryCapture {
7317 snap,
7318 pos: split,
7319 logits: prime_logits.clone(),
7320 // rows [0..split) of h_all are the prefix prime's hiddens — copied
7321 // just above, before the tail prime overwrites nothing (append-only).
7322 last_h: capture_boundary_hidden(e, &h_all, split, n_embd),
7323 });
7324 }
7325 }
7326 }
7327 let tail = &prompt[split..];
7328 if tail.len() >= crate::hybrid_forward::PRIME_MIN_T
7329 && std::env::var("MEMRA_PRIME_TOKENWISE").is_err()
7330 && !e.frozen_cpu_experts_prefer_tokenwise_prime()
7331 {
7332 let (l, _, h_tail) = self.prime_cache(e, tail, &mut *cache, 0)?;
7333 e.copy_into(&mut h_all, split * n_embd, &h_tail, tail.len() * n_embd)?;
7334 prime_logits = l;
7335 } else {
7336 for (i, &tok) in tail.iter().enumerate() {
7337 let (l, h) = self.decode_step_h(e, tok, &mut *cache)?;
7338 e.copy_into(&mut h_all, (split + i) * n_embd, &h, n_embd)?;
7339 prime_logits = l;
7340 }
7341 }
7342 if std::env::var("MEMRA_SPEC_STATS").as_deref() == Ok("1") {
7343 eprintln!("[spec-prime] affinity split={split} tail={}", tail.len());
7344 }
7345 prompt_h = Some(h_all);
7346 } else if batched_prime {
7347 let (l, _h_seed, hiddens) = self.prime_cache(e, prompt, &mut *cache, 0)?;
7348 prime_logits = l;
7349 prompt_h = Some(hiddens);
7350 } else {
7351 prime_logits = Vec::new();
7352 prompt_h = Some(e.uninit(prompt.len() * n_embd)?);
7353 for (i, &tok) in prompt.iter().enumerate() {
7354 let (l, h) = self.spec_target_step_h(e, tok, &mut *cache)?;
7355 if let Some(ph) = prompt_h.as_mut() {
7356 e.copy_into(ph, i * n_embd, &h, n_embd)?;
7357 }
7358 prime_logits = l;
7359 }
7360 }
7361 e.stream().synchronize()?;
7362 // PREFIX-CACHE SEED CAPTURE (lane/spec-prefix-cache): boundary == prompt end (the seed
7363 // case — no shared-prefix split, publish the whole prompt). The prime just finished, so
7364 // cache.pos == base + prompt.len() and the recurrent state IS the boundary state;
7365 // prime_logits are the boundary logits. Cold sessions only (base == 0) — same law as
7366 // prime_split. The mid-prompt capture above already consumed the request if it matched.
7367 if !continuation && base == 0 {
7368 if let Some((requested, slot)) = sess_capture.as_mut() {
7369 if *requested == Some(prompt.len()) && slot.is_none() {
7370 debug_assert_eq!(cache.pos, prompt.len(), "seed capture off prompt end");
7371 if let Ok(snap) = cache.snapshot(e) {
7372 **slot = Some(SpecBoundaryCapture {
7373 snap,
7374 pos: prompt.len(),
7375 logits: prime_logits.clone(),
7376 last_h: prompt_h
7377 .as_ref()
7378 .map(|ph| capture_boundary_hidden(e, ph, prompt.len(), n_embd))
7379 .unwrap_or_default(),
7380 });
7381 }
7382 }
7383 }
7384 }
7385 // Harness timing contract (see crate::PRIME_NANOS): gen-only throughput without the
7386 // prime-subtraction hack.
7387 crate::PRIME_NANOS.store(
7388 t_prime.elapsed().as_nanos() as u64,
7389 std::sync::atomic::Ordering::Relaxed,
7390 );
7391
7392 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
7393 // Resident table is fastest when it fits. Large spill deployments can preserve that HBM
7394 // for expert-cache slots and gather only the exact rows needed by MTP/verify from host.
7395 let host_embd = spec_host_embd();
7396 let embd_gpu = if host_embd {
7397 None
7398 } else {
7399 Some(
7400 self.embd_gpu
7401 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
7402 )
7403 };
7404 let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
7405 if host_embd {
7406 eprintln!(
7407 "[spec] host-row embedding: {} bytes kept off HBM",
7408 self.embd.raw.len()
7409 );
7410 }
7411 let mut out: Vec<u32> = Vec::with_capacity(max_new);
7412 let mut total_drafted = 0usize;
7413 let mut total_accepted = 0usize;
7414
7415 // --- SAMPLER FIRST (lane/sampled-spec-quality, 2026-08-19) ---
7416 // The sampler config, the session's Philox counters and the penalty window are parsed
7417 // HERE, above the boundary-token selection, because the boundary token must be drawn
7418 // from the sampler the request asked for. Pre-lane this block sat ~50 lines BELOW the
7419 // selection, which is the whole mechanical reason the boundary token was an argmax:
7420 // the sampler state was not in scope yet. Nothing here depends on the round loop, so
7421 // moving it up is a pure reordering for greedy (`sampled == false` ⇒ every branch
7422 // below takes the argmax path it always took).
7423 // --- SAMPLED SPEC (MEMRA_SPEC_TEMP>0, research/sampled-spec-impl-map.md): rejection-
7424 // sampling verify (Leviathan/Chen) — accept draft x at u < p(x)/q(x), resample from
7425 // norm(max(0,p-q)) on reject, bonus sampled from p on full accept. Counter-based Philox
7426 // everywhere (seed, event) -> reproducible. temp==0/unset = the greedy path, untouched.
7427 let sp = sampling.unwrap_or_else(|| SpecSampling {
7428 temp: std::env::var("MEMRA_SPEC_TEMP")
7429 .ok()
7430 .and_then(|v| v.parse().ok())
7431 .unwrap_or(0.0),
7432 seed: std::env::var("MEMRA_SEED")
7433 .ok()
7434 .and_then(|v| v.parse().ok())
7435 .unwrap_or(42),
7436 top_k: std::env::var("MEMRA_TOP_K")
7437 .ok()
7438 .and_then(|v| v.parse().ok())
7439 .unwrap_or(0),
7440 top_p: std::env::var("MEMRA_TOP_P")
7441 .ok()
7442 .and_then(|v| v.parse().ok())
7443 .unwrap_or(1.0),
7444 min_p: std::env::var("MEMRA_MIN_P")
7445 .ok()
7446 .and_then(|v| v.parse().ok())
7447 .unwrap_or(0.0),
7448 penalty_last_n: std::env::var("MEMRA_PENALTY_LAST_N")
7449 .ok()
7450 .and_then(|v| v.parse().ok())
7451 .unwrap_or(0),
7452 penalty_repeat: std::env::var("MEMRA_PENALTY_REPEAT")
7453 .ok()
7454 .and_then(|v| v.parse().ok())
7455 .unwrap_or(1.0),
7456 penalty_freq: std::env::var("MEMRA_PENALTY_FREQ")
7457 .ok()
7458 .and_then(|v| v.parse().ok())
7459 .unwrap_or(0.0),
7460 penalty_present: std::env::var("MEMRA_PENALTY_PRESENT")
7461 .ok()
7462 .and_then(|v| v.parse().ok())
7463 .unwrap_or(0.0),
7464 });
7465 let (sp_temp, sp_seed) = (sp.temp, sp.seed);
7466 let sampled = sp_temp > 0.0;
7467 // Counters resume from the session (burst continuity: randomness must never repeat
7468 // across generate_spec_session calls); one-shot callers start at (0,0). Read through
7469 // sess_tail — `sess` was take()n into it above, so sess.as_ref() here is always None.
7470 let mut sctr: u32 = sess_tail.as_ref().map(|(_, _, _, s, _)| **s).unwrap_or(0);
7471 let mut uctr: u32 = sess_tail.as_ref().map(|(_, _, _, _, u)| **u).unwrap_or(0);
7472 // Penalties (v2.1): applied to COPIES of q rows and p columns symmetrically (exactness
7473 // for the penalized+filtered target). History = generated tokens, host-tracked window.
7474 let pen_on = sampled
7475 && sp.penalty_last_n > 0
7476 && (sp.penalty_repeat != 1.0 || sp.penalty_freq != 0.0 || sp.penalty_present != 0.0);
7477 // SESSION-SPANNING PENALTY WINDOW (Item 2). Pre-lane this was
7478 // `prompt.iter().rev().take(64).rev()` — the BURST's suffix slice — so a continuation
7479 // burst (the majority of a stream's tokens, and ALL of a converted cache hit's) started
7480 // with an EMPTY penalty history and the client's repetition/frequency/presence penalties
7481 // silently reset at every burst boundary. The window now spans `committed ++ prompt`,
7482 // which is what the API contract says and what the plain sampler's own `history` does.
7483 // Byte-identical to the pre-lane seed for a cold turn-1 burst at the default window.
7484 let mut pen_hist: Vec<u32> = if pen_on {
7485 let sess_hist: &[u32] = if spec_pen_session_on() {
7486 sess_tail
7487 .as_ref()
7488 .map(|(c, ..)| c.as_slice())
7489 .unwrap_or(&[])
7490 } else {
7491 &[] // MEMRA_SPEC_PEN_SESSION=0: pre-lane burst-local window
7492 };
7493 pen_window_seed(sess_hist, prompt, sp.penalty_last_n)
7494 } else {
7495 Vec::new()
7496 };
7497 // First generated token = the BOUNDARY token: greedy takes the argmax of the prompt's
7498 // last logits (== greedy's first token, byte-contract); SAMPLED draws it from the
7499 // request's own filtered/penalized target through the session's Philox stream
7500 // (`sample_boundary_token`, lane/sampled-spec-quality Item 1 — pre-lane this was an
7501 // argmax in both regimes, so ~1 token per burst of a sampled stream was greedy).
7502 // Emit it, then FEED it to establish the loop invariant below.
7503 // PENDING-CARRY: the carried bonus was already emitted by the LAST burst — it becomes
7504 // last_token WITHOUT re-emission, and round 0 consumes it as pending (no init feed).
7505 // CONSTRAINED entry rules: the first emitted token is the MASKED argmax of the
7506 // prompt's last logits (plain constrained-greedy identity); a continuation without
7507 // a carried pending would emit an UNMASKED stashed next_pred — refused loudly (the
7508 // worker never resumes constrained sessions from the pool, so this cannot fire).
7509 if let Some(c) = constraint.as_deref_mut() {
7510 if continuation && carried_pending.is_none() {
7511 return Err("constrained spec continuation requires a carried pending \
7512 (pool resume is unconstrained-only)"
7513 .into());
7514 }
7515 if !continuation {
7516 c.mask_logits(&mut prime_logits)
7517 .map_err(|e2| format!("constraint: {e2}"))?;
7518 }
7519 }
7520 let mut last_token = if let Some(b) = carried_pending {
7521 b
7522 } else if continuation {
7523 // A continuation's boundary token was DRAWN by the burst that stashed it (the
7524 // session tail below), or by `spec_session_from_restored` for a converted
7525 // prefix-cache hit — in both cases from the correct logits row with this same
7526 // session's Philox stream, which is why it can be consumed here as-is.
7527 sess_tail.as_ref().unwrap().2.unwrap()
7528 } else if sampled && constraint.is_none() && spec_sampled_boundary_on() {
7529 sample_boundary_token(e, &prime_logits, &sp, &pen_hist, &mut sctr, "cold-prime")?
7530 } else {
7531 // greedy (byte contract), the rollback door, or constrained (masked-argmax
7532 // identity — the worker routes sampled+constrained to the plain path, and this
7533 // function refuses the combination outright above).
7534 argmax(&prime_logits) as u32
7535 };
7536 if pen_on {
7537 // The boundary token is a GENERATED token: the plain sampler `accept()`s every
7538 // emitted token into its penalty history, and pre-lane the burst's first token
7539 // was invisible to penalties forever (never pushed, and never in `committed`
7540 // until this burst's tail). Covers the carry/continuation seeds too — neither is
7541 // in `committed` yet.
7542 pen_hist.push(last_token);
7543 }
7544 if carried_pending.is_none() {
7545 out.push(last_token);
7546 // grammar advances with every emitted token (carried pendings were consumed
7547 // by the burst that emitted them).
7548 if let Some(c) = constraint.as_deref_mut() {
7549 c.consume(last_token)
7550 .map_err(|e2| format!("constraint: {e2}"))?;
7551 }
7552 }
7553 if continuation {
7554 // draft-KV invariant: entries [0..base) are the session's exact fills; truncate any
7555 // overhang so the chain's first append lands at slot base (== committed.len()).
7556 scratch.set_len(e, base)?;
7557 }
7558 // sse-cadence: hand the caller every not-yet-flushed token (disjoint in-order slices
7559 // concatenating to the full `out`). Called after the prime's first token and after each
7560 // round commit — emission timing only, token bytes untouched. The slice may be EMPTY
7561 // (poll-only boundary: zero-round folds commit nothing new); returns the caller's
7562 // continue-verdict (admission yield, 2026-08-06) — false ends the burst at this round.
7563 fn flush_commit(
7564 cb: &mut Option<&mut dyn FnMut(&[u32]) -> bool>,
7565 out: &[u32],
7566 flushed: &mut usize,
7567 ) -> bool {
7568 if let Some(f) = cb.as_mut() {
7569 let keep = f(&out[*flushed..]);
7570 *flushed = out.len();
7571 keep
7572 } else {
7573 true
7574 }
7575 }
7576 keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
7577 // INVARIANT at loop top: `last_token` is the most-recently-committed/emitted token, its
7578 // KV+recur state IS in `cache` (cache.pos = position right AFTER last_token), `last_pred`
7579 // is the greedy ARGMAX of the logits that predict the token FOLLOWING last_token, and
7580 // `h_seed` = last_token's pre-output_norm hidden. Establish it by feeding last_token once
7581 // (mirrors plain greedy). DEVICE-ARGMAX lever: the accept walk only ever consumes the
7582 // argmax of those logits — never the full vector — so a host u32 replaces the Vec<f32>.
7583 // Trimmed heads: q lives on the trimmed vocab; accept gathers use the TRIMMED index and
7584 // the residual scatters q into target-id space (q=-inf off-trim — the head cannot propose
7585 // those, so their residual mass is p(x), correct by construction).
7586 let d2t_dev: Option<CudaSlice<u32>> = if sampled || crate::spec::spec_stream() {
7587 match &mtp.d2t {
7588 Some(map) => Some(e.htod_u32_v(map)?),
7589 None => None,
7590 }
7591 } else {
7592 None
7593 };
7594 let mut q_full_buf: Option<CudaSlice<f32>> = None;
7595 // host Philox4x32-10 (mirrors spec_sample.cu; independent stream via ctr_lo tag)
7596 let host_u01 = |seed: u64, ctr: u32| -> f32 {
7597 let (m0, m1) = (0xD2511F53u32, 0xCD9E8D57u32);
7598 let (mut c0, mut c1, mut c2, mut c3) = (0xFFFF_FFFEu32, ctr, 0u32, 0u32);
7599 let (mut k0, mut k1) = ((seed & 0xFFFF_FFFF) as u32, (seed >> 32) as u32);
7600 for _ in 0..10 {
7601 let (h0, l0) = (((m0 as u64 * c0 as u64) >> 32) as u32, m0.wrapping_mul(c0));
7602 let (h1, l1) = (((m1 as u64 * c2 as u64) >> 32) as u32, m1.wrapping_mul(c2));
7603 let (n0, n1, n2, n3) = (h1 ^ c1 ^ k0, l1, h0 ^ c3 ^ k1, l0);
7604 c0 = n0;
7605 c1 = n1;
7606 c2 = n2;
7607 c3 = n3;
7608 k0 = k0.wrapping_add(0x9E3779B9);
7609 k1 = k1.wrapping_add(0xBB67AE85);
7610 }
7611 (c0 as f32 + 1.0) * (1.0 / 4294967296.0)
7612 };
7613 let mut draft_logits: Vec<CudaSlice<f32>> = Vec::new(); // retained head logits (q), per slot
7614 let mut draft_stats: Vec<(f32, f32, f32)> = Vec::new(); // (row_max, th_e, z_e) per slot
7615 let mut perturb_buf: Option<CudaSlice<f32>> = None; // gumbel scratch (max(n_vocab,d_vocab))
7616 let mut sample_tok = e.alloc_u32_zeroed(1)?; // residual/bonus sample out
7617 let mut col_buf: Option<CudaSlice<f32>> = None; // materialized verify column
7618 let mut pen_hist_d: Option<CudaSlice<u32>> = None;
7619 let mut pcol_buf: Option<CudaSlice<f32>> = None; // penalized p-column scratch
7620 // MEMRA_SPEC_SETUP_TRACE=1 (diagnostics): per-call wall decomposition of the burst
7621 // SETUP + TAIL segments (the round loop's internals are MEMRA_SPEC_PHASE's job) —
7622 // built to pin the serve per-burst fixed cost (research/spec-serving-20260801).
7623 let setup_trace = std::env::var("MEMRA_SPEC_SETUP_TRACE").as_deref() == Ok("1");
7624 let t_ent = std::time::Instant::now();
7625
7626 // SESSION-AFFINITY TURN CHECKPOINT (lane/session-affinity, 2026-08-05): capture the
7627 // PROMPT-END boundary state so a LATER turn can rewind here and re-prime only its own
7628 // delta instead of the whole conversation. See `SpecCheckpoint` for why this boundary is
7629 // the one that matters (a history-rewriting client mutates what the session GENERATED,
7630 // so the next turn's prompt agrees with this one up to exactly here).
7631 //
7632 // WHERE — AND WHY THIS EXACT LINE. Right after the trunk prime, BEFORE the init feed
7633 // (`decode_step_h(last_token)`) and before round 0: the last instant at which the caches
7634 // hold exactly `base + prompt.len()` rows and nothing generated.
7635 //
7636 // This was WRONG in the first cut of this lane: the capture sat after the draft-KV fill,
7637 // which is also after the init feed, so `cache.pos` was `base + prompt.len() + 1` — the
7638 // boundary included the FIRST GENERATED TOKEN. That token is the first thing inside the
7639 // `<think>` block the client strips, so every later turn's diff diverged exactly one
7640 // token below the checkpoint and affinity declined 100% of the time. Measured on the
7641 // owner regime: "history diverged at 12233 of checkpoint 12234". The off-by-one made the
7642 // whole mechanism inert while looking, from the outside, like a working
7643 // correctness-declines-safely path — hence the decline log carries the offsets.
7644 //
7645 // The full-attn planes are `len`-truncatable so the snapshot copies only the GDN conv/ssm
7646 // state (the reason a spec session could not rewind before). The draft scratch needs no
7647 // copy: rows below the boundary are rewritten by the next turn's own fill.
7648 //
7649 // WHEN: non-empty prime only. An empty-suffix continuation burst adds no prompt boundary
7650 // (its "prompt end" IS the previous checkpoint's, already held), so it keeps the existing
7651 // checkpoint rather than replacing it with a strictly worse one.
7652 //
7653 // FAILURE IS SILENT BY DESIGN: on a VRAM-tight rig the snapshot alloc can fail. That
7654 // costs the NEXT turn its rewind (it re-primes fully, today's behavior) and must never
7655 // fail the burst that is already running — so the error is swallowed, loud only under
7656 // MEMRA_DEBUG_SPEC.
7657 if let Some(slot) = sess_ckpt_slot {
7658 if !continuation {
7659 let pos = cache.pos;
7660 debug_assert_eq!(
7661 pos,
7662 base + prompt.len(),
7663 "turn checkpoint must sit at the prompt end, before the init feed"
7664 );
7665 let anchor: Result<CudaSlice<f32>, Box<dyn std::error::Error>> =
7666 if let Some(ph) = &prompt_h {
7667 // hidden of the LAST primed row = the predecessor anchor at this
7668 // boundary (exactly what a fresh prime of committed[..pos] leaves in
7669 // last_h, and what the next prime's fill reads for its first row).
7670 let np = prompt.len();
7671 e.uninit(n_embd).and_then(|mut a| {
7672 e.copy_view_into(
7673 &mut a,
7674 0,
7675 &ph.slice((np - 1) * n_embd..np * n_embd),
7676 n_embd,
7677 )?;
7678 Ok(a)
7679 })
7680 } else {
7681 Err("no prompt hiddens".into())
7682 };
7683 match (cache.snapshot(e), anchor) {
7684 (Ok(snap), Ok(last_h)) => {
7685 *slot = Some(SpecCheckpoint { snap, pos, last_h });
7686 }
7687 (s, a) => {
7688 *slot = None; // a stale checkpoint would rewind to the WRONG boundary
7689 if std::env::var("MEMRA_DEBUG_SPEC").is_ok() {
7690 let err = s
7691 .err()
7692 .map(|e| e.to_string())
7693 .or_else(|| a.err().map(|e| e.to_string()))
7694 .unwrap_or_default();
7695 eprintln!(
7696 "[spec] turn checkpoint skipped ({err}); \
7697 next turn re-primes in full"
7698 );
7699 }
7700 }
7701 }
7702 }
7703 }
7704 // INIT FEED — skipped on a pending carry: last_token (the carried bonus) is NOT in the
7705 // caches and must NOT be fed solo; round 0's batched verify commits it as col 0. Its
7706 // seed/anchor hidden is the carried last_h (copied below); last_pred is dead in the
7707 // pending path (t_pred reads verify col 0 — the accept walk overwrites it).
7708 let mut last_pred = 0u32;
7709 let mut last_col_logits: Option<CudaSlice<f32>> = None;
7710 // CONSTRAINED: the init feed's logits back the (n_acc==0, base==0) masked-argmax
7711 // recompute in the grammar-truncation walk — retained host-side, round 0 only.
7712 let mut init_logits_host: Option<Vec<f32>> = None;
7713 let h_seed0: CudaSlice<f32> = if carried_pending.is_none() {
7714 let (init_logits, h) = self.spec_target_step_h(e, last_token, &mut *cache)?;
7715 last_pred = argmax(&init_logits) as u32;
7716 if constraint.is_some() {
7717 init_logits_host = Some(init_logits.clone());
7718 }
7719 // sampled mode: p-distribution after last_token, for the j==0/base==0 accept test.
7720 if sampled {
7721 last_col_logits = Some(e.htod(&init_logits)?);
7722 }
7723 h
7724 } else {
7725 // predecessor-row anchor: hidden of the last COMMITTED row (the carry contract).
7726 let lh = sess_tail
7727 .as_ref()
7728 .unwrap()
7729 .1
7730 .as_ref()
7731 .expect("pending carry requires last_h");
7732 e.clone_dtod(lh)?
7733 };
7734 let t_init = t_ent.elapsed();
7735 let mut last_col_stats: Option<(f32, f32, f32)> = None;
7736 // PERSISTENT h_seed buffer (allocated BEFORE any graph capture so no captured scratch can
7737 // alias it): every path that updates the round seed copies INTO it — no per-round allocs,
7738 // stable pointer for the graph-draft round-start copy.
7739 let mut h_seed_buf = e.clone_dtod(&h_seed0)?;
7740 // Predecessor-pairing trackers: `fill_prev` = trunk hidden AT the last COMMITTED row (the
7741 // predecessor of the next verify's col 0 — the reference's carried pending-h analogue;
7742 // also the predecessor-row hidden for the round-0 legacy-replay seed). At round 0 that
7743 // row is last_token's own (h_seed0). The chain step-0 seed under the pairing default =
7744 // hidden of the row BEFORE last_token = the prompt's last row at round 0 (h_seed_buf
7745 // overwritten below).
7746 let mut fill_prev = e.clone_dtod(&h_seed0)?;
7747 {
7748 if let Some(ph) = &prompt_h {
7749 let np = prompt.len();
7750 e.copy_view_into(
7751 &mut h_seed_buf,
7752 0,
7753 &ph.slice((np - 1) * n_embd..np * n_embd),
7754 n_embd,
7755 )?;
7756 } else if continuation {
7757 if let Some((_, lh, _, _, _)) = sess_tail.as_ref() {
7758 if let Some(lh) = lh.as_ref() {
7759 e.copy_into(&mut h_seed_buf, 0, lh, n_embd)?;
7760 }
7761 }
7762 }
7763 }
7764 // Persistent device prediction slots for the accept walk (max k+1 verify columns).
7765 let mut preds_d = e.alloc_u32_zeroed(k + 2)?;
7766
7767 let debug_spec = std::env::var("MEMRA_DEBUG_SPEC").is_ok();
7768 let fork_mode = OptiForkGateMode::configured();
7769 // MEMRA_SPEC_STATS=1: per-slot accept histogram + draft-length histogram, printed once at
7770 // the end. Metric normalization vs the reference engine: BOTH engines count
7771 // accepted/drafted where the chain stopped at p-min and the sub-threshold token is
7772 // discarded uncounted — per-slot decay + chain-length mix are the extra dimensions.
7773 let spec_stats = std::env::var("MEMRA_SPEC_STATS").is_ok();
7774 let mut st_drafted = vec![0usize; k];
7775 let mut st_accepted = vec![0usize; k];
7776 let mut st_len_hist = vec![0usize; k + 1];
7777 let mut st_full = 0usize;
7778 // P-MIN CONFIDENCE GATE (MEMRA_SPEC_PMIN, the serve script's --spec-draft-p-min mechanism):
7779 // stop the draft chain early when the head's softmax confidence in its own pick drops
7780 // below p_min. Hoisted above the loop: the graph capture bakes the prob kernels iff on.
7781 static PMIN: std::sync::OnceLock<f32> = std::sync::OnceLock::new();
7782 let p_min = *PMIN.get_or_init(|| {
7783 std::env::var("MEMRA_SPEC_PMIN")
7784 .ok()
7785 .and_then(|v| v.parse().ok())
7786 .unwrap_or(0.0)
7787 });
7788 // ZERO-DRAFT ROUNDS (MEMRA_SPEC_PMIN0=1, vendored from llama.cpp's draft gating): let the
7789 // p-min gate apply at j==0 too, so a low-confidence round drafts NOTHING and the verify
7790 // batch is just the pending bonus (m=1 = a plain decode step). llama's 35B win rides
7791 // exactly this — draft acceptance 76% at mean len 2.5 because unpredictable stretches
7792 // never pay draft+verify overhead. Only legal when a pending bonus exists (an empty
7793 // verify batch is not); the j==0 exemption stays for pending-less rounds.
7794 let pmin0 = std::env::var("MEMRA_SPEC_PMIN0")
7795 .map(|v| v == "1")
7796 .unwrap_or(false);
7797
7798 // --- GRAPH DRAFT setup: persistent I/O buffers + ONE capture (2 warmups inside). The
7799 // warmups mutate scratch len_d / pos / tok / seed — all reset at every round start, so the
7800 // only restore needed is the scratch counter. Capture failure (e.g. a non-capturable
7801 // cuBLAS path in an exotic head) falls back to the eager draft chain.
7802 // PER-SESSION PERSISTENCE (2026-08-01): session calls reuse the DraftGraphCtx parked on
7803 // the SpecSession — the capture (2 warmup head forwards + instantiate) ran ONCE at the
7804 // session's first burst, not per burst (measured ~16ms/burst fixed cost on H100 q27,
7805 // research/spec-serving-20260801). Reuse is pointer-exact: the graph bakes the session's
7806 // own scratch KV (never realloc'd), the model's resident embedding, the OnceLock p_min,
7807 // and the g_* buffers carried in the ctx — replay dispatch is identical to a fresh
7808 // capture, so draft tokens are bit-identical (drafts never decide exactness anyway; the
7809 // verify arbitrates). Single-shot calls (sess=None) build a fresh ctx and drop it.
7810 let mut dctx: DraftGraphCtx = match sess_draft_slot.as_mut().and_then(|s| s.take()) {
7811 Some(c) => c,
7812 None => DraftGraphCtx::new(e, n_embd, if sampled { d_vocab } else { 1 })?,
7813 };
7814 // A session that ran greedy bursts first sized g_q/g_perturb at 1; a sampled resume
7815 // needs d_vocab. Realloc is legal exactly while graph_s is None (nothing baked them).
7816 if sampled && dctx.g_q.len() < d_vocab {
7817 dctx.g_q = e.zeros(d_vocab)?;
7818 dctx.g_perturb = e.zeros(d_vocab)?;
7819 }
7820 // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask, 2026-08-04): the drafter samples the
7821 // grammar's legal set, so proposals are legal BY CONSTRUCTION and the verify-side
7822 // truncation (the correctness backstop) stops cutting every tight-schema round.
7823 // The mask is one node inside the captured draft chain — presence is a CAPTURE-TIME
7824 // shape, so a parked graph of the other shape is dropped and recaptured.
7825 let dmask_on = constraint
7826 .as_deref()
7827 .is_some_and(|c| c.draft_mask_enabled());
7828 let dmask_words = if dmask_on { d_vocab.div_ceil(32) } else { 0 };
7829 if dmask_on && dctx.g_dmask.len() < dmask_words {
7830 dctx.g_dmask = e.alloc_u32_zeroed(dmask_words)?;
7831 dctx.graph = None; // the old capture baked the old (or no) mask pointer
7832 dctx.failed.clear_greedy();
7833 dctx.keeper.clear();
7834 }
7835 if dctx.graph.is_some() && dctx.graph_masked != dmask_on {
7836 dctx.graph = None;
7837 dctx.failed.clear_greedy();
7838 dctx.keeper.clear();
7839 }
7840 if graph_draft && !sampled && dctx.graph.is_none() && !dctx.failed.greedy_failed() {
7841 let DraftGraphCtx {
7842 g_tok,
7843 g_pos,
7844 g_seed,
7845 g_p,
7846 g_dmask,
7847 ..
7848 } = &mut dctx;
7849 // capture-time contents: ALL-ONES (ban nothing). A replay only ever runs after the
7850 // host uploads the position's real words, so the warmups stay grammar-free.
7851 if dmask_on {
7852 e.htod_u32_into(g_dmask, &vec![u32::MAX; dmask_words])?;
7853 }
7854 let g_dmask_ro: &CudaSlice<u32> = &*g_dmask;
7855 // CAPTURE-RETAIN (#68 fix): the warmup transients' pool addresses are baked into the
7856 // captured graph; the keeper pins them for the graph's lifetime. capture_graph (non-
7857 // retained) freed them at exit — safe for one-shot generate_spec (nothing else touches
7858 // the pool between replays) but WRONG for sessions: burst-boundary prime/fill/commit
7859 // passes (and, in serve, other sessions) recycle those addresses and the replay then
7860 // clobbers live buffers — the ST serve-spec corruption (research/serve-st-20260803).
7861 let cap_res = e.capture_graph_retained(|e| {
7862 self.mtp_head_forward_cap(
7863 e,
7864 mtp,
7865 g_tok,
7866 g_pos,
7867 g_seed,
7868 g_p,
7869 &mut *scratch,
7870 p_min > 0.0 || fork_mode == OptiForkGateMode::Controller,
7871 true,
7872 embd_gpu.expect("graph draft requires resident embedding"),
7873 embd_qt,
7874 embd_rb,
7875 d_vocab,
7876 None,
7877 None,
7878 if dmask_on {
7879 Some((g_dmask_ro, dmask_words))
7880 } else {
7881 None
7882 },
7883 )
7884 });
7885 match cap_res {
7886 Ok((g, keep)) => {
7887 scratch.set_len(e, base)?;
7888 dctx.graph = Some(g);
7889 dctx.graph_masked = dmask_on;
7890 dctx.keeper = keep;
7891 }
7892 Err(err) => {
7893 scratch.set_len(e, base)?;
7894 // LOUD flip (audit Q2): a dropped draft graph is a coverage loss, never
7895 // silent. Once per flip — mark returns None on an already-failed ctx.
7896 if let Some(line) = dctx.failed.mark_greedy(&err.to_string()) {
7897 eprintln!("{line}");
7898 }
7899 }
7900 }
7901 }
7902 // --- SAMPLED GRAPH DRAFT setup (step 3 of the sampled-spec arc): a SECOND capture, own
7903 // graph object, built only when sampled && graph-eligible — the greedy capture above is
7904 // untouched (and skipped when sampled: its graph would never be launched). Same head
7905 // forward, but the in-graph argmax reads GUMBEL-PERTURBED logits; the Philox event
7906 // counter lives in the persistent device g_ctr (bumped in-graph, host-seeded from sctr
7907 // once per round); the raw head logits land in the persistent g_q for the host's
7908 // per-replay async D2D into the round's q slot (q_slots, K x d_vocab, allocated once).
7909 // seed/temp are capture-time constants — baked into graph_s, so a pool-resumed request
7910 // with a different (seed, temp, k) drops the parked sampled graph and recaptures.
7911 // COST OF THE FRESH-SEED SERVE DEFAULT (dogfood F4, 2026-08-04): omitting `seed` on a
7912 // serve request now draws fresh per-request entropy (it used to default to a pinned 0),
7913 // so a seed-omitting request that RESUMES a parked spec session finds an s_key baked
7914 // with the PREVIOUS request's seed and pays one recapture. Bounded, and it does not
7915 // reopen the ~16ms/burst regression the persistent ctx exists to fix: a session's seed
7916 // is fixed for its whole lifetime (worker.rs reads s.sampler.seed() per burst), so
7917 // this compare misses at most ONCE per resumed request — the first burst recaptures
7918 // and every later burst in that request replays. A client that wants the parked graph
7919 // AND reproducibility supplies an explicit `seed`, honored exactly, which keeps s_key
7920 // stable across its whole conversation.
7921 // COMPOSITION RULE (fspec x gsd merge): the in-graph chain samples from the RAW
7922 // softmax — it can hold neither per-row filter stats nor the varying penalty history.
7923 // The sampled graph therefore engages only in the PURE-TEMP regime; filters/penalties
7924 // force the eager draft (which computes stats/penalties per row).
7925 let pure_temp = sp.top_k == 0 && sp.top_p >= 1.0 && sp.min_p <= 0.0 && !pen_on;
7926 let s_key = (sp_seed, sp_temp.to_bits(), k);
7927 if sampled && dctx.s_key.is_some_and(|old| old != s_key) {
7928 dctx.graph_s = None;
7929 dctx.failed.clear_sampled();
7930 dctx.s_key = None;
7931 dctx.q_slots.clear();
7932 dctx.keeper_s.clear();
7933 }
7934 if graph_draft
7935 && sampled
7936 && pure_temp
7937 && dctx.graph_s.is_none()
7938 && !dctx.failed.sampled_failed()
7939 {
7940 let DraftGraphCtx {
7941 g_tok,
7942 g_pos,
7943 g_seed,
7944 g_p,
7945 g_ctr,
7946 g_perturb,
7947 g_q,
7948 ..
7949 } = &mut dctx;
7950 // CAPTURE-RETAIN (#68 fix): same keeper contract as the greedy capture above.
7951 let cap_res = e.capture_graph_retained(|e| {
7952 self.mtp_head_forward_cap(
7953 e,
7954 mtp,
7955 g_tok,
7956 g_pos,
7957 g_seed,
7958 g_p,
7959 &mut *scratch,
7960 p_min > 0.0,
7961 true,
7962 embd_gpu.expect("graph draft requires resident embedding"),
7963 embd_qt,
7964 embd_rb,
7965 d_vocab,
7966 Some((g_ctr, g_perturb, g_q, sp_seed, sp_temp)),
7967 None,
7968 None, // constrained spec is greedy-only — sampled never carries a hook
7969 )
7970 });
7971 match cap_res {
7972 Ok((g, keep)) => {
7973 scratch.set_len(e, base)?;
7974 for _ in 0..k {
7975 dctx.q_slots.push(e.zeros(d_vocab)?);
7976 }
7977 dctx.graph_s = Some(g);
7978 dctx.s_key = Some(s_key);
7979 dctx.keeper_s = keep;
7980 }
7981 Err(err) => {
7982 scratch.set_len(e, base)?;
7983 // LOUD flip (audit Q2): same contract as the greedy capture above.
7984 if let Some(line) = dctx.failed.mark_sampled(&err.to_string()) {
7985 eprintln!("{line}");
7986 }
7987 }
7988 }
7989 }
7990 let t_cap = t_ent.elapsed();
7991 // PERSISTENT DRAFT KV: fill the MTP block's K/V for every prompt position from the exact
7992 // trunk hiddens collected during prime — ONE batched K/V-only pass (overwrites any
7993 // capture-warmup garbage; capture left len at 0). last_token (the init feed) needs no
7994 // fill: the first chain step processes it and appends its entry at slot prompt.len().
7995 if let Some(ph) = &prompt_h {
7996 // SESSION: rows [0..base) are the previous turns' exact fills (refresh overwrote them
7997 // with true verify hiddens) — truncate any draft overhang, fill ONLY the suffix at
7998 // global positions [base..base+tp). Fresh call: base==0, identical to before.
7999 scratch.set_len(e, base)?;
8000 // CHUNKED FILL (long-ctx OOM fix, 2026-07-05): mtp_kv_fill's transients scale with its
8001 // T (concat = T*2*n_embd*4B — 1.5GB at 40k) and its concat loop is 2*T launches. The
8002 // fill is a pure sequential append, so chunking is exact: each chunk appends its rows
8003 // at pos0=base+start with the identical per-row math. Same knob as the trunk prime.
8004 let tp = prompt.len();
8005 let fill_chunk: usize = if crate::cache::swa_ring_on() {
8006 crate::hybrid_forward::prime_chunk_tokens(tp, self.layers.len())
8007 } else {
8008 // Preserve the flag-OFF schedule byte-for-byte, including the legacy zero value
8009 // meaning one monolithic fill.
8010 std::env::var("MEMRA_PRIME_CHUNK")
8011 .ok()
8012 .and_then(|v| v.parse().ok())
8013 .unwrap_or(4096)
8014 };
8015 let fill_chunk = if fill_chunk == 0 { tp } else { fill_chunk };
8016 let mut start = 0usize;
8017 while start < tp {
8018 let end = (start + fill_chunk).min(tp);
8019 let tc = end - start;
8020 {
8021 // PREDECESSOR pairing: row i gets h[i-1]; global row 0 a zeros row (the
8022 // reference engine's initial pending-h is zeroed too); a session turn's row 0
8023 // gets the PREVIOUS turn's last committed hidden (sess.last_h). Per chunk:
8024 // rows start..end read h[start-1..end-1] — one dtod into a chunk buffer.
8025 let mut phs = e.zeros(tc * n_embd)?;
8026 let (src_lo, dst_off) = if start == 0 {
8027 (0, n_embd)
8028 } else {
8029 ((start - 1) * n_embd, 0)
8030 };
8031 let n_copy = if start == 0 {
8032 (tc - 1) * n_embd
8033 } else {
8034 tc * n_embd
8035 };
8036 if start == 0 {
8037 if let Some((_, lh, _, _, _)) = sess_tail.as_ref() {
8038 if let Some(lh) = lh.as_ref() {
8039 e.copy_into(&mut phs, 0, lh, n_embd)?;
8040 }
8041 }
8042 }
8043 if n_copy > 0 {
8044 e.copy_view_into(
8045 &mut phs,
8046 dst_off,
8047 &ph.slice(src_lo..src_lo + n_copy),
8048 n_copy,
8049 )?;
8050 }
8051 self.mtp_kv_fill(
8052 e,
8053 mtp,
8054 &prompt[start..end],
8055 &phs,
8056 base + start,
8057 &mut *scratch,
8058 embd_dev,
8059 )?;
8060 }
8061 start = end;
8062 }
8063 }
8064 // MEMRA_PROFILE_SPEC=2: profiler capture starts HERE — after the prime, so an
8065 // `nsys -c cudaProfilerApi` capture contains ONLY the round loop (draft/verify/commit).
8066 // (=1 brackets the whole call in run_spec.rs, prime included.)
8067 if std::env::var("MEMRA_PROFILE_SPEC").as_deref() == Ok("2") {
8068 unsafe extern "C" {
8069 fn cudaProfilerStart() -> i32;
8070 }
8071 unsafe {
8072 cudaProfilerStart();
8073 }
8074 }
8075 // ROUND-STREAM stage (c) 4 (MEMRA_SPEC_STREAM=1, experimental): pre-issued M-round
8076 // bursts with ZERO per-round host readbacks — the accept/seed/rollback/ring kernels
8077 // consume each other's device outputs; the host drains the ring every M rounds. v1
8078 // constraints: greedy, !spec_replay, single-shot, batched-linear layers, no refresh
8079 // fills (acceptance effect A/B-arbitrated), enters from round 1 (pending guaranteed).
8080 // NOTE: not gated on the caller's graph_draft (its trunk_dense conjunct turns the 35B
8081 // MoE off) — the stream capture encloses ONLY the dense MTP head; the head-dense /
8082 // full-prec / k gates are re-derived here and a failed capture degrades to stream-off.
8083 let stream_on = crate::spec::spec_stream()
8084 && !sampled
8085 && !spec_replay
8086 && constraint.is_none()
8087 && !session_mode
8088 && embd_gpu.is_some()
8089 && !crate::model::full_prec_enabled()
8090 && k + 2 < 96;
8091 let mut stream_graph: Option<cudarc::driver::CudaGraph> = None;
8092 let mut g_tokp2k = e.alloc_u32_zeroed(2 * k.max(1))?;
8093 if stream_on {
8094 let cap = e.capture_graph(|e| {
8095 for j in 0..k.max(1) {
8096 self.mtp_head_forward_cap(
8097 e,
8098 mtp,
8099 &mut dctx.g_tok,
8100 &mut dctx.g_pos,
8101 &mut dctx.g_seed,
8102 &mut dctx.g_p,
8103 &mut *scratch,
8104 true,
8105 true,
8106 embd_gpu.expect("round stream requires resident embedding"),
8107 embd_qt,
8108 embd_rb,
8109 d_vocab,
8110 None,
8111 Some((&mut g_tokp2k, j, d2t_dev.as_ref())),
8112 None, // round-stream requires constraint.is_none() (see stream_on)
8113 )?;
8114 }
8115 Ok(())
8116 });
8117 match cap {
8118 Ok(g) => {
8119 scratch.set_len(e, 0)?;
8120 stream_graph = Some(g);
8121 }
8122 Err(err) => {
8123 scratch.set_len(e, 0)?;
8124 if debug_spec {
8125 eprintln!("[spec] stream-graph capture failed ({err}); stream off");
8126 }
8127 }
8128 }
8129 }
8130 let stream_active = stream_on && stream_graph.is_some();
8131 if debug_spec {
8132 eprintln!(
8133 "[spec] stream_on={stream_on} env={} samp={sampled} dg={} captured={} active={stream_active} session={session_mode} replay={spec_replay}",
8134 crate::spec::spec_stream(),
8135 dctx.graph.is_some(),
8136 stream_graph.is_some()
8137 );
8138 }
8139 let t_v_s = k + 1;
8140 // ROUND-STREAM buffers + ptr tables now live in the model-generic round_stream
8141 // module (extracted 2026-07-12; the gemma burst reuses them).
8142 let sb = crate::round_stream::StreamBufs::new(e, k, crate::spec::spec_stream_m())?;
8143 let crate::round_stream::StreamBufs {
8144 mut vtok_d,
8145 mut brk_d,
8146 mut pend_d,
8147 last_pred_d,
8148 mut pos_ctr,
8149 mut pos_start_d,
8150 mut ring_d,
8151 acc_d: mut stream_acc,
8152 m_rounds,
8153 k: _,
8154 } = sb;
8155 let stream_ptrs: Option<CudaSlice<u64>> = if stream_active {
8156 Some(crate::round_stream::kv_len_ptr_table(
8157 e,
8158 cache,
8159 Some(&pos_ctr),
8160 )?)
8161 } else {
8162 None
8163 };
8164
8165 let t_fill = t_ent.elapsed();
8166 let mut round = 0usize;
8167 // ADAPTIVE DRAFT LENGTH (MEMRA_SPEC_ADAPT=1, opt-in — the gemma_spec accepted-run law,
8168 // ported 2026-08-01): next round's draft depth = last round's accepted run + 1, clamped
8169 // to [floor(pos), k_cap] — a miss shrinks the next draft to the miss point + 1,
8170 // full-accept streaks re-deepen one step per round. NOT the 2026-07-07 acceptance-EMA
8171 // (that arm measured an HONEST LOSS to static per-class optima — 115.0/85.8/73.4 vs
8172 // 121.6/92.7/75.6, EMA lag — and was removed 2026-07-08; rig5090.jsonl has the record).
8173 // The gemma law has no lag class: it reacts within one round, and was worth +7-20% on
8174 // the gemma cells at unchanged exactness (2026-07-10 flip; floor sweep 2026-07-25;
8175 // position key 2026-07-26). Signal = n_acc from the round's EXISTING accept readback —
8176 // zero new syncs; the draft graph is a SINGLE-STEP capture replayed per drafted token,
8177 // so a per-round depth needs no re-capture (unlike gemma's whole-chain graphs). qwen's
8178 // in-round p-min cut already shortens chains mid-round, so gemma's one-round-late p-min
8179 // fold into kc is unnecessary here — the accepted-run law sees the cut via n_acc.
8180 // Exactness is the verify's job at ANY depth (same contract as p-min variable rounds).
8181 // DEFAULT OFF on the qwen path until its cells gate a flip (gemma's is default-on).
8182 // MEASURED 2026-08-01 (H100 GPU-3, interleaved x3, NGEN=256, same-invocation plain
8183 // denominators; research/qwen-adaptive-k-20260801/): REFUTED on the tuned qwen configs.
8184 // q27 K=3+HPOST+PMIN=0.3: short +0.8% (noise; law ~idles, len_hist identical), board
8185 // -1.9%, agentic -0.5%; board PMIN=0 -2.1% (not p-min shadowing — the law itself);
8186 // floor=1 -2.8% (gemma's floor-collapse, reproduced). q35 K=2 board: -6.4% (52/136
8187 // rounds shrink to depth 1; no depth to reclaim at K=2). The gemma direction DOES
8188 // appear at untuned depth-K — q27 K=6 floor=4 +1.5% over fixed K=6 — but stays -3.7%
8189 // below fixed K=3: same verdict class as the retired EMA arm (honest loss to static
8190 // per-class optima). Acceptance-rate rises under the law while tokens/round falls —
8191 // it buys accept-% by adding rounds, and a round's fixed draft+verify cost wins.
8192 // K=1..8 self-consistency PASS both models with the law ON (exactness held).
8193 let adapt = std::env::var("MEMRA_SPEC_ADAPT").as_deref() == Ok("1");
8194 // floor: per-model default keyed on n_embd (gemma's tiering — models with an expensive
8195 // verify keep deep drafts after a miss); MEMRA_SPEC_ADAPT_FLOOR pins it everywhere.
8196 let adapt_floor_env: Option<usize> = std::env::var("MEMRA_SPEC_ADAPT_FLOOR")
8197 .ok()
8198 .and_then(|v| v.parse().ok());
8199 let adapt_floor_default: usize = if self.cfg.n_embd as usize >= 3500 {
8200 4
8201 } else if self.cfg.n_embd as usize >= 2500 {
8202 2
8203 } else {
8204 1
8205 };
8206 let adapt_floor: usize = adapt_floor_env.unwrap_or(adapt_floor_default);
8207 // position key: past floor_ctx a HIGH floor (>=4) relaxes to 1 — forced-deep drafts
8208 // turn net-negative at depth (gemma 31B d1736 evidence); MEMRA_SPEC_FLOOR_CTX moves
8209 // the boundary, an explicit MEMRA_SPEC_ADAPT_FLOOR pins the floor everywhere.
8210 let floor_ctx: usize = std::env::var("MEMRA_SPEC_FLOOR_CTX")
8211 .ok()
8212 .and_then(|v| v.parse().ok())
8213 .unwrap_or(1024);
8214 let floor_at = |pos: usize| -> usize {
8215 if adapt_floor_env.is_some() || pos < floor_ctx {
8216 adapt_floor
8217 } else if adapt_floor >= 4 {
8218 1
8219 } else {
8220 adapt_floor
8221 }
8222 };
8223 // cap: MEMRA_SPEC_CAPMAX (gemma semantics, default 7). Binds only under adapt — the
8224 // fixed-K default path is untouched by this whole block.
8225 let cap_max: usize = std::env::var("MEMRA_SPEC_CAPMAX")
8226 .ok()
8227 .and_then(|v| v.parse().ok())
8228 .unwrap_or(7);
8229 let k_cap = k.min(cap_max).max(1);
8230 let mut kc = k_cap;
8231 let mut opti_fork: Option<OptiForkState> = None;
8232 let mut fork_snapshot: Option<crate::cache::CacheSnapshot> = None;
8233 if fork_mode != OptiForkGateMode::Disabled {
8234 let fence = crate::pp::pp_cuts(self.layers.len());
8235 let refusal = if !session_mode {
8236 Some("not-session")
8237 } else if k != 1 || adapt {
8238 Some("requires-fixed-k1")
8239 } else if sampled || constraint.is_some() || spec_replay {
8240 Some("sampled-constrained-or-replay")
8241 } else if pipe.is_some() {
8242 Some("two-session-pipeline")
8243 } else if !spec_devacc() {
8244 Some("requires-device-accept")
8245 } else if stream_active || crate::spec::spec_stream() {
8246 Some("round-stream")
8247 } else if crate::cache::swa_ring_on() || cache.has_swa_ring() {
8248 Some("swa-ring")
8249 } else if crate::pp::pp_host_bounce_active() {
8250 Some("host-bounce")
8251 } else if fork_mode == OptiForkGateMode::Controller
8252 && cache.recur.iter().any(Option::is_some)
8253 {
8254 Some("controller-requires-zero-recurrent-state")
8255 } else if fence.as_ref().is_none_or(|f| f.len() != 3) {
8256 Some("requires-pp2")
8257 } else {
8258 None
8259 };
8260 if let Some(reason) = refusal {
8261 OPTI_FORK_REFUSALS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8262 eprintln!("[opti-fork] refused reason={reason}");
8263 } else {
8264 let fence = fence.expect("validated PP-2 fence");
8265 let rt = crate::pp::PpNRt::get(e)?;
8266 let primary_stage0 = rt.engine(0, e).ctx().ordinal() == e.ctx().ordinal();
8267 let primary_stage1 = rt.engine(1, e).ctx().ordinal() == e.ctx().ordinal();
8268 let primary_supported =
8269 primary_stage0 || (fork_mode == OptiForkGateMode::Controller && primary_stage1);
8270 if !rt.cross_device() || !primary_supported {
8271 OPTI_FORK_REFUSALS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8272 eprintln!("[opti-fork] refused reason=requires-supported-primary-cross-device");
8273 } else {
8274 // Both recurrent snapshots and both seed generations are allocated before
8275 // the first fork, each through its owning PP stage. Allocation failure
8276 // therefore happens before any optimistic state mutation can occur.
8277 let current_snapshot = opti_snapshot_stage_owned(e, cache, rt, &fence)?;
8278 let alternate_snapshot = opti_snapshot_stage_owned(e, cache, rt, &fence)?;
8279 let fork = OptiForkState::new(
8280 e,
8281 cache,
8282 fork_mode,
8283 alternate_snapshot,
8284 &h_seed_buf,
8285 &fill_prev,
8286 rt,
8287 fence[1],
8288 self.layers.len(),
8289 )?;
8290 eprintln!(
8291 "[opti-fork] armed mode={fork_mode:?} snapshots=2 seeds=2 split={} \
8292 payload_dev0={} payload_dev1={} q_threshold={:.3}",
8293 fence[1],
8294 fork.logical_payload_bytes[0],
8295 fork.logical_payload_bytes[1],
8296 fork.controller.map_or(0.0, |policy| policy.threshold),
8297 );
8298 fork_snapshot = Some(current_snapshot);
8299 opti_fork = Some(fork);
8300 }
8301 }
8302 }
8303 // Persistent snapshot buffers are allocated once and refreshed in place. The fork arm
8304 // uses stage-owned snapshots; refused/disabled arms retain the existing generic helper.
8305 let mut snap = match fork_snapshot {
8306 Some(snapshot) => snapshot,
8307 None => cache.snapshot(e)?,
8308 };
8309 let mut carried_opti: Option<OptiControllerTicket> = None;
8310 // ROUND-STREAM stage (b) 3a: device table of per-layer kvl.len_d pointers (stable — the
8311 // cache never reallocates len_d; see cache.rs "stable pointer" note). 0 = no KV layer.
8312 let kv_len_ptrs: Option<CudaSlice<u64>> = if spec_devacc() && !spec_replay {
8313 Some(crate::round_stream::kv_len_ptr_table(e, cache, None)?)
8314 } else {
8315 None
8316 };
8317 // BONUS FOLD (2026-07-04): after a FULL accept the bonus token is NOT committed with a
8318 // separate T=1 trunk pass (a full weight read per round). It stays PENDING and rides as
8319 // column 0 of the NEXT round's verify batch. Under predecessor pairing the next chain
8320 // seeds from the bonus's predecessor's TRUE verify hidden (free — no extra
8321 // pass of any kind). Verify still
8322 // checks every emitted token against the target -> exactness holds by construction; only
8323 // DRAFT QUALITY can shift, which the acceptance numbers arbitrate.
8324 // bonus emitted but not yet committed to cache. A carried pending (see SpecSession::
8325 // pending_tok) enters round 0 directly — the burst boundary becomes a plain round edge.
8326 let mut pending: Option<u32> = carried_pending;
8327 // MEMRA_SPEC_PHASE=1: per-round wall decomposition (draft / verify / accept+commit) —
8328 // no tracing, no extra syncs (each phase is naturally sync-bounded: draft readbacks,
8329 // the verify accept readback). Printed once at loop end via spec-stats.
8330 let anatomy_on = std::env::var("MEMRA_SPEC_PP_ANATOMY").as_deref() == Ok("1");
8331 let phase_on = anatomy_on || std::env::var("MEMRA_SPEC_PHASE").as_deref() == Ok("1");
8332 // DRAFT-MASK receipt (lane/draft-mask): speculative-clone wall + rounds, printed with
8333 // spec-stats. The clone is the one cost the design adds per round — measured, not assumed.
8334 let (mut dm_clone_ns, mut dm_rounds) = (0u128, 0usize);
8335 // grammar-truncation counters: how many rounds the verify-side cut fired and how many
8336 // already-verified tokens it threw away. THIS is the quantity draft masking targets.
8337 let (mut dm_cuts, mut dm_cut_tokens) = (0usize, 0usize);
8338 let (mut ph_draft, mut ph_verify, mut ph_rest) = (0f64, 0f64, 0f64);
8339 let mut ph_wait = 0f64;
8340 let mut ph_commit = 0f64;
8341 let mut ph_t = std::time::Instant::now();
8342 let mut ph_mark = |acc: &mut f64, on: bool| {
8343 if on {
8344 let now = std::time::Instant::now();
8345 *acc += (now - ph_t).as_secs_f64();
8346 ph_t = now;
8347 }
8348 };
8349 if let Some(p) = pipe {
8350 p.setup_end();
8351 }
8352 while keep_going && out.len() < max_new {
8353 // ROUND-STREAM BURST: from round 1 (pending guaranteed by every non-replay arm),
8354 // issue M rounds with zero readbacks, then drain the ring + reconcile mirrors.
8355 if let (true, Some(sg), Some(ptrs)) = (
8356 stream_active && round >= 1 && pending.is_some(),
8357 &stream_graph,
8358 &stream_ptrs,
8359 ) {
8360 if debug_spec {
8361 static ONCE: std::sync::Once = std::sync::Once::new();
8362 ONCE.call_once(|| {
8363 eprintln!("[memra] ROUND-STREAM burst engaged (M={m_rounds} k={k})")
8364 });
8365 }
8366 e.set_i32_one(&mut pos_ctr, cache.pos as i32)?;
8367 e.set_u32_one(&mut pend_d, pending.unwrap())?;
8368 e.set_u32_one(&mut ring_d, 0)?; // ring count = 0 (writes element 0)
8369 for _mi in 0..m_rounds {
8370 e.i32_copy_add(&pos_ctr, &mut pos_start_d, 0)?;
8371 cache.snapshot_into(e, &mut snap)?; // device D2Ds, stream-ordered
8372 e.i32_copy_add(&pos_ctr, &mut scratch.kv.len_d, 0)?; // draft-KV rollback
8373 e.i32_copy_add(&pos_ctr, &mut dctx.g_pos, 1)?; // rope pos = pos + base
8374 e.u32_copy(&pend_d, &mut dctx.g_tok)?;
8375 e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
8376 sg.launch()?;
8377 e.spec_assemble_verify(
8378 &g_tokp2k,
8379 &pend_d,
8380 d2t_dev.as_ref(),
8381 &mut vtok_d,
8382 &mut brk_d,
8383 p_min,
8384 k,
8385 pmin0,
8386 )?;
8387 let mut ck = VerifyCkpt::new(self.layers.len());
8388 let dummy = vec![0u32; t_v_s];
8389 let (tl_d, vx) = self.decode_step_t_core_stream(
8390 e,
8391 &dummy,
8392 0,
8393 &mut *cache,
8394 embd_dev,
8395 Some(&mut ck),
8396 Some((&vtok_d, &pos_ctr)),
8397 None,
8398 )?;
8399 for j in 0..t_v_s {
8400 e.argmax_token_device_col(&tl_d, j, n_vocab, &mut preds_d, j)?;
8401 }
8402 e.spec_accept_greedy_dc(
8403 &preds_d,
8404 &vtok_d,
8405 &last_pred_d,
8406 &brk_d,
8407 &mut stream_acc,
8408 )?;
8409 e.spec_seed_gather(&vx, &fill_prev, &stream_acc, &mut h_seed_buf, 1, n_embd)?;
8410 e.copy_into(&mut fill_prev, 0, &h_seed_buf, n_embd)?;
8411 self.commit_verified_prefix_stream(
8412 e,
8413 &mut *cache,
8414 &snap,
8415 &ck,
8416 &stream_acc,
8417 1,
8418 t_v_s,
8419 )?;
8420 e.spec_rollback_stream(
8421 ptrs,
8422 &pos_start_d,
8423 &stream_acc,
8424 1,
8425 self.layers.len() + 1,
8426 )?;
8427 e.spec_ring_commit(&vtok_d, &stream_acc, &brk_d, &mut ring_d, &mut pend_d)?;
8428 }
8429 e.stream().synchronize()?;
8430 let ring_h = e.dtoh_u32(&ring_d)?;
8431 let cnt = ring_h[0] as usize;
8432 for i in 0..cnt {
8433 if out.len() < max_new {
8434 out.push(ring_h[1 + i]);
8435 }
8436 }
8437 let pos_h = e.dtoh_i32(&pos_ctr)?[0] as usize;
8438 for il in 0..self.layers.len() {
8439 if let Some(kvl) = cache.kv[il].as_mut() {
8440 kvl.len = pos_h;
8441 }
8442 }
8443 cache.pos = pos_h;
8444 scratch.kv.len = pos_h;
8445 pending = Some(ring_h[cnt]); // last drained token = the live bonus
8446 last_token = ring_h[cnt];
8447 total_drafted += k * m_rounds; // upper bound (p-min breaks uncounted)
8448 total_accepted += cnt.saturating_sub(m_rounds);
8449 if let Some(t) = sess_telem {
8450 // totals only — the burst's per-round accept counts stayed on device
8451 // (that is the point of the round-stream arm). pos_* untouched.
8452 t.record_totals(m_rounds, k * m_rounds, cnt.saturating_sub(m_rounds));
8453 }
8454 round += m_rounds;
8455 // sse-cadence: the drained ring is committed — flush it at burst-drain cadence.
8456 keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
8457 continue;
8458 }
8459 let pipe_draft = match pipe {
8460 Some(p) => Some(p.draft_begin(round)?),
8461 None => None,
8462 };
8463 let pos = cache.pos; // #tokens committed (EXCLUDES a pending bonus)
8464 let mut current_opti = carried_opti.take();
8465 let mut fork_generation = if current_opti.is_none() && pending.is_some() {
8466 match opti_fork.as_mut() {
8467 Some(fork) if fork.mode.is_forced() => Some(fork.reserve(&mut snap)?),
8468 None => None,
8469 Some(_) => None,
8470 }
8471 } else {
8472 None
8473 };
8474 if current_opti.is_none() {
8475 if let Some(fork) = opti_fork.as_ref() {
8476 opti_snapshot_stage_owned_into(e, cache, fork.rt, &fork.fence, &mut snap)?;
8477 } else {
8478 cache.snapshot_into(e, &mut snap)?;
8479 }
8480 } else if snap.pos != pos {
8481 return Err(format!(
8482 "optipipe carried snapshot pos {} != current pos {pos}",
8483 snap.pos
8484 )
8485 .into());
8486 } // §C: snapshot BEFORE draft+verify (already retained for a carried successor)
8487 ph_mark(&mut ph_rest, phase_on);
8488
8489 // --- 1. DRAFT k tokens with the NextN head (autoregressive, T=1 each) ---
8490 // p-min semantics (both paths): stop the chain early when the head's confidence in
8491 // its own pick drops below p_min — the just-drafted token is DISCARDED, but its
8492 // scratch append stands (identical to the eager chain's ordering). j==0 always drafts.
8493 let base0 = if pending.is_some() { 1usize } else { 0usize };
8494 // fixed draft length by default; MEMRA_SPEC_ADAPT=1 drafts at last round's
8495 // accepted run + 1 (the gemma law — see the setup block above the loop).
8496 let k_this = if adapt { kc } else { k };
8497 let mut draft: Vec<u32> = Vec::with_capacity(k);
8498 let mut draft_idx: Vec<u32> = Vec::with_capacity(k); // trimmed-vocab ids (== draft when untrimmed)
8499 let mut controller_draft_prob: Option<f32> = None;
8500 let mut controller_eager_state: Option<(u32, CudaSlice<f32>)> = None;
8501 if let Some(ticket) = current_opti.as_mut() {
8502 let carried_pending = pending.ok_or("optipipe carried successor lost pending")?;
8503 if ticket.verify_tokens[0] != carried_pending {
8504 return Err(format!(
8505 "optipipe carried pending mismatch: ticket={} live={carried_pending}",
8506 ticket.verify_tokens[0],
8507 )
8508 .into());
8509 }
8510 draft.push(ticket.verify_tokens[1]);
8511 controller_draft_prob = Some(ticket.draft_prob);
8512 controller_eager_state = ticket
8513 .take_eager_seed()
8514 .map(|seed| (ticket.verify_tokens[1], seed));
8515 } else {
8516 // Round-start draft-KV sync (BOTH paths). Persistent: truncate/align to the committed
8517 // history — slots 0..P hold entries for the tokens before last_token@P (P = pos +
8518 // base0 - 1); this single set_len IS the draft-side rollback (drops last round's
8519 // rejected drafts and p-min extras via the len mechanism).
8520 scratch.set_len(e, pos + base0 - 1)?;
8521 if pen_on {
8522 // PEN_WINDOW_MAX also bounds the per-round upload and the O(n_hist^2)
8523 // device dedup: `penalty_last_n` is usize::MAX for any serve request with
8524 // a penalty, so without the cap this grew with the whole session.
8525 let win = sp.penalty_last_n.min(PEN_WINDOW_MAX);
8526 let w0 = pen_hist.len().saturating_sub(win);
8527 pen_hist_d = Some(e.htod_u32_v(&pen_hist[w0..])?);
8528 }
8529 if sampled {
8530 draft_logits.clear();
8531 draft_stats.clear();
8532 }
8533 // DRAFT-SIDE GRAMMAR MASK: clone the committed grammar state ONCE per round; each
8534 // position's mask is computed on that clone and advanced by the PROPOSED token. The
8535 // real state moves only on emission (verify's job), so the emitted stream is
8536 // unchanged — the mask only removes tokens the verify would have truncated anyway.
8537 let mut dmask_live = dmask_on;
8538 if dmask_live {
8539 let t_c = std::time::Instant::now();
8540 constraint
8541 .as_deref_mut()
8542 .unwrap()
8543 .draft_begin()
8544 .map_err(|e2| format!("constraint: {e2}"))?;
8545 dm_clone_ns += t_c.elapsed().as_nanos();
8546 dm_rounds += 1;
8547 }
8548 if let (false, Some(gr)) = (sampled || pen_on, &dctx.graph) {
8549 // GRAPH DRAFT: one dispatch per drafted token. The chain feeds itself on-device
8550 // (in-graph argmax -> tok_d -> next replay's embed; h_nextn -> h_seed_d; pos_d
8551 // inc'd in-graph); the host only reads 4B token (+4B p) and decides the break.
8552 e.set_i32_one(&mut dctx.g_pos, (pos + base0) as i32)?;
8553 e.set_u32_one(&mut dctx.g_tok, last_token)?;
8554 e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
8555 for j in 0..k_this {
8556 // per-position mask upload (contents only — the graph's baked pointer is
8557 // dctx.g_dmask). All-ones once masking goes dead mid-chain, so the captured
8558 // mask node degrades to a no-op ban instead of needing a second graph.
8559 if dmask_live
8560 && !upload_draft_mask(
8561 e,
8562 constraint.as_deref_mut().unwrap(),
8563 &mut dctx.g_dmask,
8564 mtp.d2t.as_ref(),
8565 d_vocab,
8566 dmask_words,
8567 )?
8568 {
8569 // no draft-vocab row is grammar-legal here (a trimmed FR-Spec head can
8570 // genuinely miss the legal set): neutralize the captured mask node and
8571 // finish the chain UNMASKED — exactly pre-lane behaviour, never worse.
8572 e.htod_u32_into(&mut dctx.g_dmask, &vec![u32::MAX; dmask_words])?;
8573 dmask_live = false;
8574 }
8575 gr.launch()?;
8576 scratch.kv.len += 1; // host mirror (len_d advanced in-graph)
8577 let idx = e.dtoh_u32_one(&dctx.g_tok)?;
8578 // #87 SENTINEL TRAP: an all-NaN head-logits row leaves the device argmax's
8579 // init sentinel (0x7FFFFFFF) in g_tok — feeding it onward dereferences
8580 // embed_row(sentinel) = table + ~4.6TB (never mapped) inside the NEXT graph
8581 // replay's embed node, and the MMU fault kills the CUDA context for the
8582 // whole process (research/pp2spec-crash-20260807: 3 coredumps, byte-exact
8583 // VA arithmetic). Refuse loudly instead; the diagnostics name the first-NaN
8584 // buffer (g_seed = the verify-side handoff vs head-side compute).
8585 if (idx as usize) >= d_vocab {
8586 // g_seed is SELF-FED (the replay writes h_nextn back into it), so it
8587 // reads as the head's OUTPUT at j; h_seed_buf is the round's INPUT
8588 // seed, untouched since the round-start copy — the pair discriminates
8589 // "seed arrived poisoned" from "head forward produced NaN".
8590 let seed_h = e.dtoh(&dctx.g_seed)?;
8591 let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
8592 let in_h = e.dtoh(&h_seed_buf)?;
8593 let in_nan = in_h.iter().filter(|v| v.is_nan()).count();
8594 return Err(format!(
8595 "draft(graph) argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab} at \
8596 round {round} j={j} pos={pos}: head-out NaN {seed_nan}/{n_embd}, \
8597 round-input-seed NaN {in_nan}/{n_embd} — refusing to dereference \
8598 the embed row (#87 trap)"
8599 )
8600 .into());
8601 }
8602 // trimmed draft vocab -> target token id (identity when no d2t map)
8603 let d = match &mtp.d2t {
8604 Some(map) => map[idx as usize],
8605 None => idx,
8606 };
8607 let draft_p = if p_min > 0.0
8608 || opti_fork
8609 .as_ref()
8610 .is_some_and(|fork| fork.controller.is_some())
8611 {
8612 Some(e.dtoh(&dctx.g_p)?[0])
8613 } else {
8614 None
8615 };
8616 if j == 0 {
8617 controller_draft_prob = draft_p;
8618 }
8619 if let Some(p) = draft_p.filter(|_| p_min > 0.0) {
8620 if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
8621 break;
8622 }
8623 }
8624 draft.push(d);
8625 // with a trimmed head the NEXT embed must read the TARGET id, not the draft
8626 // index the argmax wrote — patch the persistent token buffer (4B htod).
8627 if d != idx {
8628 e.set_u32_one(&mut dctx.g_tok, d)?;
8629 }
8630 // advance the SPECULATIVE state with the proposal; a dead chain drops to
8631 // unmasked drafting for the remaining positions (verify still arbitrates).
8632 // speculative advance; a chain the grammar can no longer follow (EOS
8633 // proposed) ends here. The captured mask node always runs, so a dead chain
8634 // leaves the buffer NEUTRAL (all-ones = ban nothing) before it exits.
8635 if dmask_live
8636 && !constraint
8637 .as_deref_mut()
8638 .unwrap()
8639 .draft_advance(d)
8640 .map_err(|e2| format!("constraint: {e2}"))?
8641 {
8642 e.htod_u32_into(&mut dctx.g_dmask, &vec![u32::MAX; dmask_words])?;
8643 break;
8644 }
8645 }
8646 } else if let (true, Some(gr)) = (sampled, &dctx.graph_s) {
8647 // SAMPLED GRAPH DRAFT: one replay per drafted token — head forward + gumbel +
8648 // argmax in ONE dispatch; the host reads 4B token (+4B p), D2Ds q into slot j,
8649 // and decides the break. Event-counter continuity: g_ctr is host-seeded to
8650 // sctr-1 ONCE per round (outside the graph); the in-graph bump runs BEFORE the
8651 // perturb, so replay j consumes counter sctr+j — exactly the eager arm's Philox
8652 // stream. Host sctr advances in lockstep (computed, no readback needed).
8653 e.set_i32_one(&mut dctx.g_pos, (pos + base0) as i32)?;
8654 e.set_u32_one(&mut dctx.g_tok, last_token)?;
8655 e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
8656 e.set_u32_one(&mut dctx.g_ctr, sctr.wrapping_sub(1))?;
8657 for j in 0..k_this {
8658 gr.launch()?;
8659 scratch.kv.len += 1; // host mirror (len_d advanced in-graph)
8660 sctr += 1; // mirrors the in-graph g_ctr bump (eager parity:
8661 // counts the p-min-discarded token too)
8662 // q retention: ONE async D2D of the persistent head-logits buffer into this
8663 // round's slot j (stream-ordered after the replay, before the next one).
8664 e.copy_into(&mut dctx.q_slots[j], 0, &dctx.g_q, d_vocab)?;
8665 let idx = e.dtoh_u32_one(&dctx.g_tok)?;
8666 // #87 SENTINEL TRAP (see the greedy graph arm above).
8667 if (idx as usize) >= d_vocab {
8668 let seed_h = e.dtoh(&dctx.g_seed)?;
8669 let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
8670 return Err(format!(
8671 "draft(graph-sampled) argmax sentinel 0x{idx:08x} >= d_vocab \
8672 {d_vocab} at round {round} j={j} pos={pos}: round-seed NaN \
8673 {seed_nan}/{n_embd} — refusing to dereference the embed row \
8674 (#87 trap)"
8675 )
8676 .into());
8677 }
8678 let d = match &mtp.d2t {
8679 Some(map) => map[idx as usize],
8680 None => idx,
8681 };
8682 draft_idx.push(idx);
8683 if p_min > 0.0 {
8684 let p = e.dtoh(&dctx.g_p)?[0];
8685 if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
8686 break;
8687 }
8688 }
8689 draft.push(d);
8690 // trimmed head: the NEXT embed must read the TARGET id (see the greedy arm).
8691 if d != idx {
8692 e.set_u32_one(&mut dctx.g_tok, d)?;
8693 }
8694 }
8695 // uniform accept path: fill draft_stats per used slot (pure-temp regime — the
8696 // stats degenerate to th=0 / full-Z; one filter_stats launch per slot, tiny).
8697 for j in 0..draft.len().max(draft_idx.len()) {
8698 let rows0 = e.htod_i32(&[0])?;
8699 let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
8700 e.filter_stats(
8701 &dctx.q_slots[j],
8702 d_vocab,
8703 &rows0,
8704 &mut th_d,
8705 &mut z_d,
8706 &mut mx_d,
8707 d_vocab,
8708 1,
8709 sp_temp,
8710 sp.top_k,
8711 sp.top_p,
8712 sp.min_p,
8713 )?;
8714 draft_stats.push((e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0]));
8715 }
8716 } else {
8717 // EAGER DRAFT (fallback: MoE head/trunk, huge k, MEMRA_SPEC_NOGRAPH, capture fail).
8718 let mut e_tok = last_token;
8719 let mut d_seed = e.clone_dtod(&h_seed_buf)?;
8720 for j in 0..k_this {
8721 // GPU-ARGMAX DRAFT (2026-07-03): device logits + device argmax + 4-byte token
8722 // read instead of the ~600KB full-vocab dtoh + host argmax per draft token.
8723 let mtp_pos = pos + base0 + j;
8724 // draft-side grammar mask (eager twin of the graph arm's in-graph node).
8725 // A position with no legal draft-vocab row drops to unmasked drafting for
8726 // the rest of the chain (pre-lane behaviour; verify still arbitrates).
8727 if dmask_live {
8728 dmask_live = upload_draft_mask(
8729 e,
8730 constraint.as_deref_mut().unwrap(),
8731 &mut dctx.g_dmask,
8732 mtp.d2t.as_ref(),
8733 d_vocab,
8734 dmask_words,
8735 )?;
8736 }
8737 let (dl_d, h_nextn) = self.mtp_head_forward_dev(
8738 e,
8739 mtp,
8740 e_tok,
8741 &d_seed,
8742 &mut *scratch,
8743 mtp_pos,
8744 embd_dev,
8745 if dmask_live {
8746 Some((&dctx.g_dmask, dmask_words))
8747 } else {
8748 None
8749 },
8750 )?;
8751 let tok_d = if sampled {
8752 // FILTERED Gumbel-max: stats -> masked perturb -> argmax = one draw from
8753 // the filtered softmax (filters off => th=0, exact v1 semantics).
8754 if perturb_buf.is_none() {
8755 perturb_buf = Some(e.zeros(d_vocab.max(n_vocab))?);
8756 }
8757 let mut q_row = e.clone_dtod(&dl_d)?; // retained q (penalized when on)
8758 if pen_on {
8759 let h = pen_hist_d.as_ref().unwrap();
8760 let nh = h.len();
8761 e.penalize_logits(
8762 &mut q_row,
8763 h,
8764 nh,
8765 sp.penalty_repeat,
8766 sp.penalty_freq,
8767 sp.penalty_present,
8768 d_vocab,
8769 )?;
8770 }
8771 let rows0 = e.htod_i32(&[0])?;
8772 let (mut th_d, mut z_d, mut mx_d) =
8773 (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
8774 e.filter_stats(
8775 &q_row, d_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, d_vocab,
8776 1, sp_temp, sp.top_k, sp.top_p, sp.min_p,
8777 )?;
8778 let (th, z, mx) =
8779 (e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0], e.dtoh(&mx_d)?[0]);
8780 let pb = perturb_buf.as_mut().unwrap();
8781 e.gumbel_perturb_filtered(
8782 &q_row, pb, d_vocab, sp_seed, sctr, sp_temp, mx, th,
8783 )?;
8784 sctr += 1;
8785 draft_logits.push(q_row);
8786 draft_stats.push((mx, th, z));
8787 e.argmax_token_device(pb, d_vocab)?
8788 } else {
8789 e.argmax_token_device(&dl_d, d_vocab)?
8790 };
8791 let idx = e.dtoh_u32_one(&tok_d)?;
8792 // #87 SENTINEL TRAP (eager twin — see the graph arm). Extra diagnostics
8793 // here because the eager chain's operands are all readable: dl_d (the head
8794 // logits row) and d_seed (this step's h_seed) name the first-NaN buffer.
8795 if (idx as usize) >= d_vocab {
8796 let dl_h = e.dtoh(&dl_d)?;
8797 let dl_nan = dl_h.iter().filter(|v| v.is_nan()).count();
8798 let seed_h = e.dtoh(&d_seed)?;
8799 let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
8800 return Err(format!(
8801 "draft(eager) argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab} at \
8802 round {round} j={j} pos={pos}: head-logits NaN {dl_nan}/{d_vocab}, \
8803 step-seed NaN {seed_nan}/{n_embd} — refusing to dereference the \
8804 embed row (#87 trap)"
8805 )
8806 .into());
8807 }
8808 let d = match &mtp.d2t {
8809 Some(map) => map[idx as usize],
8810 None => idx,
8811 };
8812 if sampled {
8813 draft_idx.push(idx);
8814 }
8815 let draft_p = if p_min > 0.0
8816 || opti_fork
8817 .as_ref()
8818 .is_some_and(|fork| fork.controller.is_some())
8819 {
8820 let p_d = e.prob_of_token_device(&dl_d, &tok_d, d_vocab)?;
8821 Some(e.dtoh(&p_d)?[0])
8822 } else {
8823 None
8824 };
8825 if j == 0 {
8826 controller_draft_prob = draft_p;
8827 }
8828 if let Some(p) = draft_p.filter(|_| p_min > 0.0) {
8829 if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
8830 break;
8831 }
8832 }
8833 draft.push(d);
8834 e_tok = d;
8835 d_seed = h_nextn;
8836 // speculative advance; a chain the grammar can no longer follow (EOS
8837 // proposed) ends here — the prefix already proposed still rides verify.
8838 if dmask_live
8839 && !constraint
8840 .as_deref_mut()
8841 .unwrap()
8842 .draft_advance(d)
8843 .map_err(|e2| format!("constraint: {e2}"))?
8844 {
8845 break;
8846 }
8847 }
8848 if opti_fork
8849 .as_ref()
8850 .is_some_and(|fork| fork.controller.is_some())
8851 {
8852 controller_eager_state = Some((e_tok, d_seed));
8853 }
8854 }
8855 }
8856 let k_round = draft.len();
8857 if let Some(p) = pipe {
8858 p.draft_end(round);
8859 }
8860 drop(pipe_draft);
8861
8862 ph_mark(&mut ph_draft, phase_on);
8863 // --- 2. VERIFY: one batched target forward. With a pending bonus, it rides as col 0
8864 // (committing its KV/recur inside the SAME weight read); drafts follow. ---
8865 let verify_tokens: Vec<u32> = match pending {
8866 Some(b) => {
8867 let mut v = Vec::with_capacity(k_round + 1);
8868 v.push(b);
8869 v.extend_from_slice(&draft);
8870 v
8871 }
8872 None => draft.clone(),
8873 };
8874 let base = if pending.is_some() { 1 } else { 0 };
8875 // ckpt (REPLAY-FREE partial accept): retain per-layer state-rebuild inputs alongside
8876 // the verify. Pure buffer keep-alives + dtod clones — kernel work is unchanged.
8877 let mut ckpt = if let Some(ticket) = current_opti.as_mut() {
8878 Some(ticket.take_ckpt())
8879 } else if spec_replay {
8880 None
8881 } else {
8882 Some(VerifyCkpt::new(self.layers.len()))
8883 };
8884 let controller_can_probe = base == 1
8885 && k_round == 1
8886 && out.len().saturating_add(2) < max_new
8887 && controller_draft_prob.is_some()
8888 && opti_fork
8889 .as_ref()
8890 .and_then(|fork| fork.controller.as_ref())
8891 .is_some_and(|policy| !policy.breaker_tripped);
8892 let mut successor_attempt: Option<OptiControllerTicket> = None;
8893 let mut rejected_probe: Option<(f32, u32)> = None;
8894 let mut controller_prepared: Option<OptiControllerPrepared> = None;
8895 if controller_can_probe {
8896 // Prepare d2/q and, on admission, d3 before either current verify half is
8897 // issued. N stage 0 can then be followed immediately by N+1 stage 0; once N's
8898 // boundary fires, those dev0 launches overlap N stage 1 on dev1. Preparing on
8899 // the primary stream after N stage 1 would serialize the supposed pipeline.
8900 let eager_pos = scratch.kv.len + 1;
8901 let (optimistic_pending, pending_probability) = self.opti_controller_draft_step(
8902 e,
8903 mtp,
8904 &mut dctx,
8905 &mut *scratch,
8906 d_vocab,
8907 &mut controller_eager_state,
8908 eager_pos,
8909 embd_dev,
8910 )?;
8911 let first_probability = controller_draft_prob
8912 .ok_or("optipipe controller probe lost first-token probability")?;
8913 let q_proxy = first_probability * pending_probability;
8914 OPTI_GATE_CHECKS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8915 OPTI_SHADOW_DRAFT_TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8916 let admitted = opti_fork
8917 .as_ref()
8918 .and_then(|fork| fork.controller.as_ref())
8919 .ok_or("optipipe controller policy disappeared")?
8920 .admit(q_proxy);
8921 if admitted {
8922 OPTI_GATE_ADMITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8923 let eager_pos = scratch.kv.len + 1;
8924 let (optimistic_draft, optimistic_draft_probability) = self
8925 .opti_controller_draft_step(
8926 e,
8927 mtp,
8928 &mut dctx,
8929 &mut *scratch,
8930 d_vocab,
8931 &mut controller_eager_state,
8932 eager_pos,
8933 embd_dev,
8934 )?;
8935 OPTI_SHADOW_DRAFT_TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8936 let eager_seed = controller_eager_state.take().map(|(token, seed)| {
8937 debug_assert_eq!(token, optimistic_draft);
8938 seed
8939 });
8940 controller_prepared = Some(OptiControllerPrepared {
8941 verify_tokens: [optimistic_pending, optimistic_draft],
8942 draft_prob: optimistic_draft_probability,
8943 eager_seed,
8944 q_proxy,
8945 scratch_len: scratch.kv.len,
8946 });
8947 } else {
8948 OPTI_GATE_REJECTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8949 OPTI_WASTED_DRAFT_TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8950 rejected_probe = Some((q_proxy, optimistic_pending));
8951 eprintln!(
8952 "[opti-controller] reject q={q_proxy:.6} threshold={:.3}",
8953 opti_fork
8954 .as_ref()
8955 .and_then(|fork| fork.controller.as_ref())
8956 .expect("controller policy")
8957 .threshold,
8958 );
8959 }
8960 }
8961 let fork_attempt = match fork_generation.take() {
8962 Some(generation) if base == 1 && k_round == 1 => Some(generation),
8963 Some(generation) => {
8964 opti_fork
8965 .as_mut()
8966 .expect("fork generation without fork state")
8967 .retire(generation)?;
8968 None
8969 }
8970 None => None,
8971 };
8972 let (tlogits_d, vx) = if let Some(p) = pipe {
8973 self.decode_step_t_core_pipelined(
8974 e,
8975 &verify_tokens,
8976 pos,
8977 &mut *cache,
8978 embd_dev,
8979 ckpt.as_mut(),
8980 p,
8981 round,
8982 )?
8983 } else if controller_can_probe {
8984 let fence = opti_fork
8985 .as_ref()
8986 .ok_or("optipipe controller probe lost fork state")?
8987 .fence;
8988 let boundary = match current_opti.as_mut() {
8989 Some(ticket) => ticket.take_boundary(),
8990 None => self.verify_stage0_issue(
8991 e,
8992 &verify_tokens,
8993 pos,
8994 &mut *cache,
8995 embd_dev,
8996 ckpt.as_mut(),
8997 None,
8998 &fence,
8999 Some(true),
9000 None,
9001 )?,
9002 };
9003 if let Some(prepared) = controller_prepared.take() {
9004 let generation = {
9005 let fork = opti_fork
9006 .as_mut()
9007 .ok_or("optipipe controller admission lost fork state")?;
9008 let generation = fork.reserve_successor()?;
9009 let rt = fork.rt;
9010 let snapshot_fence = fork.fence;
9011 opti_snapshot_one_stage_owned_into(
9012 e,
9013 cache,
9014 rt,
9015 &snapshot_fence,
9016 0,
9017 fork.successor_snapshot_mut(),
9018 )?;
9019 generation
9020 };
9021 let mut successor_ckpt = VerifyCkpt::new(self.layers.len());
9022 let successor_boundary = self.verify_stage0_issue(
9023 e,
9024 &prepared.verify_tokens,
9025 pos + verify_tokens.len(),
9026 &mut *cache,
9027 embd_dev,
9028 Some(&mut successor_ckpt),
9029 None,
9030 &fence,
9031 Some(false),
9032 None,
9033 )?;
9034 OPTI_FORK_ATTEMPTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9035 let fork = opti_fork
9036 .as_ref()
9037 .ok_or("optipipe controller ticket lost fork state")?;
9038 successor_attempt = Some(fork.controller_ticket(
9039 generation,
9040 successor_boundary,
9041 successor_ckpt,
9042 prepared.verify_tokens,
9043 prepared.draft_prob,
9044 prepared.eager_seed,
9045 prepared.q_proxy,
9046 prepared.scratch_len,
9047 ));
9048 eprintln!(
9049 "[opti-controller] issue generation={} q={:.6} threshold={:.3} \
9050 verify={:?}",
9051 generation.id,
9052 prepared.q_proxy,
9053 fork.controller.expect("controller policy").threshold,
9054 prepared.verify_tokens,
9055 );
9056 }
9057 let result = self.verify_stage1_finish(
9058 e,
9059 boundary,
9060 &mut *cache,
9061 ckpt.as_mut(),
9062 None,
9063 &fence,
9064 successor_attempt.is_none(),
9065 )?;
9066 if let Some(ticket) = current_opti.as_mut() {
9067 ticket.settle();
9068 }
9069 if successor_attempt.is_some() {
9070 let fork = opti_fork
9071 .as_mut()
9072 .ok_or("optipipe successor snapshot lost fork state")?;
9073 let rt = fork.rt;
9074 let snapshot_fence = fork.fence;
9075 opti_snapshot_one_stage_owned_into(
9076 e,
9077 cache,
9078 rt,
9079 &snapshot_fence,
9080 1,
9081 fork.successor_snapshot_mut(),
9082 )?;
9083 // Publish N only after both independent successor-state queues are complete.
9084 fork.rt.publish_to(1, &e.stream())?;
9085 }
9086 result
9087 } else if let Some(ticket) = current_opti.as_mut() {
9088 let fork = opti_fork
9089 .as_mut()
9090 .ok_or("optipipe carried controller ticket lost fork state")?;
9091 let boundary = ticket.take_boundary();
9092 let result = self.verify_stage1_finish(
9093 e,
9094 boundary,
9095 &mut *cache,
9096 ckpt.as_mut(),
9097 None,
9098 &fork.fence,
9099 true,
9100 )?;
9101 ticket.settle();
9102 result
9103 } else if let Some(generation) = fork_attempt {
9104 let fork = opti_fork
9105 .as_mut()
9106 .expect("fork generation without fork state");
9107 fork.capture_seed(e, generation, &h_seed_buf, &fill_prev, scratch.kv.len)?;
9108 let action = fork.mode.action(generation.id);
9109 let boundary = self.verify_stage0_issue(
9110 e,
9111 &verify_tokens,
9112 pos,
9113 &mut *cache,
9114 embd_dev,
9115 ckpt.as_mut(),
9116 None,
9117 &fork.fence,
9118 Some(true),
9119 None,
9120 )?;
9121 OPTI_FORK_ATTEMPTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9122 let mut ticket = fork.ticket(generation, boundary);
9123 if action == OptiForkAction::Abort {
9124 return Err(format!(
9125 "optipipe forced abort with generation {} stage0 in flight",
9126 generation.id,
9127 )
9128 .into());
9129 }
9130 fork.reconcile(
9131 e,
9132 &mut *cache,
9133 &mut *scratch,
9134 &snap,
9135 &mut h_seed_buf,
9136 &mut fill_prev,
9137 generation,
9138 action,
9139 verify_tokens[0],
9140 )?;
9141 let result = if action == OptiForkAction::Hit {
9142 let boundary = ticket.take_boundary();
9143 self.verify_stage1_finish(
9144 e,
9145 boundary,
9146 &mut *cache,
9147 ckpt.as_mut(),
9148 None,
9149 &fork.fence,
9150 true,
9151 )?
9152 } else {
9153 // The optimistic boundary slot has no reader. Re-run the unchanged serial
9154 // verify only after E_restart published the restored stage-0 state.
9155 self.decode_step_t_core(
9156 e,
9157 &verify_tokens,
9158 pos,
9159 &mut *cache,
9160 embd_dev,
9161 ckpt.as_mut(),
9162 )?
9163 };
9164 ticket.settle();
9165 debug_assert_eq!(ticket.generation, generation);
9166 fork.retire(generation)?;
9167 result
9168 } else {
9169 self.decode_step_t_core(
9170 e,
9171 &verify_tokens,
9172 pos,
9173 &mut *cache,
9174 embd_dev,
9175 ckpt.as_mut(),
9176 )?
9177 };
9178 let pipe_accept = match pipe {
9179 Some(p) => Some(p.accept_begin(round)?),
9180 None => None,
9181 };
9182
9183 ph_mark(&mut ph_verify, phase_on);
9184 // --- 3. GREEDY ACCEPT (walk prefix, stop at first mismatch) ---
9185 // DEVICE-ARGMAX ACCEPT: argmax every verify column ON DEVICE (same 2-pass kernels +
9186 // smallest-index tie-break as host argmax, argmax_gate-validated) and read back ONE
9187 // [T] u32 — replaces the T x n_vocab f32 dtoh + T host argmaxes per round.
9188 // t_pred[j] = target's greedy prediction for the slot after draft[j-1] (j>=1) or after
9189 // last_token (j==0). With a pending bonus, col 0 IS the prediction after last_token
9190 // (== the bonus), so every index shifts by `base` and last_pred is unused.
9191 let t_v = verify_tokens.len();
9192 let mut preds: Vec<u32> = Vec::new();
9193 if !sampled {
9194 for j in 0..t_v {
9195 e.argmax_token_device_col(&tlogits_d, j, n_vocab, &mut preds_d, j)?;
9196 }
9197 preds = e.dtoh_u32(&preds_d)?; // <- the verify-GPU wait lands here
9198 // #87 SENTINEL TRAP, verify side: a sentinel pred becomes the round's bonus =
9199 // next round's last_token = the next chain's embed lookup. Catch it at the
9200 // source with the column named — an all-NaN VERIFY column implicates the
9201 // stage-split trunk (decode_step_t_core_ppn), not the draft head.
9202 if let Some(bad) = preds[..t_v].iter().position(|&p| (p as usize) >= n_vocab) {
9203 let col = &tlogits_d.slice(bad * n_vocab..(bad + 1) * n_vocab);
9204 let mut probe = e.zeros(n_vocab)?;
9205 e.copy_view_into(&mut probe, 0, col, n_vocab)?;
9206 let col_h = e.dtoh(&probe)?;
9207 let col_nan = col_h.iter().filter(|v| v.is_nan()).count();
9208 return Err(format!(
9209 "verify argmax sentinel 0x{:08x} >= n_vocab {n_vocab} at round {round} \
9210 col {bad}/{t_v} pos={pos}: verify-logits col NaN {col_nan}/{n_vocab} \
9211 — the stage-split verify produced a poisoned column (#87 trap)",
9212 preds[bad]
9213 )
9214 .into());
9215 }
9216 }
9217 ph_mark(&mut ph_wait, phase_on);
9218 let t_pred = |j: usize| -> u32 {
9219 if j == 0 && base == 0 {
9220 last_pred
9221 } else {
9222 preds[base + j - 1]
9223 }
9224 };
9225 let mut devacc_seeded = false;
9226 let mut devacc_acc: Option<CudaSlice<u32>> = None;
9227 let (n_acc, bonus) = if !sampled {
9228 // ROUND-STREAM stage (a) (MEMRA_SPEC_DEVACC=1 opt-in): the walk runs ON DEVICE
9229 // (spec_accept_greedy, verbatim rule) and the host reads back 8B (n_acc, bonus)
9230 // instead of the [T] preds. Same sync count — machinery for stages (b)/(c),
9231 // gated on token identity vs the host walk (the arms below are bit-equal rules).
9232 if crate::spec::spec_devacc() && k_round > 0 && !spec_replay && constraint.is_none()
9233 {
9234 let draft_d = e.htod_u32_v(&draft)?;
9235 let mut acc_out = e.alloc_u32_zeroed(2)?;
9236 e.spec_accept_greedy(
9237 &preds_d,
9238 &draft_d,
9239 last_pred,
9240 base,
9241 k_round,
9242 &mut acc_out,
9243 )?;
9244 devacc_acc = Some(acc_out.clone());
9245 // stage (b): next-round seed gathered ON DEVICE from acc_out before the host
9246 // ever reads n_acc (j=base+n_acc -> vx col j-1; j==0 -> fill_prev). The three
9247 // non-replay commit arms skip their host-offset seed copies (guarded below);
9248 // the legacy spec_replay arm keeps its own rx-based seeding (excluded here).
9249 // NOTE: fill_prev is NOT updated here — the commit arms' TRUE-HIDDEN
9250 // REFRESH reads the OLD fill_prev (predecessor of this round's verify batch);
9251 // the update lands after the arms (devacc_seeded guard below).
9252 e.spec_seed_gather(&vx, &fill_prev, &acc_out, &mut h_seed_buf, base, n_embd)?;
9253 // 3a: KV lens roll back on device (len = saved + base + n_acc, all arms'
9254 // unified rule; full accept rewrites the verify-left value). Host mirrors
9255 // update after the readback; commit_verified_prefix skips its len_d writes.
9256 if let Some(successor) = successor_attempt.as_ref() {
9257 opti_fork
9258 .as_mut()
9259 .ok_or("optipipe successor reconcile lost fork state")?
9260 .queue_actual_reconcile(
9261 e,
9262 &snap,
9263 &acc_out,
9264 successor.verify_tokens[0],
9265 base,
9266 )?;
9267 } else if let Some(ptrs) = &kv_len_ptrs {
9268 let saved: Vec<i32> = (0..self.layers.len())
9269 .map(|il| snap.kv_len[il].map(|v| v as i32).unwrap_or(0))
9270 .collect();
9271 let saved_d = e.htod_i32(&saved)?;
9272 e.spec_rollback_kv(ptrs, &saved_d, &acc_out, base, self.layers.len())?;
9273 }
9274 devacc_seeded = true;
9275 let ab = e.dtoh_u32(&acc_out)?;
9276 (ab[0] as usize, ab[1])
9277 } else {
9278 let mut n_acc = 0usize;
9279 for j in 0..k_round {
9280 if t_pred(j) == draft[j] {
9281 n_acc += 1;
9282 } else {
9283 break;
9284 }
9285 }
9286 // bonus = target's own token at the first non-accepted slot. n_acc in 0..=k; t_pred
9287 // is defined for j in 0..=k (j==0 -> last_logits, j>=1 -> col j-1, last col = k-1).
9288 (n_acc, t_pred(n_acc))
9289 }
9290 } else {
9291 // --- SAMPLED ACCEPT (rejection sampling): u_j < p_j(x_j)/q_j(x_j) walk ---
9292 if col_buf.is_none() {
9293 col_buf = Some(e.zeros(n_vocab)?);
9294 }
9295 // FILTERED p_j: per-verify-col stats (one batched filter_stats call), then the
9296 // filtered gather. j==0&&base==0 reads last_col (its own stats row appended).
9297 let mut pj = vec![0f32; k_round.max(1)];
9298 let mut col_stats: Vec<(f32, f32, f32)> = Vec::new(); // (max, th, z) per verify col used
9299 if k_round > 0 {
9300 let mut ids: Vec<u32> = Vec::new();
9301 let mut rows: Vec<i32> = Vec::new();
9302 for j in 0..k_round {
9303 if j > 0 || base == 1 {
9304 ids.push(draft[j]);
9305 rows.push((base + j) as i32 - 1);
9306 }
9307 }
9308 if !ids.is_empty() {
9309 let nr = rows.len();
9310 // penalties: materialize the used columns into one contiguous penalized
9311 // buffer (rows remapped 0..nr) so stats+gathers see the penalized p.
9312 // penalties: materialize used columns contiguously, penalize all rows in
9313 // one launch, and point stats+gathers at the penalized buffer (rows 0..nr).
9314 let p_rows: Vec<i32> = if pen_on {
9315 (0..nr as i32).collect()
9316 } else {
9317 rows.clone()
9318 };
9319 if pen_on {
9320 if pcol_buf.as_ref().map(|b| b.len()).unwrap_or(0) < nr * n_vocab {
9321 pcol_buf = Some(e.zeros(nr * n_vocab)?);
9322 }
9323 let pc = pcol_buf.as_mut().unwrap();
9324 for (i2, &r) in rows.iter().enumerate() {
9325 let c = r as usize;
9326 e.copy_view_into(
9327 pc,
9328 i2 * n_vocab,
9329 &tlogits_d.slice(c * n_vocab..(c + 1) * n_vocab),
9330 n_vocab,
9331 )?;
9332 }
9333 let h = pen_hist_d.as_ref().unwrap();
9334 let nh = h.len();
9335 e.penalize_logits_rows(
9336 pc,
9337 h,
9338 nh,
9339 sp.penalty_repeat,
9340 sp.penalty_freq,
9341 sp.penalty_present,
9342 n_vocab,
9343 nr,
9344 )?;
9345 }
9346 let p_src: &CudaSlice<f32> = if pen_on {
9347 pcol_buf.as_ref().unwrap()
9348 } else {
9349 &tlogits_d
9350 };
9351 let rowsd = e.htod_i32(&p_rows)?;
9352 let (mut th_d, mut z_d, mut mx_d) =
9353 (e.zeros(nr)?, e.zeros(nr)?, e.zeros(nr)?);
9354 e.filter_stats(
9355 p_src, n_vocab, &rowsd, &mut th_d, &mut z_d, &mut mx_d, n_vocab, nr,
9356 sp_temp, sp.top_k, sp.top_p, sp.min_p,
9357 )?;
9358 let idsd = e.htod_u32_v(&ids)?;
9359 let mut outd = e.zeros(nr)?;
9360 e.softmax_gather_filtered(
9361 p_src, n_vocab, &idsd, &rowsd, &th_d, &z_d, &mut outd, n_vocab, nr,
9362 sp_temp,
9363 )?;
9364 let outv = e.dtoh(&outd)?;
9365 let (thv, zv, mxv) = (e.dtoh(&th_d)?, e.dtoh(&z_d)?, e.dtoh(&mx_d)?);
9366 let mut oi = 0usize;
9367 for j in 0..k_round {
9368 if j > 0 || base == 1 {
9369 pj[j] = outv[oi];
9370 oi += 1;
9371 }
9372 }
9373 col_stats = (0..nr).map(|i| (mxv[i], thv[i], zv[i])).collect();
9374 }
9375 if base == 0 {
9376 let lc: &CudaSlice<f32> = if pen_on {
9377 if col_buf.is_none() {
9378 col_buf = Some(e.zeros(n_vocab)?);
9379 }
9380 let cb = col_buf.as_mut().unwrap();
9381 e.copy_into(
9382 cb,
9383 0,
9384 last_col_logits
9385 .as_ref()
9386 .expect("sampled: last_col_logits unset"),
9387 n_vocab,
9388 )?;
9389 let h = pen_hist_d.as_ref().unwrap();
9390 let nh = h.len();
9391 e.penalize_logits(
9392 cb,
9393 h,
9394 nh,
9395 sp.penalty_repeat,
9396 sp.penalty_freq,
9397 sp.penalty_present,
9398 n_vocab,
9399 )?;
9400 col_buf.as_ref().unwrap()
9401 } else {
9402 last_col_logits
9403 .as_ref()
9404 .expect("sampled: last_col_logits unset")
9405 };
9406 let rows0 = e.htod_i32(&[0])?;
9407 let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
9408 e.filter_stats(
9409 lc, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1,
9410 sp_temp, sp.top_k, sp.top_p, sp.min_p,
9411 )?;
9412 let idsd = e.htod_u32_v(&[draft[0]])?;
9413 let mut outd = e.zeros(1)?;
9414 e.softmax_gather_filtered(
9415 lc, n_vocab, &idsd, &rows0, &th_d, &z_d, &mut outd, n_vocab, 1, sp_temp,
9416 )?;
9417 pj[0] = e.dtoh(&outd)?[0];
9418 last_col_stats =
9419 Some((e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0]));
9420 }
9421 }
9422 // q source: the graph arm retained the head logits in the persistent q_slots;
9423 // the eager arm in per-round draft_logits clones. Same raw-logit values either way.
9424 // FILTERED q_j: stats from draft_stats (eager pushes in-chain; the graph arm
9425 // computes them post-replay — graph engages only filter/penalty-free, so the
9426 // stats degenerate to th=0/full-Z there, keeping ONE accept path).
9427 let q_bufs: &[CudaSlice<f32>] = if dctx.graph_s.is_some() {
9428 &dctx.q_slots
9429 } else {
9430 &draft_logits
9431 };
9432 let mut n_acc = 0usize;
9433 for j in 0..k_round {
9434 let (qmx, qth, qz) = draft_stats[j];
9435 let idsd = e.htod_u32_v(&[draft_idx[j]])?;
9436 let rowsd = e.htod_i32(&[0])?;
9437 let thd = e.htod(&[qth])?;
9438 let zd = e.htod(&[qz])?;
9439 let _ = qmx;
9440 let mut outd = e.zeros(1)?;
9441 e.softmax_gather_filtered(
9442 &q_bufs[j], d_vocab, &idsd, &rowsd, &thd, &zd, &mut outd, d_vocab, 1,
9443 sp_temp,
9444 )?;
9445 let qj = e.dtoh(&outd)?[0];
9446 let u = host_u01(sp_seed, uctr);
9447 uctr += 1;
9448 if (u as f64) * (qj as f64) < pj[j] as f64 {
9449 n_acc += 1;
9450 } else {
9451 break;
9452 }
9453 }
9454 let bonus = if n_acc == k_round {
9455 // FULL ACCEPT: bonus ~ FILTERED softmax at the last verify column.
9456 let col = base + k_round - 1;
9457 let cb = col_buf.as_mut().unwrap();
9458 e.copy_view_into(
9459 cb,
9460 0,
9461 &tlogits_d.slice(col * n_vocab..(col + 1) * n_vocab),
9462 n_vocab,
9463 )?;
9464 if pen_on {
9465 let h = pen_hist_d.as_ref().unwrap();
9466 let nh = h.len();
9467 e.penalize_logits(
9468 cb,
9469 h,
9470 nh,
9471 sp.penalty_repeat,
9472 sp.penalty_freq,
9473 sp.penalty_present,
9474 n_vocab,
9475 )?;
9476 }
9477 if perturb_buf.is_none() {
9478 perturb_buf = Some(e.zeros(d_vocab.max(n_vocab))?);
9479 }
9480 // STATS MUST COME FROM THIS COLUMN (bug fix 2026-08-05, lane/sampler-
9481 // truncation-fix; receipts research/sampfix-20260805/). The old code reused
9482 // `col_stats.last()` here, which is ALWAYS the wrong row: the gathered set
9483 // covers verify columns 0..=(base+k_round-2) (rows pushed as base+j-1), while
9484 // the full-accept bonus samples column base+k_round-1 — exactly ONE PAST the
9485 // last gathered column, in both base arms. `th` is a threshold in e-units of
9486 // its OWN row's max, so feeding a neighbour's (row_max, th) into
9487 // gumbel_perturb_filtered mis-scales every e0 = exp((x-row_max)/T). When the
9488 // donor column's peak is higher by more than T*ln(1/th), EVERY id fails
9489 // `e0 >= th`, the whole perturbed row becomes -3.4e38, and the 2-pass argmax
9490 // falls through to its smallest-index tie-break => token id 0 ("!") spliced
9491 // mid-word. Fragility is ordered by how large th is: min_p pins th = min_p
9492 // (0.05 => trigger at delta > 2.4 at T=0.8, fires constantly), top_p's
9493 // mass-boundary th is smaller, top_k's k-th-largest th smaller still — which
9494 // is why the head-to-head matrix saw min_p and top_p corrupt while top_k-only
9495 // stayed clean. The pure-temp default regime is immune (th == 0 masks nothing,
9496 // and row_max is unused once nothing is masked), so this fix is a byte-level
9497 // no-op for the untruncated serve default. One extra one-block filter_stats
9498 // per full-accept round is the whole cost.
9499 let (mx, th) = {
9500 let rows0 = e.htod_i32(&[0])?;
9501 let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
9502 let cb0 = col_buf.as_ref().unwrap();
9503 e.filter_stats(
9504 cb0, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1,
9505 sp_temp, sp.top_k, sp.top_p, sp.min_p,
9506 )?;
9507 (e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0])
9508 };
9509 let pb = perturb_buf.as_mut().unwrap();
9510 let cb2 = col_buf.as_ref().unwrap();
9511 e.gumbel_perturb_filtered(cb2, pb, n_vocab, sp_seed, sctr, sp_temp, mx, th)?;
9512 sctr += 1;
9513 let td = e.argmax_token_device(pb, n_vocab)?;
9514 e.dtoh_u32_one(&td)?
9515 } else {
9516 // REJECT at n_acc: bonus ~ norm(max(0, softmax_T(p) - softmax_T(q))).
9517 let cb = col_buf.as_mut().unwrap();
9518 if n_acc > 0 || base == 1 {
9519 let col = base + n_acc - 1;
9520 e.copy_view_into(
9521 cb,
9522 0,
9523 &tlogits_d.slice(col * n_vocab..(col + 1) * n_vocab),
9524 n_vocab,
9525 )?;
9526 } else {
9527 let lc = last_col_logits.as_ref().unwrap();
9528 e.copy_into(cb, 0, lc, n_vocab)?;
9529 }
9530 if pen_on {
9531 let h = pen_hist_d.as_ref().unwrap();
9532 let nh = h.len();
9533 e.penalize_logits(
9534 cb,
9535 h,
9536 nh,
9537 sp.penalty_repeat,
9538 sp.penalty_freq,
9539 sp.penalty_present,
9540 n_vocab,
9541 )?;
9542 }
9543 let cb2 = col_buf.as_ref().unwrap();
9544 let sc = sctr;
9545 sctr += 1;
9546 // p-stats for the reject column: from col_stats when the col was gathered,
9547 // else (j==0&&base==0) from last_col_stats.
9548 let p_stats = if n_acc > 0 || base == 1 {
9549 // col index within the gathered set == number of gathered cols before n_acc
9550 let gi = if base == 1 { n_acc } else { n_acc - 1 };
9551 col_stats.get(gi).copied().unwrap_or_else(|| {
9552 (0.0, 0.0, 1.0) // unreachable: gathered cols always cover the reject slot
9553 })
9554 } else {
9555 last_col_stats.expect("sampled: last_col_stats unset at reject")
9556 };
9557 let q_stats = draft_stats[n_acc];
9558 if let Some(map) = &d2t_dev {
9559 if q_full_buf.is_none() {
9560 q_full_buf = Some(e.zeros(n_vocab)?);
9561 }
9562 let qf = q_full_buf.as_mut().unwrap();
9563 e.scatter_trim_logits(&q_bufs[n_acc], map, qf, d_vocab, n_vocab)?;
9564 let qf2 = q_full_buf.as_ref().unwrap();
9565 e.residual_sample_filtered(
9566 cb2,
9567 Some(qf2),
9568 n_vocab,
9569 sp_temp,
9570 sp_seed,
9571 sc,
9572 p_stats,
9573 q_stats,
9574 &mut sample_tok,
9575 )?;
9576 } else {
9577 e.residual_sample_filtered(
9578 cb2,
9579 Some(&q_bufs[n_acc]),
9580 n_vocab,
9581 sp_temp,
9582 sp_seed,
9583 sc,
9584 p_stats,
9585 q_stats,
9586 &mut sample_tok,
9587 )?;
9588 }
9589 e.dtoh_u32(&sample_tok)?[0]
9590 };
9591 (n_acc, bonus)
9592 };
9593 // --- 3b. GRAMMAR TRUNCATION (constrained spec, 2026-08-03): the grammar is
9594 // an extra rejection rule AFTER the exactness verify (the batched-verify-twins
9595 // ordering). Walk the accepted drafts through the grammar in commit order; the
9596 // first illegal token truncates acceptance at its slot, and that slot's emission
9597 // is recomputed as the MASKED argmax of the target's own verify column — token-
9598 // identical to constrained plain greedy decode (an unmasked argmax that is
9599 // grammar-legal IS the masked argmax: masking only removes competitors). The
9600 // column D2H (~1MB) is paid only when a cut fires — the tight-grammar cost,
9601 // measured in acceptance numbers, never hidden.
9602 let (n_acc, bonus) = match constraint.as_deref_mut() {
9603 None => (n_acc, bonus),
9604 Some(c) => {
9605 fn ce(e2: String) -> Box<dyn std::error::Error> {
9606 format!("constraint: {e2}").into()
9607 }
9608 let mut na = n_acc;
9609 let mut cut = false;
9610 for (j, &d) in draft.iter().enumerate().take(n_acc) {
9611 if c.is_allowed(d).map_err(ce)? {
9612 c.consume(d).map_err(ce)?;
9613 } else {
9614 na = j;
9615 cut = true;
9616 dm_cut_tokens += n_acc - j;
9617 break;
9618 }
9619 }
9620 if cut {
9621 dm_cuts += 1;
9622 }
9623 let mut bo = bonus;
9624 if cut || !c.is_allowed(bo).map_err(ce)? {
9625 let mut row = if na == 0 && base == 0 {
9626 init_logits_host
9627 .clone()
9628 .ok_or("constraint: init logits missing (round-0 cut)")?
9629 } else {
9630 e.dtoh_view(
9631 &tlogits_d.slice((base + na - 1) * n_vocab..(base + na) * n_vocab),
9632 )?
9633 };
9634 c.mask_logits(&mut row).map_err(ce)?;
9635 bo = argmax(&row) as u32;
9636 }
9637 c.consume(bo).map_err(ce)?;
9638 (na, bo)
9639 }
9640 };
9641 let mut successor_valid = false;
9642 if let Some((q_proxy, expected_d2)) = rejected_probe {
9643 let v_n = n_acc == 1 && bonus == expected_d2;
9644 eprintln!(
9645 "[opti-controller] shadow q={q_proxy:.6} admitted=false v_n={v_n} \
9646 expected_d2={expected_d2} n_acc={n_acc} bonus={bonus}",
9647 );
9648 }
9649 if let Some(successor) = successor_attempt.as_ref() {
9650 successor_valid = n_acc == 1 && bonus == successor.verify_tokens[0];
9651 let generation = successor.generation;
9652 let q_proxy = successor.q_proxy;
9653 let expected_pending = successor.verify_tokens[0];
9654 let resolution_ms = successor.issued_at.elapsed().as_secs_f64() * 1e3;
9655 let fork = opti_fork
9656 .as_mut()
9657 .ok_or("optipipe successor resolution lost fork state")?;
9658 fork.finish_actual_reconcile(e, &mut *cache, &snap, n_acc, base, successor_valid)?;
9659 if successor_valid {
9660 OPTI_FORK_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9661 } else {
9662 OPTI_FORK_MISSES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9663 OPTI_RECONCILES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9664 OPTI_WASTED_DRAFT_TOKENS.fetch_add(2, std::sync::atomic::Ordering::Relaxed);
9665 }
9666 let breaker_tripped = fork
9667 .controller
9668 .as_mut()
9669 .expect("controller policy")
9670 .resolve(successor_valid);
9671 if breaker_tripped {
9672 OPTI_BREAKER_TRIPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9673 }
9674 eprintln!(
9675 "[opti-controller] resolve generation={} hit={} q={q_proxy:.6} \
9676 expected_pending={expected_pending} n_acc={n_acc} bonus={bonus} \
9677 resolution_ms={resolution_ms:.3} reconcile={} breaker={}",
9678 generation.id, successor_valid, !successor_valid, breaker_tripped,
9679 );
9680 if !successor_valid {
9681 let mut successor = successor_attempt
9682 .take()
9683 .expect("controller successor disappeared on miss");
9684 successor.settle();
9685 fork.retire(generation)?;
9686 }
9687 }
9688 total_drafted += k_round;
9689 total_accepted += n_acc;
9690 if let Some(t) = sess_telem {
9691 // Greedy, rejection-sampling, and grammar truncation all converge here after
9692 // the accept decision is already on host. Fixed-size relaxed atomics only.
9693 t.record_round(k_round, n_acc);
9694 }
9695 if spec_stats {
9696 st_len_hist[k_round] += 1;
9697 for j in 0..k_round {
9698 st_drafted[j] += 1;
9699 }
9700 for j in 0..n_acc {
9701 st_accepted[j] += 1;
9702 }
9703 if n_acc == k_round {
9704 st_full += 1;
9705 }
9706 }
9707
9708 if debug_spec {
9709 eprintln!(
9710 "[R{round}] pos={pos} out_len={} last_tok={last_token} draft={draft:?} n_acc={n_acc} bonus={bonus} t_pred0={}",
9711 out.len(),
9712 t_pred(0)
9713 );
9714 }
9715
9716 // --- 4. COMMIT: draft[0..n_acc] then bonus (n_acc + 1 tokens) ---
9717 let commit_started = std::time::Instant::now();
9718 // SESSION MODE: every accepted column is already in the CACHE — `out` must carry all
9719 // of them (overshoot past max_new included) or `committed` under-counts the cache rows
9720 // and the next turn's continuation seeds one token off (gate-caught 2026-07-05). The
9721 // single-shot path keeps the cap (its caller truncates + drops the cache anyway).
9722 for j in 0..n_acc {
9723 if !session_mode && out.len() >= max_new {
9724 break;
9725 }
9726 out.push(draft[j]);
9727 }
9728 if pen_on {
9729 pen_hist.extend_from_slice(&draft[0..n_acc]);
9730 pen_hist.push(bonus);
9731 }
9732 let bonus_emitted = session_mode || out.len() < max_new;
9733 if bonus_emitted {
9734 out.push(bonus);
9735 }
9736 last_token = bonus;
9737
9738 // --- 5. ROLLBACK + advance (§C) ---
9739 if n_acc == k_round && !spec_replay {
9740 // FULL ACCEPT, BONUS FOLD: all verify columns (pending? + drafts) are committed in
9741 // cache; the NEW bonus stays PENDING for the next round's verify batch — NO extra
9742 // T=1 trunk pass. The next draft chain seeds from the MTP block's h_nextn at the
9743 // bonus position: one MTP-block pass (~1/33 trunk cost) replaces the trunk read.
9744 // last_pred is dead in the pending path (t_pred reads verify col 0).
9745 //
9746 // PERSISTENT DRAFT KV, full-accept fill: the chain covered last_token +
9747 // draft[0..k_round-2] as INPUTS (slots P..P'-2); draft[k_round-1] (slot P'-1) was
9748 // only ever an output, so its entry is MISSING. Fill it from vh_seed — its EXACT
9749 // trunk hidden (the last verify column). set_len first: a p-min break may have
9750 // left one extra chain append at that slot. Partial accepts need NO fill (the
9751 // chain already covered every accepted position; round-start set_len truncates).
9752 let mut vh_seed = e.zeros(n_embd)?;
9753 e.copy_view_into(
9754 &mut vh_seed,
9755 0,
9756 &vx.slice((t_v - 1) * n_embd..t_v * n_embd),
9757 n_embd,
9758 )?;
9759 if refresh {
9760 // TRUE-HIDDEN REFRESH (2026-07-03, the HANDOVER-listed acceptance lever):
9761 // overwrite ALL committed positions' scratch entries with K/V from their EXACT
9762 // verify hiddens — the reference engine's mtp_update fills from true hiddens;
9763 // the full stack (vx) is already resident from the verify. Replaces both the
9764 // chain-approximate entries AND the old last-token-only fill. Acceptance-only
9765 // (draft attention quality); exactness stays the verify's job.
9766 scratch.set_len(e, pos)?;
9767 // PREDECESSOR pairing: row i gets vx[i-1]; row 0 the carried fill_prev
9768 // (hidden of the last committed row before this verify batch).
9769 let mut vxs = e.zeros(t_v * n_embd)?;
9770 e.copy_into(&mut vxs, 0, &fill_prev, n_embd)?;
9771 if t_v > 1 {
9772 e.copy_view_into(
9773 &mut vxs,
9774 n_embd,
9775 &vx.slice(0..(t_v - 1) * n_embd),
9776 (t_v - 1) * n_embd,
9777 )?;
9778 }
9779 self.mtp_kv_fill(e, mtp, &verify_tokens, &vxs, pos, &mut *scratch, embd_dev)?;
9780 } else {
9781 scratch.set_len(e, pos + base + k_round - 1)?;
9782 // predecessor of the last draft = verify col t_v-2 (or fill_prev at t_v==1)
9783 let mut hp = e.zeros(n_embd)?;
9784 if t_v >= 2 {
9785 e.copy_view_into(
9786 &mut hp,
9787 0,
9788 &vx.slice((t_v - 2) * n_embd..(t_v - 1) * n_embd),
9789 n_embd,
9790 )?;
9791 } else {
9792 e.copy_into(&mut hp, 0, &fill_prev, n_embd)?;
9793 }
9794 self.mtp_kv_fill(
9795 e,
9796 mtp,
9797 &[draft[k_round - 1]],
9798 &hp,
9799 pos + base + k_round - 1,
9800 &mut *scratch,
9801 embd_dev,
9802 )?;
9803 }
9804 // REFERENCE SEEDING: no pseudo pass — the next chain's step 0 IS the
9805 // reference's (id_last, h_prev) draft row; it appends the bonus's scratch
9806 // entry itself. Seed = TRUE hidden of the bonus's predecessor (last verify
9807 // col). Saves one MTP-block pass per round on top of the pairing fix.
9808 if !devacc_seeded {
9809 e.copy_into(&mut h_seed_buf, 0, &vh_seed, n_embd)?;
9810 e.copy_into(&mut fill_prev, 0, &vh_seed, n_embd)?;
9811 }
9812 pending = Some(bonus);
9813 if debug_spec {
9814 eprintln!(" -> FULL ACCEPT (bonus pending, prev-h seed)");
9815 }
9816 } else if !spec_replay && base + n_acc >= 1 {
9817 // PARTIAL ACCEPT, REPLAY-FREE (2026-07-03 — the profiled #1 long-ctx spec cost):
9818 // the verify's first j = base+n_acc columns ARE the committed sequence, computed
9819 // bit-identically to eager (decode-exact contract) — so KEEP them: KV truncates to
9820 // pos+j, recurrent state rebuilds from the VerifyCkpt (same-kernel gdn prefix
9821 // re-run / pure state-clone restore), and the bonus stays PENDING exactly like the
9822 // full-accept path — the legacy duplicate trunk replay is gone. The next chain
9823 // seeds from the MTP pseudo-hidden of the bonus, whose seed = the TRUE verify
9824 // hidden of its predecessor (col j-1) — same one-hop pseudo structure as full
9825 // accept (never compounds: the next verify recomputes true hiddens for all
9826 // committed columns).
9827 let j = base + n_acc;
9828 self.commit_verified_prefix(
9829 e,
9830 &mut *cache,
9831 &snap,
9832 ckpt.as_ref().unwrap(),
9833 j,
9834 devacc_seeded,
9835 if devacc_seeded {
9836 devacc_acc.as_ref().map(|a| (a, base, t_v))
9837 } else {
9838 None
9839 },
9840 )?;
9841 let mut seed = e.zeros(n_embd)?;
9842 e.copy_view_into(
9843 &mut seed,
9844 0,
9845 &vx.slice((j - 1) * n_embd..j * n_embd),
9846 n_embd,
9847 )?;
9848 // Draft scratch: TRUE-HIDDEN REFRESH of the committed prefix (see the full-accept
9849 // branch); without it the chain entries stand and only the tail truncates. Either
9850 // way len ends at pos+j so the pseudo append lands at the bonus's slot pos+j
9851 // (persistent mode), rope pos+j+1 (chain convention).
9852 if refresh {
9853 scratch.set_len(e, pos)?;
9854 let mut vxs = e.zeros(j * n_embd)?;
9855 e.copy_into(&mut vxs, 0, &fill_prev, n_embd)?;
9856 if j > 1 {
9857 e.copy_view_into(
9858 &mut vxs,
9859 n_embd,
9860 &vx.slice(0..(j - 1) * n_embd),
9861 (j - 1) * n_embd,
9862 )?;
9863 }
9864 self.mtp_kv_fill(
9865 e,
9866 mtp,
9867 &verify_tokens[0..j],
9868 &vxs,
9869 pos,
9870 &mut *scratch,
9871 embd_dev,
9872 )?;
9873 } else {
9874 scratch.set_len(e, pos + j)?;
9875 }
9876 // REFERENCE SEEDING (see the full-accept branch): seed = TRUE hidden of the
9877 // bonus's predecessor (verify col j-1); no pseudo pass.
9878 if !devacc_seeded {
9879 e.copy_into(&mut h_seed_buf, 0, &seed, n_embd)?;
9880 e.copy_into(&mut fill_prev, 0, &seed, n_embd)?;
9881 }
9882 pending = Some(bonus);
9883 if debug_spec {
9884 eprintln!(" -> PARTIAL(replay-free j={j}, bonus pending, prev-h seed)");
9885 }
9886 } else if !spec_replay {
9887 // ZERO ROUND FOLD (2026-07-10, verify-cost target #3): base+n_acc == 0 — a
9888 // pending-less round where nothing was accepted (PMIN0 zero-draft chains after a
9889 // replay/commit, or plain 0-accept rounds at round 0). The old path replayed
9890 // [bonus] through a FULL m=1 trunk+head forward (the 489us full-vocab head pass
9891 // measured at ~0.75/round on PMIN0 configs). Instead: restore the pre-round
9892 // snapshot and let the bonus ride the NEXT round's verify as col 0 — the existing
9893 // base=1 pending machinery, bit-identical by the decode-exact verify contract.
9894 // Seed: the bonus's predecessor is the last COMMITTED token, whose hidden
9895 // fill_prev already carries (same seeding as the 1-token-replay case it replaces).
9896 cache.rollback(e, &snap, 0)?;
9897 scratch.set_len(e, pos)?;
9898 e.copy_into(&mut h_seed_buf, 0, &fill_prev, n_embd)?;
9899 pending = Some(bonus);
9900 if debug_spec {
9901 eprintln!(" -> ZERO-ROUND FOLD (bonus pending, fill_prev seed)");
9902 }
9903 } else {
9904 // PARTIAL ACCEPT, LEGACY REPLAY (seam MEMRA_SPEC_REPLAY=1 — or j==0: nothing of
9905 // this round survives, only possible before the first pending exists, ~round 0):
9906 // restore EVERYTHING to the pre-round snapshot (KV truncate to pos + recur
9907 // restore), then replay the committed prefix pending? ++ draft[0..n_acc] ++
9908 // [bonus] as ONE batched T forward — single weight read, bit-identical to greedy
9909 // (the verify-all-columns path is the same math). Commits the bonus with a TRUE
9910 // trunk hidden.
9911 cache.rollback(e, &snap, 0)?; // accept_len=0: KV len = pos, recur = snapshot
9912 let mut replay: Vec<u32> = Vec::with_capacity(base + n_acc + 1);
9913 if let Some(b) = pending.take() {
9914 replay.push(b);
9915 }
9916 replay.extend_from_slice(&draft[0..n_acc]);
9917 replay.push(bonus);
9918 // Full-stack forward (decode_step_t_core = decode_step_t_h_emb_dev's body):
9919 // Predecessor pairing seeds from the PREDECESSOR row (col len-2) — the same-row path takes the
9920 // last col exactly as before (byte-identical to the old _h_emb_dev call).
9921 let (rl_d, rx) = if self.qwen35_serving_class() {
9922 let mut logits = Vec::with_capacity(replay.len() * n_vocab);
9923 let mut hidden = e.uninit(replay.len() * n_embd)?;
9924 for (row, &token) in replay.iter().enumerate() {
9925 let (row_logits, row_hidden) =
9926 self.spec_target_step_h(e, token, &mut *cache)?;
9927 logits.extend_from_slice(&row_logits);
9928 e.dtod_copy_into(&row_hidden, &mut hidden, row * n_embd)?;
9929 }
9930 (e.htod(&logits)?, hidden)
9931 } else {
9932 self.decode_step_t_core(e, &replay, pos, &mut *cache, embd_dev, None)?
9933 };
9934 // last_pred = argmax of the LAST column's logits (predicts the token after `bonus`)
9935 // — device argmax + one 4-byte read instead of the full-vocab column dtoh.
9936 e.argmax_token_device_col(&rl_d, replay.len() - 1, n_vocab, &mut preds_d, 0)?;
9937 last_pred = e.dtoh_u32(&preds_d)?[0];
9938 if sampled {
9939 let lr0 = replay.len();
9940 let lc = last_col_logits
9941 .as_mut()
9942 .expect("sampled: last_col_logits unset");
9943 e.copy_view_into(
9944 lc,
9945 0,
9946 &rl_d.slice((lr0 - 1) * n_vocab..lr0 * n_vocab),
9947 n_vocab,
9948 )?;
9949 }
9950 let lr = replay.len();
9951 if lr >= 2 {
9952 e.copy_view_into(
9953 &mut h_seed_buf,
9954 0,
9955 &rx.slice((lr - 2) * n_embd..(lr - 1) * n_embd),
9956 n_embd,
9957 )?;
9958 } else {
9959 // 1-token replay (round-0 miss): the bonus's predecessor is the OLD
9960 // last_token, whose own-row hidden fill_prev still holds.
9961 e.copy_into(&mut h_seed_buf, 0, &fill_prev, n_embd)?;
9962 }
9963 // the bonus is COMMITTED here — it becomes the last committed row.
9964 let mut rh_last = e.zeros(n_embd)?;
9965 e.copy_view_into(
9966 &mut rh_last,
9967 0,
9968 &rx.slice((lr - 1) * n_embd..lr * n_embd),
9969 n_embd,
9970 )?;
9971 e.copy_into(&mut fill_prev, 0, &rh_last, n_embd)?;
9972 if debug_spec {
9973 eprintln!(" -> PARTIAL(replay={replay:?}), next_pred={last_pred}");
9974 }
9975 }
9976 if devacc_seeded {
9977 // stage (b) epilogue: fill_prev takes the gathered seed AFTER the refresh fills
9978 // consumed the old value (both slots carry the same value in every non-replay arm).
9979 e.copy_into(&mut fill_prev, 0, &h_seed_buf, n_embd)?;
9980 }
9981 if successor_valid {
9982 let optimistic_scratch_len = successor_attempt
9983 .as_ref()
9984 .expect("valid controller successor disappeared")
9985 .scratch_len;
9986 // The normal current-round commit refreshed/truncated the logical scratch tail.
9987 // Its optimistic successor row was already written physically, so restoring only
9988 // the retained logical length makes that row live for the carried round.
9989 scratch.set_len(e, optimistic_scratch_len)?;
9990 }
9991 if let Some(current) = current_opti.take() {
9992 opti_fork
9993 .as_mut()
9994 .ok_or("optipipe current retirement lost fork state")?
9995 .retire(current.generation)?;
9996 }
9997 if successor_valid {
9998 let successor = successor_attempt
9999 .take()
10000 .expect("valid controller successor disappeared before promotion");
10001 let generation = successor.generation;
10002 opti_fork
10003 .as_mut()
10004 .ok_or("optipipe successor promotion lost fork state")?
10005 .promote_successor_snapshot(&mut snap, generation);
10006 carried_opti = Some(successor);
10007 }
10008 if anatomy_on {
10009 // Commit/rollback is normally asynchronous on the primary/head stream. Bound it
10010 // only for this diagnostic so it does not disappear into the following draft's
10011 // first token readback.
10012 e.stream().synchronize()?;
10013 ph_commit += commit_started.elapsed().as_secs_f64();
10014 }
10015 // adaptive-K update (host math, zero syncs): next round drafts accepted-run + 1,
10016 // clamped to [floor(pos), k_cap]. cache.pos is post-rollback here (the round's
10017 // final position — the floor's position key reads the committed depth). Burst
10018 // rounds (`continue` above) draft the captured fixed depth and skip this, exactly
10019 // like gemma's burst arm.
10020 if adapt {
10021 let fl_now = floor_at(cache.pos);
10022 kc = (n_acc + 1).clamp(fl_now.min(k_cap), k_cap);
10023 }
10024 ph_mark(&mut ph_rest, phase_on);
10025 if let Some(p) = pipe {
10026 p.accept_end(round);
10027 }
10028 drop(pipe_accept);
10029 round += 1;
10030 // sse-cadence: this round's accepted drafts + bonus are committed (out is
10031 // append-only past step 4) — flush at round cadence.
10032 keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
10033 }
10034 if let Some(mut ticket) = carried_opti.take() {
10035 opti_fork
10036 .as_mut()
10037 .ok_or("optipipe tail drain lost fork state")?
10038 .cancel_controller_ticket(e, &mut *cache, &mut *scratch, &snap, &mut ticket)?;
10039 }
10040 // sse-cadence: nothing below appends to `out`; flush any remainder (defensive).
10041 // (verdict ignored — the burst is over either way; the session tail runs unchanged.)
10042 let _ = flush_commit(&mut on_commit, &out, &mut flushed);
10043
10044 if spec_stats {
10045 let per_slot: Vec<String> = (0..k)
10046 .map(|j| {
10047 if st_drafted[j] > 0 {
10048 format!(
10049 "{}/{}={:.3}",
10050 st_accepted[j],
10051 st_drafted[j],
10052 st_accepted[j] as f64 / st_drafted[j] as f64
10053 )
10054 } else {
10055 "0/0".into()
10056 }
10057 })
10058 .collect();
10059 let acc = if total_drafted > 0 {
10060 total_accepted as f64 / total_drafted as f64
10061 } else {
10062 0.0
10063 };
10064 eprintln!(
10065 "[spec-stats] rounds={round} full_accept={st_full} len_hist={st_len_hist:?} \
10066 per_slot=[{}] total={total_accepted}/{total_drafted}={acc:.3} \
10067 tok_per_round={:.3}",
10068 per_slot.join(" "),
10069 (total_accepted + round) as f64 / round.max(1) as f64
10070 );
10071 }
10072 if constraint.is_some() {
10073 eprintln!(
10074 "[draft-mask] mask_rounds={dm_rounds} clone_total={:.3}ms \
10075 clone_per_round={:.4}ms gram_cuts={dm_cuts}/{round} cut_tokens={dm_cut_tokens}",
10076 dm_clone_ns as f64 / 1e6,
10077 dm_clone_ns as f64 / 1e6 / dm_rounds.max(1) as f64
10078 );
10079 }
10080 if phase_on {
10081 let tot = ph_draft + ph_verify + ph_wait + ph_rest;
10082 eprintln!(
10083 "[spec-phase] draft={:.1}ms ({:.1}%) verify-issue={:.1}ms ({:.1}%) verify-wait={:.1}ms ({:.1}%) commit-host={:.1}ms ({:.1}%) rounds={round}",
10084 ph_draft * 1e3,
10085 ph_draft / tot * 100.0,
10086 ph_verify * 1e3,
10087 ph_verify / tot * 100.0,
10088 ph_wait * 1e3,
10089 ph_wait / tot * 100.0,
10090 ph_rest * 1e3,
10091 ph_rest / tot * 100.0
10092 );
10093 }
10094 if anatomy_on {
10095 let rounds_f = round.max(1) as f64;
10096 let other = (ph_rest - ph_commit).max(0.0);
10097 eprintln!(
10098 "[spec-anatomy] per-round draft={:.3}ms pp-verify={:.3}ms \
10099 verify-accept={:.3}ms commit-rollback={:.3}ms other={:.3}ms rounds={round}",
10100 ph_draft * 1e3 / rounds_f,
10101 ph_verify * 1e3 / rounds_f,
10102 ph_wait * 1e3 / rounds_f,
10103 ph_commit * 1e3 / rounds_f,
10104 other * 1e3 / rounds_f,
10105 );
10106 }
10107 let _pipe_tail = pipe.map(|p| p.primary());
10108 // SESSION TAIL: leave the session in the exact invariant the next turn's suffix prime
10109 // expects — every row in `committed` has trunk KV/recur state AND an exact draft-KV row.
10110 // Park the draft-graph ctx back on the session (the serve-burst fixed-cost fix): the next
10111 // burst replays instead of recapturing. Error paths (`?` above) drop it — recaptured then.
10112 if let Some(slot) = sess_draft_slot.take() {
10113 *slot = Some(dctx);
10114 }
10115 let t_rounds = t_ent.elapsed();
10116 if let Some((committed, last_h, next_pred_slot, sctr_slot, uctr_slot)) = sess_tail.take() {
10117 // NEXT BURST'S BOUNDARY TOKEN (lane/sampled-spec-quality, Item 1). Greedy stashes
10118 // the argmax `last_pred` exactly as before (byte contract). SAMPLED draws the token
10119 // HERE, where the sampler, the session Philox counters and the penalty window are
10120 // all live and the boundary logits row still exists — that is the "make the state
10121 // available" half of the fix; the consuming burst then just emits it. `sctr` is
10122 // written to the session BELOW the draws so the advance is never lost.
10123 *next_pred_slot = Some(last_pred);
10124 let sample_boundary = sampled && constraint.is_none() && spec_sampled_boundary_on();
10125 let mut stashed_pending = false;
10126 if let Some(b) = pending.take() {
10127 if !sampled {
10128 // PENDING-CARRY (2026-08-01): stash the bonus on the session instead of
10129 // committing it with a solo T=1 pass — the next empty-suffix greedy burst
10130 // consumes it as round-0 verify col 0 (a plain round edge; the old tail
10131 // commit + next burst's init feed were 11.6+11.5ms solo trunk passes per
10132 // burst on H100 q27, [spec-setup] trace). b stays in `out` (emitted) but
10133 // OUT of `committed` (cache rows == committed); the consuming call
10134 // prepends it once its verify commits the row. next_pred is unknowable
10135 // without the commit pass — None; callers gate on pending_tok too.
10136 debug_assert_eq!(out.last(), Some(&b), "pending must be the last emitted");
10137 if let Some(slot) = sess_pending_slot.take() {
10138 *slot = Some(b);
10139 }
10140 *next_pred_slot = None;
10141 // fill_prev = hidden of the last COMMITTED row (b's predecessor) — the
10142 // exact chain-seed/fill anchor the consuming burst (or a flush) needs.
10143 *last_h = Some(e.clone_dtod(&fill_prev)?);
10144 stashed_pending = true;
10145 } else {
10146 // SAMPLED tail (unchanged): commit the bonus (one T=1 pass) + draft fill —
10147 // the sampled round-0 accept needs this pass's logits (last_col_logits).
10148 let pos_b = cache.pos;
10149 scratch.set_len(e, pos_b)?;
10150 let (lg_b, hb) = self.spec_target_step_h(e, b, &mut *cache)?;
10151 // after a FULL-accept exit `last_pred` is STALE (it predicted the bonus
10152 // itself — the prediction AFTER the bonus never materialized; it would have
10153 // been the next round's verify col 0). The commit's logits ARE that
10154 // prediction — so they are also the row the next burst's boundary token
10155 // comes off, and (lane/sampled-spec-quality) it is DRAWN from them here.
10156 *next_pred_slot = Some(if sample_boundary {
10157 sample_boundary_token(
10158 e,
10159 &lg_b,
10160 &sp,
10161 &pen_hist,
10162 &mut sctr,
10163 "burst-tail-commit",
10164 )?
10165 } else {
10166 argmax(&lg_b) as u32
10167 });
10168 self.mtp_kv_fill(e, mtp, &[b], &fill_prev, pos_b, &mut *scratch, embd_dev)?;
10169 *last_h = Some(hb);
10170 }
10171 } else {
10172 // fill_prev tracks the hidden of the last COMMITTED row throughout the loop.
10173 *last_h = Some(e.clone_dtod(&fill_prev)?);
10174 if sample_boundary {
10175 // No pending to commit, so the boundary row is the one `last_pred` was
10176 // argmaxed from and the sampled path keeps it on device: the init feed's
10177 // logits when the burst ran zero rounds, else the legacy-replay path's
10178 // last verify column (both predict the token AFTER the last committed
10179 // row). It is retained precisely because round 0's accept test needs it,
10180 // so the draw costs no extra D2H of the [n_vocab] row.
10181 match last_col_logits.as_ref() {
10182 Some(lc) => {
10183 *next_pred_slot = Some(sample_boundary_token_dev(
10184 e,
10185 lc,
10186 n_vocab,
10187 &sp,
10188 &pen_hist,
10189 &mut sctr,
10190 "burst-tail-nopending",
10191 )?);
10192 }
10193 // NAME THE FALLBACK (house standard): unreachable today — a sampled
10194 // burst always feeds or replays, so the row exists — but if it ever
10195 // is, the stream takes a greedy token and SAYS so rather than
10196 // silently regressing to the pre-lane behaviour.
10197 None => eprintln!(
10198 "[spec-boundary] sampled tail kept the ARGMAX boundary token \
10199 (reason: no retained boundary logits row)"
10200 ),
10201 }
10202 }
10203 }
10204 *sctr_slot = sctr;
10205 *uctr_slot = uctr;
10206 committed.extend_from_slice(prompt);
10207 if let Some(cb) = carried_pending {
10208 // the consumed carry's cache row landed in round 0's verify (every pending
10209 // round commits col 0) — it joins `committed` here, in sequence order.
10210 committed.push(cb);
10211 }
10212 if stashed_pending {
10213 // ZERO-EMIT BURST (2026-08-06 c=8 serve panic, pre-existing since b4aea184):
10214 // `out.len() - 1` underflowed on an EMPTY `out` — "range end index
10215 // 18446744073709551615 out of range for slice of length 0", killing the
10216 // memra-gpu-worker and failing 31 of 32 concurrent requests with "worker closed
10217 // stream". Reachable because `pending` starts as `carried_pending` (a bonus
10218 // stashed by the PREVIOUS burst) while `out` starts empty, and the carry is
10219 // deliberately NOT pushed to `out` (line ~3239: the burst that emitted it already
10220 // did). So a burst that stashes a pending without emitting anything of its own —
10221 // the round loop exits before a push, e.g. the ring drain's `out.len() < max_new`
10222 // guard skipping every token under a tight budget — arrives here with
10223 // out.len() == 0 and stashed_pending == true.
10224 //
10225 // The invariant is unchanged: `committed` gets every emitted token EXCEPT the
10226 // stashed bonus. With nothing emitted, that is nothing — and the carry pushed
10227 // just above is already accounted. Saturating, not a min/assert: an empty `out`
10228 // here is a legitimate burst shape, not a corrupt state.
10229 let emitted = out.len().saturating_sub(1);
10230 committed.extend_from_slice(&out[..emitted]);
10231 } else {
10232 committed.extend_from_slice(&out); // FULL out incl. overshoot — all committed
10233 }
10234 debug_assert_eq!(
10235 cache.pos,
10236 committed.len(),
10237 "session invariant: cache rows == committed tokens"
10238 );
10239 if setup_trace {
10240 e.stream().synchronize()?; // bound the async tail fill in the trace
10241 let t_tail = t_ent.elapsed();
10242 eprintln!(
10243 "[spec-setup] init={:.2}ms cap={:.2}ms fill={:.2}ms rounds={:.2}ms tail={:.2}ms total={:.2}ms out={} cont={}",
10244 t_init.as_secs_f64() * 1e3,
10245 (t_cap - t_init).as_secs_f64() * 1e3,
10246 (t_fill - t_cap).as_secs_f64() * 1e3,
10247 (t_rounds - t_fill).as_secs_f64() * 1e3,
10248 (t_tail - t_rounds).as_secs_f64() * 1e3,
10249 t_tail.as_secs_f64() * 1e3,
10250 out.len(),
10251 continuation
10252 );
10253 }
10254 return Ok((out, total_drafted, total_accepted));
10255 }
10256 out.truncate(max_new);
10257 Ok((out, total_drafted, total_accepted))
10258 }
10259
10260 /// Anchor-bounded DSpark target extraction. The trunk sees the exact generated token tape;
10261 /// only requested hidden rows and target-logit rows cross PCIe. An anchor token at p pairs
10262 /// with the pre-output-norm h[p-1] carrier, exactly as the existing replay/NextN path does.
10263 pub fn extract_dspark_anchors(
10264 &self,
10265 e: &Engine,
10266 tokens: &[u32],
10267 anchor_positions: &[usize],
10268 gamma: usize,
10269 top_k: usize,
10270 chunk: usize,
10271 temperature: f32,
10272 ) -> Result<Vec<DsparkAnchorRecord>, Box<dyn std::error::Error>> {
10273 if tokens.len() < gamma + 2 || gamma == 0 || chunk < 2 {
10274 return Err("DSpark extraction token tape/gamma/chunk is invalid".into());
10275 }
10276 if anchor_positions.windows(2).any(|pair| pair[0] >= pair[1]) {
10277 return Err("DSpark anchor positions must be sorted and unique".into());
10278 }
10279 for &position in anchor_positions {
10280 if position == 0 || position + gamma >= tokens.len() {
10281 return Err(format!(
10282 "DSpark anchor {position} has no predecessor or cannot cover gamma={gamma} in {} tokens",
10283 tokens.len()
10284 )
10285 .into());
10286 }
10287 }
10288
10289 let n_vocab = self.output.out_features();
10290 let n_embd = self.cfg.n_embd as usize;
10291 let mut cache = crate::pp::new_cache(e, &self.cfg, tokens.len() + gamma + 8)?;
10292 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
10293 let embd_gpu = if spec_host_embd() {
10294 None
10295 } else {
10296 Some(
10297 self.embd_gpu
10298 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
10299 )
10300 };
10301 let embd_dev = embd_gpu.map(|gpu| (gpu, embd_qt, embd_rb));
10302
10303 struct PendingRecord {
10304 position: usize,
10305 hidden: Option<Vec<f32>>,
10306 tokens: Vec<u32>,
10307 target_top_ids: Vec<Option<Vec<u32>>>,
10308 target_top_logits: Vec<Option<Vec<f32>>>,
10309 target_top_probs: Vec<Option<Vec<f32>>>,
10310 target_tail_probs: Vec<Option<f32>>,
10311 }
10312
10313 let mut pending: Vec<PendingRecord> = anchor_positions
10314 .iter()
10315 .map(|&position| PendingRecord {
10316 position,
10317 hidden: None,
10318 tokens: tokens[position..=position + gamma].to_vec(),
10319 target_top_ids: vec![None; gamma],
10320 target_top_logits: vec![None; gamma],
10321 target_top_probs: vec![None; gamma],
10322 target_tail_probs: vec![None; gamma],
10323 })
10324 .collect();
10325
10326 let mut start = 0usize;
10327 while start < tokens.len() {
10328 let end = (start + chunk).min(tokens.len());
10329 let chunk_tokens = &tokens[start..end];
10330 let (target_logits, hidden_rows) =
10331 self.decode_step_t_core(e, chunk_tokens, start, &mut cache, embd_dev, None)?;
10332 for record in &mut pending {
10333 let hidden_position = record.position - 1;
10334 if hidden_position >= start && hidden_position < end {
10335 let local = hidden_position - start;
10336 record.hidden = Some(
10337 e.dtoh_view(&hidden_rows.slice(local * n_embd..(local + 1) * n_embd))?,
10338 );
10339 }
10340 for slot in 0..gamma {
10341 let target_row = record.position + slot;
10342 if target_row < start || target_row >= end {
10343 continue;
10344 }
10345 let local = target_row - start;
10346 let logits =
10347 e.dtoh_view(&target_logits.slice(local * n_vocab..(local + 1) * n_vocab))?;
10348 let (ids, top_logits, probs, tail) =
10349 dspark_sparse_softmax_topk(&logits, top_k, temperature)?;
10350 record.target_top_ids[slot] = Some(ids);
10351 record.target_top_logits[slot] = Some(top_logits);
10352 record.target_top_probs[slot] = Some(probs);
10353 record.target_tail_probs[slot] = Some(tail);
10354 }
10355 }
10356 start = end;
10357 }
10358
10359 pending
10360 .into_iter()
10361 .map(|record| {
10362 let hidden = record
10363 .hidden
10364 .ok_or_else(|| format!("missing DSpark hidden at {}", record.position))?;
10365 let target_top_ids =
10366 flatten_dspark_rows(record.target_top_ids, record.position, "target ids")?;
10367 let target_top_logits = flatten_dspark_rows(
10368 record.target_top_logits,
10369 record.position,
10370 "target logits",
10371 )?;
10372 let target_top_probs =
10373 flatten_dspark_rows(record.target_top_probs, record.position, "target probs")?;
10374 let target_tail_probs = record
10375 .target_tail_probs
10376 .into_iter()
10377 .enumerate()
10378 .map(|(slot, value)| {
10379 value.ok_or_else(|| {
10380 format!("missing DSpark tail at {} slot {slot}", record.position)
10381 })
10382 })
10383 .collect::<Result<Vec<_>, _>>()?;
10384 Ok(DsparkAnchorRecord {
10385 position: record.position,
10386 hidden,
10387 tokens: record.tokens,
10388 target_top_ids,
10389 target_top_logits,
10390 target_top_probs,
10391 target_tail_probs,
10392 })
10393 })
10394 .collect()
10395 }
10396
10397 /// TEACHER-FORCED REPLAY ACCEPTANCE (hqmtp MTP-heal protocol): walk a FIXED token
10398 /// sequence and, at sampled positions, compare the MTP head's K-token draft chain against
10399 /// the trunk's own teacher-forced greedy predictions. Nothing is generated — the context is
10400 /// the corpus text itself, so (a) degenerate self-generated loops cannot inflate acceptance
10401 /// and (b) two arms (bf16 ceiling vs NVFP4) score on IDENTICAL contexts, isolating the
10402 /// quant-induced head/hidden-state mismatch from text drift.
10403 ///
10404 /// Per eval position p (context = tokens[0..=p], predecessor pairing as in spec decode):
10405 /// draft_j = chain token j from (tokens[p], h_{p-1}), then its own drafts — the exact
10406 /// eager spec-decode chain (same mtp_head_forward_dev, same rope positions).
10407 /// target_j = teacher-forced greedy pick for position p+1+j (argmax of the trunk logits
10408 /// at forced context tokens[0..p+j]). For j==0 this equals live spec
10409 /// acceptance; for j>=1 live verify would condition on the drafts, here it
10410 /// conditions on the corpus — deterministic and arm-comparable by design.
10411 ///
10412 /// Returns (rows, bg): one (p, drafts[k], targets[k]) row per eval position (ascending p),
10413 /// plus the full teacher-forced greedy track bg (bg[i] = greedy pick for position i, i>=1)
10414 /// so harnesses can cross-check runs (e.g. different chunk sizes must give identical bg).
10415 ///
10416 /// `hdump`: when Some, every position's pre-output_norm trunk hidden (the exact rows the
10417 /// draft-KV fill pairs from) streams to the file as little-endian f32 [t_total, n_embd] —
10418 /// the head-distillation extraction (hqmtp): the ENGINE is the source of truth for trunk
10419 /// hiddens (HF torch reproductions of the hybrid trunk measured only ~0.5 greedy
10420 /// agreement vs this path — not usable as a training-data source).
10421 pub fn replay_acceptance(
10422 &self,
10423 e: &Engine,
10424 tokens: &[u32],
10425 k: usize,
10426 stride: usize,
10427 chunk: usize,
10428 mut hdump: Option<&mut std::fs::File>,
10429 ) -> Result<(Vec<(usize, Vec<u32>, Vec<u32>)>, Vec<u32>), Box<dyn std::error::Error>> {
10430 assert!(k >= 1 && stride >= 1 && chunk >= 2);
10431 let mtp = self
10432 .mtp
10433 .as_ref()
10434 .expect("replay_acceptance requires an MTP head");
10435 let n_vocab = self.output.out_features();
10436 let d_vocab = mtp
10437 .shared_head_head
10438 .as_ref()
10439 .unwrap_or(&self.output)
10440 .out_features();
10441 let n_embd = self.cfg.n_embd as usize;
10442 let t_total = tokens.len();
10443 assert!(t_total >= 8, "corpus too short ({t_total} tokens)");
10444 // STAGE-OWNED KV (lane/pp2-spec 2026-08-06) — see `new_session`. Door shut = `Cache::new`.
10445 let mut cache = crate::pp::new_cache(e, &self.cfg, t_total + k + 8)?;
10446 let mut scratch = MtpScratch::new(
10447 e,
10448 &self.cfg,
10449 t_total + k + 8,
10450 self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
10451 )?;
10452 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
10453 let embd_gpu = if spec_host_embd() {
10454 None
10455 } else {
10456 Some(
10457 self.embd_gpu
10458 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
10459 )
10460 };
10461 let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
10462
10463 // bg[i] = the trunk's greedy pick for position i under the forced context (i >= 1).
10464 let mut bg: Vec<u32> = vec![0; t_total + 1];
10465 let mut rows: Vec<(usize, Vec<u32>, Vec<u32>)> = Vec::new();
10466 let mut prev_last_h = e.zeros(n_embd)?; // predecessor hidden entering the chunk
10467 let mut seed_buf = e.zeros(n_embd)?;
10468 let mut preds_d = e.alloc_u32_zeroed(chunk)?;
10469 let nll_on = std::env::var("MEMRA_REPLAY_NLL").as_deref() == Ok("1");
10470 let (mut nll_sum, mut nll_cnt) = (0f64, 0u64);
10471 let mut s = 0usize;
10472 while s < t_total {
10473 let cend = (s + chunk).min(t_total);
10474 let tc = cend - s;
10475 let ch = &tokens[s..cend];
10476 // 1. forced trunk pass — verify path (decode-exact contract): all-column logits +
10477 // the chunk's true hiddens.
10478 let (tl_d, vx) = self.decode_step_t_core(e, ch, s, &mut cache, embd_dev, None)?;
10479 for j in 0..tc {
10480 e.argmax_token_device_col(&tl_d, j, n_vocab, &mut preds_d, j)?;
10481 }
10482 let preds = e.dtoh_u32(&preds_d)?;
10483 for j in 0..tc {
10484 bg[s + j + 1] = preds[j];
10485 }
10486 // MEMRA_REPLAY_NLL=1: teacher-forced NLL/perplexity over the same forced pass — the
10487 // checkpoint-quality metric (position j's logits score the GOLD next token).
10488 if nll_on {
10489 let jmax = if cend < t_total { tc } else { tc - 1 }; // last pos has no gold next
10490 if jmax > 0 {
10491 let ids: Vec<u32> = (0..jmax).map(|j| tokens[s + j + 1]).collect();
10492 let rows: Vec<i32> = (0..jmax as i32).collect();
10493 let idsd = e.htod_u32_v(&ids)?;
10494 let rowsd = e.htod_i32(&rows)?;
10495 let mut outd = e.zeros(jmax)?;
10496 e.softmax_gather(&tl_d, n_vocab, &idsd, &rowsd, &mut outd, n_vocab, jmax, 1.0)?;
10497 for pr in e.dtoh(&outd)? {
10498 nll_sum += -((pr.max(1e-30)) as f64).ln();
10499 nll_cnt += 1;
10500 }
10501 }
10502 }
10503 if let Some(f) = hdump.as_deref_mut() {
10504 use std::io::Write;
10505 let host: Vec<f32> = e.dtoh(&vx)?;
10506 // bf16 round-to-nearest-even — f32 doubled the disk bill at bulk
10507 // extraction scale (20M tokens x 4096 = 320GB f32 vs 160GB bf16).
10508 let mut bytes = Vec::with_capacity(tc * n_embd * 2);
10509 for v in &host[..tc * n_embd] {
10510 let b = v.to_bits();
10511 let r = b.wrapping_add(0x7FFF + ((b >> 16) & 1));
10512 bytes.extend_from_slice(&((r >> 16) as u16).to_le_bytes());
10513 }
10514 f.write_all(&bytes)?;
10515 }
10516 // CHAINLESS extraction (stride > corpus, the bulk-hdump mode): no chunk ever
10517 // drafts, so the draft-KV fills are pure waste — skip them (2 MTP-block passes
10518 // per token saved; the forced trunk pass + hdump is all the mode needs).
10519 let chainless = stride > t_total;
10520 if chainless {
10521 e.copy_view_into(
10522 &mut prev_last_h,
10523 0,
10524 &vx.slice((tc - 1) * n_embd..tc * n_embd),
10525 n_embd,
10526 )?;
10527 s = cend;
10528 continue;
10529 }
10530 // 2. TRUE predecessor-paired draft-KV fill for the chunk (row i carries h_{i-1};
10531 // row s reads the previous chunk's last true hidden, zeros at corpus start).
10532 let mut vxs = e.zeros(tc * n_embd)?;
10533 e.copy_into(&mut vxs, 0, &prev_last_h, n_embd)?;
10534 if tc > 1 {
10535 e.copy_view_into(
10536 &mut vxs,
10537 n_embd,
10538 &vx.slice(0..(tc - 1) * n_embd),
10539 (tc - 1) * n_embd,
10540 )?;
10541 }
10542 scratch.set_len(e, s)?;
10543 self.mtp_kv_fill(e, mtp, ch, &vxs, s, &mut scratch, embd_dev)?;
10544 // 3. draft chains at sampled positions, DESCENDING: a chain reads only slots
10545 // [0..p) (true fills) and appends at >= p; the next (smaller-p) chain's set_len
10546 // truncates those approximate appends before they can ever be read.
10547 let ps: Vec<usize> = (s..cend)
10548 .filter(|p| *p >= 1 && *p % stride == 0 && *p + k <= t_total)
10549 .collect();
10550 for &p in ps.iter().rev() {
10551 scratch.set_len(e, p)?;
10552 if p == s {
10553 e.copy_into(&mut seed_buf, 0, &prev_last_h, n_embd)?;
10554 } else {
10555 e.copy_view_into(
10556 &mut seed_buf,
10557 0,
10558 &vx.slice((p - 1 - s) * n_embd..(p - s) * n_embd),
10559 n_embd,
10560 )?;
10561 }
10562 let mut e_tok = tokens[p];
10563 let mut d_seed = e.clone_dtod(&seed_buf)?;
10564 let mut drafts: Vec<u32> = Vec::with_capacity(k);
10565 for j in 0..k {
10566 let (dl_d, h_nextn) = self.mtp_head_forward_dev(
10567 e,
10568 mtp,
10569 e_tok,
10570 &d_seed,
10571 &mut scratch,
10572 p + 1 + j,
10573 embd_dev,
10574 None, // acceptance-oracle walk: no grammar
10575 )?;
10576 let tok_d = e.argmax_token_device(&dl_d, d_vocab)?;
10577 let idx = e.dtoh_u32_one(&tok_d)?;
10578 let d = match &mtp.d2t {
10579 Some(map) => map[idx as usize],
10580 None => idx,
10581 };
10582 drafts.push(d);
10583 e_tok = d;
10584 d_seed = h_nextn;
10585 }
10586 // targets may live in a LATER chunk's bg — resolved after the walk.
10587 rows.push((p, drafts, Vec::new()));
10588 }
10589 // 4. restore TRUE entries for the whole chunk (the next chunk's chains and fills
10590 // expect scratch.len == cend with exact rows).
10591 scratch.set_len(e, s)?;
10592 self.mtp_kv_fill(e, mtp, ch, &vxs, s, &mut scratch, embd_dev)?;
10593 e.copy_view_into(
10594 &mut prev_last_h,
10595 0,
10596 &vx.slice((tc - 1) * n_embd..tc * n_embd),
10597 n_embd,
10598 )?;
10599 s = cend;
10600 }
10601 for (p, drafts, targets) in rows.iter_mut() {
10602 for j in 0..drafts.len() {
10603 targets.push(bg[*p + 1 + j]);
10604 }
10605 }
10606 rows.sort_by_key(|r| r.0);
10607 if nll_cnt > 0 {
10608 let mean = nll_sum / nll_cnt as f64;
10609 println!(
10610 "[replay-nll] tokens={nll_cnt} nll/token={mean:.5} ppl={:.4}",
10611 mean.exp()
10612 );
10613 }
10614 Ok((rows, bg))
10615 }
10616}
10617
10618#[cfg(test)]
10619mod dspark_sparse_tests {
10620 use super::dspark_sparse_softmax_topk;
10621
10622 #[test]
10623 fn topk_keeps_full_softmax_mass_and_stable_ties() {
10624 let logits = [1.0f32, 3.0, 3.0, -2.0];
10625 let (ids, top_logits, probs, tail) = dspark_sparse_softmax_topk(&logits, 2, 1.0).unwrap();
10626 assert_eq!(ids, vec![1, 2]);
10627 assert_eq!(top_logits, vec![3.0, 3.0]);
10628 let denominator = logits.iter().map(|value| (value - 3.0).exp()).sum::<f32>();
10629 let expected = 1.0 / denominator;
10630 assert!((probs[0] - expected).abs() < 1.0e-6);
10631 assert!((probs[1] - expected).abs() < 1.0e-6);
10632 assert!((tail - (1.0 - 2.0 * expected)).abs() < 1.0e-6);
10633 assert!((probs.iter().sum::<f32>() + tail - 1.0).abs() < 1.0e-6);
10634 }
10635}
10636
10637#[cfg(test)]
10638mod spec_replay_env_tests {
10639 use super::spec_replay_env_on;
10640
10641 #[test]
10642 fn replay_requires_literal_one() {
10643 assert!(!spec_replay_env_on(None));
10644 assert!(!spec_replay_env_on(Some("")));
10645 assert!(!spec_replay_env_on(Some("0")));
10646 assert!(!spec_replay_env_on(Some("true")));
10647 assert!(!spec_replay_env_on(Some("2")));
10648 assert!(spec_replay_env_on(Some("1")));
10649 }
10650}
10651
10652#[cfg(test)]
10653mod telem_tests {
10654 use super::{SPEC_TELEM_POS, SpecTelemetry, SpecTelemetryCounters};
10655
10656 #[test]
10657 fn synthetic_accept_masks_produce_tau_and_position_histogram() {
10658 let counters = SpecTelemetryCounters::default();
10659 for mask in [
10660 [true, true, true],
10661 [true, true, false],
10662 [true, false, false],
10663 [false, false, false],
10664 ] {
10665 let accepted = mask.iter().take_while(|&&value| value).count();
10666 counters.record_round(mask.len(), accepted);
10667 }
10668
10669 let snapshot = counters.snapshot();
10670 assert_eq!(
10671 (snapshot.rounds, snapshot.drafted, snapshot.accepted),
10672 (4, 12, 6)
10673 );
10674 assert_eq!(&snapshot.pos_drafted[..3], &[4, 4, 4]);
10675 assert_eq!(&snapshot.pos_accepted[..3], &[3, 2, 1]);
10676 assert_eq!(snapshot.tau(), 1.5);
10677 assert_eq!(snapshot.pos_drafted[3..], [0; SPEC_TELEM_POS - 3]);
10678 assert_eq!(snapshot.pos_accepted[3..], [0; SPEC_TELEM_POS - 3]);
10679 }
10680
10681 /// The worker's per-burst pattern: stash, accumulate, diff — the delta must isolate
10682 /// exactly the burst's contribution (pool-resumed sessions carry prior requests' counts).
10683 #[test]
10684 fn delta_isolates_burst_contribution() {
10685 let mut t = SpecTelemetry::default();
10686 // "previous request": 2 rounds of k=3, accepts 3 then 1.
10687 for (kr, na) in [(3usize, 3usize), (3, 1)] {
10688 t.rounds += 1;
10689 t.drafted += kr as u64;
10690 t.accepted += na as u64;
10691 for j in 0..kr {
10692 t.pos_drafted[j] += 1;
10693 }
10694 for j in 0..na {
10695 t.pos_accepted[j] += 1;
10696 }
10697 }
10698 let before = t;
10699 // "this burst": 1 round k=3, accepts 2.
10700 t.rounds += 1;
10701 t.drafted += 3;
10702 t.accepted += 2;
10703 for j in 0..3 {
10704 t.pos_drafted[j] += 1;
10705 }
10706 for j in 0..2 {
10707 t.pos_accepted[j] += 1;
10708 }
10709 let d = t.delta_since(&before);
10710 assert_eq!((d.rounds, d.drafted, d.accepted), (1, 3, 2));
10711 assert_eq!(&d.pos_drafted[..3], &[1, 1, 1]);
10712 assert_eq!(&d.pos_accepted[..3], &[1, 1, 0]);
10713 assert_eq!(d.pos_drafted[3..], [0; SPEC_TELEM_POS - 3]);
10714 }
10715
10716 /// merge(delta) then merge(delta2) equals accumulating both — the per-model /metrics
10717 /// aggregation invariant.
10718 #[test]
10719 fn merge_accumulates_fieldwise() {
10720 let mut agg = SpecTelemetry::default();
10721 let mut d1 = SpecTelemetry {
10722 rounds: 2,
10723 drafted: 6,
10724 accepted: 4,
10725 ..Default::default()
10726 };
10727 d1.pos_drafted[0] = 2;
10728 d1.pos_accepted[0] = 2;
10729 let mut d2 = SpecTelemetry {
10730 rounds: 1,
10731 drafted: 3,
10732 accepted: 1,
10733 ..Default::default()
10734 };
10735 d2.pos_drafted[0] = 1;
10736 d2.pos_accepted[0] = 1;
10737 d2.pos_drafted[1] = 1;
10738 agg.merge(&d1);
10739 agg.merge(&d2);
10740 assert_eq!((agg.rounds, agg.drafted, agg.accepted), (3, 9, 5));
10741 assert_eq!(agg.pos_drafted[0], 3);
10742 assert_eq!(agg.pos_accepted[0], 3);
10743 assert_eq!(agg.pos_drafted[1], 1);
10744 assert_eq!(agg.pos_accepted[1], 0);
10745 }
10746
10747 /// Wrong-snapshot diff saturates to zero instead of wrapping — the counters feed a
10748 /// public metrics surface and must never publish a u64-wrapped garbage value.
10749 #[test]
10750 fn delta_saturates_never_wraps() {
10751 let small = SpecTelemetry {
10752 rounds: 1,
10753 drafted: 2,
10754 accepted: 1,
10755 ..Default::default()
10756 };
10757 let big = SpecTelemetry {
10758 rounds: 5,
10759 drafted: 15,
10760 accepted: 9,
10761 ..Default::default()
10762 };
10763 let d = small.delta_since(&big);
10764 assert_eq!((d.rounds, d.drafted, d.accepted), (0, 0, 0));
10765 }
10766}
10767
10768#[cfg(test)]
10769mod opti_fork_tests {
10770 use super::{
10771 OptiControllerPolicy, OptiForkAction, OptiForkGateMode, OptiForkGenerationTracker,
10772 };
10773
10774 #[test]
10775 fn controller_threshold_and_three_miss_breaker_are_exact() {
10776 let mut policy = OptiControllerPolicy {
10777 threshold: 0.7,
10778 consecutive_misses: 0,
10779 breaker_tripped: false,
10780 };
10781 assert!(!policy.admit(0.699_999));
10782 assert!(policy.admit(0.7));
10783 assert!(!policy.resolve(false));
10784 assert!(!policy.resolve(false));
10785 assert!(policy.resolve(false));
10786 assert!(policy.breaker_tripped);
10787 assert!(!policy.admit(1.0));
10788 assert!(
10789 !policy.resolve(true),
10790 "a resolved hit cannot re-arm a tripped request"
10791 );
10792 assert!(policy.breaker_tripped);
10793 }
10794
10795 #[test]
10796 fn zero_threshold_is_the_true_unconditional_measurement_arm() {
10797 let mut policy = OptiControllerPolicy {
10798 threshold: 0.0,
10799 consecutive_misses: 0,
10800 breaker_tripped: false,
10801 };
10802 for _ in 0..16 {
10803 assert!(policy.admit(0.0));
10804 assert!(!policy.resolve(false));
10805 }
10806 for invalid in [f32::NAN, f32::INFINITY, -0.01, 1.01] {
10807 assert!(
10808 !policy.admit(invalid),
10809 "invalid q proxy must fail closed: {invalid}"
10810 );
10811 }
10812 assert!(!policy.breaker_tripped);
10813 assert_eq!(policy.consecutive_misses, 0);
10814 }
10815
10816 #[test]
10817 fn alternating_mode_flips_by_generation_not_round_parity() {
10818 assert_eq!(OptiForkGateMode::Alternate.action(0), OptiForkAction::Hit);
10819 assert_eq!(OptiForkGateMode::Alternate.action(1), OptiForkAction::Miss);
10820 assert_eq!(OptiForkGateMode::Alternate.action(8), OptiForkAction::Hit);
10821 assert_eq!(OptiForkGateMode::Alternate.action(9), OptiForkAction::Miss);
10822 }
10823
10824 #[test]
10825 fn live_generation_cannot_be_overwritten() {
10826 let mut tracker = OptiForkGenerationTracker::default();
10827 let g0 = tracker.reserve().unwrap();
10828 let g1 = tracker.reserve().unwrap();
10829 let err = tracker.reserve().unwrap_err().to_string();
10830 assert!(
10831 err.contains("still owns generation 0"),
10832 "unexpected error: {err}"
10833 );
10834 tracker.retire(g0).unwrap();
10835 let g2 = tracker.reserve().unwrap();
10836 assert_eq!((g2.id, g2.slot), (2, 0));
10837 tracker.retire(g1).unwrap();
10838 tracker.retire(g2).unwrap();
10839 }
10840
10841 #[test]
10842 fn teardown_rejects_a_stale_generation_tag() {
10843 let mut tracker = OptiForkGenerationTracker::default();
10844 let g0 = tracker.reserve().unwrap();
10845 tracker.retire(g0).unwrap();
10846 let err = tracker.retire(g0).unwrap_err().to_string();
10847 assert!(err.contains("teardown mismatch"), "unexpected error: {err}");
10848 }
10849}
10850
10851#[cfg(test)]
10852mod draft_graph_fallback_tests {
10853 use super::DraftGraphFallback;
10854
10855 /// The Q2 contract, part (a): a fallback flip is LOUD — exactly once per flip.
10856 #[test]
10857 fn flip_is_loud_once_and_memoized_after() {
10858 let mut f = DraftGraphFallback::default();
10859 let line = f
10860 .mark_greedy("out of memory")
10861 .expect("first flip must return the warn line");
10862 assert!(
10863 line.contains("WARN"),
10864 "flip line must be warn-level: {line}"
10865 );
10866 assert!(
10867 line.contains("out of memory"),
10868 "flip line must carry the reason: {line}"
10869 );
10870 assert!(f.greedy_failed());
10871 // re-marking an already-failed graph is the memoization: quiet, still failed.
10872 assert!(f.mark_greedy("out of memory").is_none());
10873 assert!(f.greedy_failed());
10874 // the two graphs' flags are independent (greedy flip leaves sampled capturable).
10875 assert!(!f.sampled_failed());
10876 let line_s = f
10877 .mark_sampled("capture unsupported")
10878 .expect("sampled flip is its own flip");
10879 assert!(
10880 line_s.contains("sampled"),
10881 "sampled flip names itself: {line_s}"
10882 );
10883 assert!(f.mark_sampled("capture unsupported").is_none());
10884 }
10885
10886 /// The Q2 contract, part (b): resume-from-pool RESETS both flags (fresh capture chance),
10887 /// and says so exactly when there was something to reset.
10888 #[test]
10889 fn reset_on_resume_clears_flags_and_logs_once() {
10890 let mut f = DraftGraphFallback::default();
10891 // clean session: resume is silent, nothing to reset.
10892 assert!(f.reset_on_resume().is_none());
10893 f.mark_greedy("oom").unwrap();
10894 f.mark_sampled("oom").unwrap();
10895 let note = f
10896 .reset_on_resume()
10897 .expect("a set flag must produce the reset note");
10898 assert!(
10899 note.contains("greedy+sampled"),
10900 "note names what was reset: {note}"
10901 );
10902 assert!(
10903 !f.greedy_failed() && !f.sampled_failed(),
10904 "both flags cleared"
10905 );
10906 // and the NEXT failure after a reset is a fresh flip — loud again.
10907 assert!(f.mark_greedy("oom again").is_some());
10908 let note2 = f.reset_on_resume().expect("greedy-only reset");
10909 assert!(note2.contains("(greedy)"), "single-flag note: {note2}");
10910 }
10911
10912 /// Shape-change clears (dmask realloc / mask-shape mismatch / s_key change) stay silent —
10913 /// they precede a fresh capture attempt whose own failure re-flips loudly.
10914 #[test]
10915 fn shape_change_clears_are_silent() {
10916 let mut f = DraftGraphFallback::default();
10917 f.mark_greedy("oom").unwrap();
10918 f.clear_greedy();
10919 assert!(!f.greedy_failed());
10920 f.mark_sampled("oom").unwrap();
10921 f.clear_sampled();
10922 assert!(!f.sampled_failed());
10923 // after a silent clear there is nothing left for resume to report.
10924 assert!(f.reset_on_resume().is_none());
10925 }
10926}