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
713struct SpecPipeTraceClock {
714 pair: usize,
715 started: std::time::Instant,
716}
717
718#[derive(Clone)]
719struct SpecPipeTraceCtx {
720 clock: std::sync::Arc<SpecPipeTraceClock>,
721 round: usize,
722 lane: usize,
723}
724
725struct SpecPipeTraceMarker {
726 trace: SpecPipeTraceCtx,
727 phase: &'static str,
728 edge: &'static str,
729 slot: Option<usize>,
730}
731
732unsafe extern "C" fn spec_pipe_trace_marker(raw: *mut std::ffi::c_void) {
733 let marker = unsafe { Box::from_raw(raw.cast::<SpecPipeTraceMarker>()) };
734 let lane = if marker.trace.lane == 0 { "A" } else { "B" };
735 let slot = marker
736 .slot
737 .map(|v| v.to_string())
738 .unwrap_or_else(|| "-".into());
739 let t_ms = marker.trace.clock.started.elapsed().as_secs_f64() * 1e3;
740 use std::io::Write as _;
741 let stderr = std::io::stderr();
742 let mut stderr = stderr.lock();
743 let _ = writeln!(
744 stderr,
745 "[spec-pipe-timeline] pair={} round={} lane={lane} phase={} edge={} \
746 slot={slot} t_ms={t_ms:.3}",
747 marker.trace.clock.pair, marker.trace.round, marker.phase, marker.edge,
748 );
749}
750
751fn enqueue_spec_pipe_trace_marker(
752 stream: &cudarc::driver::CudaStream,
753 trace: Option<&SpecPipeTraceCtx>,
754 phase: &'static str,
755 edge: &'static str,
756 slot: Option<usize>,
757) -> Result<(), Box<dyn std::error::Error>> {
758 let Some(trace) = trace else {
759 return Ok(());
760 };
761 let marker = Box::new(SpecPipeTraceMarker {
762 trace: trace.clone(),
763 phase,
764 edge,
765 slot,
766 });
767 let raw = Box::into_raw(marker);
768 let result = unsafe {
769 cudarc::driver::result::stream::launch_host_function(
770 stream.cu_stream(),
771 spec_pipe_trace_marker,
772 raw.cast(),
773 )
774 };
775 if let Err(err) = result {
776 unsafe {
777 drop(Box::from_raw(raw));
778 }
779 return Err(err.into());
780 }
781 Ok(())
782}
783
784#[derive(Default)]
785struct SpecPipeProgress {
786 setup_done: [bool; 2],
787 draft_done: [usize; 2],
788 stage0_done: [usize; 2],
789 verify_done: [usize; 2],
790 accept_done: [usize; 2],
791 finished: [bool; 2],
792 aborted: bool,
793}
794
795/// Host-side issue coordinator for the reduced two-session speculative pipeline. Each session
796/// keeps its existing call stack and round locals; this object only orders phase entry. The
797/// primary mutex spans whole draft/accept/tail issue regions so Engine's single-stream scratch
798/// cannot be interleaved by the two host threads.
799struct SpecPipeSync {
800 progress: std::sync::Mutex<SpecPipeProgress>,
801 changed: std::sync::Condvar,
802 primary: std::sync::Mutex<()>,
803 trace: Option<std::sync::Arc<SpecPipeTraceClock>>,
804}
805
806impl SpecPipeSync {
807 fn new() -> Self {
808 static TRACE_PAIR: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
809 let trace = (std::env::var("MEMRA_SPEC_PIPE_TRACE").as_deref() == Ok("1")).then(|| {
810 std::sync::Arc::new(SpecPipeTraceClock {
811 pair: TRACE_PAIR.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1,
812 started: std::time::Instant::now(),
813 })
814 });
815 Self {
816 progress: std::sync::Mutex::new(SpecPipeProgress::default()),
817 changed: std::sync::Condvar::new(),
818 primary: std::sync::Mutex::new(()),
819 trace,
820 }
821 }
822}
823
824#[derive(Clone)]
825struct SpecPipeLane {
826 sync: std::sync::Arc<SpecPipeSync>,
827 lane: usize,
828}
829
830impl SpecPipeLane {
831 fn peer(&self) -> usize {
832 1 - self.lane
833 }
834
835 fn aborted() -> Box<dyn std::error::Error> {
836 "paired speculative peer aborted".into()
837 }
838
839 fn trace(&self, round: usize) -> Option<SpecPipeTraceCtx> {
840 self.sync.trace.as_ref().map(|clock| SpecPipeTraceCtx {
841 clock: clock.clone(),
842 round,
843 lane: self.lane,
844 })
845 }
846
847 fn setup_begin(&self) -> Result<(), Box<dyn std::error::Error>> {
848 let mut p = self.sync.progress.lock().unwrap();
849 while !p.aborted && self.lane == 1 && !p.setup_done[0] && !p.finished[0] {
850 p = self.sync.changed.wait(p).unwrap();
851 }
852 if p.aborted {
853 Err(Self::aborted())
854 } else {
855 Ok(())
856 }
857 }
858
859 fn setup_end(&self) {
860 let mut p = self.sync.progress.lock().unwrap();
861 p.setup_done[self.lane] = true;
862 self.sync.changed.notify_all();
863 }
864
865 fn draft_begin(
866 &self,
867 round: usize,
868 ) -> Result<std::sync::MutexGuard<'_, ()>, Box<dyn std::error::Error>> {
869 let peer = self.peer();
870 let mut p = self.sync.progress.lock().unwrap();
871 loop {
872 if p.aborted {
873 return Err(Self::aborted());
874 }
875 let setup_ready =
876 (p.setup_done[0] || p.finished[0]) && (p.setup_done[1] || p.finished[1]);
877 let prior_ready = p.accept_done[self.lane] >= round
878 && (p.accept_done[peer] >= round || p.finished[peer]);
879 let turn_ready = if self.lane == 0 {
880 true
881 } else {
882 p.draft_done[0] > round || p.finished[0]
883 };
884 if setup_ready && prior_ready && turn_ready {
885 break;
886 }
887 p = self.sync.changed.wait(p).unwrap();
888 }
889 drop(p);
890 Ok(self.sync.primary.lock().unwrap())
891 }
892
893 fn draft_end(&self, round: usize) {
894 let mut p = self.sync.progress.lock().unwrap();
895 p.draft_done[self.lane] = round + 1;
896 self.sync.changed.notify_all();
897 }
898
899 /// Admit stage 0 and return whether this lane owns the interval's one reverse fence.
900 /// Lane B releases as soon as lane A has issued its boundary TX, not after A's full body.
901 fn stage0_begin(&self, round: usize) -> Result<bool, Box<dyn std::error::Error>> {
902 let peer = self.peer();
903 let mut p = self.sync.progress.lock().unwrap();
904 loop {
905 if p.aborted {
906 return Err(Self::aborted());
907 }
908 let ready = if self.lane == 0 {
909 p.draft_done[0] > round && (p.draft_done[1] > round || p.finished[1])
910 } else {
911 p.draft_done[1] > round && (p.stage0_done[0] > round || p.finished[0])
912 };
913 if ready {
914 return Ok(self.lane == 0 || p.finished[peer]);
915 }
916 p = self.sync.changed.wait(p).unwrap();
917 }
918 }
919
920 fn stage0_end(&self, round: usize) {
921 let mut p = self.sync.progress.lock().unwrap();
922 p.stage0_done[self.lane] = round + 1;
923 self.sync.changed.notify_all();
924 }
925
926 /// Stage 1 is single-owner per engine. A proceeds immediately after its own ticket; B waits
927 /// for A's full stage1/head issue so only A.S1 and B.S0 can overlap.
928 fn stage1_begin(&self, round: usize) -> Result<(), Box<dyn std::error::Error>> {
929 let mut p = self.sync.progress.lock().unwrap();
930 while !p.aborted
931 && !(p.stage0_done[self.lane] > round
932 && (self.lane == 0 || p.verify_done[0] > round || p.finished[0]))
933 {
934 p = self.sync.changed.wait(p).unwrap();
935 }
936 if p.aborted {
937 Err(Self::aborted())
938 } else {
939 Ok(())
940 }
941 }
942
943 fn verify_end(&self, round: usize) {
944 let mut p = self.sync.progress.lock().unwrap();
945 p.verify_done[self.lane] = round + 1;
946 self.sync.changed.notify_all();
947 }
948
949 fn accept_begin(
950 &self,
951 round: usize,
952 ) -> Result<std::sync::MutexGuard<'_, ()>, Box<dyn std::error::Error>> {
953 let mut p = self.sync.progress.lock().unwrap();
954 loop {
955 if p.aborted {
956 return Err(Self::aborted());
957 }
958 let ready = if self.lane == 0 {
959 p.verify_done[0] > round && (p.verify_done[1] > round || p.finished[1])
960 } else {
961 p.verify_done[1] > round && (p.accept_done[0] > round || p.finished[0])
962 };
963 if ready {
964 break;
965 }
966 p = self.sync.changed.wait(p).unwrap();
967 }
968 drop(p);
969 Ok(self.sync.primary.lock().unwrap())
970 }
971
972 fn accept_end(&self, round: usize) {
973 let mut p = self.sync.progress.lock().unwrap();
974 p.accept_done[self.lane] = round + 1;
975 self.sync.changed.notify_all();
976 }
977
978 fn primary(&self) -> std::sync::MutexGuard<'_, ()> {
979 self.sync.primary.lock().unwrap()
980 }
981
982 fn finish(&self, failed: bool) {
983 let mut p = self.sync.progress.lock().unwrap();
984 p.finished[self.lane] = true;
985 p.aborted |= failed;
986 self.sync.changed.notify_all();
987 }
988}
989
990struct SpecPipeFinish<'a> {
991 lane: &'a SpecPipeLane,
992 closed: bool,
993}
994
995impl<'a> SpecPipeFinish<'a> {
996 fn new(lane: &'a SpecPipeLane) -> Self {
997 Self {
998 lane,
999 closed: false,
1000 }
1001 }
1002
1003 fn close(&mut self, failed: bool) {
1004 self.lane.finish(failed);
1005 self.closed = true;
1006 }
1007}
1008
1009impl Drop for SpecPipeFinish<'_> {
1010 fn drop(&mut self) {
1011 if !self.closed {
1012 self.lane.finish(true);
1013 }
1014 }
1015}
1016
1017/// Scoped transfer of one exclusively-borrowed session to the second host issue thread.
1018/// `CudaGraph` is not marked Send by cudarc because its raw driver handles carry no automatic
1019/// trait. CUDA driver graph handles are context-scoped rather than OS-thread-affine; the caller
1020/// binds that context before touching the session, joins before returning, and never aliases the
1021/// pointer. Keep this exception local to the experimental pair call instead of marking the public
1022/// session type Send.
1023struct SpecPipeSessionPtr(*mut SpecSession);
1024
1025unsafe impl Send for SpecPipeSessionPtr {}
1026
1027impl SpecPipeSessionPtr {
1028 unsafe fn get_mut(&mut self) -> &mut SpecSession {
1029 unsafe { &mut *self.0 }
1030 }
1031}
1032
1033/// Per-session persistent draft-graph context: the captured CUDA graph(s) plus the device
1034/// buffers whose POINTERS the capture bakes. Reuse legality: the greedy capture bakes only
1035/// session-stable pointers (the session's own MtpScratch KV — allocated once, never realloc'd;
1036/// the model's resident embedding; the process-wide OnceLock p_min) and the g_* buffers held
1037/// HERE — so one capture serves the session's whole lifetime. The sampled capture additionally
1038/// bakes (seed, temp) as capture-time constants and needs k q-slots — keyed by `s_key`, dropped
1039/// and recaptured when a pool-resumed request changes them. `*_failed` memoizes a failed capture
1040/// so the eager fallback doesn't pay a doomed capture attempt every burst.
1041pub(crate) struct DraftGraphCtx {
1042 g_tok: CudaSlice<u32>,
1043 g_pos: CudaSlice<i32>,
1044 g_seed: CudaSlice<f32>,
1045 g_p: CudaSlice<f32>,
1046 g_ctr: CudaSlice<u32>,
1047 g_q: CudaSlice<f32>,
1048 g_perturb: CudaSlice<f32>,
1049 q_slots: Vec<CudaSlice<f32>>,
1050 /// DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): packed allowed-set words over the DRAFT
1051 /// head's vocab, at a STABLE address so the captured draft graph's mask node reads the
1052 /// per-position contents the host re-uploads before each replay (the graph-promote
1053 /// pattern from decode.rs). Empty unless the session drafts under a grammar.
1054 g_dmask: CudaSlice<u32>,
1055 /// was `graph` captured WITH the mask node? A parked graph of the wrong shape is dropped.
1056 graph_masked: bool,
1057 graph: Option<cudarc::driver::CudaGraph>,
1058 graph_s: Option<cudarc::driver::CudaGraph>,
1059 /// Failed-capture memoization for both graphs — LOUD on flip, cleared on pool resume
1060 /// (audit Q2, the TRT #16072 silent-permanent-coverage-loss class).
1061 failed: DraftGraphFallback,
1062 /// (seed, temp.to_bits(), k) baked into graph_s at its capture.
1063 s_key: Option<(u64, u32, usize)>,
1064 /// CAPTURE-RETAIN keepers (#68 root cause, 2026-08-04): the warmup-run transients whose
1065 /// pool addresses the captured graph(s) bake. Without these, the transients return to the
1066 /// pool at capture-body exit and later work (burst-boundary prime/fill/commit passes, or a
1067 /// co-served session in the worker) reuses those addresses — the persisted graph's replay
1068 /// then reads/writes live unrelated buffers (exactness corruption, first seen as the ST
1069 /// serve-spec 4B graph-arm corruption; one-shot CLI calls never re-shuffled the pool, which
1070 /// is why run-spec K=1..8 passed on the same checkpoint). Same fix class as
1071 /// capture_graph_retained's gemma/decode.rs sites — hold as long as the graph replays.
1072 keeper: Vec<Box<dyn std::any::Any + Send>>,
1073 keeper_s: Vec<Box<dyn std::any::Any + Send>>,
1074}
1075
1076/// Failed-capture memoization for the two draft graphs (audit Q2, 2026-08-05 — the
1077/// TRT #16072 trap class: pressure-triggered, silent, long-lived coverage loss).
1078///
1079/// Three contracts:
1080/// - LOUD FLIP: `mark_*` returns the warn line exactly on the false→true transition
1081/// (returned, not printed, so the once-per-flip contract is unit-testable); the caller
1082/// `eprintln!`s it UNCONDITIONALLY — a dropped draft graph is never silent. Re-marking
1083/// an already-failed graph returns None (the per-burst memoization that keeps the eager
1084/// fallback from paying a doomed capture attempt every burst).
1085/// - RESET ON RESUME: `reset_on_resume` clears both flags — a parked session resumed by a
1086/// NEW request gets one fresh capture chance instead of carrying a transient-pressure
1087/// failure for the pool's whole lifetime. Returns the note line only when a flag was
1088/// actually set (quiet on the common clean-resume path).
1089/// - Shape-change clears (`clear_*`) stay silent, exactly as before: they precede a fresh
1090/// capture attempt whose own failure would re-flip loudly.
1091#[derive(Default)]
1092pub(crate) struct DraftGraphFallback {
1093 greedy: bool,
1094 sampled: bool,
1095}
1096impl DraftGraphFallback {
1097 fn mark_greedy(&mut self, reason: &str) -> Option<String> {
1098 if self.greedy {
1099 return None;
1100 }
1101 self.greedy = true;
1102 Some(format!(
1103 "[spec] WARN: draft-graph capture failed ({reason}); eager fallback until session resume"
1104 ))
1105 }
1106 fn mark_sampled(&mut self, reason: &str) -> Option<String> {
1107 if self.sampled {
1108 return None;
1109 }
1110 self.sampled = true;
1111 Some(format!(
1112 "[spec] WARN: sampled draft-graph capture failed ({reason}); eager fallback until session resume"
1113 ))
1114 }
1115 fn greedy_failed(&self) -> bool {
1116 self.greedy
1117 }
1118 fn sampled_failed(&self) -> bool {
1119 self.sampled
1120 }
1121 fn clear_greedy(&mut self) {
1122 self.greedy = false;
1123 }
1124 fn clear_sampled(&mut self) {
1125 self.sampled = false;
1126 }
1127 /// Pool-resume reset: both graphs get a fresh capture chance. Some(note) iff any flag
1128 /// was set (so clean resumes stay quiet).
1129 pub(crate) fn reset_on_resume(&mut self) -> Option<String> {
1130 if !self.greedy && !self.sampled {
1131 return None;
1132 }
1133 let which = match (self.greedy, self.sampled) {
1134 (true, true) => "greedy+sampled",
1135 (true, false) => "greedy",
1136 _ => "sampled",
1137 };
1138 self.greedy = false;
1139 self.sampled = false;
1140 Some(format!(
1141 "[spec] draft-graph fallback reset on session resume ({which}); recapture eligible"
1142 ))
1143 }
1144}
1145
1146impl DraftGraphCtx {
1147 fn new(e: &Engine, n_embd: usize, qlen: usize) -> Result<Self, Box<dyn std::error::Error>> {
1148 Ok(DraftGraphCtx {
1149 g_tok: e.alloc_u32_zeroed(1)?,
1150 g_pos: e.htod_i32(&[0])?,
1151 g_seed: e.zeros(n_embd)?,
1152 g_p: e.zeros(1)?,
1153 g_ctr: e.alloc_u32_zeroed(1)?,
1154 g_q: e.zeros(qlen)?,
1155 g_perturb: e.zeros(qlen)?,
1156 q_slots: Vec::new(),
1157 g_dmask: e.alloc_u32_zeroed(1)?,
1158 graph_masked: false,
1159 graph: None,
1160 graph_s: None,
1161 failed: DraftGraphFallback::default(),
1162 s_key: None,
1163 keeper: Vec::new(),
1164 keeper_s: Vec::new(),
1165 })
1166 }
1167}
1168
1169pub(crate) struct MtpScratch {
1170 kv: KvLayer,
1171 /// Logical row capacity. On the graph/DC draft path it also doubles as fa_decode_dc's
1172 /// bucket_max: n_splits is sized from it ONCE, so the graph captured at round 0 stays valid
1173 /// for every later t_kv. Step35 refuses that path and may back this logical extent with the
1174 /// smaller host-indexed SWA ring instead.
1175 cap: usize,
1176}
1177
1178fn mtp_scratch_layout(
1179 cfg: &memra_gguf::config::ModelConfig,
1180 geom: Option<&crate::hybrid::DraftGeom>,
1181) -> (usize, usize, usize, usize) {
1182 // Student draft heads carry fewer KV heads (head_dim unchanged) -> smaller scratch rows.
1183 let n_head_kv = geom.map(|g| g.n_head_kv).unwrap_or(cfg.n_head_kv as usize);
1184 let head_dim_k = cfg.head_dim_k as usize;
1185 let head_dim_v = cfg.head_dim_v as usize;
1186 assert!(
1187 head_dim_k % 32 == 0 && head_dim_v % 32 == 0,
1188 "KVQUANT requires head_dim%32==0 (MTP scratch)"
1189 );
1190 let kv_dim_k = head_dim_k * n_head_kv;
1191 let kv_dim_v = head_dim_v * n_head_kv;
1192 // The fp8-KV arm deliberately does not reach the draft scratch; keep the exact format
1193 // policy shared with `MtpScratch::new` so admission scales the same allocation.
1194 let (kbb, vbb) = crate::kv_blk_bytes();
1195 let k_tok_bytes = (kv_dim_k / 32) * kbb;
1196 let v_tok_bytes = (kv_dim_v / 32) * vbb;
1197 (kv_dim_k, kv_dim_v, k_tok_bytes, v_tok_bytes)
1198}
1199
1200impl MtpScratch {
1201 fn new(
1202 e: &Engine,
1203 cfg: &memra_gguf::config::ModelConfig,
1204 cap: usize,
1205 geom: Option<&crate::hybrid::DraftGeom>,
1206 ) -> Result<Self, Box<dyn std::error::Error>> {
1207 // env-selected KV formats (default 34/24). The fp8-KV arm (MEMRA_KV_FP8) deliberately
1208 // does NOT reach the draft scratch: fp8 drafts drifted acceptance 69-88% -> 46%
1209 // (2026-07-12 A/B); the scratch is tiny, so it keeps baseline q8_0/q5_1 numerics
1210 // while the TRUNK cache carries the fp8 depth win. Scratch append/fa pass g=false.
1211 let (kv_dim_k, kv_dim_v, k_tok_bytes, v_tok_bytes) = mtp_scratch_layout(cfg, geom);
1212 let ring = if crate::cache::swa_ring_on() && cfg.arch.is_step35() {
1213 let window = cfg.step35.as_ref().unwrap().sliding_window as usize;
1214 Some(crate::cache::KvRing::new(
1215 crate::cache::swa_ring_rows(window, cap),
1216 window,
1217 ))
1218 } else {
1219 None
1220 };
1221 let alloc_rows = ring.as_ref().map(crate::cache::KvRing::rows).unwrap_or(cap);
1222 Ok(MtpScratch {
1223 kv: KvLayer {
1224 k: e.alloc_u8(alloc_rows * k_tok_bytes)?,
1225 v: e.alloc_u8(alloc_rows * v_tok_bytes)?,
1226 kv_dim_k,
1227 kv_dim_v,
1228 k_tok_bytes,
1229 v_tok_bytes,
1230 len: 0,
1231 ring,
1232 len_d: e.htod_i32(&[0])?,
1233 },
1234 cap,
1235 })
1236 }
1237 /// Set BOTH length counters: the host mirror AND the device len_d the captured append/fa read
1238 /// (a 4-byte in-place htod — the counter pointer is baked into the graph, never realloc'd).
1239 /// This is the ONLY truncation/rollback mechanism the persistent draft KV needs.
1240 fn set_len(&mut self, e: &Engine, n: usize) -> Result<(), Box<dyn std::error::Error>> {
1241 if self
1242 .kv
1243 .ring
1244 .as_ref()
1245 .is_some_and(|ring| !ring.can_rewind_to(n))
1246 {
1247 return Err("SWA ring MTP checkpoint has been lapped; full re-prime required".into());
1248 }
1249 self.kv.len = n;
1250 e.set_i32_one(&mut self.kv.len_d, n as i32)
1251 }
1252
1253 fn can_rewind_to(&self, n: usize) -> bool {
1254 self.kv
1255 .ring
1256 .as_ref()
1257 .is_none_or(|ring| ring.can_rewind_to(n))
1258 }
1259}
1260
1261/// Retained verify intermediates for the REPLAY-FREE partial accept (2026-07-03, the profiled
1262/// #1 spec cost at long ctx: the partial-accept replay was a DUPLICATE trunk pass — ~0.54 extra
1263/// full weight reads per round — recomputing columns the verify had already produced
1264/// bit-identically). Holds, per linear layer, everything needed to rebuild its recurrent state
1265/// to "after the first j verify columns" WITHOUT re-running the trunk:
1266/// - BATCHED-path layers (`gdn`): the exact token-major inputs the round's ONE gdn_scan
1267/// consumed. A prefix re-run of the SAME kernel (t=j) from the snapshot state is bit-identical
1268/// to the first j iterations of the verify's scan — the kernel's t-loop carries state in
1269/// registers and iteration t never depends on T. `qkv_mixed` (the conv input) feeds the
1270/// pure-copy ring rebuild.
1271/// - PER-COLUMN-path layers (`cols`): dtod clones of (conv_state, ssm_state) taken after each
1272/// column 0..t-2 — pure copies of the actual chain states (the last column is never a rebuild
1273/// target: j <= t-1).
1274/// Full-attn layers need nothing: their verify KV rows are bit-identical to eager's (the
1275/// decode-exact contract; verify-probe pins it), so rollback = len truncation.
1276struct GdnStash {
1277 qkv_mixed: CudaSlice<f32>, // [t, conv_dim] token-major (conv input)
1278 q_l2: CudaSlice<f32>,
1279 k_l2: CudaSlice<f32>,
1280 v_g: CudaSlice<f32>, // [t, num_v, d_state]
1281 g_log: CudaSlice<f32>,
1282 beta: CudaSlice<f32>, // [t, num_v]
1283}
1284struct VerifyCkpt {
1285 gdn: Vec<Option<GdnStash>>, // [n_layer], Some iff batched linear path ran
1286 cols: Vec<Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>>>, // [n_layer][col] = (conv, ssm) after col
1287}
1288/// Opaque handle for the dspark round (dflash.rs) — VerifyCkpt stays spec-private.
1289pub(crate) struct DsparkVerifyCkpt(VerifyCkpt);
1290
1291impl VerifyCkpt {
1292 fn new(n_layer: usize) -> Self {
1293 VerifyCkpt {
1294 gdn: (0..n_layer).map(|_| None).collect(),
1295 cols: (0..n_layer).map(|_| None).collect(),
1296 }
1297 }
1298}
1299
1300/// The stage-0/TX half of one PP verify. The boundary slot is the ownership token: stage 1
1301/// consumes exactly the slot selected by `tx()` / `tx_pipelined()`, never a slot inferred from
1302/// a logical round number.
1303struct VerifyBoundaryTicket {
1304 rt: &'static crate::pp::PpNRt,
1305 caller_stream: std::sync::Arc<cudarc::driver::CudaStream>,
1306 slot: usize,
1307 pos0: usize,
1308 t: usize,
1309 payload: usize,
1310 n_st: usize,
1311 pipelined: bool,
1312 pp_anatomy: bool,
1313 pp_started: std::time::Instant,
1314 reverse_ms: f64,
1315 stage0_ms: f64,
1316 tx_ms: f64,
1317 trace: Option<SpecPipeTraceCtx>,
1318}
1319
1320/// Explicit OPTIPIPE diagnostic control. Forced modes are set only by `optipipe-gate`; the
1321/// increment-2 controller can also be armed by the server's fresh-process research door.
1322#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1323pub enum OptiForkGateMode {
1324 Disabled,
1325 Hit,
1326 Miss,
1327 Alternate,
1328 Abort,
1329 Controller,
1330}
1331
1332static OPTI_FORK_GATE_MODE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
1333static OPTI_CONTROLLER_THRESHOLD: std::sync::atomic::AtomicU32 =
1334 std::sync::atomic::AtomicU32::new(0);
1335static OPTI_FORK_ATTEMPTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1336static OPTI_FORK_HITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1337static OPTI_FORK_MISSES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1338static OPTI_FORK_ABORT_DRAINS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1339static OPTI_FORK_REFUSALS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1340static OPTI_GATE_CHECKS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1341static OPTI_GATE_ADMITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1342static OPTI_GATE_REJECTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1343static OPTI_RECONCILES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1344static OPTI_WASTED_DRAFT_TOKENS: std::sync::atomic::AtomicU64 =
1345 std::sync::atomic::AtomicU64::new(0);
1346static OPTI_SHADOW_DRAFT_TOKENS: std::sync::atomic::AtomicU64 =
1347 std::sync::atomic::AtomicU64::new(0);
1348static OPTI_BREAKER_TRIPS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1349
1350impl OptiForkGateMode {
1351 fn code(self) -> u8 {
1352 match self {
1353 Self::Disabled => 0,
1354 Self::Hit => 1,
1355 Self::Miss => 2,
1356 Self::Alternate => 3,
1357 Self::Abort => 4,
1358 Self::Controller => 5,
1359 }
1360 }
1361
1362 fn configured() -> Self {
1363 match OPTI_FORK_GATE_MODE.load(std::sync::atomic::Ordering::Relaxed) {
1364 1 => Self::Hit,
1365 2 => Self::Miss,
1366 3 => Self::Alternate,
1367 4 => Self::Abort,
1368 5 => Self::Controller,
1369 _ => Self::Disabled,
1370 }
1371 }
1372
1373 fn action(self, generation: u64) -> OptiForkAction {
1374 match self {
1375 Self::Hit => OptiForkAction::Hit,
1376 Self::Miss => OptiForkAction::Miss,
1377 Self::Alternate if generation & 1 == 0 => OptiForkAction::Hit,
1378 Self::Alternate => OptiForkAction::Miss,
1379 Self::Abort => OptiForkAction::Abort,
1380 Self::Disabled | Self::Controller => {
1381 unreachable!("non-forced mode cannot choose a forced fork action")
1382 }
1383 }
1384 }
1385
1386 fn is_forced(self) -> bool {
1387 matches!(self, Self::Hit | Self::Miss | Self::Alternate | Self::Abort)
1388 }
1389}
1390
1391/// Arm or disarm the forced harness. Serving uses only `set_optipipe_controller_threshold`.
1392pub fn set_optipipe_gate_mode(mode: OptiForkGateMode) {
1393 OPTI_FORK_GATE_MODE.store(mode.code(), std::sync::atomic::Ordering::Relaxed);
1394}
1395
1396/// Arm the increment-2 diagnostic controller. The threshold applies to the uncalibrated
1397/// two-token draft-probability product. Serving can call this only through its explicit
1398/// fresh-process research door; the absent-door default remains byte-for-byte disabled.
1399pub fn set_optipipe_controller_threshold(threshold: f32) {
1400 assert!(threshold.is_finite() && (0.0..=1.0).contains(&threshold));
1401 OPTI_CONTROLLER_THRESHOLD.store(threshold.to_bits(), std::sync::atomic::Ordering::Relaxed);
1402 set_optipipe_gate_mode(OptiForkGateMode::Controller);
1403}
1404
1405#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1406pub struct OptiForkGateStats {
1407 pub attempts: u64,
1408 pub hits: u64,
1409 pub misses: u64,
1410 pub abort_drains: u64,
1411 pub refusals: u64,
1412 pub gate_checks: u64,
1413 pub gate_admits: u64,
1414 pub gate_rejects: u64,
1415 pub reconciles: u64,
1416 pub wasted_draft_tokens: u64,
1417 pub shadow_draft_tokens: u64,
1418 pub breaker_trips: u64,
1419}
1420
1421#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1422pub struct OptiForkStateIdentity {
1423 pub trunk_kv_bytes: usize,
1424 pub recurrent_bytes: usize,
1425 pub scratch_kv_bytes: usize,
1426 pub hidden_bytes: usize,
1427}
1428
1429pub fn reset_optipipe_gate_stats() {
1430 for counter in [
1431 &OPTI_FORK_ATTEMPTS,
1432 &OPTI_FORK_HITS,
1433 &OPTI_FORK_MISSES,
1434 &OPTI_FORK_ABORT_DRAINS,
1435 &OPTI_FORK_REFUSALS,
1436 &OPTI_GATE_CHECKS,
1437 &OPTI_GATE_ADMITS,
1438 &OPTI_GATE_REJECTS,
1439 &OPTI_RECONCILES,
1440 &OPTI_WASTED_DRAFT_TOKENS,
1441 &OPTI_SHADOW_DRAFT_TOKENS,
1442 &OPTI_BREAKER_TRIPS,
1443 ] {
1444 counter.store(0, std::sync::atomic::Ordering::Relaxed);
1445 }
1446}
1447
1448pub fn optipipe_gate_stats() -> OptiForkGateStats {
1449 let load = |v: &std::sync::atomic::AtomicU64| v.load(std::sync::atomic::Ordering::Relaxed);
1450 OptiForkGateStats {
1451 attempts: load(&OPTI_FORK_ATTEMPTS),
1452 hits: load(&OPTI_FORK_HITS),
1453 misses: load(&OPTI_FORK_MISSES),
1454 abort_drains: load(&OPTI_FORK_ABORT_DRAINS),
1455 refusals: load(&OPTI_FORK_REFUSALS),
1456 gate_checks: load(&OPTI_GATE_CHECKS),
1457 gate_admits: load(&OPTI_GATE_ADMITS),
1458 gate_rejects: load(&OPTI_GATE_REJECTS),
1459 reconciles: load(&OPTI_RECONCILES),
1460 wasted_draft_tokens: load(&OPTI_WASTED_DRAFT_TOKENS),
1461 shadow_draft_tokens: load(&OPTI_SHADOW_DRAFT_TOKENS),
1462 breaker_trips: load(&OPTI_BREAKER_TRIPS),
1463 }
1464}
1465
1466#[derive(Clone, Copy, Debug)]
1467struct OptiControllerPolicy {
1468 threshold: f32,
1469 consecutive_misses: u8,
1470 breaker_tripped: bool,
1471}
1472
1473impl OptiControllerPolicy {
1474 fn configured() -> Self {
1475 Self {
1476 threshold: f32::from_bits(
1477 OPTI_CONTROLLER_THRESHOLD.load(std::sync::atomic::Ordering::Relaxed),
1478 ),
1479 consecutive_misses: 0,
1480 breaker_tripped: false,
1481 }
1482 }
1483
1484 fn admit(&self, q_proxy: f32) -> bool {
1485 q_proxy.is_finite()
1486 && (0.0..=1.0).contains(&q_proxy)
1487 && (self.threshold == 0.0 || (!self.breaker_tripped && q_proxy >= self.threshold))
1488 }
1489
1490 /// Returns true exactly when this resolution newly trips the three-miss breaker.
1491 fn resolve(&mut self, hit: bool) -> bool {
1492 // q*=0 is the lane's explicit unconditional measurement arm. Its purpose is to price
1493 // every optimistic opportunity, so the safety breaker is measured separately and must
1494 // not silently turn this arm into "three attempts then serial".
1495 if self.threshold == 0.0 {
1496 self.consecutive_misses = 0;
1497 return false;
1498 }
1499 if hit {
1500 self.consecutive_misses = 0;
1501 return false;
1502 }
1503 self.consecutive_misses = self.consecutive_misses.saturating_add(1);
1504 if !self.breaker_tripped && self.consecutive_misses >= 3 {
1505 self.breaker_tripped = true;
1506 return true;
1507 }
1508 false
1509 }
1510}
1511
1512#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1513enum OptiForkAction {
1514 Hit,
1515 Miss,
1516 Abort,
1517}
1518
1519#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1520struct OptiForkGeneration {
1521 id: u64,
1522 slot: usize,
1523}
1524
1525#[derive(Default)]
1526struct OptiForkGenerationTracker {
1527 next: u64,
1528 live: [Option<u64>; 2],
1529}
1530
1531impl OptiForkGenerationTracker {
1532 fn reserve(&mut self) -> Result<OptiForkGeneration, Box<dyn std::error::Error>> {
1533 let generation = OptiForkGeneration {
1534 id: self.next,
1535 slot: (self.next & 1) as usize,
1536 };
1537 if let Some(live) = self.live[generation.slot] {
1538 return Err(format!(
1539 "optipipe snapshot slot {} still owns generation {live}; refusing to overwrite it",
1540 generation.slot,
1541 )
1542 .into());
1543 }
1544 self.next += 1;
1545 self.live[generation.slot] = Some(generation.id);
1546 Ok(generation)
1547 }
1548
1549 fn retire(&mut self, generation: OptiForkGeneration) -> Result<(), Box<dyn std::error::Error>> {
1550 match self.live[generation.slot] {
1551 Some(id) if id == generation.id => {
1552 self.live[generation.slot] = None;
1553 Ok(())
1554 }
1555 other => Err(format!(
1556 "optipipe generation teardown mismatch: ticket={} slot={} live={other:?}",
1557 generation.id, generation.slot,
1558 )
1559 .into()),
1560 }
1561 }
1562}
1563
1564struct OptiForkSeedGeneration {
1565 h_seed: CudaSlice<f32>,
1566 fill_prev: CudaSlice<f32>,
1567 scratch_len: usize,
1568}
1569
1570/// Allocate or refresh one full checkpoint through the engine that owns each PP stage. The
1571/// generic cache helper accepts one device and therefore cannot copy GDN state split across
1572/// devices. KV lengths and position stay host metadata; only recurrent buffers need stage-local
1573/// device ownership.
1574fn opti_snapshot_stage_owned(
1575 e: &Engine,
1576 cache: &Cache,
1577 rt: &'static crate::pp::PpNRt,
1578 fence: &[usize],
1579) -> Result<crate::cache::CacheSnapshot, Box<dyn std::error::Error>> {
1580 let n = cache.kv.len();
1581 let mut snapshot = crate::cache::CacheSnapshot {
1582 kv_len: vec![None; n],
1583 conv: (0..n).map(|_| None).collect(),
1584 ssm: (0..n).map(|_| None).collect(),
1585 pos: cache.pos,
1586 };
1587 opti_snapshot_stage_owned_into(e, cache, rt, fence, &mut snapshot)?;
1588 Ok(snapshot)
1589}
1590
1591fn opti_snapshot_stage_owned_into(
1592 e: &Engine,
1593 cache: &Cache,
1594 rt: &'static crate::pp::PpNRt,
1595 fence: &[usize],
1596 snapshot: &mut crate::cache::CacheSnapshot,
1597) -> Result<(), Box<dyn std::error::Error>> {
1598 if fence.len() != rt.n_stages() + 1 || snapshot.kv_len.len() != cache.kv.len() {
1599 return Err("optipipe stage-owned snapshot shape mismatch".into());
1600 }
1601 for stage in 0..rt.n_stages() {
1602 opti_snapshot_one_stage_owned_into(e, cache, rt, fence, stage, snapshot)?;
1603 }
1604 snapshot.pos = cache.pos;
1605 Ok(())
1606}
1607
1608/// Refresh one PP stage of a checkpoint. Increment 2 uses this split form so stage 0's
1609/// optimistic post-N state is captured before N+1 stage 0 is queued, while stage 1's matching
1610/// post-N state is captured only after N stage 1 is enqueued. Calling the all-stage helper at
1611/// either point would capture one side of the fork at the wrong generation.
1612fn opti_snapshot_one_stage_owned_into(
1613 e: &Engine,
1614 cache: &Cache,
1615 rt: &'static crate::pp::PpNRt,
1616 fence: &[usize],
1617 stage: usize,
1618 snapshot: &mut crate::cache::CacheSnapshot,
1619) -> Result<(), Box<dyn std::error::Error>> {
1620 if fence.len() != rt.n_stages() + 1
1621 || snapshot.kv_len.len() != cache.kv.len()
1622 || stage >= rt.n_stages()
1623 {
1624 return Err("optipipe single-stage snapshot shape mismatch".into());
1625 }
1626 let _scope = rt.enter(stage);
1627 let owner = rt.engine(stage, e);
1628 for il in fence[stage]..fence[stage + 1] {
1629 snapshot.kv_len[il] = cache.kv[il].as_ref().map(|kv| kv.len);
1630 match &cache.recur[il] {
1631 Some(recur) => {
1632 match snapshot.conv[il].as_mut() {
1633 Some(dst) => {
1634 owner.copy_into(dst, 0, &recur.conv_state, recur.conv_state.len())?
1635 }
1636 None => snapshot.conv[il] = Some(owner.clone_dtod(&recur.conv_state)?),
1637 }
1638 match snapshot.ssm[il].as_mut() {
1639 Some(dst) => {
1640 owner.copy_into(dst, 0, &recur.ssm_state, recur.ssm_state.len())?
1641 }
1642 None => snapshot.ssm[il] = Some(owner.clone_dtod(&recur.ssm_state)?),
1643 }
1644 }
1645 None if snapshot.conv[il].is_some() || snapshot.ssm[il].is_some() => {
1646 return Err(
1647 format!("optipipe stage-owned snapshot layer {il} changed shape").into(),
1648 );
1649 }
1650 None => {}
1651 }
1652 }
1653 snapshot.pos = cache.pos;
1654 Ok(())
1655}
1656
1657/// Increment-1 persistent fork state. Exactly two snapshot/seed slots alternate; a live ticket
1658/// names its generation and keeps teardown fail-closed. Only stage 0 is allowed to mutate before
1659/// resolve, so the reconcile tables and conditional restores are stage-local.
1660struct OptiForkState {
1661 mode: OptiForkGateMode,
1662 controller: Option<OptiControllerPolicy>,
1663 generations: OptiForkGenerationTracker,
1664 active_snapshot_slot: usize,
1665 alternate_snapshot: crate::cache::CacheSnapshot,
1666 seeds: [OptiForkSeedGeneration; 2],
1667 rt: &'static crate::pp::PpNRt,
1668 fence: [usize; 3],
1669 split: usize,
1670 len_ptrs: CudaSlice<u64>,
1671 saved_lens: CudaSlice<i32>,
1672 forced_acc: CudaSlice<u32>,
1673 valid: CudaSlice<u32>,
1674 stage0_stream: std::sync::Arc<cudarc::driver::CudaStream>,
1675 logical_payload_bytes: [usize; 2],
1676}
1677
1678struct OptiForkTicket {
1679 generation: OptiForkGeneration,
1680 boundary: Option<VerifyBoundaryTicket>,
1681 drain: std::sync::Arc<cudarc::driver::CudaStream>,
1682 settled: bool,
1683}
1684
1685struct OptiControllerTicket {
1686 generation: OptiForkGeneration,
1687 boundary: Option<VerifyBoundaryTicket>,
1688 ckpt: Option<VerifyCkpt>,
1689 verify_tokens: [u32; 2],
1690 draft_prob: f32,
1691 eager_seed: Option<CudaSlice<f32>>,
1692 q_proxy: f32,
1693 scratch_len: usize,
1694 issued_at: std::time::Instant,
1695 drain: std::sync::Arc<cudarc::driver::CudaStream>,
1696 settled: bool,
1697}
1698
1699struct OptiControllerPrepared {
1700 verify_tokens: [u32; 2],
1701 draft_prob: f32,
1702 eager_seed: Option<CudaSlice<f32>>,
1703 q_proxy: f32,
1704 scratch_len: usize,
1705}
1706
1707impl OptiControllerTicket {
1708 fn take_boundary(&mut self) -> VerifyBoundaryTicket {
1709 self.boundary
1710 .take()
1711 .expect("controller boundary ticket already consumed")
1712 }
1713
1714 fn take_ckpt(&mut self) -> VerifyCkpt {
1715 self.ckpt
1716 .take()
1717 .expect("controller verify checkpoint already consumed")
1718 }
1719
1720 fn take_eager_seed(&mut self) -> Option<CudaSlice<f32>> {
1721 self.eager_seed.take()
1722 }
1723
1724 fn settle(&mut self) {
1725 self.settled = true;
1726 }
1727}
1728
1729impl Drop for OptiControllerTicket {
1730 fn drop(&mut self) {
1731 if !self.settled {
1732 let _ = self.drain.synchronize();
1733 OPTI_FORK_ABORT_DRAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1734 }
1735 }
1736}
1737
1738impl OptiForkTicket {
1739 fn take_boundary(&mut self) -> VerifyBoundaryTicket {
1740 self.boundary
1741 .take()
1742 .expect("fork ticket boundary already consumed")
1743 }
1744
1745 fn settle(&mut self) {
1746 self.settled = true;
1747 }
1748}
1749
1750impl Drop for OptiForkTicket {
1751 fn drop(&mut self) {
1752 if !self.settled {
1753 let _ = self.drain.synchronize();
1754 OPTI_FORK_ABORT_DRAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1755 }
1756 }
1757}
1758
1759impl OptiForkState {
1760 #[allow(clippy::too_many_arguments)]
1761 fn new(
1762 e: &Engine,
1763 cache: &Cache,
1764 mode: OptiForkGateMode,
1765 alternate_snapshot: crate::cache::CacheSnapshot,
1766 h_seed: &CudaSlice<f32>,
1767 fill_prev: &CudaSlice<f32>,
1768 rt: &'static crate::pp::PpNRt,
1769 split: usize,
1770 n_layer: usize,
1771 ) -> Result<Self, Box<dyn std::error::Error>> {
1772 let fence = [0, split, n_layer];
1773 let mut logical_payload_bytes = [0usize; 2];
1774 for stage in 0..2 {
1775 for il in fence[stage]..fence[stage + 1] {
1776 logical_payload_bytes[stage] += alternate_snapshot.conv[il]
1777 .as_ref()
1778 .map_or(0, |v| v.len() * std::mem::size_of::<f32>());
1779 logical_payload_bytes[stage] += alternate_snapshot.ssm[il]
1780 .as_ref()
1781 .map_or(0, |v| v.len() * std::mem::size_of::<f32>());
1782 }
1783 }
1784 let seeds = [
1785 OptiForkSeedGeneration {
1786 h_seed: e.clone_dtod(h_seed)?,
1787 fill_prev: e.clone_dtod(fill_prev)?,
1788 scratch_len: 0,
1789 },
1790 OptiForkSeedGeneration {
1791 h_seed: e.clone_dtod(h_seed)?,
1792 fill_prev: e.clone_dtod(fill_prev)?,
1793 scratch_len: 0,
1794 },
1795 ];
1796 let (len_ptrs, saved_lens, forced_acc, valid, stage0_stream) = {
1797 let _stage = rt.enter(0);
1798 let e0 = rt.engine(0, e);
1799 (
1800 crate::round_stream::kv_len_ptr_table_range(e0, cache, 0..split, None)?,
1801 e0.htod_i32(&vec![0; split])?,
1802 e0.alloc_u32_zeroed(2)?,
1803 e0.alloc_u32_zeroed(1)?,
1804 e0.stream(),
1805 )
1806 };
1807 logical_payload_bytes[0] += seeds
1808 .iter()
1809 .map(|seed| (seed.h_seed.len() + seed.fill_prev.len()) * std::mem::size_of::<f32>())
1810 .sum::<usize>();
1811 logical_payload_bytes[0] += len_ptrs.len() * std::mem::size_of::<u64>()
1812 + saved_lens.len() * std::mem::size_of::<i32>()
1813 + forced_acc.len() * std::mem::size_of::<u32>()
1814 + valid.len() * std::mem::size_of::<u32>();
1815 Ok(Self {
1816 mode,
1817 controller: (mode == OptiForkGateMode::Controller)
1818 .then(OptiControllerPolicy::configured),
1819 generations: OptiForkGenerationTracker::default(),
1820 active_snapshot_slot: 0,
1821 alternate_snapshot,
1822 seeds,
1823 rt,
1824 fence,
1825 split,
1826 len_ptrs,
1827 saved_lens,
1828 forced_acc,
1829 valid,
1830 stage0_stream,
1831 logical_payload_bytes,
1832 })
1833 }
1834
1835 fn reserve(
1836 &mut self,
1837 current_snapshot: &mut crate::cache::CacheSnapshot,
1838 ) -> Result<OptiForkGeneration, Box<dyn std::error::Error>> {
1839 let generation = self.generations.reserve()?;
1840 if generation.slot != self.active_snapshot_slot {
1841 std::mem::swap(current_snapshot, &mut self.alternate_snapshot);
1842 self.active_snapshot_slot = generation.slot;
1843 }
1844 Ok(generation)
1845 }
1846
1847 fn capture_seed(
1848 &mut self,
1849 e: &Engine,
1850 generation: OptiForkGeneration,
1851 h_seed: &CudaSlice<f32>,
1852 fill_prev: &CudaSlice<f32>,
1853 scratch_len: usize,
1854 ) -> Result<(), Box<dyn std::error::Error>> {
1855 let seed = &mut self.seeds[generation.slot];
1856 e.copy_into(&mut seed.h_seed, 0, h_seed, h_seed.len())?;
1857 e.copy_into(&mut seed.fill_prev, 0, fill_prev, fill_prev.len())?;
1858 seed.scratch_len = scratch_len;
1859 Ok(())
1860 }
1861
1862 fn ticket(
1863 &self,
1864 generation: OptiForkGeneration,
1865 boundary: VerifyBoundaryTicket,
1866 ) -> OptiForkTicket {
1867 OptiForkTicket {
1868 generation,
1869 boundary: Some(boundary),
1870 drain: self.stage0_stream.clone(),
1871 settled: false,
1872 }
1873 }
1874
1875 #[allow(clippy::too_many_arguments)]
1876 fn controller_ticket(
1877 &self,
1878 generation: OptiForkGeneration,
1879 boundary: VerifyBoundaryTicket,
1880 ckpt: VerifyCkpt,
1881 verify_tokens: [u32; 2],
1882 draft_prob: f32,
1883 eager_seed: Option<CudaSlice<f32>>,
1884 q_proxy: f32,
1885 scratch_len: usize,
1886 ) -> OptiControllerTicket {
1887 OptiControllerTicket {
1888 generation,
1889 boundary: Some(boundary),
1890 ckpt: Some(ckpt),
1891 verify_tokens,
1892 draft_prob,
1893 eager_seed,
1894 q_proxy,
1895 scratch_len,
1896 issued_at: std::time::Instant::now(),
1897 drain: self.stage0_stream.clone(),
1898 settled: false,
1899 }
1900 }
1901
1902 fn reserve_successor(&mut self) -> Result<OptiForkGeneration, Box<dyn std::error::Error>> {
1903 self.generations.reserve()
1904 }
1905
1906 fn successor_snapshot_mut(&mut self) -> &mut crate::cache::CacheSnapshot {
1907 &mut self.alternate_snapshot
1908 }
1909
1910 fn promote_successor_snapshot(
1911 &mut self,
1912 current_snapshot: &mut crate::cache::CacheSnapshot,
1913 generation: OptiForkGeneration,
1914 ) {
1915 std::mem::swap(current_snapshot, &mut self.alternate_snapshot);
1916 self.active_snapshot_slot = generation.slot;
1917 }
1918
1919 fn queue_actual_reconcile(
1920 &mut self,
1921 e: &Engine,
1922 snapshot: &crate::cache::CacheSnapshot,
1923 acc: &CudaSlice<u32>,
1924 optimistic_pending: u32,
1925 base: usize,
1926 ) -> Result<(), Box<dyn std::error::Error>> {
1927 let saved: Vec<i32> = (0..self.split)
1928 .map(|il| snapshot.kv_len[il].map(|v| v as i32).unwrap_or(0))
1929 .collect();
1930 // Serving keeps the caller/accept walk on the head (stage-1) device. Record the accept
1931 // decision point there and append a wait to stage 0 after its optimistic successor/TX;
1932 // the validity/reconcile kernels must never peer-read acc before it is written. The
1933 // increment-1 harness uses primary stage 0, where stream order already provides this.
1934 if self.rt.engine(0, e).ctx().ordinal() != e.ctx().ordinal() {
1935 self.rt.fence_stages_behind(&e.stream())?;
1936 }
1937 let _stage = self.rt.enter(0);
1938 let e0 = self.rt.engine(0, e);
1939 e0.htod_i32_into(&mut self.saved_lens, &saved)?;
1940 e0.spec_fork_valid(acc, optimistic_pending, &mut self.valid)?;
1941 e0.spec_fork_reconcile_kv(
1942 &self.len_ptrs,
1943 &self.saved_lens,
1944 acc,
1945 &self.valid,
1946 base,
1947 self.split,
1948 )
1949 }
1950
1951 fn finish_actual_reconcile(
1952 &mut self,
1953 e: &Engine,
1954 cache: &mut Cache,
1955 snapshot: &crate::cache::CacheSnapshot,
1956 n_acc: usize,
1957 base: usize,
1958 hit: bool,
1959 ) -> Result<(), Box<dyn std::error::Error>> {
1960 if hit {
1961 return Ok(());
1962 }
1963 let len_delta = base + n_acc;
1964 for il in 0..self.split {
1965 if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
1966 kv.len = saved + len_delta;
1967 }
1968 }
1969 {
1970 let _stage = self.rt.enter(1);
1971 let e1 = self.rt.engine(1, e);
1972 for il in self.split..self.fence[2] {
1973 if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
1974 kv.len = saved + len_delta;
1975 e1.set_i32_one(&mut kv.len_d, kv.len as i32)?;
1976 }
1977 }
1978 }
1979 self.rt.publish_to(0, &e.stream())?;
1980 Ok(())
1981 }
1982
1983 fn cancel_controller_ticket(
1984 &mut self,
1985 e: &Engine,
1986 cache: &mut Cache,
1987 scratch: &mut MtpScratch,
1988 snapshot: &crate::cache::CacheSnapshot,
1989 ticket: &mut OptiControllerTicket,
1990 ) -> Result<(), Box<dyn std::error::Error>> {
1991 {
1992 let _stage = self.rt.enter(0);
1993 let e0 = self.rt.engine(0, e);
1994 for il in 0..self.split {
1995 if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
1996 kv.len = saved;
1997 e0.set_i32_one(&mut kv.len_d, saved as i32)?;
1998 }
1999 }
2000 }
2001 scratch.set_len(e, snapshot.pos)?;
2002 ticket.settle();
2003 self.generations.retire(ticket.generation)?;
2004 OPTI_FORK_ABORT_DRAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2005 OPTI_WASTED_DRAFT_TOKENS.fetch_add(2, std::sync::atomic::Ordering::Relaxed);
2006 eprintln!(
2007 "[opti-controller] tail-drain generation={} slot={}",
2008 ticket.generation.id, ticket.generation.slot,
2009 );
2010 Ok(())
2011 }
2012
2013 #[allow(clippy::too_many_arguments)]
2014 fn reconcile(
2015 &mut self,
2016 e: &Engine,
2017 cache: &mut Cache,
2018 scratch: &mut MtpScratch,
2019 snapshot: &crate::cache::CacheSnapshot,
2020 h_seed: &mut CudaSlice<f32>,
2021 fill_prev: &mut CudaSlice<f32>,
2022 generation: OptiForkGeneration,
2023 action: OptiForkAction,
2024 optimistic_pending: u32,
2025 ) -> Result<(), Box<dyn std::error::Error>> {
2026 debug_assert!(action != OptiForkAction::Abort);
2027 let miss_started = std::time::Instant::now();
2028 let keep = action == OptiForkAction::Hit;
2029 let saved: Vec<i32> = (0..self.split)
2030 .map(|il| snapshot.kv_len[il].map(|v| v as i32).unwrap_or(0))
2031 .collect();
2032 let seed = &self.seeds[generation.slot];
2033 {
2034 let _stage = self.rt.enter(0);
2035 let e0 = self.rt.engine(0, e);
2036 e0.htod_i32_into(&mut self.saved_lens, &saved)?;
2037 let forced = if keep {
2038 [1u32, optimistic_pending]
2039 } else {
2040 [0u32, optimistic_pending]
2041 };
2042 e0.htod_u32_into(&mut self.forced_acc, &forced)?;
2043 e0.spec_fork_valid(&self.forced_acc, optimistic_pending, &mut self.valid)?;
2044 e0.spec_fork_reconcile_kv(
2045 &self.len_ptrs,
2046 &self.saved_lens,
2047 &self.forced_acc,
2048 &self.valid,
2049 0,
2050 self.split,
2051 )?;
2052 for il in 0..self.split {
2053 if let Some(recur) = cache.recur[il].as_mut() {
2054 let conv = snapshot.conv[il]
2055 .as_ref()
2056 .ok_or("optipipe stage0 snapshot missing conv state")?;
2057 let ssm = snapshot.ssm[il]
2058 .as_ref()
2059 .ok_or("optipipe stage0 snapshot missing ssm state")?;
2060 e0.spec_fork_restore_f32(conv, &mut recur.conv_state, &self.valid)?;
2061 e0.spec_fork_restore_f32(ssm, &mut recur.ssm_state, &self.valid)?;
2062 }
2063 }
2064 e0.spec_fork_restore_f32(&seed.h_seed, h_seed, &self.valid)?;
2065 e0.spec_fork_restore_f32(&seed.fill_prev, fill_prev, &self.valid)?;
2066 }
2067
2068 if keep {
2069 OPTI_FORK_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2070 return Ok(());
2071 }
2072
2073 for il in 0..self.split {
2074 if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
2075 kv.len = saved;
2076 }
2077 }
2078 scratch.set_len(e, seed.scratch_len)?;
2079 // Targeted E_restart: publish only stage 0's reconcile to the caller, then bound the
2080 // forced diagnostic so the retained number is the actual miss cost, not enqueue time.
2081 let caller = e.stream();
2082 self.rt.publish_to(0, &caller)?;
2083 caller.synchronize()?;
2084 let miss_ms = miss_started.elapsed().as_secs_f64() * 1e3;
2085 eprintln!(
2086 "[opti-fork-reconcile] generation={} slot={} miss_ms={miss_ms:.3}",
2087 generation.id, generation.slot,
2088 );
2089 OPTI_FORK_MISSES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2090 Ok(())
2091 }
2092
2093 fn retire(&mut self, generation: OptiForkGeneration) -> Result<(), Box<dyn std::error::Error>> {
2094 self.generations.retire(generation)
2095 }
2096}
2097
2098impl HybridModel {
2099 fn opti_graph_draft_step(
2100 &self,
2101 e: &Engine,
2102 mtp: &MtpHead,
2103 dctx: &mut DraftGraphCtx,
2104 scratch: &mut MtpScratch,
2105 d_vocab: usize,
2106 ) -> Result<(u32, f32), Box<dyn std::error::Error>> {
2107 dctx.graph
2108 .as_ref()
2109 .ok_or("optipipe controller requires the greedy draft graph")?
2110 .launch()?;
2111 scratch.kv.len += 1;
2112 let idx = e.dtoh_u32_one(&dctx.g_tok)?;
2113 if (idx as usize) >= d_vocab {
2114 return Err(
2115 format!("optipipe draft argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab}").into(),
2116 );
2117 }
2118 let probability = e.dtoh(&dctx.g_p)?[0];
2119 if !probability.is_finite() || !(0.0..=1.0).contains(&probability) {
2120 return Err(format!("optipipe draft probability is invalid: {probability}").into());
2121 }
2122 let token = match &mtp.d2t {
2123 Some(map) => map[idx as usize],
2124 None => idx,
2125 };
2126 if token != idx {
2127 e.set_u32_one(&mut dctx.g_tok, token)?;
2128 }
2129 Ok((token, probability))
2130 }
2131
2132 #[allow(clippy::too_many_arguments)]
2133 fn opti_controller_draft_step(
2134 &self,
2135 e: &Engine,
2136 mtp: &MtpHead,
2137 dctx: &mut DraftGraphCtx,
2138 scratch: &mut MtpScratch,
2139 d_vocab: usize,
2140 eager_state: &mut Option<(u32, CudaSlice<f32>)>,
2141 eager_pos: usize,
2142 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
2143 ) -> Result<(u32, f32), Box<dyn std::error::Error>> {
2144 if dctx.graph.is_some() {
2145 return self.opti_graph_draft_step(e, mtp, dctx, scratch, d_vocab);
2146 }
2147 let (input_token, input_seed) = eager_state
2148 .take()
2149 .ok_or("optipipe eager continuation seed is unavailable")?;
2150 let (logits, next_seed) = self.mtp_head_forward_dev(
2151 e,
2152 mtp,
2153 input_token,
2154 &input_seed,
2155 scratch,
2156 eager_pos,
2157 embd_dev,
2158 None,
2159 )?;
2160 let token_d = e.argmax_token_device(&logits, d_vocab)?;
2161 let idx = e.dtoh_u32_one(&token_d)?;
2162 if (idx as usize) >= d_vocab {
2163 return Err(format!(
2164 "optipipe eager draft argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab}"
2165 )
2166 .into());
2167 }
2168 let probability_d = e.prob_of_token_device(&logits, &token_d, d_vocab)?;
2169 let probability = e.dtoh(&probability_d)?[0];
2170 if !probability.is_finite() || !(0.0..=1.0).contains(&probability) {
2171 return Err(
2172 format!("optipipe eager draft probability is invalid: {probability}").into(),
2173 );
2174 }
2175 let token = match &mtp.d2t {
2176 Some(map) => map[idx as usize],
2177 None => idx,
2178 };
2179 *eager_state = Some((token, next_seed));
2180 Ok((token, probability))
2181 }
2182
2183 /// NextN head forward for ONE draft token (§A ops 1-13, T=1).
2184 /// Inputs: `e_tok` = the token to predict FROM (last committed / previous draft); `h_seed` =
2185 /// the trunk's pre-output_norm hidden of that token (§A op 2 input). `mtp_pos` = absolute
2186 /// position of the token being predicted from. Returns (draft_logits[n_vocab] host, h_nextn dev).
2187 /// `h_nextn` (§A op 10) becomes `h_seed` for the next autoregressive draft step.
2188 /// Device-resident: returns draft logits ON DEVICE (no [n_vocab] dtoh). The greedy draft
2189 /// loop only needs argmax — paired with `argmax_token_device` this cuts the ~600KB logits
2190 /// transfer + host argmax per draft token from the K-token draft chain.
2191 #[allow(clippy::too_many_arguments)]
2192 fn mtp_head_forward_dev(
2193 &self,
2194 e: &Engine,
2195 mtp: &MtpHead,
2196 e_tok: u32,
2197 h_seed: &CudaSlice<f32>,
2198 scratch: &mut MtpScratch,
2199 mtp_pos: usize,
2200 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
2201 // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): (packed draft-vocab allowed set, words).
2202 // Applied to the head logits BEFORE they are returned, so every consumer (argmax,
2203 // gumbel draw, p-min prob) sees the grammar-legal row. None = unmasked (pre-lane).
2204 mask: Option<(&CudaSlice<u32>, usize)>,
2205 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
2206 let cfg = &self.cfg;
2207 let n_embd = cfg.n_embd as usize;
2208 // Distilled-student geometry: the block runs at the INNER width `di` (eh_proj out /
2209 // attn / ffn); the n_embd interface (embed, norms in, carrier out, head in) is unchanged.
2210 let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
2211 let eps = cfg.rms_eps;
2212 let pos_d = e.htod_i32(&[mtp_pos as i32])?;
2213
2214 // op A: a resident table transfers one 4B token id. The exact host-row capacity path
2215 // expands this one row on CPU and transfers n_embd f32 values instead.
2216 let e_emb = match embd_dev {
2217 Some((g, qt, rb)) => e.embed_gather_device_t(g, &[e_tok], n_embd, qt, rb)?,
2218 None => e.htod(&self.embd.gather(n_embd, &[e_tok]))?,
2219 };
2220
2221 // op 1/2: e_norm = RMSNorm(e, enorm); h_norm = RMSNorm(h_seed, hnorm)
2222 let mut e_norm = e.zeros(n_embd)?;
2223 e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, 1, eps)?;
2224 let mut h_norm = e.zeros(n_embd)?;
2225 e.rms_norm(h_seed, mtp.hnorm.float_data(), &mut h_norm, n_embd, 1, eps)?;
2226
2227 // op 3: concat = [e_norm ; h_norm] -> [2*n_embd], e_norm in [0,n_embd), h_norm in [n_embd,2n_embd)
2228 let mut concat = e.zeros(2 * n_embd)?;
2229 e.copy_into(&mut concat, 0, &e_norm, n_embd)?;
2230 e.copy_into(&mut concat, n_embd, &h_norm, n_embd)?;
2231
2232 // op 4: inpSA = eh_proj @ concat (eh_proj [2*n_embd, n_embd]) -> [n_embd]
2233 let inp_sa = e.matmul(&mtp.eh_proj, &concat, 1)?;
2234
2235 // op 5: a_norm = RMSNorm(inpSA, attn_norm)
2236 let mut a_norm = e.zeros(di)?;
2237 e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, 1, eps)?;
2238
2239 // op 6: attention on the scratch KV. SAME dc launcher as the graph path (bucket_max =
2240 // scratch.cap, length from the device len_d) so eager drafts match graph drafts
2241 // bit-for-bit at any t_kv (the parity gate). Host len mirrored here (the dc append
2242 // advances only the device counter).
2243 let attn_out = match (&mtp.mixer, mtp.step35.as_ref()) {
2244 // step35 MTP block: PER-LAYER geometry + a separate head-wise gate + an SWA window,
2245 // none of which the dc launcher can express (see `mtp_step35_attn`). Host-len arm.
2246 // Advances BOTH the host len and the device counter itself (unlike the dc arm,
2247 // whose host-side mirror the caller does).
2248 (Mixer::Full(fa), Some(g)) => {
2249 self.mtp_step35_attn(e, fa, g, &a_norm, &pos_d, scratch)?
2250 }
2251 (Mixer::Full(fa), None) => {
2252 let out =
2253 self.mtp_full_attn_dc(e, fa, &a_norm, &pos_d, scratch, mtp.geom.as_ref())?;
2254 scratch.kv.len += 1;
2255 out
2256 }
2257 (Mixer::Linear(_), _) => {
2258 panic!("MTP block is full-attn in qwen35; linear MTP not supported")
2259 }
2260 (Mixer::Mla(_), _) => crate::hybrid::mla_forward_unimplemented(),
2261 };
2262
2263 // op 7: x1 = inpSA + attn_out
2264 let mut x1 = e.zeros(di)?;
2265 e.add(&inp_sa, &attn_out, &mut x1, di)?;
2266
2267 // op 8: z = RMSNorm(x1, post_attn_norm) (pre-FFN norm)
2268 let mut z = e.zeros(di)?;
2269 e.rms_norm(&x1, mtp.post_attn_norm.float_data(), &mut z, di, 1, eps)?;
2270
2271 // op 9: FFN (Dense or MoE) — same as the trunk decode FFN
2272 let ffn_out = match &mtp.ffn {
2273 crate::hybrid::Ffn::Dense {
2274 ffn_gate,
2275 ffn_up,
2276 ffn_down,
2277 } => {
2278 let n_ff = ffn_gate.out_features();
2279 let (gate, up) = if e.uses_q8_1_fast(ffn_gate) && e.uses_q8_1_fast(ffn_up) {
2280 let (zq, zd) = e.quantize_q8_1(&z, 1, di)?;
2281 (
2282 e.matmul_pre(ffn_gate, &zq, &zd, &z, 1)?,
2283 e.matmul_pre(ffn_up, &zq, &zd, &z, 1)?,
2284 )
2285 } else {
2286 (e.matmul(ffn_gate, &z, 1)?, e.matmul(ffn_up, &z, 1)?)
2287 };
2288 let mut act = e.zeros(n_ff)?;
2289 // step35: a DENSE FFN reads the per-layer SHEXP clamp (upstream's one `build_ffn`
2290 // serves the dense MLP and the shared expert off `swiglu_clamp_shexp` —
2291 // llama-graph.cpp:1751), resolved for the MTP block's OWN index. Every other arch
2292 // passes None, which is `ffn_act`'s dispatch verbatim.
2293 Self::ffn_act_lim(
2294 e,
2295 &self.cfg,
2296 &gate,
2297 &up,
2298 1.0,
2299 1.0,
2300 mtp.step35.as_ref().and_then(|s| s.clamp_shexp),
2301 &mut act,
2302 n_ff,
2303 )?;
2304 e.matmul(ffn_down, &act, 1)?
2305 }
2306 // MTP head is a distinct block — key its experts under a separate layer index (u16::MAX)
2307 // so they never alias trunk layer 0's cache keys.
2308 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, 1, u16::MAX)?,
2309 };
2310
2311 // op 10: h_nextn = x1 + ffn_out (at di)
2312 let mut h_inner = e.zeros(di)?;
2313 e.add(&x1, &ffn_out, &mut h_inner, di)?;
2314
2315 // op 10.5 (student): up-project the inner hidden back to n_embd — training semantics:
2316 // the chain carrier AND the head input are out_up(h_inner) (pre-final-norm).
2317 let h_nextn = match mtp.geom.as_ref() {
2318 Some(g) => e.matmul(&g.out_up, &h_inner, 1)?,
2319 None => h_inner,
2320 };
2321
2322 // op 11: final = RMSNorm(h_nextn, shared_head_norm OR output_norm)
2323 let final_norm = mtp.shared_head_norm.as_ref().unwrap_or(&self.output_norm);
2324 let mut final_h = e.zeros(n_embd)?;
2325 e.rms_norm(
2326 &h_nextn,
2327 final_norm.float_data(),
2328 &mut final_h,
2329 n_embd,
2330 1,
2331 eps,
2332 )?;
2333
2334 // op 12: draft_logits = (shared_head_head OR output) @ final — stays ON DEVICE.
2335 let head = mtp.shared_head_head.as_ref().unwrap_or(&self.output);
2336 let mut logits = e.matmul(head, &final_h, 1)?;
2337 // op 12b (lane/draft-mask): grammar mask over the DRAFT vocab, applied here so the
2338 // caller's argmax / gumbel draw / p-min prob all read the grammar-legal row.
2339 if let Some((mask_d, mw)) = mask {
2340 let d_vocab = head.out_features();
2341 e.mask_logits_col(&mut logits, mask_d, 0, d_vocab, mw)?;
2342 }
2343 // Chain recurrence hand-over: pre-norm h_nextn (default) or post-norm final_h
2344 // (MEMRA_SPEC_HPOST — llama.cpp #24025's t_h_nextn is taken AFTER the head norm).
2345 Ok((logits, if spec_hpost() { final_h } else { h_nextn }))
2346 }
2347
2348 /// step35 MTP-block attention, T=1, on the scratch KV — the EAGER-ONLY twin of
2349 /// `mtp_full_attn_dc`. Three things force a separate arm rather than a geometry parameter on
2350 /// the dc path, and all three are properties of this arch's MTP block:
2351 ///
2352 /// 1. **The SWA window.** Block 45 is an SWA-type block (`sliding_window_pattern[45]=true`,
2353 /// window 512). Windowed decode in memra is a token-aligned VIEW OFFSET into the quantized
2354 /// cache (the gemma4 R6 / `step35_decode_attn` pattern: keys carry absolute rope and the
2355 /// mask is purely positional, so one query at `len-1` attending the last `win` rows IS the
2356 /// windowed result). `fa_decode_dc` takes the key count from a DEVICE counter and always
2357 /// starts at row 0 — it cannot express a nonzero offset, so a windowed dc arm would need a
2358 /// new kernel. That is deliberately not built here: see the CUDA-graph note below.
2359 /// 2. **Per-layer head count.** 96 q heads over 8 KV (GQA 12) at this block, vs the trunk's 64
2360 /// on its full-attn layers. The trunk cfg's `n_head` scalar is the MAX over layers, and the
2361 /// trunk ARTIFACT's per-layer arrays stop at index 44 — so the count must come from the
2362 /// resolved `Step35MtpGeom`, never from `cfg`.
2363 /// 3. **The separate head-wise gate.** `blk.45.attn_gate.weight [n_embd, 96]` produces one
2364 /// sigmoid scalar per head (broadcast over head_dim) — `attn_head_gate`, not the qwen35
2365 /// fused-into-wq `q_gate_split` form the dc arm handles.
2366 ///
2367 /// WHY EAGER-ONLY IS NOT A GAP TODAY: `graph_draft` requires `trunk_dense`, and this SKU's
2368 /// trunk is a 288-expert MoE, so the graph draft is already off for every step35 model — the
2369 /// eager chain IS the served path. `mtp_head_forward_cap` refuses step35 explicitly rather
2370 /// than silently capturing a window-less (wrong past `win` draft rows) graph.
2371 ///
2372 /// Unlike the dc arm this advances BOTH the host `kv.len` and the device counter, so the
2373 /// caller must not mirror.
2374 fn mtp_step35_attn(
2375 &self,
2376 e: &Engine,
2377 fa: &FullAttnLayer,
2378 g: &crate::hybrid::Step35MtpGeom,
2379 h: &CudaSlice<f32>,
2380 pos_d: &CudaSlice<i32>,
2381 scratch: &mut MtpScratch,
2382 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2383 let (nh, nkv, hd) = (g.n_head, g.n_head_kv, self.cfg.head_dim_k as usize);
2384 let eps = self.cfg.rms_eps;
2385 let scale = 1.0 / (hd as f32).sqrt(); // step35.cpp:255 kq_scale
2386 let n_embd = self.cfg.n_embd as usize;
2387 let gw = fa
2388 .attn_gate
2389 .as_ref()
2390 .ok_or("step35 MTP block is missing attn_gate.weight (head-wise attention gate)")?;
2391
2392 let (q0, k0, v0, gt) = if e.uses_q8_1_fast(&fa.wq)
2393 && e.uses_q8_1_fast(&fa.wk)
2394 && e.uses_q8_1_fast(&fa.wv)
2395 && e.uses_q8_1_fast(gw)
2396 {
2397 let (hq, hdq) = e.quantize_q8_1(h, 1, n_embd)?;
2398 let (a, b, c) = match e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, &hq, &hdq)? {
2399 Some(t3) => t3,
2400 None => (
2401 e.matmul_pre(&fa.wq, &hq, &hdq, h, 1)?,
2402 e.matmul_pre(&fa.wk, &hq, &hdq, h, 1)?,
2403 e.matmul_pre(&fa.wv, &hq, &hdq, h, 1)?,
2404 ),
2405 };
2406 (a, b, c, e.matmul_pre(gw, &hq, &hdq, h, 1)?)
2407 } else {
2408 (
2409 e.matmul(&fa.wq, h, 1)?,
2410 e.matmul(&fa.wk, h, 1)?,
2411 e.matmul(&fa.wv, h, 1)?,
2412 e.matmul(gw, h, 1)?,
2413 )
2414 };
2415
2416 let mut q = e.uninit(nh * hd)?;
2417 e.rms_norm(&q0, fa.q_norm.float_data(), &mut q, hd, nh, eps)?;
2418 let mut k = e.uninit(nkv * hd)?;
2419 e.rms_norm(&k0, fa.k_norm.float_data(), &mut k, hd, nkv, eps)?;
2420 // `rope_freqs.weight` (llama3 factors) applies to the FULL-attn layers ONLY; SWA passes
2421 // null (llama-hparams / step35.cpp). Block 45 is SWA, so `ff` is None there — but read
2422 // the resolved flag, not the constant, so an all-full sibling stays correct.
2423 let ff = if g.swa {
2424 None
2425 } else {
2426 self.step35_aux.as_ref().and_then(|a| a.rope_freqs(e))
2427 };
2428 #[cfg(debug_assertions)]
2429 if let Some(ff) = ff {
2430 crate::debug_assert_tensor_stream_device(ff, &e.stream(), "mtp_step35_attn.rope_freqs");
2431 }
2432 e.rope_neox2(
2433 &mut q,
2434 &mut k,
2435 pos_d,
2436 hd,
2437 g.n_rot,
2438 nh,
2439 nkv,
2440 1,
2441 g.rope_base,
2442 1.0,
2443 ff,
2444 )?;
2445
2446 // Append at the HOST slot, then re-stamp the device counter: the eager chain has the
2447 // length on the host anyway, and the windowed view below needs it there to compute the
2448 // offset. The device counter is kept in lockstep so `mtp_kv_fill`'s `set_i32_one` and any
2449 // dc-family consumer of this scratch still agree.
2450 let kv = &mut scratch.kv;
2451 assert!(
2452 kv.len < scratch.cap,
2453 "step35 MTP scratch overflow ({} >= {})",
2454 kv.len,
2455 scratch.cap
2456 );
2457 let next_len = kv.len + 1;
2458 let (off, t_kv) = if g.swa && next_len > g.window {
2459 (next_len - g.window, g.window)
2460 } else {
2461 (0, next_len)
2462 };
2463 let write_row = e.prepare_kv_append(kv, off & !31usize, 1)?;
2464 e.append_kv_quantized(
2465 &k,
2466 &v0,
2467 &mut kv.k,
2468 &mut kv.v,
2469 write_row,
2470 kv.kv_dim_k,
2471 kv.kv_dim_v,
2472 kv.k_tok_bytes,
2473 kv.v_tok_bytes,
2474 false,
2475 )?;
2476 kv.len = next_len;
2477 e.set_i32_one(&mut kv.len_d, kv.len as i32)?;
2478 // SWA view offset (see note 1). The draft chain is short (k+2 rows), but the scratch is
2479 // PERSISTENT across rounds — `mtp_kv_fill` leaves one row per committed token behind, so
2480 // `kv.len` tracks absolute position and crosses 512 in any real generation. The window is
2481 // therefore live, not theoretical.
2482 let physical = kv.physical_rows(off, off + t_kv)?;
2483 let k_view = e.view_u8_range(
2484 &kv.k,
2485 physical.start * kv.k_tok_bytes,
2486 physical.end * kv.k_tok_bytes,
2487 );
2488 let v_view = e.view_u8_range(
2489 &kv.v,
2490 physical.start * kv.v_tok_bytes,
2491 physical.end * kv.v_tok_bytes,
2492 );
2493 let mut attn = e.uninit(nh * hd)?;
2494 e.fa_decode_kvmod(
2495 &q,
2496 &k_view,
2497 &v_view,
2498 &mut attn,
2499 hd,
2500 nh,
2501 nkv,
2502 t_kv,
2503 scale,
2504 kv.k_tok_bytes,
2505 kv.v_tok_bytes,
2506 false,
2507 )?;
2508
2509 let mut ag = e.uninit(nh * hd)?;
2510 e.attn_head_gate(&attn, >, &mut ag, None, hd, nh, 1)?;
2511 Ok(e.matmul(&fa.wo, &ag, 1)?)
2512 }
2513
2514 /// MTP-block full attention, T=1, on the scratch KV (BOTH draft paths — eager and graph):
2515 /// the scratch write slot and the attention bound come from `scratch.kv.len_d` (device i32[1])
2516 /// so the launch args are FIXED across draft steps — ONE captured graph serves the whole
2517 /// chain, and replays keep seeing KV growth through the device counter (no recapture).
2518 /// Geometry contract: n_splits is sized from `scratch.cap` (the persistent capacity); splits
2519 /// whose key range lies beyond the device t_kv exit empty and the shared combine skips them
2520 /// (fa_decode_dc bit-correct-for-any-t_kv<=bucket_max contract). The eager path uses the SAME
2521 /// launcher with the SAME bucket_max -> identical dispatch -> bit-identical draft tokens (the
2522 /// graph-vs-eager parity gate). Host len is NOT advanced here (graph contract); callers mirror.
2523 fn mtp_full_attn_dc(
2524 &self,
2525 e: &Engine,
2526 fa: &FullAttnLayer,
2527 h: &CudaSlice<f32>,
2528 pos_d: &CudaSlice<i32>,
2529 scratch: &mut MtpScratch,
2530 geom: Option<&crate::hybrid::DraftGeom>,
2531 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2532 let cfg = &self.cfg;
2533 let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
2534 let geometry = cfg.full_attention_geometry_at(mtp_il);
2535 let n_head = geom.map(|g| g.n_head).unwrap_or(geometry.n_head as usize);
2536 let n_head_kv = geom
2537 .map(|g| g.n_head_kv)
2538 .unwrap_or(geometry.n_head_kv as usize);
2539 let head_dim = geometry.head_dim_k as usize;
2540 let eps = cfg.rms_eps;
2541 let scale = geometry.attention_scale();
2542 let n_embd = geom.map(|g| g.d_inner).unwrap_or(cfg.n_embd as usize);
2543 let bucket_max = scratch.cap; // < 96 guaranteed by the graph_draft eligibility gate
2544
2545 let (qf, mut k, v) =
2546 if e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk) && e.uses_q8_1_fast(&fa.wv) {
2547 let (hq, hd) = e.quantize_q8_1(h, 1, n_embd)?;
2548 (
2549 e.matmul_pre(&fa.wq, &hq, &hd, h, 1)?,
2550 e.matmul_pre(&fa.wk, &hq, &hd, h, 1)?,
2551 e.matmul_pre(&fa.wv, &hq, &hd, h, 1)?,
2552 )
2553 } else {
2554 (
2555 e.matmul(&fa.wq, h, 1)?,
2556 e.matmul(&fa.wk, h, 1)?,
2557 e.matmul(&fa.wv, h, 1)?,
2558 )
2559 };
2560 // M3/Hy3 have no attention output gate — wq out is exactly q; skip the split.
2561 let gated = geometry.attention_gate == memra_gguf::config::AttentionGateKind::FusedQ;
2562 let (mut q, gate) = if gated {
2563 let mut q = e.zeros(n_head * head_dim)?;
2564 let mut gate = e.zeros(n_head * head_dim)?;
2565 e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, 1)?;
2566 (q, Some(gate))
2567 } else {
2568 (qf, None)
2569 };
2570
2571 let mut qn = e.zeros(n_head * head_dim)?;
2572 e.rms_norm(&q, fa.q_norm.float_data(), &mut qn, head_dim, n_head, eps)?;
2573 q = qn;
2574 let mut kn = e.zeros(n_head_kv * head_dim)?;
2575 e.rms_norm(
2576 &k,
2577 fa.k_norm.float_data(),
2578 &mut kn,
2579 head_dim,
2580 n_head_kv,
2581 eps,
2582 )?;
2583 k = kn;
2584 let rope_dims = geometry.n_rot as usize;
2585 e.rope_neox(
2586 &mut q,
2587 pos_d,
2588 head_dim,
2589 rope_dims,
2590 n_head,
2591 1,
2592 geometry.rope_base,
2593 1.0,
2594 )?;
2595 e.rope_neox(
2596 &mut k,
2597 pos_d,
2598 head_dim,
2599 rope_dims,
2600 n_head_kv,
2601 1,
2602 geometry.rope_base,
2603 1.0,
2604 )?;
2605
2606 let kv = &mut scratch.kv;
2607 // append at the DEVICE slot (kv.len_d == old len), then advance the counter in-graph.
2608 e.append_kv_quantized_dc(
2609 &k,
2610 &v,
2611 &mut kv.k,
2612 &mut kv.v,
2613 &kv.len_d,
2614 kv.kv_dim_k,
2615 kv.kv_dim_v,
2616 kv.k_tok_bytes,
2617 kv.v_tok_bytes,
2618 false,
2619 )?;
2620 e.inc_seqlen(&mut kv.len_d)?;
2621 // full-buffer views (any in-round t_kv stays in range on replay); the kernel bounds the
2622 // key range from the device counter.
2623 let k_view = e.view_u8(&kv.k, kv.k.len());
2624 let v_view = e.view_u8(&kv.v, kv.v.len());
2625 let (ktb, vtb) = (kv.k_tok_bytes, kv.v_tok_bytes);
2626 let mut attn = e.zeros(n_head * head_dim)?;
2627 e.fa_decode_dc(
2628 &q, &k_view, &v_view, &mut attn, head_dim, n_head, n_head_kv, &kv.len_d, bucket_max,
2629 scale, ktb, vtb, false,
2630 )?;
2631
2632 let attn_g = match &gate {
2633 Some(gate) => {
2634 let mut gsig = e.zeros(n_head * head_dim)?;
2635 e.sigmoid(gate, &mut gsig, n_head * head_dim)?;
2636 let mut ag = e.zeros(n_head * head_dim)?;
2637 e.mul(&attn, &gsig, &mut ag, n_head * head_dim)?;
2638 ag
2639 }
2640 None => attn,
2641 };
2642 Ok(e.matmul(&fa.wo, &attn_g, 1)?)
2643 }
2644
2645 /// PERSISTENT-DRAFT-KV fill (the reference engine's "mtp_update" analogue): compute the MTP
2646 /// block's K/V for `tokens` (committed tokens at positions pos0..pos0+T) from their EXACT
2647 /// trunk hiddens `h` ([T, n_embd] token-major, pre-output_norm) and append at slots pos0.. of
2648 /// the scratch KV. K/V-ONLY — ops A/1-5 plus the K-side of op 6 (wk/wv + k_norm + rope +
2649 /// quantized append); no wq/attention/FFN/lm_head, so per-token cost ~= eh_proj + wk/wv (a
2650 /// small fraction of one trunk layer), T-batched. Rope follows the chain convention
2651 /// rope(token@p) = p+1. Runs at round boundaries OUTSIDE the captured graph in BOTH draft
2652 /// modes -> draft parity by construction. Caller must have scratch.kv.len == pos0.
2653 #[allow(clippy::too_many_arguments)]
2654 fn mtp_kv_fill(
2655 &self,
2656 e: &Engine,
2657 mtp: &MtpHead,
2658 tokens: &[u32],
2659 h: &CudaSlice<f32>,
2660 pos0: usize,
2661 scratch: &mut MtpScratch,
2662 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
2663 ) -> Result<(), Box<dyn std::error::Error>> {
2664 let cfg = &self.cfg;
2665 let n_embd = cfg.n_embd as usize;
2666 let eps = cfg.rms_eps;
2667 let t = tokens.len();
2668 assert_eq!(scratch.kv.len, pos0, "mtp_kv_fill: append slot mismatch");
2669 assert!(pos0 + t <= scratch.cap, "mtp_kv_fill: scratch overflow");
2670 let Mixer::Full(fa) = &mtp.mixer else {
2671 panic!("MTP block is full-attn in qwen35; linear MTP not supported")
2672 };
2673 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i + 1) as i32).collect();
2674 let pos_d = e.htod_i32(&pos_vec)?;
2675
2676 // ops A/1/2: embed + the two input norms, T-wide.
2677 let e_emb = match embd_dev {
2678 Some((g, qt, rb)) => e.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
2679 None => e.htod(&self.embd.gather(n_embd, tokens))?,
2680 };
2681 let mut e_norm = e.zeros(t * n_embd)?;
2682 e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, t, eps)?;
2683 let mut h_norm = e.zeros(t * n_embd)?;
2684 e.rms_norm(h, mtp.hnorm.float_data(), &mut h_norm, n_embd, t, eps)?;
2685
2686 // op 3: per-row [e_norm ; h_norm] concat, token-major [T, 2*n_embd].
2687 let mut concat = e.zeros(t * 2 * n_embd)?;
2688 for i in 0..t {
2689 e.copy_view_into(
2690 &mut concat,
2691 i * 2 * n_embd,
2692 &e_norm.slice(i * n_embd..(i + 1) * n_embd),
2693 n_embd,
2694 )?;
2695 e.copy_view_into(
2696 &mut concat,
2697 i * 2 * n_embd + n_embd,
2698 &h_norm.slice(i * n_embd..(i + 1) * n_embd),
2699 n_embd,
2700 )?;
2701 }
2702
2703 // ops 4/5: eh_proj + attn_norm, T-wide (at the student inner width when geom is set).
2704 let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
2705 let inp_sa = e.matmul(&mtp.eh_proj, &concat, t)?;
2706 let mut a_norm = e.zeros(t * di)?;
2707 e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, t, eps)?;
2708
2709 // op 6 (K/V half): wk/wv + k_norm + rope + per-row quantized append. No wq/attention —
2710 // the fill only has to leave correct K/V rows behind for later chains to attend over.
2711 let n_head_kv = mtp
2712 .geom
2713 .as_ref()
2714 .map(|g| g.n_head_kv)
2715 .or(mtp.step35.as_ref().map(|s| s.n_head_kv))
2716 .unwrap_or_else(|| {
2717 let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
2718 cfg.full_attention_geometry_at(mtp_il).n_head_kv as usize
2719 });
2720 let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
2721 let geometry = cfg.full_attention_geometry_at(mtp_il);
2722 let head_dim = geometry.head_dim_k as usize;
2723 let mut k = e.matmul(&fa.wk, &a_norm, t)?;
2724 let v = e.matmul(&fa.wv, &a_norm, t)?;
2725 let mut kn = e.zeros(t * n_head_kv * head_dim)?;
2726 e.rms_norm(
2727 &k,
2728 fa.k_norm.float_data(),
2729 &mut kn,
2730 head_dim,
2731 n_head_kv * t,
2732 eps,
2733 )?;
2734 k = kn;
2735 // step35: rotary width AND base are per-layer, and the MTP block's values come from the
2736 // resolved `Step35MtpGeom` — NOT from `cfg.rope_dim_count`/`cfg.rope_freq_base`, which
2737 // carry the arch defaults (128 / 5e6, i.e. the FULL-attn layers' base). Getting this wrong
2738 // writes K rows the attention arm then re-derives at a different theta: correct-looking
2739 // output with dead acceptance, invisible to the exactness gates.
2740 let (rope_dims, rope_base, ff) = match mtp.step35.as_ref() {
2741 Some(s) => (
2742 s.n_rot,
2743 s.rope_base,
2744 if s.swa {
2745 None
2746 } else {
2747 self.step35_aux.as_ref().and_then(|a| a.rope_freqs(e))
2748 },
2749 ),
2750 None => (geometry.n_rot as usize, geometry.rope_base, None),
2751 };
2752 #[cfg(debug_assertions)]
2753 if let Some(ff) = ff {
2754 crate::debug_assert_tensor_stream_device(ff, &e.stream(), "mtp_kv_fill.rope_freqs");
2755 }
2756 match ff {
2757 Some(f) => e.rope_neox_ff(
2758 &mut k, &pos_d, head_dim, rope_dims, n_head_kv, t, rope_base, 1.0, f,
2759 )?,
2760 None => e.rope_neox(
2761 &mut k, &pos_d, head_dim, rope_dims, n_head_kv, t, rope_base, 1.0,
2762 )?,
2763 }
2764
2765 let kv = &mut scratch.kv;
2766 // Match the trunk prime contract: a chunk may need the aligned window immediately before
2767 // its first row, so preserve that prefix when the physical tail rebases at wrap.
2768 let retain_from = kv
2769 .ring
2770 .as_ref()
2771 .map(|ring| pos0.saturating_sub(ring.window() - 1) & !31usize)
2772 .unwrap_or(0);
2773 let write_row = e.prepare_kv_append(kv, retain_from, t)?;
2774 for i in 0..t {
2775 let k_row = k.slice(i * kv.kv_dim_k..(i + 1) * kv.kv_dim_k);
2776 let v_row = v.slice(i * kv.kv_dim_v..(i + 1) * kv.kv_dim_v);
2777 e.append_kv_quantized_view(
2778 &k_row,
2779 &v_row,
2780 &mut kv.k,
2781 &mut kv.v,
2782 write_row + i,
2783 kv.kv_dim_k,
2784 kv.kv_dim_v,
2785 kv.k_tok_bytes,
2786 kv.v_tok_bytes,
2787 false,
2788 )?;
2789 }
2790 kv.len = pos0 + t;
2791 e.set_i32_one(&mut kv.len_d, kv.len as i32)?;
2792 Ok(())
2793 }
2794
2795 /// CAPTURE body for the GRAPH DRAFT (stage 2 of graph-grade spec): ONE MTP head forward with
2796 /// every varying input device-resident —
2797 /// - token id from the persistent `tok_d` (the previous replay's in-graph argmax wrote it,
2798 /// so the chain feeds itself; the host reads the same 4 bytes for the draft list),
2799 /// - h_seed from the persistent `h_seed_d` (h_nextn is copied BACK into it at the end),
2800 /// - rope pos from the persistent `pos_d` counter (inc'd in-graph),
2801 /// - scratch KV slot/bound from `scratch.kv.len_d` (see mtp_full_attn_dc).
2802 /// The p-min confidence lands in the persistent `p_d` iff `with_prob` (env is fixed per run).
2803 /// Same kernels, same dispatch as the eager mtp_head_forward_dev chain -> same draft tokens
2804 /// (exactness never depends on drafts — the verify arbitrates — but acceptance parity does).
2805 /// `with_head=false` captures the HEAD-LESS twin for the pseudo-seed replay (2026-07-03):
2806 /// the pseudo pass only needs h_nextn (op 10) + the scratch append — the lm_head read
2807 /// (~1.06ms q6_K on the 9B), argmax and prob are dead weight there. h_nextn's inputs are
2808 /// untouched, so the seed value is identical; round-start resets overwrite tok_d/p_d anyway.
2809 /// `sampled_cap` = Some((ctr_d, perturb_d, q_out_d, seed, temp)) captures the SAMPLED twin
2810 /// (step 3 of the sampled-spec arc): head logits are retained in the persistent `q_out_d`
2811 /// (host D2Ds them to the round's q slot after each replay), the DEVICE event counter is
2812 /// bumped in-graph, and the argmax reads GUMBEL-PERTURBED logits — one categorical draw per
2813 /// replay, bit-identical to the eager arm's gumbel_perturb at the same (seed, sctr, temp).
2814 /// seed/temp are capture-time constants (fixed per generate call, like p_min).
2815 #[allow(clippy::too_many_arguments)]
2816 fn mtp_head_forward_cap(
2817 &self,
2818 e: &Engine,
2819 mtp: &MtpHead,
2820 tok_d: &mut CudaSlice<u32>,
2821 pos_d: &mut CudaSlice<i32>,
2822 h_seed_d: &mut CudaSlice<f32>,
2823 p_d: &mut CudaSlice<f32>,
2824 scratch: &mut MtpScratch,
2825 with_prob: bool,
2826 with_head: bool,
2827 embd_gpu: &CudaSlice<u8>,
2828 embd_qt: i32,
2829 embd_rb: usize,
2830 d_vocab: usize,
2831 sampled_cap: Option<(
2832 &mut CudaSlice<u32>,
2833 &mut CudaSlice<f32>,
2834 &mut CudaSlice<f32>,
2835 u64,
2836 f32,
2837 )>,
2838 stream_pack: Option<(&mut CudaSlice<u32>, usize, Option<&CudaSlice<u32>>)>,
2839 // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): (packed draft-vocab allowed-set buffer,
2840 // word count). Captured as ONE mask_logits_f32 node between the head matmul and the
2841 // in-graph argmax; the buffer address is baked, its CONTENTS are re-uploaded by the
2842 // host before every replay (the decode.rs graph-mask pattern). All-ones contents = a
2843 // no-op ban, so a position the grammar cannot constrain costs one pass over the row.
2844 mask_cap: Option<(&CudaSlice<u32>, usize)>,
2845 ) -> Result<(), Box<dyn std::error::Error>> {
2846 let cfg = &self.cfg;
2847 let n_embd = cfg.n_embd as usize;
2848 // step35 REFUSAL (deliberate, named): the graph body's attention is `mtp_full_attn_dc`,
2849 // whose device-counter key bound always starts at row 0 — it cannot express this block's
2850 // SWA view offset, so a captured chain would silently attend OUTSIDE the window once the
2851 // persistent scratch passes 512 rows. Nothing is lost today: `graph_draft` also requires
2852 // `trunk_dense`, and step35's trunk is a 288-expert MoE, so the eager chain
2853 // (`mtp_head_forward_dev` -> `mtp_step35_attn`) is the served path. Returning Err (not a
2854 // panic) is what the two capture sites and the round-stream capture already handle by
2855 // degrading to eager / stream-off.
2856 if mtp.step35.is_some() {
2857 return Err(
2858 "step35 has no captured draft chain (fa_decode_dc cannot express the MTP \
2859 block's SWA view offset; same root cause as the dc decode refusal) — the \
2860 eager draft chain serves this arch"
2861 .into(),
2862 );
2863 }
2864 // student inner width (see mtp_head_forward_dev) — interface dims stay n_embd.
2865 let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
2866 let eps = cfg.rms_eps;
2867 let e_emb = e.embed_gather_device(embd_gpu, tok_d, n_embd, embd_qt, embd_rb)?;
2868 let mut e_norm = e.zeros(n_embd)?;
2869 e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, 1, eps)?;
2870 let mut h_norm = e.zeros(n_embd)?;
2871 e.rms_norm(
2872 &*h_seed_d,
2873 mtp.hnorm.float_data(),
2874 &mut h_norm,
2875 n_embd,
2876 1,
2877 eps,
2878 )?;
2879 let mut concat = e.zeros(2 * n_embd)?;
2880 e.copy_into(&mut concat, 0, &e_norm, n_embd)?;
2881 e.copy_into(&mut concat, n_embd, &h_norm, n_embd)?;
2882 let inp_sa = e.matmul(&mtp.eh_proj, &concat, 1)?;
2883 let mut a_norm = e.zeros(di)?;
2884 e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, 1, eps)?;
2885 let attn_out = match &mtp.mixer {
2886 Mixer::Full(fa) => {
2887 self.mtp_full_attn_dc(e, fa, &a_norm, pos_d, scratch, mtp.geom.as_ref())?
2888 }
2889 Mixer::Linear(_) => {
2890 panic!("MTP block is full-attn in qwen35; linear MTP not supported")
2891 }
2892 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
2893 };
2894 let mut x1 = e.zeros(di)?;
2895 e.add(&inp_sa, &attn_out, &mut x1, di)?;
2896 let mut z = e.zeros(di)?;
2897 e.rms_norm(&x1, mtp.post_attn_norm.float_data(), &mut z, di, 1, eps)?;
2898 let ffn_out = match &mtp.ffn {
2899 crate::hybrid::Ffn::Dense {
2900 ffn_gate,
2901 ffn_up,
2902 ffn_down,
2903 } => {
2904 let n_ff = ffn_gate.out_features();
2905 let (gate, up) = if e.uses_q8_1_fast(ffn_gate) && e.uses_q8_1_fast(ffn_up) {
2906 let (zq, zd) = e.quantize_q8_1(&z, 1, di)?;
2907 (
2908 e.matmul_pre(ffn_gate, &zq, &zd, &z, 1)?,
2909 e.matmul_pre(ffn_up, &zq, &zd, &z, 1)?,
2910 )
2911 } else {
2912 (e.matmul(ffn_gate, &z, 1)?, e.matmul(ffn_up, &z, 1)?)
2913 };
2914 let mut act = e.zeros(n_ff)?;
2915 Self::ffn_act(e, &self.cfg, &gate, &up, &mut act, n_ff)?;
2916 e.matmul(ffn_down, &act, 1)?
2917 }
2918 // ROUND-STREAM: the 35B NextN block carries a MoE FFN. With RESIDENT experts the
2919 // dev path is pure device launches (device top-k + rows kernels, ZERO-DtoH by
2920 // design) — capture-legal. Non-resident (SLRU-lock) stays rejected: the capture
2921 // error arm degrades the caller to eager/stream-off.
2922 crate::hybrid::Ffn::Moe(m) if m.dev_exps.is_some() => {
2923 self.moe_ffn_il(e, m, &z, 1, u16::MAX)?
2924 }
2925 crate::hybrid::Ffn::Moe(_) => {
2926 return Err("graph draft requires a Dense (or resident-MoE) MTP FFN".into());
2927 }
2928 };
2929 let mut h_inner = e.zeros(di)?;
2930 e.add(&x1, &ffn_out, &mut h_inner, di)?;
2931 // student: up-project back to n_embd (carrier + head input; see mtp_head_forward_dev).
2932 let h_nextn = match mtp.geom.as_ref() {
2933 Some(g) => e.matmul(&g.out_up, &h_inner, 1)?,
2934 None => h_inner,
2935 };
2936 // MEMRA_SPEC_HPOST needs final_h even head-less (it IS the next seed under that convention).
2937 let final_h = if with_head || spec_hpost() {
2938 let final_norm = mtp.shared_head_norm.as_ref().unwrap_or(&self.output_norm);
2939 let mut fh = e.zeros(n_embd)?;
2940 e.rms_norm(&h_nextn, final_norm.float_data(), &mut fh, n_embd, 1, eps)?;
2941 Some(fh)
2942 } else {
2943 None
2944 };
2945 if with_head {
2946 let head = mtp.shared_head_head.as_ref().unwrap_or(&self.output);
2947 let mut logits = e.matmul(head, final_h.as_ref().unwrap(), 1)?;
2948 // DRAFT-SIDE GRAMMAR MASK: ban the grammar-illegal draft ids IN the captured chain,
2949 // before the argmax — proposals become legal by construction. Contents-only
2950 // per-replay upload keeps the capture valid.
2951 if let Some((mask_d, mw)) = mask_cap {
2952 e.mask_logits_col(&mut logits, mask_d, 0, d_vocab, mw)?;
2953 }
2954 if let Some((ctr_d, perturb_d, q_out_d, seed, temp)) = sampled_cap {
2955 // SAMPLED chain: retain q (raw head logits -> persistent q_out_d; the matmul's
2956 // own buffer is pool-recycled after the capture body returns, so it can't be the
2957 // retention target), bump the device event counter, gumbel-perturb reading it,
2958 // and argmax the PERTURBED logits into tok_d — the in-graph categorical draw.
2959 e.copy_into(q_out_d, 0, &logits, d_vocab)?;
2960 e.sctr_inc(ctr_d)?;
2961 e.gumbel_perturb_ctr(&logits, perturb_d, d_vocab, seed, ctr_d, temp)?;
2962 e.argmax_token_device_into(perturb_d, tok_d, d_vocab)?;
2963 // p-min prob = the head's RAW softmax confidence in the SAMPLED pick — same
2964 // semantics as the eager sampled arm's prob_of_token_device(dl_d, tok_d).
2965 if with_prob {
2966 e.prob_of_token_device_into(&logits, tok_d, p_d, d_vocab)?;
2967 }
2968 } else {
2969 // draft token -> persistent tok_d (next replay's embed reads it; host reads the 4 bytes).
2970 e.argmax_token_device_into(&logits, tok_d, d_vocab)?;
2971 // p-min under a draft mask reads the MASKED row: confidence relative to the
2972 // grammar-LEGAL alternatives (illegal ids leave the softmax denominator), which
2973 // is the right semantics for "does the drafter know what comes next here" and
2974 // the same row the pick came from. Draft-quality only — verify arbitrates.
2975 if with_prob {
2976 e.prob_of_token_device_into(&logits, tok_d, p_d, d_vocab)?;
2977 }
2978 }
2979 }
2980 // ROUND-STREAM K-chain: pack (tok, p) into slot j, then remap tok through d2t so the
2981 // NEXT chained body's embed reads the TARGET id — zero host involvement per step.
2982 if let Some((out, slot, d2t)) = stream_pack {
2983 e.pack_tok_p(tok_d, p_d, out, slot)?;
2984 if let Some(map) = d2t {
2985 e.tok_map_u32(tok_d, map)?;
2986 }
2987 }
2988 // Next draft step's h_seed: pre-norm h_nextn (default) or post-norm final_h (HPOST).
2989 if spec_hpost() {
2990 e.copy_into(h_seed_d, 0, final_h.as_ref().unwrap(), n_embd)?;
2991 } else {
2992 e.copy_into(h_seed_d, 0, &h_nextn, n_embd)?;
2993 }
2994 // advance the draft rope position in-graph.
2995 e.inc_seqlen(pos_d)?;
2996 Ok(())
2997 }
2998
2999 /// Batched target verify forward over `tokens` at positions `pos0..pos0+T` (§D.3, T=K+1).
3000 /// Returns ALL T logit columns (host f32, [T*n_vocab]); appends T cols to every full-attn KV
3001 /// and advances every linear-attn recur state by T steps (the recur steps are SEQUENTIAL T=1).
3002 /// Advances `cache.pos` by T.
3003 pub fn decode_step_t(
3004 &self,
3005 e: &Engine,
3006 tokens: &[u32],
3007 pos0: usize,
3008 cache: &mut Cache,
3009 ) -> Result<Vec<f32>, Box<dyn std::error::Error>> {
3010 if self.is_gemma4_e4b() {
3011 return Ok(self.gemma4_e4b_decode_step_t_h(e, tokens, pos0, cache)?.0);
3012 }
3013 if self.cfg.gemma4.is_some() {
3014 return self.gemma4_decode_step_t(e, tokens, pos0, cache);
3015 }
3016 Ok(self.decode_step_t_h(e, tokens, pos0, cache)?.0)
3017 }
3018
3019 /// Like `decode_step_t` but ALSO returns the LAST column's pre-output_norm hidden (h_seed for
3020 /// the next draft round). This lets partial-accept replay run as ONE batched T=(n_acc+1) forward
3021 /// (single weight read) instead of n_acc+1 separate T=1 decode_steps (n_acc+1 weight reads).
3022 /// At batch=1 decode is bandwidth-bound, so batching the replay is THE MTP profitability lever.
3023 pub fn decode_step_t_h(
3024 &self,
3025 e: &Engine,
3026 tokens: &[u32],
3027 pos0: usize,
3028 cache: &mut Cache,
3029 ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3030 self.decode_step_t_h_emb(e, tokens, pos0, cache, None)
3031 }
3032
3033 /// Like `decode_step_t_h` with an optional RESIDENT embed table (spec hot loop): device
3034 /// gather instead of host dequant + [T, n_embd] f32 htod. Bit-identical rows.
3035 pub fn decode_step_t_h_emb(
3036 &self,
3037 e: &Engine,
3038 tokens: &[u32],
3039 pos0: usize,
3040 cache: &mut Cache,
3041 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3042 ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3043 let (logits_d, h_seed) = self.decode_step_t_h_emb_dev(e, tokens, pos0, cache, embd_dev)?;
3044 Ok((e.dtoh(&logits_d)?, h_seed))
3045 }
3046
3047 /// DEVICE-LOGITS verify forward (spec device-argmax lever): identical kernel chain to
3048 /// `decode_step_t_h_emb` but returns the [T, n_vocab] logits ON DEVICE — the accept walk
3049 /// argmaxes each column on-device and reads back ONE [T] u32 instead of dtoh'ing the full
3050 /// T x n_vocab f32 block (~1-4 MB + T host argmaxes, every round). Kernel dispatch is
3051 /// UNCHANGED (same decode-exact kernels); only the post-logits transfer moves.
3052 pub fn decode_step_t_h_emb_dev(
3053 &self,
3054 e: &Engine,
3055 tokens: &[u32],
3056 pos0: usize,
3057 cache: &mut Cache,
3058 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3059 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3060 let n_embd = self.cfg.n_embd as usize;
3061 let t = tokens.len();
3062 let (logits, x) = self.decode_step_t_core(e, tokens, pos0, cache, embd_dev, None)?;
3063 // h_seed for the next round = LAST column's pre-output_norm hidden ([n_embd]).
3064 let mut hs = vbuf(e, n_embd)?; // fully written by copy_view_into below
3065 e.copy_view_into(&mut hs, 0, &x.slice((t - 1) * n_embd..t * n_embd), n_embd)?;
3066 Ok((logits, hs))
3067 }
3068
3069 /// CORE verify forward: the `decode_step_t_h_emb_dev` kernel chain, returning the FULL
3070 /// pre-output_norm hidden stack x ([T, n_embd], any column extractable) and optionally
3071 /// filling a `VerifyCkpt` (retained per-layer state-rebuild inputs) for the REPLAY-FREE
3072 /// partial accept. `ckpt: None` => byte-for-byte the old behavior (the ckpt writes are pure
3073 /// retains/copies — they never change what any kernel computes).
3074 fn decode_step_t_core(
3075 &self,
3076 e: &Engine,
3077 tokens: &[u32],
3078 pos0: usize,
3079 cache: &mut Cache,
3080 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3081 mut ckpt: Option<&mut VerifyCkpt>,
3082 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3083 self.decode_step_t_core_stream(e, tokens, pos0, cache, embd_dev, ckpt.take(), None, None)
3084 }
3085
3086 /// Increment-0 two-session PP seam: release the peer after this lane's stage-0 boundary TX.
3087 /// The two independent sessions keep their own cache/checkpoint state; only issue order moves.
3088 fn decode_step_t_core_pipelined(
3089 &self,
3090 e: &Engine,
3091 tokens: &[u32],
3092 pos0: usize,
3093 cache: &mut Cache,
3094 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3095 mut ckpt: Option<&mut VerifyCkpt>,
3096 pipe: &SpecPipeLane,
3097 round: usize,
3098 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3099 let fence = crate::pp::pp_cuts(self.layers.len())
3100 .ok_or("two-session speculative pipeline requires a PP stage cut")?;
3101 if crate::pp::pp2_streams_off() || !crate::pp::spec_pp_on() {
3102 return Err("two-session speculative pipeline requires the PP verify split".into());
3103 }
3104 let interval_fence = pipe.stage0_begin(round)?;
3105 let ticket = self.verify_stage0_issue(
3106 e,
3107 tokens,
3108 pos0,
3109 cache,
3110 embd_dev,
3111 ckpt.as_deref_mut(),
3112 None,
3113 &fence,
3114 Some(interval_fence),
3115 pipe.trace(round),
3116 )?;
3117 pipe.stage0_end(round);
3118 pipe.stage1_begin(round)?;
3119 let result = self.verify_stage1_finish(e, ticket, cache, ckpt, None, &fence, true)?;
3120 pipe.verify_end(round);
3121 Ok(result)
3122 }
3123
3124 /// ROUND-STREAM stage (c) 4: `stream` = (device verify tokens [t], device pos counter) —
3125 /// when Some, rope positions come from pos_iota over the counter, the embed gathers the
3126 /// device tokens, and full_attn_verify routes appends/FA through the _dc twins reading the
3127 /// SAME counter (every layer's kvl.len == cache.pos, one counter drives all three). The
3128 /// host `tokens`/`pos0` args still size buffers (t is FIXED K+1 in stream mode).
3129 #[allow(clippy::too_many_arguments)]
3130 fn decode_step_t_core_stream(
3131 &self,
3132 e: &Engine,
3133 tokens: &[u32],
3134 pos0: usize,
3135 cache: &mut Cache,
3136 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3137 mut ckpt: Option<&mut VerifyCkpt>,
3138 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
3139 pp_pipe: Option<bool>,
3140 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3141 // PP DOOR (lane/pp2-spec 2026-08-06): the verify trunk now takes its OWN stage split,
3142 // exactly as the eager and batched steps do. This is the single funnel every verify
3143 // forward reaches (decode_step_t / _h / _h_emb / _h_emb_dev / _core all land here), so
3144 // wiring it here wires the whole spec surface — the draft/accept/commit machinery above
3145 // is untouched.
3146 //
3147 // History: pp2-hardening (2026-08-06) made this funnel FAIL CLOSED, because its trunk
3148 // walk was unsplit on one stream and a sharded cross-device placement peer-read every
3149 // remote layer's weights on every spec round (measured 13.9-28x on the batched twin).
3150 // The refusal below survives to cover the residue — MEMRA_SPEC_PP=0, MEMRA_PP_STREAMS=0,
3151 // or a placement whose PpNRt fails to build — so a config that would still walk the
3152 // whole trunk on one stream refuses instead of regressing 28x.
3153 if let Some(fence) = crate::pp::pp_cuts(self.layers.len()) {
3154 if !crate::pp::pp2_streams_off() && crate::pp::spec_pp_on() {
3155 return self.decode_step_t_core_ppn(
3156 e,
3157 tokens,
3158 pos0,
3159 cache,
3160 embd_dev,
3161 ckpt.take(),
3162 stream,
3163 &fence,
3164 pp_pipe,
3165 );
3166 }
3167 }
3168 crate::pp::refuse_unsplit_if_remote(
3169 "decode_step_t (spec verify)",
3170 "drop MEMRA_SPEC_PP=0 / MEMRA_PP_STREAMS=0 so the verify trunk takes its OWN stage \
3171 split (decode_step_t_core_ppn); or run spec on one device",
3172 )?;
3173 let cfg = &self.cfg;
3174 let n_embd = cfg.n_embd as usize;
3175 let eps = cfg.rms_eps;
3176 let t = tokens.len();
3177 let pos_d = match stream {
3178 Some((_, ctr)) => {
3179 let mut p = e.alloc_uninit::<i32>(t)?;
3180 e.pos_iota(ctr, &mut p, t)?;
3181 p
3182 }
3183 None => {
3184 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
3185 e.htod_i32(&pos_vec)?
3186 }
3187 };
3188
3189 // embed T tokens -> [T, n_embd] token-major (device gather on the spec hot loop)
3190 let x = match (stream, embd_dev) {
3191 (Some((vtok, _)), Some((g, qt, rb))) => {
3192 e.embed_gather_device_td(g, vtok, t, n_embd, qt, rb)?
3193 }
3194 (None, Some((g, qt, rb))) => e.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
3195 _ => e.htod(&self.embd.gather(n_embd, tokens))?,
3196 };
3197
3198 // TRUNK WALK: layers [0, n_layers) through the SAME range-scoped subgraph the PP-N
3199 // stage split calls per stage (`verify_layers`) — one code path, so the split cannot
3200 // drift from the unsplit dispatch mirroring. lane/pp2-spec 2026-08-06.
3201 let x = self.verify_layers(
3202 e,
3203 x,
3204 0,
3205 self.layers.len(),
3206 &pos_d,
3207 pos0,
3208 t,
3209 cache,
3210 ckpt.take(),
3211 stream,
3212 )?;
3213
3214 let mut hn = vbuf(e, t * n_embd)?;
3215 let serving_head = self.cfg.step35.is_some() || self.qwen35_serving_class();
3216 let logits = if serving_head {
3217 // Step35 and the qwen35 family (MoE 2026-08-14 AM, dense-hybrid same day PM — the
3218 // Q3.8 bring-up reproduced the identical near-tie class on dense: eager-class verify
3219 // vs batched-class live serving, ULP drift amplified through the GDN recurrence)
3220 // serve one batched numeric class at every live width, including B=1. Keep the
3221 // verify head in that same class; other generic families retain the decode-exact
3222 // head that their run-spec contract pins.
3223 e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
3224 e.matmul(&self.output, &hn, t)?
3225 } else {
3226 e.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
3227 e.matmul_decode_exact(&self.output, &hn, t)?
3228 };
3229 // stream: the device pos counter owns position; host mirror reconciles at drain.
3230 if stream.is_none() {
3231 cache.pos += t;
3232 }
3233 // Hidden stack for seeds/refresh-fills: pre-norm x (default) or post-norm hn (HPOST).
3234 Ok((logits, if spec_hpost() { hn } else { x }))
3235 }
3236
3237 /// THE VERIFY TRUNK OVER PP-N (lane/pp2-spec 2026-08-06): `decode_step_t_core_stream`'s walk
3238 /// as N stage subgraphs, each on its own engine/stream (and, under `MEMRA_PP_DEVICES`, its own
3239 /// device), with a `[T, n_embd]` boundary transfer between them. T = K+1 (the verify batch),
3240 /// so this is the batched-boundary shape the pp2-batch lane's grow-only slots already handle
3241 /// (`tx(b, x, t*n_embd)`; the slot grows to the high-water T and the transport moves exactly
3242 /// the payload).
3243 ///
3244 /// Structure is `decode_step_batch_ppn`'s, which is `decode_step_h_ppn`'s. FOUR THINGS ARE
3245 /// PER-STAGE and each for a measured reason (see `decode_step_batch_ppn`'s header for the
3246 /// receipts):
3247 ///
3248 /// 1. THE ENGINE (`rt.engine(s, e)`) — `Engine` owns lazily-grown stable-pointer scratch
3249 /// (`fa_part_pool`, `fa_vf16_scratch`, `argmax_partials`) that is single-stream-safe BY
3250 /// DESIGN. Two stage streams through one Engine is the 2026-08-02 shared-scratch race
3251 /// (35% flake, nondeterministic all-logits divergence). `PpNRt::build` gives every stage
3252 /// s>0 its own Engine even on the primary device; honouring it here is what scopes the
3253 /// pools. The verify path allocates MORE of that scratch than eager decode does (FA at
3254 /// m=T, and the per-layer `GdnStash` retains), so this is load-bearing, not inherited.
3255 ///
3256 /// 2. `pos_d` — each stage uploads its OWN copy of the T rope positions on ITS stream, so the
3257 /// buffer is allocated, consumed and freed on one stream. In `stream` mode that means each
3258 /// stage runs its own `pos_iota` over the SHARED device counter (`pos_ctr`): the counter is
3259 /// read-only during the forward (the round's `inc`/`copy_add` happen outside it), so every
3260 /// stage derives the identical iota, and each stage's own output buffer is stream-local.
3261 ///
3262 /// 3. THE EMBED lives with stage 0 (`self.embd` / `embd_gpu` are host/primary-side; the
3263 /// sharded loader leaves the table with stage 0 by construction).
3264 ///
3265 /// 4. THE HEAD (`output_norm` + `output`) runs on the LAST stage — the sharded loader uploaded
3266 /// both through that stage's engine (`hybrid.rs`: `e_head = layer_engine(e, n_trunk,
3267 /// n_trunk-1)`), so reading them anywhere else is a peer read of the biggest tensor in the
3268 /// model, every round.
3269 ///
3270 /// WHAT STAYS ON THE PRIMARY, deliberately: the returned logits and hidden stack `x`. Both are
3271 /// last-stage-allocated device buffers, and every consumer (the device argmax walk, the accept
3272 /// kernels, `spec_seed_gather`, the ckpt rebuild in `commit_verified_prefix`) reads them
3273 /// through the primary context by UVA — the same read the batched serving epilogue's
3274 /// `last_logits_dev` park does. Those consumers are per-round O(T x n_vocab) and O(n_embd),
3275 /// not per-layer, so they are not the 28x class; splitting them is a separate lane.
3276 ///
3277 /// The MTP HEAD (draft side) is NOT split: it is one block, it lives wherever the loader put
3278 /// it (`load_mtp` uses the primary engine), and it is ~1-2 GB against the trunk's tens. Draft
3279 /// placement is measured, not assumed — see `research/pp2-spec-20260806`.
3280 ///
3281 /// EXACTNESS: PP-N adds ZERO deviation. Each stage runs the SAME kernels on the SAME bytes in
3282 /// the same order via the SAME `verify_layers` the unsplit body calls; the only change is
3283 /// where the residual is materialized, and the boundary is a straight f32 copy (dtod
3284 /// same-device / `cudaMemcpyPeerAsync` cross-device, no conversion). So the split MUST be
3285 /// BIT-IDENTICAL to the unsplit verify at the same T, in both placement orders. Gate:
3286 /// `decode-batch-gate --mode ppspec`. Acceptance counts are a DERIVED consequence — greedy
3287 /// accept argmaxes these logits, so bit-identical logits force identical accept walks; the
3288 /// `run-spec` K=1..8 arm checks that end-to-end rather than trusting the implication.
3289 #[allow(clippy::too_many_arguments)]
3290 fn decode_step_t_core_ppn(
3291 &self,
3292 e: &Engine,
3293 tokens: &[u32],
3294 pos0: usize,
3295 cache: &mut Cache,
3296 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3297 mut ckpt: Option<&mut VerifyCkpt>,
3298 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
3299 fence: &[usize],
3300 pp_pipe: Option<bool>,
3301 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3302 let ticket = self.verify_stage0_issue(
3303 e,
3304 tokens,
3305 pos0,
3306 cache,
3307 embd_dev,
3308 ckpt.as_deref_mut(),
3309 stream,
3310 fence,
3311 pp_pipe,
3312 None,
3313 )?;
3314 self.verify_stage1_finish(e, ticket, cache, ckpt, stream, fence, true)
3315 }
3316
3317 /// Enqueue embed, stage 0, and the first boundary TX, then return the actual boundary slot.
3318 /// The ordinary PP verify wrapper calls `verify_stage1_finish` immediately after this return.
3319 #[allow(clippy::too_many_arguments)]
3320 fn verify_stage0_issue(
3321 &self,
3322 e: &Engine,
3323 tokens: &[u32],
3324 pos0: usize,
3325 cache: &mut Cache,
3326 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3327 mut ckpt: Option<&mut VerifyCkpt>,
3328 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
3329 fence: &[usize],
3330 pp_pipe: Option<bool>,
3331 trace: Option<SpecPipeTraceCtx>,
3332 ) -> Result<VerifyBoundaryTicket, Box<dyn std::error::Error>> {
3333 assert!(
3334 !self.is_gemma4_e4b() && self.cfg.gemma4.is_none(),
3335 "decode_step_t_core_ppn covers the hybrid non-gemma4 verify trunk only \
3336 (the gemma4 arms have their own decode_step_t twins)"
3337 );
3338 if crate::pp::pp_host_bounce_active() && (stream.is_some() || embd_dev.is_some()) {
3339 return Err(
3340 "decode_step_t_core_ppn: refused with MEMRA_PP_HOST_BOUNCE=1 — the trunk \
3341 boundary itself is host-staged, but device-resident verify still peer-reads \
3342 primary-device token/position/embedding buffers from stage 0. Run plain PP \
3343 serving on this host class; spec requires local per-stage inputs first."
3344 .into(),
3345 );
3346 }
3347 let rt = crate::pp::PpNRt::get(e)?;
3348 let n_st = fence.len() - 1;
3349 assert_eq!(
3350 rt.n_stages(),
3351 n_st,
3352 "PpNRt stage count {} != fence stages {n_st}",
3353 rt.n_stages()
3354 );
3355 let n_embd = self.cfg.n_embd as usize;
3356 let t = tokens.len();
3357 let payload = t * n_embd;
3358 if pp_pipe.is_some() {
3359 assert_eq!(n_st, 2, "spec pipeline requires exactly two PP stages");
3360 }
3361 // One-shot lane diagnostic: force natural PP-2 boundaries to completion so the server
3362 // log can price stage 0, the peer hop, the RX copy, and stage 1 + head separately without
3363 // nsys. The ordinary path keeps every enqueue asynchronous. N>2 is deliberately excluded:
3364 // the report below names exactly two stages and must never imply it measured middle ones.
3365 let pp_anatomy = n_st == 2 && std::env::var("MEMRA_SPEC_PP_ANATOMY").as_deref() == Ok("1");
3366 let pp_started = std::time::Instant::now();
3367 let (mut reverse_ms, mut stage0_ms, mut tx_ms) = (0.0f64, 0.0f64, 0.0f64);
3368 // The CALLER's ambient stream, captured BEFORE any `rt.enter()` pushes a stage stream:
3369 // this body returns DEVICE-RESIDENT buffers (the device-argmax accept walk's contract),
3370 // so the exit needs the same publication the boundaries get — see `PpNRt::publish_to`.
3371 // Taken here, not at the end, because inside the last-stage scope `e.stream()` IS the
3372 // stage stream and the wait would self-order into a no-op.
3373 let caller_stream = e.stream();
3374 // #87 ROOT-CAUSE FENCE (lane/pp2spec-crash): the PREVIOUS round's stage-allocated
3375 // outputs (logits/hidden/ckpt stashes) freed stream-ordered on the STAGE streams while
3376 // the primary stream still holds queued reads of them — with event tracking elided,
3377 // nothing stops the pool from reusing those blocks for THIS round's stage allocations,
3378 // whose writes then race the queued reads (measured: 13/4096-NaN random-bits garbage in
3379 // the spec round seed; the full anatomy is on `PpNRt::fence_stages_behind`). Order every
3380 // stage stream behind the caller before enqueueing new stage work.
3381 let reverse_started = std::time::Instant::now();
3382 if pp_pipe != Some(false) {
3383 rt.fence_stages_behind(&caller_stream)?;
3384 }
3385 if pp_pipe == Some(true) {
3386 // Both session verifies must alternate boundary slots even when the ordinary
3387 // decode overlap experiment is off. Prewarm before A's stage 0 so B cannot grow
3388 // slot 1 by synchronizing the RX stream while A's stage 1 is in flight.
3389 rt.prepare_overlap_slots(0, payload)?;
3390 }
3391 if pp_anatomy {
3392 // Drain the reverse-publication dependency before timing stage 0 itself. At c=1 this
3393 // prices any primary-stream rollback/refresh tail inherited from the prior round.
3394 for s in 0..n_st {
3395 let _st = rt.enter(s);
3396 rt.engine(s, e).stream().synchronize()?;
3397 }
3398 reverse_ms = reverse_started.elapsed().as_secs_f64() * 1e3;
3399 }
3400
3401 // Per-stage rope positions: in host mode the same [T] iota each stage uploads itself; in
3402 // stream mode each stage's own `pos_iota` over the shared read-only device counter.
3403 let stage_pos = |es: &Engine| -> Result<CudaSlice<i32>, Box<dyn std::error::Error>> {
3404 match stream {
3405 Some((_, ctr)) => {
3406 let mut p = es.alloc_uninit::<i32>(t)?;
3407 es.pos_iota(ctr, &mut p, t)?;
3408 Ok(p)
3409 }
3410 None => {
3411 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
3412 es.htod_i32(&pos_vec)
3413 }
3414 }
3415 };
3416
3417 // ---- STAGE 0: embed (the table lives with stage 0) + layers [0, fence[1]) + TX ----
3418 let slot = {
3419 let _st0 = rt.enter(0);
3420 let e0 = rt.engine(0, e);
3421 enqueue_spec_pipe_trace_marker(&e0.stream(), trace.as_ref(), "S0", "start", None)?;
3422 let stage0_started = std::time::Instant::now();
3423 let pos_d = stage_pos(e0)?;
3424 let x = match (stream, embd_dev) {
3425 (Some((vtok, _)), Some((g, qt, rb))) => {
3426 e0.embed_gather_device_td(g, vtok, t, n_embd, qt, rb)?
3427 }
3428 (None, Some((g, qt, rb))) => e0.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
3429 _ => e0.htod(&self.embd.gather(n_embd, tokens))?,
3430 };
3431 let x = self.verify_layers(
3432 e0,
3433 x,
3434 fence[0],
3435 fence[1],
3436 &pos_d,
3437 pos0,
3438 t,
3439 cache,
3440 ckpt.as_deref_mut(),
3441 stream,
3442 )?;
3443 if pp_anatomy {
3444 e0.stream().synchronize()?;
3445 stage0_ms = stage0_started.elapsed().as_secs_f64() * 1e3;
3446 }
3447 let tx_started = std::time::Instant::now();
3448 let slot = if pp_pipe.is_some() {
3449 rt.tx_pipelined(0, &x, payload)?
3450 } else {
3451 rt.tx(0, &x, payload)?
3452 };
3453 enqueue_spec_pipe_trace_marker(&e0.stream(), trace.as_ref(), "S0", "end", Some(slot))?;
3454 if pp_anatomy {
3455 e0.stream().synchronize()?;
3456 tx_ms = tx_started.elapsed().as_secs_f64() * 1e3;
3457 }
3458 slot
3459 // x + pos_d drop here: freed stream-ordered on stage-0's stream after use.
3460 };
3461
3462 Ok(VerifyBoundaryTicket {
3463 rt,
3464 caller_stream,
3465 slot,
3466 pos0,
3467 t,
3468 payload,
3469 n_st,
3470 pipelined: pp_pipe.is_some(),
3471 pp_anatomy,
3472 pp_started,
3473 reverse_ms,
3474 stage0_ms,
3475 tx_ms,
3476 trace,
3477 })
3478 }
3479
3480 /// Consume a stage-0 boundary ticket and enqueue the remaining PP stages plus the head.
3481 /// On PP-2 this is exactly stage 1; PP-N keeps its pre-existing middle-stage walk here.
3482 #[allow(clippy::too_many_arguments)]
3483 fn verify_stage1_finish(
3484 &self,
3485 e: &Engine,
3486 ticket: VerifyBoundaryTicket,
3487 cache: &mut Cache,
3488 mut ckpt: Option<&mut VerifyCkpt>,
3489 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
3490 fence: &[usize],
3491 publish_to_caller: bool,
3492 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3493 let VerifyBoundaryTicket {
3494 rt,
3495 caller_stream,
3496 slot,
3497 pos0,
3498 t,
3499 payload,
3500 n_st,
3501 pipelined,
3502 pp_anatomy,
3503 pp_started,
3504 reverse_ms,
3505 stage0_ms,
3506 tx_ms,
3507 trace,
3508 } = ticket;
3509 let n_embd = self.cfg.n_embd as usize;
3510 let eps = self.cfg.rms_eps;
3511 let mut slot = slot;
3512 let (mut rx_ms, mut stage1_ms) = (0.0f64, 0.0f64);
3513 let stage_pos = |es: &Engine| -> Result<CudaSlice<i32>, Box<dyn std::error::Error>> {
3514 match stream {
3515 Some((_, ctr)) => {
3516 let mut p = es.alloc_uninit::<i32>(t)?;
3517 es.pos_iota(ctr, &mut p, t)?;
3518 Ok(p)
3519 }
3520 None => {
3521 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
3522 es.htod_i32(&pos_vec)
3523 }
3524 }
3525 };
3526
3527 // ---- MIDDLE STAGES: RX boundary s-1 -> range -> TX boundary s ----
3528 for s in 1..n_st - 1 {
3529 let _st = rt.enter(s);
3530 let es = rt.engine(s, e);
3531 let pos_d = stage_pos(es)?;
3532 let x = rt.rx(s - 1, slot, payload)?;
3533 let x = self.verify_layers(
3534 es,
3535 x,
3536 fence[s],
3537 fence[s + 1],
3538 &pos_d,
3539 pos0,
3540 t,
3541 cache,
3542 ckpt.as_deref_mut(),
3543 stream,
3544 )?;
3545 slot = if pipelined {
3546 rt.tx_pipelined(s, &x, payload)?
3547 } else {
3548 rt.tx(s, &x, payload)?
3549 };
3550 }
3551
3552 // ---- LAST STAGE: RX + final range + output_norm + lm head ----
3553 let _stl = rt.enter(n_st - 1);
3554 let el = rt.engine(n_st - 1, e);
3555 let pos_d = stage_pos(el)?;
3556 let rx_started = std::time::Instant::now();
3557 let x = rt.rx(n_st - 2, slot, payload)?;
3558 if pp_anatomy {
3559 el.stream().synchronize()?;
3560 rx_ms = rx_started.elapsed().as_secs_f64() * 1e3;
3561 }
3562 enqueue_spec_pipe_trace_marker(&el.stream(), trace.as_ref(), "S1", "start", Some(slot))?;
3563 let stage1_started = std::time::Instant::now();
3564 let x = self.verify_layers(
3565 el,
3566 x,
3567 fence[n_st - 1],
3568 fence[n_st],
3569 &pos_d,
3570 pos0,
3571 t,
3572 cache,
3573 ckpt.as_deref_mut(),
3574 stream,
3575 )?;
3576
3577 let mut hn = vbuf(el, payload)?;
3578 let logits = if self.cfg.step35.is_some() {
3579 // The PP Step35 serving path uses rms_norm + matmul for B=1 as well as B>1.
3580 // Verify must not switch numeric class merely because the same session speculates.
3581 el.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
3582 el.matmul(&self.output, &hn, t)?
3583 } else {
3584 el.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
3585 el.matmul_decode_exact(&self.output, &hn, t)?
3586 };
3587 enqueue_spec_pipe_trace_marker(&el.stream(), trace.as_ref(), "S1", "end", Some(slot))?;
3588 if pp_anatomy {
3589 el.stream().synchronize()?;
3590 stage1_ms = stage1_started.elapsed().as_secs_f64() * 1e3;
3591 }
3592 // EXIT PUBLICATION: both returned buffers are still being produced on the last stage's
3593 // stream. Order the caller's stream behind that work before the buffers escape this
3594 // scope (the 2026-08-06 same-device ppspec find: without it the caller's primary-stream
3595 // consumer read unwritten logits — nondeterministic, one-device-only, and it poisoned
3596 // the following arm's KV in the same process).
3597 if publish_to_caller {
3598 rt.publish_to(n_st - 1, &caller_stream)?;
3599 }
3600 if pp_anatomy {
3601 if publish_to_caller {
3602 caller_stream.synchronize()?;
3603 }
3604 eprintln!(
3605 "[spec-pp-anatomy] t={t} reverse={reverse_ms:.3}ms stage0={stage0_ms:.3}ms \
3606 tx={tx_ms:.3}ms rx={rx_ms:.3}ms stage1-head={stage1_ms:.3}ms total={:.3}ms",
3607 pp_started.elapsed().as_secs_f64() * 1e3,
3608 );
3609 }
3610 // stream: the device pos counter owns position; host mirror reconciles at drain.
3611 if stream.is_none() {
3612 cache.pos += t;
3613 }
3614 Ok((logits, if spec_hpost() { hn } else { x }))
3615 }
3616
3617 /// Step3.5/Step3.7 verify trunk in the serving batched numeric class.
3618 ///
3619 /// `step35_decode_batch_layers` is now authoritative at every live serving width, including
3620 /// B=1 (lane/cx-b1fix). The older verify walk deliberately mirrored the eager T=1 class:
3621 /// it replayed `step35_decode_attn` per row and used the eager/decode-exact FFN dispatch.
3622 /// Those classes are individually stable, but a near-tie prompt can choose different greedy
3623 /// bytes when a request moves from batched plain serving into speculative verify. Run the
3624 /// same authoritative B=1 stage subgraph for each verify row here. Rows still advance
3625 /// layer-by-layer, so every layer sees the preceding verify rows in its attention cache while
3626 /// every norm/projection/FFN uses exactly the live serving dispatch.
3627 #[allow(clippy::too_many_arguments)]
3628 fn step35_verify_batch_layers(
3629 &self,
3630 e: &Engine,
3631 mut x: CudaSlice<f32>,
3632 lo: usize,
3633 hi: usize,
3634 pos0: usize,
3635 t: usize,
3636 cache: &mut Cache,
3637 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3638 let n_embd = self.cfg.n_embd as usize;
3639 self.cfg
3640 .step35
3641 .as_ref()
3642 .ok_or("step35 verify batch requires step35 cfg")?;
3643 let mut ph_last = std::time::Instant::now();
3644 for il in lo..hi {
3645 let mut next = e.uninit(t * n_embd)?;
3646 for r in 0..t {
3647 let mut row = e.uninit(n_embd)?;
3648 e.dtod_copy_view(&x.slice(r * n_embd..(r + 1) * n_embd), &mut row)?;
3649 // The caller owns this verify's position. During controller overlap, cache.pos
3650 // still describes generation N while this stage-0 walk belongs to N+1.
3651 let row_pos = e.htod_i32(&[(pos0 + r) as i32])?;
3652 let mut one = [&mut *cache];
3653 let out = self.step35_decode_batch_layers(
3654 e,
3655 row,
3656 &mut one,
3657 &row_pos,
3658 il,
3659 il + 1,
3660 &mut ph_last,
3661 )?;
3662 e.dtod_copy_into(&out, &mut next, r * n_embd)?;
3663 }
3664 self.dflash_tap(e, cache, il, &next, t)?;
3665 x = next;
3666 }
3667 Ok(x)
3668 }
3669
3670 /// DSpark drafter verify (lane/dspark-q38-recover): one t-row forward through the
3671 /// SERVING-CLASS verify funnel (`decode_step_t_core_stream` — the same numeric class
3672 /// MTP verify rides, GDN state advanced in place), returning per-row argmax tokens.
3673 /// Advances `cache.pos += t`; the caller owns snapshot/rollback (block acceptance is
3674 /// prefix-keep, not all-or-nothing).
3675 pub(crate) fn dspark_verify_t_am(
3676 &self,
3677 e: &Engine,
3678 tokens: &[u32],
3679 pos0: usize,
3680 cache: &mut Cache,
3681 ) -> Result<Vec<u32>, Box<dyn std::error::Error>> {
3682 let (logits, _hn) =
3683 self.decode_step_t_core_stream(e, tokens, pos0, cache, None, None, None, None)?;
3684 let t = tokens.len();
3685 let v = self.output.out_features();
3686 let mut am_d = e.stream().alloc_zeros::<u32>(t)?;
3687 for r in 0..t {
3688 e.argmax_token_device_col(&logits, r, v, &mut am_d, r)?;
3689 }
3690 Ok(e.dtoh_u32(&am_d)?)
3691 }
3692
3693 /// DSpark verify with the MTP column-stash armed: identical forward to
3694 /// `dspark_verify_t_am`, but fills a `VerifyCkpt` so a partial accept can restore
3695 /// column state directly (`dspark_commit_prefix`) instead of snapshot-replay.
3696 /// The ckpt type is opaque outside spec.rs (newtype) — dflash.rs threads it through.
3697 pub(crate) fn dspark_verify_t_am_ckpt(
3698 &self,
3699 e: &Engine,
3700 tokens: &[u32],
3701 pos0: usize,
3702 cache: &mut Cache,
3703 ) -> Result<(Vec<u32>, DsparkVerifyCkpt), Box<dyn std::error::Error>> {
3704 let mut ck = VerifyCkpt::new(self.layers.len());
3705 let (logits, _hn) = self.decode_step_t_core_stream(
3706 e,
3707 tokens,
3708 pos0,
3709 cache,
3710 None,
3711 Some(&mut ck),
3712 None,
3713 None,
3714 )?;
3715 let t = tokens.len();
3716 let v = self.output.out_features();
3717 let mut am_d = e.stream().alloc_zeros::<u32>(t)?;
3718 for r in 0..t {
3719 e.argmax_token_device_col(&logits, r, v, &mut am_d, r)?;
3720 }
3721 Ok((e.dtoh_u32(&am_d)?, DsparkVerifyCkpt(ck)))
3722 }
3723
3724 /// Restore the round to `keep` accepted columns from the verify stash: KV lens and
3725 /// pos from the pre-verify snapshot + keep, GDN conv/ssm from the stashed column
3726 /// state — no replay forward. The exact `commit_verified_prefix` the MTP path ships.
3727 pub(crate) fn dspark_commit_prefix(
3728 &self,
3729 e: &Engine,
3730 cache: &mut Cache,
3731 snap: &crate::cache::CacheSnapshot,
3732 ckpt: &DsparkVerifyCkpt,
3733 keep: usize,
3734 ) -> Result<(), Box<dyn std::error::Error>> {
3735 self.commit_verified_prefix(e, cache, snap, &ckpt.0, keep, false, None)
3736 }
3737
3738 /// Qwen35-family verify trunk in the live serving numeric class.
3739 ///
3740 /// Serving intentionally keeps this architecture in the generic batched program even at
3741 /// B=1. The older verify walk used its own mirrored dispatch and can flip near-tie argmaxes.
3742 ///
3743 /// Two arms, one numeric class:
3744 /// - DENSE (`Arch::Qwen35`, t<=16): `qwen35_verify_tparallel` — the weight ops (norms,
3745 /// projections, FFN) hoist to m=T through the exact-tier batched kernels whose per-row
3746 /// program IS the m=1 program (`matmul_pre == fused2 per (tensor,row); _bN mmvq per-row
3747 /// == m=1` — decode_batch.rs v2 note), while the state ops (conv ring, gdn scan, KV
3748 /// append, fa decode) stay a per-row loop running the b_n=1 serving kernels with each
3749 /// row's own t_kv-driven arm pick (the straddle law: every row executes the exact
3750 /// program its isolated serving step would). One weight read per layer per round
3751 /// instead of T — this is what makes MTP profitable in the exact class (the per-row
3752 /// walk measured verify(K+1) ~= (K+1) plain steps: 69 -> 44 tok/s served, 2026-08-15).
3753 /// - MoE / t>16 / `MEMRA_SPEC_VERIFY_ROWWISE=1`: the per-row replay of the authoritative
3754 /// serving layer body, preserving single-session autoregressive cache order (the
3755 /// correctness reference; also the rollback seam for the t-parallel arm).
3756 ///
3757 /// Bit-identity of the t-parallel arm vs the rowwise arm is gated by spec-serve-gate
3758 /// (zero differing logits at T=1..4, K arms) + the 8-prompt ON/OFF canary before ship.
3759 #[allow(clippy::too_many_arguments)]
3760 fn qwen35_verify_batch_layers(
3761 &self,
3762 e: &Engine,
3763 x: CudaSlice<f32>,
3764 lo: usize,
3765 hi: usize,
3766 pos0: usize,
3767 t: usize,
3768 cache: &mut Cache,
3769 ckpt: Option<&mut VerifyCkpt>,
3770 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3771 let rowwise = std::env::var("MEMRA_SPEC_VERIFY_ROWWISE").as_deref() == Ok("1")
3772 || !matches!(self.cfg.arch, memra_gguf::config::Arch::Qwen35)
3773 || t > 16;
3774 if rowwise {
3775 self.qwen35_verify_rowwise(e, x, lo, hi, pos0, t, cache, ckpt)
3776 } else {
3777 self.qwen35_verify_tparallel(e, x, lo, hi, pos0, t, cache, ckpt)
3778 }
3779 }
3780
3781 /// The per-row correctness reference: replay each verify row through the authoritative
3782 /// serving layer body (`decode_batch_layers` at b_n=1). T full weight reads per layer.
3783 #[allow(clippy::too_many_arguments)]
3784 fn qwen35_verify_rowwise(
3785 &self,
3786 e: &Engine,
3787 mut x: CudaSlice<f32>,
3788 lo: usize,
3789 hi: usize,
3790 pos0: usize,
3791 t: usize,
3792 cache: &mut Cache,
3793 mut ckpt: Option<&mut VerifyCkpt>,
3794 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3795 let n_embd = self.cfg.n_embd as usize;
3796 let saved_pos = cache.pos;
3797 let mut ph_last = std::time::Instant::now();
3798 for il in lo..hi {
3799 let mut next = e.uninit(t * n_embd)?;
3800 let mut col_states: Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>> =
3801 if ckpt.is_some() && t >= 2 && matches!(self.layers[il].mixer, Mixer::Linear(_)) {
3802 Some(Vec::with_capacity(t - 1))
3803 } else {
3804 None
3805 };
3806 for r in 0..t {
3807 cache.pos = pos0 + r;
3808 let mut row = e.uninit(n_embd)?;
3809 e.dtod_copy_view(&x.slice(r * n_embd..(r + 1) * n_embd), &mut row)?;
3810 let row_pos = e.htod_i32(&[(pos0 + r) as i32])?;
3811 let mut one = [&mut *cache];
3812 let ctx = self.batch_layer_ctx(e, &one, il, il + 1)?;
3813 let out = match self.decode_batch_layers(
3814 e,
3815 row,
3816 &mut one,
3817 &ctx,
3818 &row_pos,
3819 &mut ph_last,
3820 ) {
3821 Ok(out) => out,
3822 Err(error) => {
3823 cache.pos = saved_pos;
3824 return Err(error);
3825 }
3826 };
3827 e.dtod_copy_into(&out, &mut next, r * n_embd)?;
3828 if r + 1 < t {
3829 if let Some(states) = col_states.as_mut() {
3830 let recur = cache.recur[il]
3831 .as_ref()
3832 .ok_or("Qwen35-MoE linear verify layer has no recurrent state")?;
3833 states.push((
3834 e.clone_dtod(&recur.conv_state)?,
3835 e.clone_dtod(&recur.ssm_state)?,
3836 ));
3837 }
3838 }
3839 }
3840 if let (Some(checkpoint), Some(states)) = (ckpt.as_deref_mut(), col_states) {
3841 checkpoint.cols[il] = Some(states);
3842 }
3843 x = next;
3844 }
3845 cache.pos = saved_pos;
3846 Ok(x)
3847 }
3848
3849 /// T-PARALLEL VERIFY IN THE SERVING NUMERIC CLASS (lane/tparallel-verify, 2026-08-15).
3850 ///
3851 /// The weight ops run ONCE per layer at m=T; the state ops run per row through the same
3852 /// b_n=1 serving kernels the rowwise replay uses. Per-row bit-identity rests on the two
3853 /// pins the serving batch tier already carries:
3854 /// * `matmul_pre` / `_bN` mmvq: per-row program == m=1 program (decode_batch.rs v2 note,
3855 /// kernel-check pinned) — so a [T, n_embd] projection row equals the row projected
3856 /// alone;
3857 /// * row-indexed norms/elementwise (`rms_norm`, `quantize_q8_1`, `add_rms_norm`,
3858 /// `gated_rmsnorm[_q8_1]`, `silu_mul`, `rope_neox` with per-row positions): the T-row
3859 /// launch is the per-row program (same pin the generic verify's fused norms rely on).
3860 /// The sequential dependencies keep their exact serving order: the conv ring / gdn scan
3861 /// chain state row -> row through the `_b` kernels at b_n=1 (ping-pong via a 6-entry
3862 /// alternating pointer table, host handles swapped per row so VerifyCkpt clones the
3863 /// canonical state exactly as the rowwise arm does), and each row's KV append + fa decode
3864 /// picks its arm from ITS OWN t_kv (append: format-only; fa: `fa_seqs_eligible` + its own
3865 /// `fa_split_keys` rung at b_n=1) — the straddle law per row, so every row executes the
3866 /// program its isolated B=1 serving step would.
3867 ///
3868 /// Cost: 1 weight read per layer per round + T state micro-launches, vs the rowwise arm's
3869 /// T weight reads. Gated bit-identical vs the rowwise arm by spec-serve-gate + canary.
3870 #[allow(clippy::too_many_arguments)]
3871 fn qwen35_verify_tparallel(
3872 &self,
3873 e: &Engine,
3874 mut x: CudaSlice<f32>,
3875 lo: usize,
3876 hi: usize,
3877 pos0: usize,
3878 t: usize,
3879 cache: &mut Cache,
3880 mut ckpt: Option<&mut VerifyCkpt>,
3881 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3882 use cudarc::driver::DevicePtr;
3883 let cfg = &self.cfg;
3884 let n_embd = cfg.n_embd as usize;
3885 let eps = cfg.rms_eps;
3886 let head_dim_global = cfg.head_dim_k as usize;
3887 let pos_host: Vec<i32> = (0..t).map(|r| (pos0 + r) as i32).collect();
3888 let pos_d = e.htod_i32(&pos_host)?;
3889 // Per-row 1-element position buffers, built ONCE per verify (the append/fa wrappers
3890 // take owned pos slices; building these inside the layer x row loops cost 16xT H2Ds).
3891 let pos_rows: Vec<CudaSlice<i32>> = (0..t)
3892 .map(|r| e.htod_i32(&[(pos0 + r) as i32]))
3893 .collect::<Result<_, _>>()?;
3894 let seqs_append =
3895 std::env::var("MEMRA_BATCH_APPEND").as_deref() != Ok("0") && !Engine::kv_fp8_on();
3896 let batch_fa_on = std::env::var("MEMRA_BATCH_FA").as_deref() != Ok("0");
3897
3898 for il in lo..hi {
3899 let layer = &self.layers[il];
3900 // ---- attn_norm + q8_1 quantize at m=T (row-indexed == per-row) ----
3901 let anorm = layer.attn_norm.float_data();
3902 let mut xn = e.uninit(t * n_embd)?;
3903 e.rms_norm(&x, anorm, &mut xn, n_embd, t, eps)?;
3904 let (hq, hd) = e.quantize_q8_1(&xn, t, n_embd)?;
3905
3906 let mixed: CudaSlice<f32> = match &layer.mixer {
3907 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
3908 Mixer::Full(fa) => {
3909 let geometry = cfg.full_attention_geometry_at(il as u32);
3910 let n_head = geometry.n_head as usize;
3911 let n_head_kv = geometry.n_head_kv as usize;
3912 let head_dim = geometry.head_dim_k as usize;
3913 let rope_dims = geometry.n_rot as usize;
3914 let rope_base = geometry.rope_base;
3915 let scale = geometry.attention_scale();
3916 // Batched projections: one weight read serves all T rows.
3917 let qf = e.matmul_pre(&fa.wq, &hq, &hd, &xn, t)?;
3918 let mut k = e.matmul_pre(&fa.wk, &hq, &hd, &xn, t)?;
3919 let v = e.matmul_pre(&fa.wv, &hq, &hd, &xn, t)?;
3920 let gated =
3921 geometry.attention_gate == memra_gguf::config::AttentionGateKind::FusedQ;
3922 let (mut q, gate) = if gated {
3923 let mut qs = e.uninit(t * n_head * head_dim)?;
3924 let mut gs = e.uninit(t * n_head * head_dim)?;
3925 e.q_gate_split(&qf, &mut qs, &mut gs, head_dim, n_head, t)?;
3926 (qs, Some(gs))
3927 } else {
3928 (qf, None)
3929 };
3930 let mut qn = e.uninit(t * n_head * head_dim)?;
3931 e.rms_norm(
3932 &q,
3933 fa.q_norm.float_data(),
3934 &mut qn,
3935 head_dim,
3936 t * n_head,
3937 eps,
3938 )?;
3939 q = qn;
3940 let mut kn = e.uninit(t * n_head_kv * head_dim)?;
3941 e.rms_norm(
3942 &k,
3943 fa.k_norm.float_data(),
3944 &mut kn,
3945 head_dim,
3946 t * n_head_kv,
3947 eps,
3948 )?;
3949 k = kn;
3950 e.rope_neox(
3951 &mut q, &pos_d, head_dim, rope_dims, n_head, t, rope_base, 1.0,
3952 )?;
3953 e.rope_neox(
3954 &mut k, &pos_d, head_dim, rope_dims, n_head_kv, t, rope_base, 1.0,
3955 )?;
3956
3957 // Per-row append + attend: row r sees rows 0..r in KV (causal within the
3958 // draft), each through the b_n=1 serving kernels at its own t_kv.
3959 let q_dim = n_head * head_dim;
3960 let kv_dim = n_head_kv * head_dim;
3961 let mut attn = e.uninit(t * q_dim)?;
3962 let (kdk, kdv, ktb, vtb, kv_view) = {
3963 let kvl = cache.kv[il].as_ref().unwrap();
3964 let s = &e.gpu.stream();
3965 let (pk, _g) = kvl.k.device_ptr(s);
3966 let (pv, _g2) = kvl.v.device_ptr(s);
3967 (
3968 kvl.kv_dim_k,
3969 kvl.kv_dim_v,
3970 kvl.k_tok_bytes,
3971 kvl.v_tok_bytes,
3972 e.htod_u64(&[pk as u64, pv as u64])?,
3973 )
3974 };
3975 for r in 0..t {
3976 // Owned per-row scratch: the b_n=1 kernels take packed batch buffers
3977 // whose row 0 is this row (arithmetic-free materialization copies,
3978 // same as decode's per-seq fallback arm).
3979 let mut k_row = e.uninit(kv_dim)?;
3980 e.dtod_copy_view(&k.slice(r * kv_dim..(r + 1) * kv_dim), &mut k_row)?;
3981 let mut v_row = e.uninit(kv_dim)?;
3982 e.dtod_copy_view(&v.slice(r * kv_dim..(r + 1) * kv_dim), &mut v_row)?;
3983 let pos_row = &pos_rows[r];
3984 let kvl = cache.kv[il].as_mut().unwrap();
3985 if seqs_append {
3986 e.append_kv_quantized_seqs(
3987 &k_row,
3988 &v_row,
3989 &kv_view.slice(0..2),
3990 pos_row,
3991 1,
3992 kdk,
3993 kdv,
3994 ktb,
3995 vtb,
3996 )?;
3997 kvl.len += 1;
3998 } else {
3999 e.append_kv_quantized_view(
4000 &k_row.slice(0..kv_dim),
4001 &v_row.slice(0..kv_dim),
4002 &mut kvl.k,
4003 &mut kvl.v,
4004 kvl.len,
4005 kvl.kv_dim_k,
4006 kvl.kv_dim_v,
4007 kvl.k_tok_bytes,
4008 kvl.v_tok_bytes,
4009 Engine::kv_fp8_on(),
4010 )?;
4011 kvl.len += 1;
4012 }
4013 let t_kv = kvl.len;
4014 let mut q_row = e.uninit(q_dim)?;
4015 e.dtod_copy_view(&q.slice(r * q_dim..(r + 1) * q_dim), &mut q_row)?;
4016 let mut a_row = e.uninit(q_dim)?;
4017 if batch_fa_on && crate::fa_seqs_eligible(t_kv, head_dim_global) {
4018 let sp0_r = crate::fa_split_keys(t_kv, cfg.n_head_kv as usize);
4019 e.fa_decode_batch_seqs_v4(
4020 &q_row,
4021 &kv_view.slice(0..2),
4022 pos_row,
4023 &mut a_row,
4024 head_dim,
4025 n_head,
4026 n_head_kv,
4027 1,
4028 t_kv,
4029 scale,
4030 sp0_r,
4031 ktb,
4032 vtb,
4033 )?;
4034 } else {
4035 let k_view = e.view_u8(&kvl.k, t_kv * kvl.k_tok_bytes);
4036 let v_view = e.view_u8(&kvl.v, t_kv * kvl.v_tok_bytes);
4037 let mut a_view = a_row.slice_mut(0..q_dim);
4038 e.fa_decode_kvmod_view(
4039 &q_row.slice(0..q_dim),
4040 &k_view,
4041 &v_view,
4042 &mut a_view,
4043 head_dim,
4044 n_head,
4045 n_head_kv,
4046 t_kv,
4047 scale,
4048 kvl.k_tok_bytes,
4049 kvl.v_tok_bytes,
4050 Engine::kv_fp8_on(),
4051 )?;
4052 }
4053 e.dtod_copy_into(&a_row, &mut attn, r * q_dim)?;
4054 }
4055
4056 // Output gate (element-wise) + o-proj at m=T.
4057 let attn_g = match &gate {
4058 Some(g) => {
4059 let n = t * q_dim;
4060 let mut gsig = e.uninit(n)?;
4061 e.sigmoid(g, &mut gsig, n)?;
4062 let mut ag = e.uninit(n)?;
4063 e.mul(&attn, &gsig, &mut ag, n)?;
4064 ag
4065 }
4066 None => attn,
4067 };
4068 e.matmul(&fa.wo, &attn_g, t)?
4069 }
4070 Mixer::Linear(la) => {
4071 let ssm = cfg.ssm.as_ref().expect("linear mixer requires ssm cfg");
4072 let d_state = ssm.state_size as usize;
4073 let num_k = ssm.group_count as usize;
4074 let num_v = ssm.time_step_rank as usize;
4075 let d_conv = ssm.conv_kernel as usize;
4076 let key_dim = d_state * num_k;
4077 let value_dim = d_state * num_v;
4078 let conv_dim = key_dim * 2 + value_dim;
4079 let gdn_scale = 1.0 / (d_state as f32).sqrt();
4080
4081 // ---- batched projections: one weight read for all T rows ----
4082 let qkv_mixed = e.matmul_pre(&la.wqkv, &hq, &hd, &xn, t)?;
4083 let z = e.matmul_pre(&la.wqkv_gate, &hq, &hd, &xn, t)?;
4084 let beta_raw = e.matmul_pre(&la.ssm_beta, &hq, &hd, &xn, t)?;
4085 let alpha = e.matmul_pre(&la.ssm_alpha, &hq, &hd, &xn, t)?;
4086 let beta_w = la.ssm_beta.out_features();
4087 let alpha_w = la.ssm_alpha.out_features();
4088 let qkv_w = la.wqkv.out_features();
4089
4090 // ---- per-row state chain through the b_n=1 serving kernels ----
4091 // 6-entry alternating pointer table expresses the ping-pong without a
4092 // rebuild per row: even rows scan s0 -> s1, odd rows s1 -> s0. Host
4093 // handles swap per row so ckpt clones the canonical state (and the
4094 // post-verify canonical handle matches the last write), exactly as the
4095 // rowwise arm leaves them.
4096 let table = {
4097 let rl = cache.recur[il].as_ref().unwrap();
4098 let s = &e.gpu.stream();
4099 let (pc, _g0) = rl.conv_state.device_ptr(s);
4100 let (p0, _g1) = rl.ssm_state.device_ptr(s);
4101 let (p1, _g2) = rl.ssm_state_alt.device_ptr(s);
4102 e.htod_u64(&[
4103 pc as u64, p0 as u64, p1 as u64, pc as u64, p1 as u64, p0 as u64,
4104 ])?
4105 };
4106 let mut o_all = e.uninit(t * value_dim)?;
4107 let mut col_states: Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>> =
4108 if ckpt.is_some() && t >= 2 {
4109 Some(Vec::with_capacity(t - 1))
4110 } else {
4111 None
4112 };
4113 // Per-row scratch reused across rows (uninit is cheap but not free at
4114 // 48 layers x T rows); row inputs/outputs pass as VIEWS into the packed
4115 // [T, ...] buffers — zero arithmetic-free copies in this loop.
4116 let mut conv_out = e.uninit(conv_dim)?;
4117 let mut q_l2 = e.uninit(value_dim)?;
4118 let mut k_l2 = e.uninit(value_dim)?;
4119 let mut v_gd = e.uninit(value_dim)?;
4120 let mut beta_b = e.uninit(num_v)?;
4121 let mut g_log = e.uninit(num_v)?;
4122 for r in 0..t {
4123 let base = if r % 2 == 0 { 0 } else { 3 };
4124 let conv_view = table.slice(base..base + 1);
4125 let in_view = table.slice(base + 1..base + 2);
4126 let out_view = table.slice(base + 2..base + 3);
4127 e.ssm_conv1d_fused_decode_b_view(
4128 &qkv_mixed.slice(r * qkv_w..(r + 1) * qkv_w),
4129 &conv_view,
4130 la.ssm_conv1d.float_data(),
4131 &mut conv_out,
4132 conv_dim,
4133 d_conv,
4134 1,
4135 )?;
4136 e.gdn_prep_decode_b_view(
4137 &conv_out,
4138 &beta_raw.slice(r * beta_w..(r + 1) * beta_w),
4139 &alpha.slice(r * alpha_w..(r + 1) * alpha_w),
4140 la.ssm_dt.float_data(),
4141 la.ssm_a.float_data(),
4142 &mut q_l2,
4143 &mut k_l2,
4144 &mut v_gd,
4145 &mut beta_b,
4146 &mut g_log,
4147 d_state,
4148 num_v,
4149 num_k,
4150 key_dim,
4151 eps,
4152 conv_dim,
4153 1,
4154 )?;
4155 let mut o_row = o_all.slice_mut(r * value_dim..(r + 1) * value_dim);
4156 e.gdn_scan_s128_batched_view(
4157 &q_l2, &k_l2, &v_gd, &g_log, &beta_b, &in_view, &out_view, &mut o_row,
4158 num_v, 1, gdn_scale,
4159 )?;
4160 {
4161 let rl = cache.recur[il].as_mut().unwrap();
4162 std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
4163 }
4164 if r + 1 < t {
4165 if let Some(states) = col_states.as_mut() {
4166 let recur = cache.recur[il]
4167 .as_ref()
4168 .ok_or("qwen35 linear verify layer has no recurrent state")?;
4169 states.push((
4170 e.clone_dtod(&recur.conv_state)?,
4171 e.clone_dtod(&recur.ssm_state)?,
4172 ));
4173 }
4174 }
4175 }
4176 if let (Some(checkpoint), Some(states)) = (ckpt.as_deref_mut(), col_states) {
4177 checkpoint.cols[il] = Some(states);
4178 }
4179
4180 // ---- batched gated norm + out-projection at m=T ----
4181 if e.uses_q8_1_fast(&la.ssm_out) {
4182 let (gq, gd) = e.gated_rmsnorm_q8_1(
4183 &o_all,
4184 la.ssm_norm.float_data(),
4185 &z,
4186 d_state,
4187 t * num_v,
4188 eps,
4189 )?;
4190 let g0 = e.zeros(0)?;
4191 e.matmul_pre(&la.ssm_out, &gq, &gd, &g0, t)?
4192 } else {
4193 let mut gn = e.uninit(t * value_dim)?;
4194 e.gated_rmsnorm(
4195 &o_all,
4196 la.ssm_norm.float_data(),
4197 &z,
4198 &mut gn,
4199 d_state,
4200 t * num_v,
4201 eps,
4202 )?;
4203 e.matmul(&la.ssm_out, &gn, t)?
4204 }
4205 }
4206 };
4207
4208 // ---- residual add + post_attn_norm + FFN at m=T (serving dispatch verbatim) ----
4209 let pnorm = layer.post_attn_norm.float_data();
4210 let mut x1 = e.uninit(t * n_embd)?;
4211 let mut zn = e.uninit(t * n_embd)?;
4212 e.add_rms_norm(&x, &mixed, pnorm, &mut x1, &mut zn, n_embd, t, eps)?;
4213 let ffn_out = match &layer.ffn {
4214 crate::hybrid::Ffn::Dense {
4215 ffn_gate,
4216 ffn_up,
4217 ffn_down,
4218 } => {
4219 assert!(
4220 self.cfg.m3.is_none(),
4221 "qwen35 t-parallel verify: M3 swigluoai FFN not yet batched"
4222 );
4223 let n_ff = ffn_gate.out_features();
4224 let (zq, zd) = e.quantize_q8_1(&zn, t, n_embd)?;
4225 let g = e.matmul_pre(ffn_gate, &zq, &zd, &zn, t)?;
4226 let u = e.matmul_pre(ffn_up, &zq, &zd, &zn, t)?;
4227 let mut act = e.uninit(t * n_ff)?;
4228 e.silu_mul(&g, &u, &mut act, t * n_ff)?;
4229 let (aq, ad) = e.quantize_q8_1(&act, t, n_ff)?;
4230 e.matmul_pre(ffn_down, &aq, &ad, &act, t)?
4231 }
4232 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il_zq8(e, m, &zn, None, t, il as u16)?,
4233 };
4234 let mut x2 = e.uninit(t * n_embd)?;
4235 e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
4236 // dspark drafter tap (no-op when no sink armed): post-layer residual verify rows
4237 self.dflash_tap(e, cache, il, &x2, t)?;
4238 x = x2;
4239 }
4240 Ok(x)
4241 }
4242
4243 /// PP-N STAGE SUBGRAPH of the verify trunk: layers `[lo, hi)` of `decode_step_t_core_stream`'s
4244 /// walk, verbatim. Enters with a MATERIALIZED `[T, n_embd]` residual (no pending fusion pair
4245 /// carried in from outside the range) and exits with the range's final residual materialized
4246 /// (the trailing add executed) — exactly the `decode_layers_eager(lo, hi)` contract, T rows
4247 /// instead of one.
4248 ///
4249 /// EXTRACTED (lane/pp2-spec 2026-08-06) rather than duplicated: `decode_step_t_core_stream` IS
4250 /// the single funnel every verify forward reaches, and its per-layer dispatch MIRRORING (norm
4251 /// fusion per layer, the t>=3/spec_m2 batched-linear window, the fused-q8 FFN chain, the
4252 /// decode-exact projections) is what makes verify bit-identical to eager decode. A second copy
4253 /// for the split arm is how those mirrors drift apart on the next lever. The unsplit body now
4254 /// calls this with `(0, n_layers)`, so the whole-trunk path and every stage range run the SAME
4255 /// code — there is no "split version" of the verify math.
4256 ///
4257 /// Bit-identity of a cut rests on the same kernel-check-pinned identity the eager arm's cut
4258 /// does — `add_rms_norm_q8_1 == add then rms_norm_q8_1` at nrows=T — because the ONLY thing a
4259 /// fence changes is that the cross-layer fusion carry breaks at `hi-1` and is re-materialized
4260 /// as an explicit `add`. `decode-batch-gate --mode ppspec` verifies end-to-end on real weights.
4261 #[allow(clippy::too_many_arguments)]
4262 fn verify_layers(
4263 &self,
4264 e: &Engine,
4265 mut x: CudaSlice<f32>,
4266 lo: usize,
4267 hi: usize,
4268 pos_d: &CudaSlice<i32>,
4269 pos0: usize,
4270 t: usize,
4271 cache: &mut Cache,
4272 mut ckpt: Option<&mut VerifyCkpt>,
4273 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
4274 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
4275 if self.cfg.step35.is_some() {
4276 if stream.is_some() {
4277 return Err(
4278 "step35 has no ROUND-STREAM verify arm (the device-counter _dc twins \
4279 cannot express the SWA offset KV view)"
4280 .into(),
4281 );
4282 }
4283 return self.step35_verify_batch_layers(e, x, lo, hi, pos0, t, cache);
4284 }
4285 if self.qwen35_serving_class() {
4286 if stream.is_some() {
4287 return Err("qwen35-family serving-class verify has no ROUND-STREAM arm".into());
4288 }
4289 return self.qwen35_verify_batch_layers(e, x, lo, hi, pos0, t, cache, ckpt.take());
4290 }
4291 let n_embd = self.cfg.n_embd as usize;
4292 let eps = self.cfg.rms_eps;
4293 // CROSS-LAYER ADD+NORM FUSION (lane/vt-fixes fix 2, mirroring decode_step_h's
4294 // launch-arc form): layer il's post-FFN residual add (x2 = x1 + ffn_out) and layer
4295 // il+1's attn_norm(+quantize) are consecutive row-wise ops — ONE add_rms_norm_q8_1
4296 // launch at nrows=t does all three (bit-identity pinned by the T-row kernel-check
4297 // arms). Carry the un-added (x1, ffn_out) pair; the fused launch materializes x2 (the
4298 // residual the next layer needs) as its `res` output. Falls back to the separate add
4299 // when the next layer is off the fused-q8 path.
4300 let mut pending: Option<(CudaSlice<f32>, CudaSlice<f32>)> = None;
4301 for il in lo..hi {
4302 let layer = &self.layers[il];
4303 // DISPATCH-MIRRORED attn-input RMSNorm (FP-order lesson #8): eager decode fuses the
4304 // 1024-thread rms_norm_q8_1 ONLY when every mixer projection is q8_1-fast; layers with
4305 // Float projections (ssm_beta/ssm_alpha on layers 1/2/4 of the 9B NVFP4 GGUF) take the
4306 // UNFUSED 256-thread rms_norm. The verify norm must mirror that PER-LAYER choice —
4307 // blockDim changes the sum-of-squares reduce order, and the ULP shift amplifies through
4308 // the GDN recurrence into argmax flips (measured: 9B text prompt, 1 ULP at layer 2 ->
4309 // 2.3e-1 logit maxdiff at the head -> K=1..8 divergence at a 0.03-margin token).
4310 let mixer_fast = self.mixer_in_q8_1_fast(e, &layer.mixer);
4311 let norm_fused = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err() && mixer_fast;
4312 // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2, 2026-08-03): when the norm is
4313 // dispatch-fused AND every consumer of `h` reads only its q8_1 form (Full mixer:
4314 // projections only; Linear mixer: the batched arm — the per-column fallback needs
4315 // f32 h), emit the attn-input norm DIRECTLY as q8_1 via `rms_norm_q8_1` at nrows=t
4316 // (row-indexed kernel — the T-row launch is the per-row m=1 program, kernel-check
4317 // pins bit-identity vs rms_norm_decode -> quantize_q8_1). Kills the standalone
4318 // quantize launch(es) + the f32 h HBM round-trip that decode never pays.
4319 // step35 (Full mixer) is the third case that needs f32 `h`: its verify arm is a
4320 // per-ROW replay of the eager decode mixer, whose `pre_q` contract is a single row —
4321 // a T-row q8_1 pair cannot be handed to it, and re-deriving per-row q8_1 from the f32
4322 // rows is exactly the dispatch being mirrored. Keep step35 on the unfused arm.
4323 let lin_q8_only = match &layer.mixer {
4324 Mixer::Linear(la) => {
4325 (t >= 3 || (t == 2 && spec_m2())) && e.uses_q8_1_fast(&la.ssm_out)
4326 }
4327 Mixer::Full(_) if self.cfg.step35.is_some() => false,
4328 _ => true,
4329 };
4330 // NOTE decode.rs's take()-first lesson: take the pending pair BEFORE branching so
4331 // a non-fused layer still performs the residual add.
4332 let taken = pending.take();
4333 let (h, h_q8) = if norm_fused && lin_q8_only {
4334 let pair = match taken {
4335 // fused add + attn_norm + q8_1: ONE launch resolves the carried residual
4336 // AND emits this layer's mixer input pre-quantized. res -> x2 (= new x).
4337 Some((x1p, f1p)) => {
4338 let mut x2 = vbuf(e, t * n_embd)?; // fully written (res output)
4339 let p = e.add_rms_norm_q8_1(
4340 &x1p,
4341 &f1p,
4342 layer.attn_norm.float_data(),
4343 &mut x2,
4344 n_embd,
4345 t,
4346 eps,
4347 )?;
4348 x = x2;
4349 p
4350 }
4351 None => e.rms_norm_q8_1(&x, layer.attn_norm.float_data(), n_embd, t, eps)?,
4352 };
4353 (e.zeros(0)?, Some(pair)) // h unused on this path (q8-only consumers)
4354 } else {
4355 if let Some((x1p, f1p)) = taken {
4356 let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
4357 e.add(&x1p, &f1p, &mut x2, t * n_embd)?;
4358 x = x2;
4359 }
4360 let mut h = vbuf(e, t * n_embd)?; // fully written by either rms_norm arm
4361 if norm_fused {
4362 e.rms_norm_decode(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
4363 } else {
4364 e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
4365 }
4366 (h, None)
4367 };
4368 let h_q8_ref = h_q8.as_ref().map(|(q, d)| (q, d));
4369
4370 let mixed = match &layer.mixer {
4371 Mixer::Full(fa) => self.full_attn_verify(
4372 e,
4373 fa,
4374 &h,
4375 h_q8_ref,
4376 pos_d,
4377 t,
4378 cache,
4379 il,
4380 stream.map(|(_, c)| c),
4381 )?,
4382 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
4383 Mixer::Linear(la) => {
4384 // BATCHED linear verify (2026-07-03, the MTP-profit lever): one T-token pass —
4385 // batched projections (weight read ONCE, hits the m=2-4 weight-resident matvec),
4386 // carried-state conv (ssm_conv1d_tm_state), GDN prep on the prefill kernels, and
4387 // ONE gdn_scan whose internal sequential t-loop is the SAME recurrence as T
4388 // chained T=1 steps (bit-identical). Falls back to the sequential per-column
4389 // chain when T < d_conv-1 (conv ring update needs T >= pad) — or when ANY
4390 // projection is off the q8_1 fast path: matmul_decode_exact would route a Float
4391 // tensor to cuBLAS at m=t (different FP accumulation than eager's per-token
4392 // GEMV), so mixed-dtype layers stay on the eager-identical per-column chain.
4393 // MEMRA_SPEC_M2 (lane/spec-m2): the t==2 batch rides the same arm — the conv
4394 // wrapper handles t<pad with a pure-copy ring rebuild; see spec_m2() header.
4395 if (t >= 3 || (t == 2 && spec_m2()))
4396 && mixer_fast
4397 && e.uses_q8_1_fast(&la.ssm_out)
4398 {
4399 let want = ckpt.is_some();
4400 let (out, stash) =
4401 self.linear_attn_verify_t(e, la, &h, h_q8_ref, t, cache, il, want)?;
4402 if let (Some(ck), Some(st)) = (ckpt.as_deref_mut(), stash) {
4403 ck.gdn[il] = Some(st);
4404 }
4405 out
4406 } else {
4407 let mut out = vbuf(e, t * n_embd)?; // every col written by copy_into
4408 let mut col_states: Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>> =
4409 if ckpt.is_some() && t >= 2 {
4410 Some(Vec::with_capacity(t - 1))
4411 } else {
4412 None
4413 };
4414 for col in 0..t {
4415 let mut h_col = vbuf(e, n_embd)?; // fully written by copy_view_into
4416 let src = h.slice(col * n_embd..(col + 1) * n_embd);
4417 e.copy_view_into(&mut h_col, 0, &src, n_embd)?;
4418 let m_col = self.linear_attn_decode(e, la, &h_col, cache, il)?;
4419 e.copy_into(&mut out, col * n_embd, &m_col, n_embd)?;
4420 // REPLAY-FREE ckpt: clone the chain's ACTUAL state after this column
4421 // (pure dtod — cannot change any computed value). Last column skipped:
4422 // rebuild targets are j <= t-1 columns.
4423 if let Some(cs) = col_states.as_mut() {
4424 if col + 1 < t {
4425 let rl = cache.recur[il].as_ref().unwrap();
4426 cs.push((
4427 e.clone_dtod(&rl.conv_state)?,
4428 e.clone_dtod(&rl.ssm_state)?,
4429 ));
4430 }
4431 }
4432 }
4433 if let (Some(ck), Some(cs)) = (ckpt.as_deref_mut(), col_states) {
4434 // ReplaySSM-assessment instrumentation (2026-07-30): the
4435 // per-column clones are the only true state snapshots left in
4436 // the verify (the batched path stashes INPUTS and replays).
4437 if std::env::var("MEMRA_SPEC_STATS").as_deref() == Ok("1") {
4438 static ONCE: std::sync::Once = std::sync::Once::new();
4439 let bytes: usize =
4440 cs.iter().map(|(c, s)| (c.len() + s.len()) * 4).sum();
4441 ONCE.call_once(|| eprintln!(
4442 "[verify-ckpt] per-column layer il={il}: {} clones, {:.2} MB/layer/round",
4443 cs.len(), bytes as f64 / 1e6));
4444 }
4445 ck.cols[il] = Some(cs);
4446 }
4447 out
4448 }
4449 }
4450 };
4451
4452 // DISPATCH-MIRRORED post-attn norm: eager residual_norm_ffn fuses add+norm+quant
4453 // (1024-thread add_rms_norm_q8_1) only for Dense FFNs whose gate+up are q8_1-fast;
4454 // otherwise (and for MoE) it runs the 256-thread fused add_rms_norm. Mirror per layer.
4455 let ffn_fuse = match &layer.ffn {
4456 crate::hybrid::Ffn::Dense {
4457 ffn_gate, ffn_up, ..
4458 } => {
4459 std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
4460 && e.uses_q8_1_fast(ffn_gate)
4461 && e.uses_q8_1_fast(ffn_up)
4462 }
4463 crate::hybrid::Ffn::Moe(_) => false,
4464 };
4465 // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): on the ffn_fuse path (Dense,
4466 // gate+up q8_1-fast, non-M3) the FFN input is emitted DIRECTLY as q8_1 by ONE
4467 // add_rms_norm_q8_1 launch at nrows=t (row-indexed kernel: the T-row launch is the
4468 // per-row m=1 program; kernel-check pins bit-identity vs the unfused
4469 // add_f32 -> rms_norm_decode -> quantize_q8_1 chain at T=2/4/5/8) — replacing the
4470 // add + rms_norm_decode launches AND the dual/singles' internal re-quantize.
4471 // M3's swigluoai must keep the f32 chain (the fused SwiGLU epilogue encodes plain
4472 // SiLU), mirroring residual_norm_ffn's m3 guard on the decode path.
4473 // step35: same guard per LAYER. A dense FFN's clamp is the SHEXP array (upstream's
4474 // one build_ffn serves dense + shared expert, llama-graph.cpp:1751), and verify MUST
4475 // mirror decode's dispatch or spec self-consistency fails.
4476 let dense_lim = self.cfg.clamp_shexp_at(il as u32);
4477 let fuse_q8 = ffn_fuse && self.cfg.m3.is_none() && dense_lim.is_none();
4478 let mut x1 = vbuf(e, t * n_embd)?; // fully written by add / add_rms_norm*
4479 let mut z = e.zeros(0)?; // replaced below on the unfused arms
4480 let z_q8 = if fuse_q8 {
4481 Some(e.add_rms_norm_q8_1(
4482 &x,
4483 &mixed,
4484 layer.post_attn_norm.float_data(),
4485 &mut x1,
4486 n_embd,
4487 t,
4488 eps,
4489 )?)
4490 } else {
4491 let mut zf = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode / add_rms_norm
4492 if ffn_fuse {
4493 e.add(&x, &mixed, &mut x1, t * n_embd)?;
4494 e.rms_norm_decode(
4495 &x1,
4496 layer.post_attn_norm.float_data(),
4497 &mut zf,
4498 n_embd,
4499 t,
4500 eps,
4501 )?;
4502 } else {
4503 e.add_rms_norm(
4504 &x,
4505 &mixed,
4506 layer.post_attn_norm.float_data(),
4507 &mut x1,
4508 &mut zf,
4509 n_embd,
4510 t,
4511 eps,
4512 )?;
4513 }
4514 z = zf;
4515 None
4516 };
4517 // DECODE-EXACT FFN projections: force MMVQ for gate/up/down at any T to match the
4518 // T=1 decode FP accumulation order. At T>=5 the generic matmul/matmul_pre falls to dp4a
4519 // (128-thread, different FP sum order). At T=2-4 the batched MMVQ is already bit-identical.
4520 let ffn_out = match &layer.ffn {
4521 crate::hybrid::Ffn::Dense {
4522 ffn_gate,
4523 ffn_up,
4524 ffn_down,
4525 } => {
4526 let n_ff = ffn_gate.out_features();
4527 if let Some((zq, zd)) = z_q8.as_ref() {
4528 // FUSED CHAIN (fix 2): pre-quantized z feeds the projections; the SwiGLU
4529 // epilogue emits act pre-quantized for ffn_down (silu_mul_scaled_q8_1,
4530 // bit-identical to silu_mul + quantize — kernel-check-pinned) with the
4531 // NVFP4 macro-scales folded (deferred-scale dual: y*s inline == the
4532 // scale_inplace store, value-exact) — the exact m=1 decode epilogue
4533 // structure at nrows=t.
4534 let pair =
4535 match e.matmul_decode_exact_dual_pre(ffn_gate, ffn_up, zq, zd, t)? {
4536 Some(((g, gs), (u, us))) => Some((g, gs, u, us)),
4537 None => None,
4538 };
4539 let (gate, gs, up, us) = match pair {
4540 Some(x4) => x4,
4541 None => (
4542 e.matmul_decode_exact_pre(ffn_gate, zq, zd, t)?,
4543 1.0, // scale already applied inside _pre
4544 e.matmul_decode_exact_pre(ffn_up, zq, zd, t)?,
4545 1.0,
4546 ),
4547 };
4548 if e.uses_q8_1_fast(ffn_down) {
4549 let (aq, ad) = e.silu_mul_scaled_q8_1(&gate, &up, gs, us, t * n_ff)?;
4550 e.matmul_decode_exact_pre(ffn_down, &aq, &ad, t)?
4551 } else {
4552 let mut act = vbuf(e, t * n_ff)?;
4553 e.silu_mul_scaled(&gate, &up, gs, us, &mut act, t * n_ff)?;
4554 e.matmul_decode_exact(ffn_down, &act, t)?
4555 }
4556 } else {
4557 // UNFUSED (pre-fix) chain — MoE-adjacent/M3/off-fast layers, unchanged.
4558 // DUAL gate+up batched twin (lane/verify-economics, 2026-08-02): one launch
4559 // for the pair at t=2..8 — bit-identical per (tensor,token,row) to the two
4560 // singles (kernel-check pins bitwise; MEMRA_SPEC_DUAL_T=0 reverts). None
4561 // (non-NVFP4 / t outside the tier / seam off) -> the two singles, unchanged.
4562 let (gate, up) =
4563 match e.matmul_decode_exact_dual(ffn_gate, ffn_up, &z, t)? {
4564 Some(pair) => pair,
4565 None => (
4566 e.matmul_decode_exact(ffn_gate, &z, t)?,
4567 e.matmul_decode_exact(ffn_up, &z, t)?,
4568 ),
4569 };
4570 let mut act = vbuf(e, t * n_ff)?; // fully written by ffn_act_lim
4571 Self::ffn_act_lim(
4572 e,
4573 &self.cfg,
4574 &gate,
4575 &up,
4576 1.0,
4577 1.0,
4578 dense_lim,
4579 &mut act,
4580 t * n_ff,
4581 )?;
4582 e.matmul_decode_exact(ffn_down, &act, t)?
4583 }
4584 }
4585 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, t, il as u16)?,
4586 };
4587 // CROSS-LAYER fusion: defer this layer's post-FFN residual add — the next layer's
4588 // fused-q8 attn norm folds it in (add_rms_norm_q8_1 == add; rms_norm; quantize,
4589 // kernel-check-pinned at nrows=T). Non-fused next layers add explicitly above.
4590 pending = Some((x1, ffn_out));
4591 }
4592 // RANGE's final add (no next norm INSIDE the range to fuse with; for the
4593 // whole-trunk call that is the last layer, whose next norm is output_norm — f32-out).
4594 if let Some((x1p, f1p)) = pending.take() {
4595 let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
4596 e.add(&x1p, &f1p, &mut x2, t * n_embd)?;
4597 x = x2;
4598 }
4599 Ok(x)
4600 }
4601 /// BATCHED linear-attn verify (T=K+1): the whole layer in ~10 launches instead of T x the
4602 /// T=1 decode chain (T x ~12 launches + T weight reads of the four projections). The GDN
4603 /// recurrence itself is inherently sequential — gdn_scan_s128 runs its internal t-loop with
4604 /// the SAME per-token math as chained T=1 calls (bit-identical state evolution); everything
4605 /// around it (projections, conv, prep, gated norm, out-proj) batches. Advances conv ring +
4606 /// ssm state exactly like T sequential decode steps.
4607 /// `want_stash`: additionally RETAIN the gdn-scan inputs (pure buffer keep-alives, zero extra
4608 /// kernels) so a partial accept can rebuild the state after any column prefix (REPLAY-FREE).
4609 #[allow(clippy::too_many_arguments)]
4610 fn linear_attn_verify_t(
4611 &self,
4612 e: &Engine,
4613 la: &LinearAttnLayer,
4614 h: &CudaSlice<f32>,
4615 h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
4616 t: usize,
4617 cache: &mut Cache,
4618 il: usize,
4619 want_stash: bool,
4620 ) -> Result<(CudaSlice<f32>, Option<GdnStash>), Box<dyn std::error::Error>> {
4621 let cfg = &self.cfg;
4622 let ssm = cfg.ssm.as_ref().unwrap();
4623 let d_state = ssm.state_size as usize;
4624 let num_k = ssm.group_count as usize;
4625 let num_v = ssm.time_step_rank as usize;
4626 let d_conv = ssm.conv_kernel as usize;
4627 let key_dim = d_state * num_k;
4628 let conv_dim = key_dim * 2 + d_state * num_v;
4629 let eps = cfg.rms_eps;
4630 let scale = 1.0 / (d_state as f32).sqrt();
4631
4632 // DECODE-EXACT projections: matmul_decode_exact forces the MMVQ (warp-per-row, 32-thread)
4633 // accumulation order for EVERY m, matching the T=1 decode path bit-for-bit. The generic
4634 // `matmul` at m>=5 falls to dp4a (128-thread, two-level reduce) which has a different FP
4635 // sum order — ULP differences propagate through gdn_scan and flip argmax on the 27B.
4636 // Q8 TRUNK-FUSION at T=1 (35B: wqkv+wqkv_gate both Q8_0): one fused2 launch, bit-identical
4637 // per (tensor,row) to the two m=1 MMVQ dispatches below — decode-exact contract holds.
4638 // VERIFY-TIER TRUNK FUSION (MEMRA_SPEC_FUSED_T, t=2-4): quantize h ONCE for every
4639 // fused-eligible same-input Q8_0 pair of this layer (35B wqkv+wqkv_gate; 9B
4640 // ssm_beta+ssm_alpha) — each fused2 batched launch then replaces two decode-exact
4641 // calls (each of which re-quantizes the same h + runs its own _b2/_b4 launch).
4642 // Bit-identical per (tensor,token,row) — see spec_fused_t().
4643 // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): `h_q8` = the attn-input norm emitted
4644 // directly as q8_1 by the caller's fused rms_norm_q8_1 (bit-identical to the unfused
4645 // chain, kernel-check-pinned). When present it REPLACES the standalone quantize below
4646 // and feeds every projection; the caller guaranteed all four input projections are
4647 // q8_1-fast. When absent, the old shared-quantize (fused-t window) stands.
4648 let h_q8_t = if h_q8.is_none()
4649 && spec_fused_t()
4650 && (2..=4).contains(&t)
4651 && ((e.uses_q8_1_fast(&la.wqkv) && e.uses_q8_1_fast(&la.wqkv_gate))
4652 || (e.uses_q8_1_fast(&la.ssm_beta) && e.uses_q8_1_fast(&la.ssm_alpha)))
4653 {
4654 Some(e.quantize_q8_1(h, t, cfg.n_embd as usize)?)
4655 } else {
4656 None
4657 };
4658 // one view: the caller's fused-norm q8 or this fn's own shared quantize.
4659 let hq8_any: Option<(&CudaSlice<i8>, &CudaSlice<f32>)> =
4660 h_q8.or(h_q8_t.as_ref().map(|(q, d)| (q, d)));
4661 let (qkv_mixed, z) = {
4662 let mut fused = None;
4663 if t == 1 && e.uses_q8_1_fast(&la.wqkv) && e.uses_q8_1_fast(&la.wqkv_gate) {
4664 let (hq, hd) = e.quantize_q8_1(h, 1, cfg.n_embd as usize)?;
4665 fused = e.matmul_q8_fused2(&la.wqkv, &la.wqkv_gate, &hq, &hd)?;
4666 } else if let Some((hq, hd)) = hq8_any {
4667 if spec_fused_t() && (2..=4).contains(&t) {
4668 fused = e.matmul_q8_fused2_t(&la.wqkv, &la.wqkv_gate, hq, hd, t)?;
4669 }
4670 }
4671 match (fused, hq8_any) {
4672 (Some(pair), _) => pair,
4673 (None, Some((hq, hd))) if h_q8.is_some() => (
4674 e.matmul_decode_exact_pre(&la.wqkv, hq, hd, t)?,
4675 e.matmul_decode_exact_pre(&la.wqkv_gate, hq, hd, t)?,
4676 ),
4677 (None, _) => (
4678 e.matmul_decode_exact(&la.wqkv, h, t)?,
4679 e.matmul_decode_exact(&la.wqkv_gate, h, t)?,
4680 ),
4681 }
4682 };
4683 // beta+alpha DUAL at T=1 (75% of p3 rounds run T=1 verify — p-min chain cuts): the dual
4684 // mr2 kernel is bit-identical per element to the m=1 MMVQ matmul_decode_exact dispatches
4685 // (same warp-per-row body, blockIdx.y picks the weight), so the decode-exact contract
4686 // holds; the run-spec battery is the arbiter. T>1 keeps the per-tensor decode-exact path.
4687 let (beta_raw, alpha) = if t == 1 {
4688 let (hq, hd) = e.quantize_q8_1(h, 1, cfg.n_embd as usize)?;
4689 match e.matmul_pre_dual_noscale(&la.ssm_beta, &la.ssm_alpha, &hq, &hd, 1)? {
4690 Some(((mut b, bs), (mut a, as_))) => {
4691 if bs != 1.0 {
4692 e.scale_inplace(&mut b, bs, la.ssm_beta.out_features())?;
4693 }
4694 if as_ != 1.0 {
4695 e.scale_inplace(&mut a, as_, la.ssm_alpha.out_features())?;
4696 }
4697 (b, a)
4698 }
4699 // Q8_0 fused2 twin (9B stores beta/alpha as Q8_0): DISPATCH-MIRRORS the eager
4700 // decode's beta_alpha closure — the fused body is qmatvec_q8_0_mmvq verbatim,
4701 // bit-identical per row (kernel-check rel=0.00e0 gate), so decode==verify holds.
4702 None => match e.matmul_q8_fused2(&la.ssm_beta, &la.ssm_alpha, &hq, &hd)? {
4703 Some((b, a)) => (b, a),
4704 None => (
4705 e.matmul_decode_exact(&la.ssm_beta, h, 1)?,
4706 e.matmul_decode_exact(&la.ssm_alpha, h, 1)?,
4707 ),
4708 },
4709 }
4710 } else {
4711 // fused-t twin (9B stores beta/alpha as Q8_0): same shared-quantize + one launch
4712 // contract as the wqkv pair above; 35B beta/alpha are Float -> None -> fallback.
4713 let mut nvfp4_fused = None;
4714 let mut q8_fused = None;
4715 if let Some((hq, hd)) = hq8_any {
4716 if t == 3 && std::env::var("MEMRA_NVFP4_AUX_DUAL").as_deref() != Ok("0") {
4717 nvfp4_fused =
4718 e.matmul_decode_exact_dual_pre(&la.ssm_beta, &la.ssm_alpha, hq, hd, t)?;
4719 if nvfp4_fused.is_some() && std::env::var("MEMRA_DEBUG").is_ok() {
4720 static ONCE: std::sync::Once = std::sync::Once::new();
4721 ONCE.call_once(|| {
4722 eprintln!("[memra] NVFP4 beta+alpha batched aux dual ENGAGED (t={t})")
4723 });
4724 }
4725 }
4726 if nvfp4_fused.is_none() && spec_fused_t() && (2..=4).contains(&t) {
4727 q8_fused = e.matmul_q8_fused2_t(&la.ssm_beta, &la.ssm_alpha, hq, hd, t)?;
4728 }
4729 }
4730 if let Some(((mut b, bs), (mut a, as_))) = nvfp4_fused {
4731 if bs != 1.0 {
4732 e.scale_inplace(&mut b, bs, t * la.ssm_beta.out_features())?;
4733 }
4734 if as_ != 1.0 {
4735 e.scale_inplace(&mut a, as_, t * la.ssm_alpha.out_features())?;
4736 }
4737 (b, a)
4738 } else if let Some(pair) = q8_fused {
4739 pair
4740 } else {
4741 match hq8_any {
4742 Some((hq, hd)) if h_q8.is_some() => (
4743 e.matmul_decode_exact_pre(&la.ssm_beta, hq, hd, t)?,
4744 e.matmul_decode_exact_pre(&la.ssm_alpha, hq, hd, t)?,
4745 ),
4746 _ => (
4747 e.matmul_decode_exact(&la.ssm_beta, h, t)?,
4748 e.matmul_decode_exact(&la.ssm_alpha, h, t)?,
4749 ),
4750 }
4751 }
4752 };
4753
4754 // conv with CARRIED state + ring roll (T >= pad rides the input-column update kernel;
4755 // T < pad — the MEMRA_SPEC_M2 t=2 arm — rolls via the pure-copy ring rebuild).
4756 let rl = cache.recur[il].as_mut().unwrap();
4757 let mut conv_out = e.uninit(conv_dim * t)?;
4758 e.ssm_conv1d_tm_state(
4759 &qkv_mixed,
4760 &mut rl.conv_state,
4761 la.ssm_conv1d.float_data(),
4762 &mut conv_out,
4763 conv_dim,
4764 t,
4765 d_conv,
4766 )?;
4767
4768 // GDN prep via the prefill kernels (repack + L2 + sigmoid + glog), T-wide.
4769 let mut q_g = e.uninit(d_state * num_v * t)?;
4770 let mut k_g = e.uninit(d_state * num_v * t)?;
4771 let mut v_g = e.uninit(d_state * num_v * t)?;
4772 e.qkv_to_gdn_repack(
4773 &conv_out, &mut q_g, &mut k_g, &mut v_g, d_state, num_v, num_k, key_dim, t,
4774 )?;
4775 let mut q_l2 = e.uninit(d_state * num_v * t)?;
4776 e.l2_norm_decode(&q_g, &mut q_l2, d_state, num_v * t, eps)?;
4777 let mut k_l2 = e.uninit(d_state * num_v * t)?;
4778 e.l2_norm_decode(&k_g, &mut k_l2, d_state, num_v * t, eps)?;
4779 let mut beta = e.uninit(t * num_v)?;
4780 e.sigmoid(&beta_raw, &mut beta, t * num_v)?;
4781 let mut g_log = e.uninit(t * num_v)?;
4782 e.gdn_glog(
4783 &alpha,
4784 la.ssm_dt.float_data(),
4785 la.ssm_a.float_data(),
4786 &mut g_log,
4787 num_v,
4788 t,
4789 )?;
4790
4791 // ONE gdn_scan over T tokens from the carried state (internal sequential loop ==
4792 // T chained T=1 steps). Ping-pong the resident buffers like eager decode.
4793 let mut o = e.uninit(d_state * num_v * t)?;
4794 {
4795 let crate::cache::RecurLayer {
4796 ssm_state,
4797 ssm_state_alt,
4798 ..
4799 } = rl;
4800 e.gdn_scan_s128(
4801 &q_l2,
4802 &k_l2,
4803 &v_g,
4804 &g_log,
4805 &beta,
4806 ssm_state,
4807 ssm_state_alt,
4808 &mut o,
4809 num_v,
4810 t,
4811 scale,
4812 )?;
4813 }
4814 std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
4815
4816 // gated RMSNorm + out projection, T-wide. FUSED-QUANTIZE ARM (lane/vt-fixes fix 2,
4817 // mirroring the T=1 decode's launch-arc form): when ssm_out rides the q8_1 fast path,
4818 // emit q8_1 straight from the gated norm at nrows=num_v*t (row-indexed kernel, the
4819 // T-wide launch is the per-row program; kernel-check pins bit-identity vs
4820 // gated_rmsnorm -> quantize_q8_1 at T=1 and T=5) and feed the decode-exact dispatch
4821 // pre-quantized — one launch replaces norm + quantize. Fallback = the f32 chain.
4822 let out = if e.uses_q8_1_fast(&la.ssm_out) {
4823 let (gq, gd) =
4824 e.gated_rmsnorm_q8_1(&o, la.ssm_norm.float_data(), &z, d_state, num_v * t, eps)?;
4825 e.matmul_decode_exact_pre(&la.ssm_out, &gq, &gd, t)?
4826 } else {
4827 let mut gn = e.uninit(d_state * num_v * t)?;
4828 e.gated_rmsnorm(
4829 &o,
4830 la.ssm_norm.float_data(),
4831 &z,
4832 &mut gn,
4833 d_state,
4834 num_v * t,
4835 eps,
4836 )?;
4837 // DECODE-EXACT out-projection: same MMVQ path as the T=1 decode (ssm_out at m>=5
4838 // would fall to dp4a with a different FP reduction order — same class of bug as
4839 // the input projs).
4840 e.matmul_decode_exact(&la.ssm_out, &gn, t)?
4841 };
4842 let stash = if want_stash {
4843 Some(GdnStash {
4844 qkv_mixed,
4845 q_l2,
4846 k_l2,
4847 v_g,
4848 g_log,
4849 beta,
4850 })
4851 } else {
4852 None
4853 };
4854 Ok((out, stash))
4855 }
4856
4857 /// REPLAY-FREE partial-accept commit (2026-07-03): make the cache state == "committed through
4858 /// the first `j` verify columns" WITHOUT the legacy rollback + duplicate trunk replay.
4859 /// - Full-attn KV: truncate len to snapshot + j. The verify's appended rows for those columns
4860 /// are bit-identical to what an eager T=1 chain writes (the decode-exact contract the
4861 /// verify-probe gates), so keeping them == replaying them.
4862 /// - Linear layers, batched path: rebuild the conv ring by PURE COPIES (ring holds raw input
4863 /// columns) and the ssm state by a prefix re-run of the SAME gdn_scan kernel (t=j) from the
4864 /// snapshot state over the stash's identical inputs — the kernel's t-loop carries state in
4865 /// registers and writes it once at the end, so iterations 0..j-1 are independent of T:
4866 /// bit-identical to the verify's own state after j tokens == the eager chain state.
4867 /// - Linear layers, per-column path: restore the cloned actual state after column j-1.
4868 /// Caller guarantees 1 <= j <= t-1 (j==0 rounds take the legacy rollback; j==t is full accept).
4869 fn commit_verified_prefix(
4870 &self,
4871 e: &Engine,
4872 cache: &mut Cache,
4873 snap: &crate::cache::CacheSnapshot,
4874 ckpt: &VerifyCkpt,
4875 j: usize,
4876 kv_lens_done: bool,
4877 dev_j: Option<(&CudaSlice<u32>, usize, usize)>,
4878 ) -> Result<(), Box<dyn std::error::Error>> {
4879 let cfg = &self.cfg;
4880 let ssm = cfg.ssm.as_ref().unwrap();
4881 let d_state = ssm.state_size as usize;
4882 let num_k = ssm.group_count as usize;
4883 let num_v = ssm.time_step_rank as usize;
4884 let d_conv = ssm.conv_kernel as usize;
4885 let conv_dim = d_state * num_k * 2 + d_state * num_v;
4886 let scale = 1.0 / (d_state as f32).sqrt();
4887 for il in 0..self.layers.len() {
4888 if let (Some(kvl), Some(saved)) = (cache.kv[il].as_mut(), snap.kv_len[il]) {
4889 kvl.len = saved + j;
4890 // devacc 3a: spec_rollback_kv already wrote len_d on-device (same value).
4891 if !kv_lens_done {
4892 e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
4893 }
4894 }
4895 if let Some(rl) = cache.recur[il].as_mut() {
4896 if let Some(st) = &ckpt.gdn[il] {
4897 let ring_old = snap.conv[il].as_ref().expect("snapshot missing conv");
4898 let state_in = snap.ssm[il].as_ref().expect("snapshot missing ssm");
4899 if let Some((acc, base, t_v)) = dev_j {
4900 // 3b: j read on-device (_dc twins, same bodies; full accept early-exits).
4901 e.ssm_conv_ring_rebuild_dc(
4902 &st.qkv_mixed,
4903 ring_old,
4904 &mut rl.conv_state,
4905 conv_dim,
4906 acc,
4907 base,
4908 t_v,
4909 d_conv,
4910 )?;
4911 let mut o = e.uninit(d_state * num_v * j.max(1))?;
4912 e.gdn_scan_s128_dc(
4913 &st.q_l2,
4914 &st.k_l2,
4915 &st.v_g,
4916 &st.g_log,
4917 &st.beta,
4918 state_in,
4919 &mut rl.ssm_state,
4920 &mut o,
4921 num_v,
4922 acc,
4923 base,
4924 t_v,
4925 scale,
4926 )?;
4927 } else {
4928 e.ssm_conv_ring_rebuild(
4929 &st.qkv_mixed,
4930 ring_old,
4931 &mut rl.conv_state,
4932 conv_dim,
4933 j,
4934 d_conv,
4935 )?;
4936 let mut o = e.uninit(d_state * num_v * j)?; // scan output, discarded
4937 e.gdn_scan_s128(
4938 &st.q_l2,
4939 &st.k_l2,
4940 &st.v_g,
4941 &st.g_log,
4942 &st.beta,
4943 state_in,
4944 &mut rl.ssm_state,
4945 &mut o,
4946 num_v,
4947 j,
4948 scale,
4949 )?;
4950 }
4951 } else if let Some(cols) = &ckpt.cols[il] {
4952 let (c, s) = &cols[j - 1];
4953 e.copy_into(&mut rl.conv_state, 0, c, c.len())?;
4954 e.copy_into(&mut rl.ssm_state, 0, s, s.len())?;
4955 } else {
4956 return Err(
4957 "commit_verified_prefix: verify ckpt missing for linear layer".into(),
4958 );
4959 }
4960 }
4961 }
4962 cache.pos = snap.pos + j;
4963 Ok(())
4964 }
4965
4966 /// ROUND-STREAM: recur restore with device-j (the _dc twins; full accept early-exits
4967 /// in-kernel). Requires the batched-linear stash on every linear layer (stream gate).
4968 fn commit_verified_prefix_stream(
4969 &self,
4970 e: &Engine,
4971 cache: &mut Cache,
4972 snap: &crate::cache::CacheSnapshot,
4973 ckpt: &VerifyCkpt,
4974 acc: &CudaSlice<u32>,
4975 base: usize,
4976 t_v: usize,
4977 ) -> Result<(), Box<dyn std::error::Error>> {
4978 let cfg = &self.cfg;
4979 let ssm = cfg.ssm.as_ref().unwrap();
4980 let d_state = ssm.state_size as usize;
4981 let num_k = ssm.group_count as usize;
4982 let num_v = ssm.time_step_rank as usize;
4983 let d_conv = ssm.conv_kernel as usize;
4984 let conv_dim = d_state * num_k * 2 + d_state * num_v;
4985 let scale = 1.0 / (d_state as f32).sqrt();
4986 for il in 0..self.layers.len() {
4987 if let Some(rl) = cache.recur[il].as_mut() {
4988 let st = ckpt.gdn[il]
4989 .as_ref()
4990 .ok_or("stream restore: batched-linear stash missing")?;
4991 let ring_old = snap.conv[il].as_ref().expect("snapshot missing conv");
4992 let state_in = snap.ssm[il].as_ref().expect("snapshot missing ssm");
4993 e.ssm_conv_ring_rebuild_dc(
4994 &st.qkv_mixed,
4995 ring_old,
4996 &mut rl.conv_state,
4997 conv_dim,
4998 acc,
4999 base,
5000 t_v,
5001 d_conv,
5002 )?;
5003 let mut o = e.uninit(d_state * num_v * t_v)?;
5004 e.gdn_scan_s128_dc(
5005 &st.q_l2,
5006 &st.k_l2,
5007 &st.v_g,
5008 &st.g_log,
5009 &st.beta,
5010 state_in,
5011 &mut rl.ssm_state,
5012 &mut o,
5013 num_v,
5014 acc,
5015 base,
5016 t_v,
5017 scale,
5018 )?;
5019 }
5020 }
5021 Ok(())
5022 }
5023
5024 /// EAGLE3 aux-capturing verify forward over `tokens` (T) — mirrors `decode_step_t_h` exactly
5025 /// (same KV append, same causal verify, same recur advance) but ALSO clones the aux residual-
5026 /// stream hiddens (blocks in `aux_layers`) for TWO columns: the LAST column (always) and the
5027 /// optional `pred_col` (the EAGLE seed = bonus's predecessor). Returns
5028 /// (all_T_logits host, last_col_aux, pred_col_aux?). Used by the EAGLE3 orchestrator's commit.
5029 pub fn decode_step_t_aux2(
5030 &self,
5031 e: &Engine,
5032 tokens: &[u32],
5033 pos0: usize,
5034 cache: &mut Cache,
5035 aux_layers: &[usize],
5036 pred_col: Option<usize>,
5037 ) -> Result<
5038 (Vec<f32>, Vec<CudaSlice<f32>>, Option<Vec<CudaSlice<f32>>>),
5039 Box<dyn std::error::Error>,
5040 > {
5041 let cfg = &self.cfg;
5042 let n_embd = cfg.n_embd as usize;
5043 let eps = cfg.rms_eps;
5044 let t = tokens.len();
5045 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
5046 let pos_d = e.htod_i32(&pos_vec)?;
5047 let mut x = e.htod(&self.embd.gather(n_embd, tokens))?;
5048 let mut aux_last: Vec<CudaSlice<f32>> = Vec::with_capacity(aux_layers.len());
5049 let mut aux_pred: Vec<CudaSlice<f32>> = Vec::new();
5050 let want_pred = pred_col.is_some();
5051
5052 for (il, layer) in self.layers.iter().enumerate() {
5053 // DISPATCH-MIRRORED norms (FP-order lesson #8) — see decode_step_t_h_emb.
5054 let mixer_fast = self.mixer_in_q8_1_fast(e, &layer.mixer);
5055 let norm_fused = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err() && mixer_fast;
5056 let mut h = vbuf(e, t * n_embd)?; // fully written by either rms_norm arm
5057 if norm_fused {
5058 e.rms_norm_decode(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
5059 } else {
5060 e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
5061 }
5062 let mixed = match &layer.mixer {
5063 Mixer::Full(fa) => {
5064 self.full_attn_verify(e, fa, &h, None, &pos_d, t, cache, il, None)?
5065 }
5066 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
5067 Mixer::Linear(la) => {
5068 let mut out = e.zeros(t * n_embd)?;
5069 for col in 0..t {
5070 let mut h_col = e.zeros(n_embd)?;
5071 let src = h.slice(col * n_embd..(col + 1) * n_embd);
5072 e.copy_view_into(&mut h_col, 0, &src, n_embd)?;
5073 let m_col = self.linear_attn_decode(e, la, &h_col, cache, il)?;
5074 e.copy_into(&mut out, col * n_embd, &m_col, n_embd)?;
5075 }
5076 out
5077 }
5078 };
5079 let ffn_fuse = match &layer.ffn {
5080 crate::hybrid::Ffn::Dense {
5081 ffn_gate, ffn_up, ..
5082 } => {
5083 std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
5084 && e.uses_q8_1_fast(ffn_gate)
5085 && e.uses_q8_1_fast(ffn_up)
5086 }
5087 crate::hybrid::Ffn::Moe(_) => false,
5088 };
5089 let mut x1 = vbuf(e, t * n_embd)?; // fully written by add / add_rms_norm
5090 let mut z = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode / add_rms_norm
5091 if ffn_fuse {
5092 e.add(&x, &mixed, &mut x1, t * n_embd)?;
5093 e.rms_norm_decode(
5094 &x1,
5095 layer.post_attn_norm.float_data(),
5096 &mut z,
5097 n_embd,
5098 t,
5099 eps,
5100 )?;
5101 } else {
5102 e.add_rms_norm(
5103 &x,
5104 &mixed,
5105 layer.post_attn_norm.float_data(),
5106 &mut x1,
5107 &mut z,
5108 n_embd,
5109 t,
5110 eps,
5111 )?;
5112 }
5113 let ffn_out = match &layer.ffn {
5114 crate::hybrid::Ffn::Dense {
5115 ffn_gate,
5116 ffn_up,
5117 ffn_down,
5118 } => {
5119 let n_ff = ffn_gate.out_features();
5120 let gate = e.matmul_decode_exact(ffn_gate, &z, t)?;
5121 let up = e.matmul_decode_exact(ffn_up, &z, t)?;
5122 let mut act = vbuf(e, t * n_ff)?; // fully written by ffn_act_lim
5123 // dense FFN clamp = the SHEXP array (upstream build_ffn serves both).
5124 Self::ffn_act_lim(
5125 e,
5126 &self.cfg,
5127 &gate,
5128 &up,
5129 1.0,
5130 1.0,
5131 self.cfg.clamp_shexp_at(il as u32),
5132 &mut act,
5133 t * n_ff,
5134 )?;
5135 e.matmul_decode_exact(ffn_down, &act, t)?
5136 }
5137 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, t, il as u16)?,
5138 };
5139 let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
5140 e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
5141 if aux_layers.contains(&il) {
5142 let mut a = e.zeros(n_embd)?;
5143 e.copy_view_into(&mut a, 0, &x2.slice((t - 1) * n_embd..t * n_embd), n_embd)?;
5144 aux_last.push(a);
5145 if let Some(pc) = pred_col {
5146 let mut ap = e.zeros(n_embd)?;
5147 e.copy_view_into(
5148 &mut ap,
5149 0,
5150 &x2.slice(pc * n_embd..(pc + 1) * n_embd),
5151 n_embd,
5152 )?;
5153 aux_pred.push(ap);
5154 }
5155 }
5156 x = x2;
5157 }
5158 let mut hn = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode
5159 e.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
5160 let logits = e.matmul_decode_exact(&self.output, &hn, t)?;
5161 let host = e.dtoh(&logits)?;
5162 cache.pos += t;
5163 Ok((
5164 host,
5165 aux_last,
5166 if want_pred { Some(aux_pred) } else { None },
5167 ))
5168 }
5169
5170 /// step35 SPEC-VERIFY attention over T query tokens — a per-row REPLAY of the eager
5171 /// `step35_decode_attn`.
5172 ///
5173 /// WHY A REPLAY AND NOT A BATCHED TWIN. The verify's whole job is to be bit-identical to what
5174 /// the eager decode would have computed for the same tokens; that is what makes greedy spec
5175 /// decode exact (run-spec asserts token identity for K=1..8). Every other verify arm in this
5176 /// file earns that identity by carefully mirroring dispatch (`matmul_decode_exact` to force
5177 /// MMVQ at any m, per-layer `ffn_fuse` mirroring, per-row `fa_decode` key bounds). step35
5178 /// stacks FOUR more per-layer degrees of freedom on top of that — per-layer `n_head`
5179 /// (64 full / 96 SWA), per-layer rotary width (64 full / 128 SWA), per-layer rope base, and a
5180 /// SEPARATE `attn_gate` tensor whose projection shares the attn-normed input — and its SWA
5181 /// layers attend through a token-OFFSET view whose offset is a function of the ABSOLUTE
5182 /// position of each query row. A batched twin would have to reproduce all of that AND the
5183 /// per-row offset in one launch; the offset alone rules out the existing rows kernels (they
5184 /// take one `base_len`, not a per-row offset).
5185 ///
5186 /// So this arm calls the eager path itself, once per row, on the same cache. Identity is then
5187 /// true BY CONSTRUCTION rather than by mirroring: row r runs exactly the kernel sequence that
5188 /// eager decode step r runs (same projections, same q8_1 fusion decision, same append, same
5189 /// view arithmetic, same `fa_decode_kvmod`, same gate), because it IS that code. Cost: T x the
5190 /// eager decode mixer instead of one batched pass — the same trade the generic arm's `else`
5191 /// per-row loop already accepts when `fa_rows_eligible` says no. Correctness first; a batched
5192 /// step35 twin is a perf lane's job and must be gated against this arm.
5193 ///
5194 /// The `h_q8` pre-quantized pair from the caller's fused norm is NOT forwarded: it is a
5195 /// T-row buffer and `step35_decode_attn`'s `pre_q` contract is one row. Instead each row's
5196 /// f32 `h` slice is handed over and the callee re-derives its own q8_1 exactly as eager decode
5197 /// does (`quantize_q8_1(h, 1, n_embd)`) — which is the dispatch being mirrored. Callers that
5198 /// took the fused arm therefore MUST still pass a live `h`; `step35_verify` asserts that.
5199 #[allow(clippy::too_many_arguments)]
5200 fn step35_verify(
5201 &self,
5202 e: &Engine,
5203 fa: &FullAttnLayer,
5204 h: &CudaSlice<f32>,
5205 h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
5206 t: usize,
5207 cache: &mut Cache,
5208 il: usize,
5209 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5210 let n_embd = self.cfg.n_embd as usize;
5211 // The fused (h-less) attn-norm arm hands `h` as a zero-length placeholder. This arm needs
5212 // the f32 rows, so the caller must not take that lever for step35 — enforced at the call
5213 // site by the `Mixer::Full(_) if self.cfg.step35.is_some() => false` arm of
5214 // `lin_q8_only` in `decode_step_t_core_stream`, and asserted here so a future caller
5215 // cannot regress it into silently reading an empty buffer.
5216 assert_eq!(
5217 h.len(),
5218 t * n_embd,
5219 "step35_verify needs the f32 attn-normed rows ([t*n_embd]); the caller took the \
5220 fused q8-only norm arm (h_q8={}) — step35 must stay on the unfused arm",
5221 h_q8.is_some()
5222 );
5223 // ROW WIDTH IS n_embd, NOT n_head*head_dim: `step35_decode_attn` returns the mixer output
5224 // AFTER `wo`, so a row is [n_embd] — the same contract the generic arm's
5225 // `matmul_decode_exact(&fa.wo, &attn_g, t)` return has. Sizing this buffer from the
5226 // per-layer head geometry (8192 on full-attn, 12288 on SWA) instead overran the row on the
5227 // FIRST copy and panicked inside `copy_into`'s `CudaView::slice` unwrap
5228 // (raw/mtp-bt-20260806T212127Z.log frames 12-13).
5229 let mut out = vbuf(e, t * n_embd)?; // each row fully written by the copy below
5230 for r in 0..t {
5231 // Absolute position of this query row. `cache.pos` is the committed length at round
5232 // start and every row before r has already been appended by this loop, so the r-th
5233 // verify token sits at cache.pos + r — the same position eager decode would give it.
5234 let pos_d = e.htod_i32(&[(cache.pos + r) as i32])?;
5235 let mut h_row = vbuf(e, n_embd)?; // fully written by copy_view_into
5236 e.copy_view_into(
5237 &mut h_row,
5238 0,
5239 &h.slice(r * n_embd..(r + 1) * n_embd),
5240 n_embd,
5241 )?;
5242 // THE eager decode mixer: appends this row's K/V at kvl.len, advances it, then
5243 // attends over the (SWA-offset) view. Post-`wo`, same contract as this fn returns.
5244 let o = self.step35_decode_attn(e, fa, il, &h_row, None, &pos_d, cache)?;
5245 debug_assert_eq!(
5246 o.len(),
5247 n_embd,
5248 "step35_decode_attn returns post-wo [n_embd]"
5249 );
5250 e.copy_into(&mut out, r * n_embd, &o, n_embd)?;
5251 }
5252 Ok(out)
5253 }
5254
5255 /// Full-attention mixer over T query tokens with a GROWING resident KV (verify path, §D.3).
5256 /// Appends the T new K/V columns to cache.kv[il] then attends causally over [0..len) via
5257 /// fa_prefill. Token-major [T, kv_dim] projection layout == cache row layout (single copy).
5258 #[allow(clippy::too_many_arguments)]
5259 fn full_attn_verify(
5260 &self,
5261 e: &Engine,
5262 fa: &FullAttnLayer,
5263 h: &CudaSlice<f32>,
5264 h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
5265 pos_d: &CudaSlice<i32>,
5266 t: usize,
5267 cache: &mut Cache,
5268 il: usize,
5269 stream_ctr: Option<&CudaSlice<i32>>,
5270 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5271 // step35: the generic geometry below is wrong for this arch (per-layer n_head, partial
5272 // per-layer rope, the SWA offset view, and a SEPARATE head-wise gate tensor), so it takes
5273 // its own arm. A verify that silently computes different attention than decode defeats the
5274 // whole self-consistency gate, so the arm is a per-row REPLAY of `step35_decode_attn`
5275 // rather than a batched twin — see `step35_verify` for why that is the exactness-correct
5276 // shape and not laziness.
5277 if self.cfg.step35.is_some() {
5278 if stream_ctr.is_some() {
5279 return Err(
5280 "step35 has no ROUND-STREAM verify arm (the device-counter _dc twins \
5281 cannot express the SWA offset KV view; same root cause as the dc \
5282 decode refusal) — run spec without the stream arm"
5283 .into(),
5284 );
5285 }
5286 return self.step35_verify(e, fa, h, h_q8, t, cache, il);
5287 }
5288 let cfg = &self.cfg;
5289 let geometry = cfg.full_attention_geometry_at(il as u32);
5290 let n_head = geometry.n_head as usize;
5291 let n_head_kv = geometry.n_head_kv as usize;
5292 let head_dim = geometry.head_dim_k as usize;
5293 let eps = cfg.rms_eps;
5294 let scale = geometry.attention_scale();
5295 let n_embd = cfg.n_embd as usize;
5296
5297 // DECODE-EXACT Q/K/V projections: matmul_decode_exact forces the MMVQ (warp-per-row) path
5298 // for every m, matching the T=1 decode's FP accumulation order. matmul_pre at m>=5 would
5299 // fall to dp4a (128-thread, two-level reduce) with a different FP sum order.
5300 // Q8 TRUNK-FUSION at T=1: DISPATCH-MIRRORS the eager decode's fused3 (bit-identical body).
5301 // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): `h_q8` = the attn-input norm's q8_1
5302 // form emitted by the fused rms_norm_q8_1 (bit-identical to rms_norm_decode ->
5303 // quantize_q8_1, kernel-check-pinned). When present (caller checked mixer q8_1-fast),
5304 // every projection consumes it — `h` may be a zero-len placeholder and must not be read.
5305 let (qf, mut k, v) = {
5306 let mut fused = None;
5307 let qkv_fast =
5308 e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk) && e.uses_q8_1_fast(&fa.wv);
5309 if t == 1 && qkv_fast {
5310 let (hq_o, hd_o);
5311 let (hq, hd): (&CudaSlice<i8>, &CudaSlice<f32>) = match h_q8 {
5312 Some(p) => p,
5313 None => {
5314 (hq_o, hd_o) = e.quantize_q8_1(h, 1, n_embd)?;
5315 (&hq_o, &hd_o)
5316 }
5317 };
5318 fused = e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, hq, hd)?;
5319 } else if spec_fused_t() && (2..=4).contains(&t) && qkv_fast {
5320 // VERIFY-TIER TRUNK FUSION (MEMRA_SPEC_FUSED_T): one shared quantize + one
5321 // fused3 batched launch replaces three decode-exact calls (3 re-quantizes of
5322 // the same h + 3 _b2/_b4 launches). Bit-identical per (tensor,token,row).
5323 let (hq_o, hd_o);
5324 let (hq, hd): (&CudaSlice<i8>, &CudaSlice<f32>) = match h_q8 {
5325 Some(p) => p,
5326 None => {
5327 (hq_o, hd_o) = e.quantize_q8_1(h, t, n_embd)?;
5328 (&hq_o, &hd_o)
5329 }
5330 };
5331 fused = e.matmul_q8_fused3_t(&fa.wq, &fa.wk, &fa.wv, hq, hd, t)?;
5332 }
5333 match (fused, h_q8) {
5334 (Some(triple), _) => triple,
5335 // shared pre-quantized activation (q8_1-fast guaranteed by the caller): the
5336 // decode-exact dispatch consumes (hq, hd) instead of re-quantizing 3x.
5337 (None, Some((hq, hd))) if qkv_fast => (
5338 e.matmul_decode_exact_pre(&fa.wq, hq, hd, t)?,
5339 e.matmul_decode_exact_pre(&fa.wk, hq, hd, t)?,
5340 e.matmul_decode_exact_pre(&fa.wv, hq, hd, t)?,
5341 ),
5342 (None, _) => (
5343 e.matmul_decode_exact(&fa.wq, h, t)?,
5344 e.matmul_decode_exact(&fa.wk, h, t)?,
5345 e.matmul_decode_exact(&fa.wv, h, t)?,
5346 ),
5347 }
5348 };
5349 // M3/Hy3 have no attention output gate — wq out is exactly q; skip the split.
5350 let gated = geometry.attention_gate == memra_gguf::config::AttentionGateKind::FusedQ;
5351 let (mut q, gate) = if gated {
5352 let mut q = vbuf(e, t * n_head * head_dim)?; // fully written by q_gate_split
5353 let mut gate = vbuf(e, t * n_head * head_dim)?; // fully written by q_gate_split
5354 e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, t)?;
5355 (q, Some(gate))
5356 } else {
5357 (qf, None)
5358 };
5359
5360 let mut qn = vbuf(e, t * n_head * head_dim)?; // fully written by rms_norm
5361 e.rms_norm(
5362 &q,
5363 fa.q_norm.float_data(),
5364 &mut qn,
5365 head_dim,
5366 n_head * t,
5367 eps,
5368 )?;
5369 q = qn;
5370 let mut kn = vbuf(e, t * n_head_kv * head_dim)?; // fully written by rms_norm
5371 e.rms_norm(
5372 &k,
5373 fa.k_norm.float_data(),
5374 &mut kn,
5375 head_dim,
5376 n_head_kv * t,
5377 eps,
5378 )?;
5379 k = kn;
5380 let rope_dims = geometry.n_rot as usize;
5381 e.rope_neox(
5382 &mut q,
5383 pos_d,
5384 head_dim,
5385 rope_dims,
5386 n_head,
5387 t,
5388 geometry.rope_base,
5389 1.0,
5390 )?;
5391 e.rope_neox(
5392 &mut k,
5393 pos_d,
5394 head_dim,
5395 rope_dims,
5396 n_head_kv,
5397 t,
5398 geometry.rope_base,
5399 1.0,
5400 )?;
5401
5402 // append T new K/V columns to the resident QUANTIZED cache. k/v are token-major [T, kv_dim]
5403 // f32; append-quantize each of the T token rows into the byte cache (q8_0 K / q5_1 V).
5404 let kvl = cache.kv[il].as_mut().unwrap();
5405 let (kv_dim_k, kv_dim_v, ktb, vtb) =
5406 (kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes, kvl.v_tok_bytes);
5407 if let Some(ctr) = stream_ctr {
5408 // stream: ONE batched append at the device counter (rows kernel = the per-view warp
5409 // math on a (block, token) grid, documented byte-identical); host len is a stale
5410 // LOWER BOUND under pre-issue (drain reconciles it).
5411 e.append_kv_quantized_rows_dc(
5412 &k,
5413 &v,
5414 &mut kvl.k,
5415 &mut kvl.v,
5416 ctr,
5417 t,
5418 kv_dim_k,
5419 kv_dim_v,
5420 ktb,
5421 vtb,
5422 crate::Engine::kv_fp8_on(),
5423 )?;
5424 } else {
5425 for i in 0..t {
5426 let k_row = k.slice(i * kv_dim_k..(i + 1) * kv_dim_k);
5427 let v_row = v.slice(i * kv_dim_v..(i + 1) * kv_dim_v);
5428 e.append_kv_quantized_view(
5429 &k_row,
5430 &v_row,
5431 &mut kvl.k,
5432 &mut kvl.v,
5433 kvl.len + i,
5434 kv_dim_k,
5435 kv_dim_v,
5436 ktb,
5437 vtb,
5438 crate::Engine::kv_fp8_on(),
5439 )?;
5440 }
5441 kvl.len += t;
5442 }
5443
5444 // BIT-IDENTICAL VERIFY ATTENTION (spec-exactness fix): the FP accumulation order must be
5445 // byte-for-byte identical to the eager decode path. fa_prefill uses a different tile size
5446 // (BLOCK_Q=64, BK=32) and online-softmax structure than fa_decode's split-K + combine,
5447 // which changes FP summation order and can flip argmax at tight logit margins. Query row r
5448 // attends to keys [0..base_len+r+1) — each successive row sees one more key (the causal
5449 // property). This matches eager: decode appends k at len, then fa_decode sees t_kv = len+1
5450 // keys. The verify appends all T tokens first but bounds the key range per row.
5451 //
5452 // MULTI-ROW FUSED PATH (the long-ctx spec fix, 2026-07-03): when every row takes the vec
5453 // kernel (base_len+1 >= FA_VEC_MIN_TKV), ONE fa_decode_rows launch executes the exact
5454 // per-row program for all T rows (grid.z = row, per-row n_splits from the same
5455 // fa_split_keys formula) — replacing T x (2 launches + 2 dtod copies + 5 partial allocs)
5456 // and multiplying resident CTAs by T on a latency-bound kernel. Bit-identical per row by
5457 // construction; kernel-check pins rows-vs-loop byte identity, run-spec is the end gate.
5458 // Short ctx (any row below the vec crossover) and MEMRA_NO_FA_VEC/MEMRA_FA_ROWS_OFF keep the
5459 // per-row loop (whose fa_decode picks scalar/vec per row exactly like eager decode).
5460 let mut attn = vbuf(e, t * n_head * head_dim)?; // fully written by every FA arm below
5461 let base_len = kvl.len - t; // KV len BEFORE this round's T tokens were appended
5462 // T=1 INCLUDED (2026-07-05): p-min cuts the draft to 1 in ~75% of rounds on hard
5463 // (agentic) content — the old t>1 gate sent those rounds to the per-row loop (262us/row
5464 // + q-row copy + per-row allocs vs 93us/row through the fused kernel at grid.z=1, same
5465 // program). nsys accounting: 1088 of 1456 verify FA launches were T=1 escapees.
5466 // LEAN T=1 ARM (MEMRA_SPEC_LEAN, close35): at t==1, q IS one row and fa_decode on it is
5467 // the EXACT eager decode dispatch (vec_q_v2 + combine_f32; the rows pair measured +50us
5468 // at m=1). Byte-identical: kernel-check pins rows-vs-loop identity, and the per-row loop
5469 // at t=1 is fa_decode on the same q with zero-offset copies. Gates arbitrate.
5470 if let Some(ctr) = stream_ctr {
5471 // STREAM ARM: causal base from the device counter; host kvl.len is a stale lower
5472 // bound used only for the split-sizing upper bound (+64 slack covers M pre-issued
5473 // rounds at K<=8). Views span the bound; per-row limits derive in-kernel.
5474 let upper = kvl.len + t + 64;
5475 let k_view = e.view_u8(&kvl.k, (upper.min(cache.max_ctx)) * ktb);
5476 let v_view = e.view_u8(&kvl.v, (upper.min(cache.max_ctx)) * vtb);
5477 e.fa_decode_rows_dc(
5478 &q,
5479 &k_view,
5480 &v_view,
5481 &mut attn,
5482 head_dim,
5483 n_head,
5484 n_head_kv,
5485 ctr,
5486 upper.min(cache.max_ctx),
5487 t,
5488 scale,
5489 ktb,
5490 vtb,
5491 0,
5492 false,
5493 )?;
5494 } else if spec_lean() && t == 1 {
5495 let t_kv = base_len + 1;
5496 let k_view = e.view_u8(&kvl.k, t_kv * ktb);
5497 let v_view = e.view_u8(&kvl.v, t_kv * vtb);
5498 e.fa_decode_kvmod(
5499 &q,
5500 &k_view,
5501 &v_view,
5502 &mut attn,
5503 head_dim,
5504 n_head,
5505 n_head_kv,
5506 t_kv,
5507 scale,
5508 ktb,
5509 vtb,
5510 crate::Engine::kv_fp8_on(),
5511 )?;
5512 } else if e.fa_rows_eligible(base_len, head_dim) {
5513 let k_view = e.view_u8(&kvl.k, (base_len + t) * ktb);
5514 let v_view = e.view_u8(&kvl.v, (base_len + t) * vtb);
5515 e.fa_decode_rows(
5516 &q,
5517 &k_view,
5518 &v_view,
5519 &mut attn,
5520 head_dim,
5521 n_head,
5522 n_head_kv,
5523 base_len,
5524 t,
5525 scale,
5526 ktb,
5527 vtb,
5528 None,
5529 false,
5530 crate::Engine::kv_fp8_on(),
5531 None,
5532 )?;
5533 } else {
5534 for r in 0..t {
5535 let t_kv_r = base_len + r + 1; // this row sees keys [0..t_kv_r)
5536 let k_view_r = e.view_u8(&kvl.k, t_kv_r * ktb);
5537 let v_view_r = e.view_u8(&kvl.v, t_kv_r * vtb);
5538 // copy q row into an owned buffer (fa_decode takes &CudaSlice, not CudaView)
5539 let mut q_row = vbuf(e, n_head * head_dim)?; // fully written by copy_view_into
5540 let q_src = q.slice(r * n_head * head_dim..(r + 1) * n_head * head_dim);
5541 e.copy_view_into(&mut q_row, 0, &q_src, n_head * head_dim)?;
5542 let mut attn_row = vbuf(e, n_head * head_dim)?; // fully written by fa_decode
5543 e.fa_decode_kvmod(
5544 &q_row,
5545 &k_view_r,
5546 &v_view_r,
5547 &mut attn_row,
5548 head_dim,
5549 n_head,
5550 n_head_kv,
5551 t_kv_r,
5552 scale,
5553 ktb,
5554 vtb,
5555 crate::Engine::kv_fp8_on(),
5556 )?;
5557 e.copy_into(
5558 &mut attn,
5559 r * n_head * head_dim,
5560 &attn_row,
5561 n_head * head_dim,
5562 )?;
5563 }
5564 }
5565
5566 let attn_g = match &gate {
5567 Some(gate) => {
5568 let mut gsig = vbuf(e, t * n_head * head_dim)?; // fully written by sigmoid
5569 e.sigmoid(gate, &mut gsig, t * n_head * head_dim)?;
5570 let mut ag = vbuf(e, t * n_head * head_dim)?; // fully written by mul
5571 e.mul(&attn, &gsig, &mut ag, t * n_head * head_dim)?;
5572 ag
5573 }
5574 None => attn,
5575 };
5576 // DECODE-EXACT wo projection: at m>=5 (K=4+ with pending) the generic matmul would use dp4a
5577 // (128-thread, different FP sum order than MMVQ). Force MMVQ for bit-identity with decode.
5578 Ok(e.matmul_decode_exact(&fa.wo, &attn_g, t)?)
5579 }
5580
5581 /// Context-linear bytes for a plain serving session's trunk cache.
5582 pub fn plain_session_kv_bytes_per_token(&self) -> usize {
5583 crate::cache::cache_bytes_per_token(&self.cfg)
5584 }
5585
5586 /// `(logical bytes/token, ring-capped bytes/token, ring row cap)` for exact admission.
5587 pub fn plain_session_kv_shape(&self) -> (usize, usize, usize) {
5588 (
5589 self.plain_session_kv_bytes_per_token(),
5590 crate::cache::cache_ring_bytes_per_token(&self.cfg),
5591 crate::cache::cache_ring_row_cap(&self.cfg),
5592 )
5593 }
5594
5595 /// Context-linear bytes for a speculative serving session: trunk cache plus persistent MTP
5596 /// scratch. With no MTP head this equals the plain coefficient.
5597 pub fn spec_session_kv_bytes_per_token(&self) -> usize {
5598 let scratch = self
5599 .mtp
5600 .as_ref()
5601 .map(|mtp| {
5602 let (_, _, k, v) = mtp_scratch_layout(&self.cfg, mtp.geom.as_ref());
5603 k + v
5604 })
5605 .unwrap_or(0);
5606 self.plain_session_kv_bytes_per_token()
5607 .saturating_add(scratch)
5608 }
5609
5610 /// Spec twin of [`HybridModel::plain_session_kv_shape`]; Step35's persistent MTP scratch is
5611 /// capped by the same SWA ring rows as the trunk.
5612 pub fn spec_session_kv_shape(&self) -> (usize, usize, usize) {
5613 let total = self.spec_session_kv_bytes_per_token();
5614 let (_, mut ring, rows) = self.plain_session_kv_shape();
5615 if rows > 0 {
5616 ring = ring.saturating_add(
5617 self.mtp
5618 .as_ref()
5619 .map(|mtp| {
5620 let (_, _, k, v) = mtp_scratch_layout(&self.cfg, mtp.geom.as_ref());
5621 k + v
5622 })
5623 .unwrap_or(0),
5624 );
5625 }
5626 (total, ring, rows)
5627 }
5628
5629 /// Greedy MTP speculative decode (§B). Token-identical to `generate(prompt, max_new)` but uses
5630 /// the NextN head to draft K tokens then verifies them in one batched target forward.
5631 /// Returns (generated tokens, total_drafted, total_accepted) so the caller can report
5632 /// acceptance rate. `k` = draft length per round.
5633 ///
5634 /// GRAPH DRAFT (stage 2 of graph-grade spec): when the model is all-Dense and the MTP head is
5635 /// Dense (no MoE host readbacks), the fixed-shape T=1 MTP forward is CUDA-graph-captured ONCE
5636 /// and replayed per draft step — the ~40 eager launches per drafted token collapse into one
5637 /// graph dispatch; only the 4-byte token id (and 4-byte p-min confidence) round-trip per step.
5638 /// Event tracking is disabled for the whole call (generate_graph pattern) so every buffer the
5639 /// captured graph references is event-free; the spec loop is strictly single-stream.
5640 /// MEMRA_SPEC_NOGRAPH=1 forces the eager draft chain.
5641 /// SAMPLED mode (MEMRA_SPEC_TEMP>0) has its OWN capture (gumbel-perturbed in-graph argmax,
5642 /// device Philox event counter, persistent q retention) — graph-vs-eager sampled streams are
5643 /// bit-identical for the same (seed, prompt, K, temp); see the sampled-graph setup in
5644 /// generate_spec_inner2.
5645 /// Multi-turn session: trunk cache + MTP draft scratch persist across generate calls, so
5646 /// turn N+1 primes ONLY its new suffix (the 124k-conversation daily pattern — re-priming a
5647 /// 32k history costs ~54s; a suffix prime costs seconds). APPEND-ONLY by construction: the
5648 /// hybrid linear-attn states are in-place (no position index), so a session can extend but
5649 /// never rewind — `committed` is the exact token list whose state the caches hold (includes
5650 /// any overshoot tokens past max_new; the caller renders from `committed`, not its own echo).
5651 pub fn new_session(
5652 &self,
5653 e: &Engine,
5654 max_ctx: usize,
5655 ) -> Result<SpecSession, Box<dyn std::error::Error>> {
5656 Ok(SpecSession {
5657 // STAGE-OWNED KV (lane/pp2-spec 2026-08-06): `pp::new_cache`, not `Cache::new`. This
5658 // is the SERVING spec-session path, and with the ppN door open across two cards a
5659 // primary-homed cache makes every remote stage peer-read its OWN KV on every verify
5660 // round — the wrong-card class already fixed on the two batched serving paths
5661 // (worker.rs 2483 / 2837). With the door shut `new_cache` IS `Cache::new` (same
5662 // branch, same allocations), so single-device behavior is byte-unchanged.
5663 cache: crate::pp::new_cache(e, &self.cfg, max_ctx)?,
5664 scratch: MtpScratch::new(
5665 e,
5666 &self.cfg,
5667 max_ctx,
5668 self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
5669 )?,
5670 committed: Vec::new(),
5671 last_h: None,
5672 next_pred: None,
5673 sctr: 0,
5674 uctr: 0,
5675 draft_ctx: None,
5676 pending_tok: None,
5677 turn_ckpt: None,
5678 telem: SpecTelemetryCounters::default(),
5679 capture_at: None,
5680 boundary_capture: None,
5681 })
5682 }
5683
5684 /// SPEC-ON-CACHE-HIT restore (lane/spec-on-cache-hit, 2026-08-18 — PORT-PLAN item 3,
5685 /// research/cache-spec-design-20260814, scoped to WHOLE-ENTRY restores only): build a
5686 /// SpecSession around a trunk cache the worker already restored from a prefix-cache
5687 /// entry, re-installing the entry's published draft plane as the MTP scratch rows
5688 /// `[0..prefix.len())` and the entry's boundary hidden as `last_h`, then feeding the
5689 /// prompt SUFFIX here — through EXACTLY the plain path's program selection — so the
5690 /// worker always receives a fully-warm continuation session (committed = whole
5691 /// prompt, `next_pred` + `last_h` set; caller sets `next_pred` from the entry's
5692 /// boundary logits on the empty-suffix shape).
5693 ///
5694 /// PROGRAM LAW (the splitiso two-programs class, learned AGAIN in this lane's own
5695 /// gate): the identity target for a converted hit is the PLAIN hit serving the same
5696 /// request, and plain feeds a carried suffix via eager `decode_step` below
5697 /// PRIME_MIN_T and via `prime_cache` at/above it (prefill_tick's arms). The generate
5698 /// path's tokenwise arm routes qwen35-class through the BATCHED T=1 program
5699 /// (`spec_target_step_h`) instead — ULP-different suffix rows, and the gate measured
5700 /// the near-tie flip at generated token ~8 (research/spec-cache-20260818, qwen r3).
5701 /// So the suffix is fed HERE, mirroring prefill_tick arm-for-arm, not handed to the
5702 /// burst prime. GREEDY ONLY by contract: `next_pred = argmax(feed logits)` is the
5703 /// continuation seed; a sampled first token must be host-sampled and stays plain.
5704 ///
5705 /// NOT the rolled-back partial-restore hazard: the caller restores at exactly the
5706 /// entry's captured endpoint (`e.pos`) through the shipping whole-entry path;
5707 /// mid-entry (`at < e.pos`) trunk restores stay behind MEMRA_PREFIX_PARTIAL_RESTORE
5708 /// and are never routed here.
5709 ///
5710 /// Failure contract: `Err((Some(cache), why))` before any trunk mutation — the
5711 /// worker rebuilds the plain carrier and the hit serves plain, byte-unchanged.
5712 /// `Err((None, why))` after the suffix feed began — the carrier is part-fed and
5713 /// UNUSABLE; the worker serves the request cold-plain (correct, slower) and the
5714 /// entry stays published for the next request.
5715 #[allow(clippy::too_many_arguments)]
5716 pub fn spec_session_from_restored(
5717 &self,
5718 e: &Engine,
5719 mut cache: Cache,
5720 prefix: Vec<u32>,
5721 suffix: &[u32],
5722 draft_k: &CudaSlice<u8>,
5723 draft_v: &CudaSlice<u8>,
5724 draft_k_tok_bytes: usize,
5725 draft_v_tok_bytes: usize,
5726 draft_len: usize,
5727 last_h: &[f32],
5728 require_anchor: bool,
5729 max_ctx: usize,
5730 ) -> Result<SpecSession, (Option<Cache>, String)> {
5731 let pos = prefix.len();
5732 let fail = |cache: Cache, msg: String| -> Result<SpecSession, (Option<Cache>, String)> {
5733 Err((Some(cache), msg))
5734 };
5735 if self.mtp.is_none() {
5736 return fail(cache, "no MTP head attached (nothing to draft with)".into());
5737 }
5738 if pos == 0 {
5739 return fail(cache, "empty committed prefix".into());
5740 }
5741 if cache.pos != pos {
5742 let msg = format!(
5743 "restored cache pos {} != restored prefix len {pos}",
5744 cache.pos
5745 );
5746 return fail(cache, msg);
5747 }
5748 if draft_len != pos {
5749 return fail(
5750 cache,
5751 format!("draft plane len {draft_len} != restored prefix len {pos}"),
5752 );
5753 }
5754 if pos + suffix.len() >= max_ctx {
5755 return fail(
5756 cache,
5757 format!(
5758 "prompt {} + suffix would not leave generation room in ctx {max_ctx}",
5759 pos + suffix.len(),
5760 ),
5761 );
5762 }
5763 let mut scratch = match MtpScratch::new(
5764 e,
5765 &self.cfg,
5766 max_ctx,
5767 self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
5768 ) {
5769 Ok(s) => s,
5770 Err(err) => return fail(cache, format!("draft scratch alloc failed: {err}")),
5771 };
5772 if scratch.kv.ring.is_some() {
5773 return fail(
5774 cache,
5775 "ring-backed draft scratch (Step35 SWA) cannot take a flat prefix restore".into(),
5776 );
5777 }
5778 if scratch.kv.k_tok_bytes != draft_k_tok_bytes
5779 || scratch.kv.v_tok_bytes != draft_v_tok_bytes
5780 {
5781 return fail(
5782 cache,
5783 format!(
5784 "draft plane layout {draft_k_tok_bytes}/{draft_v_tok_bytes} != scratch \
5785 {}/{} bytes/token (stale entry across a format change)",
5786 scratch.kv.k_tok_bytes, scratch.kv.v_tok_bytes,
5787 ),
5788 );
5789 }
5790 if pos > scratch.cap {
5791 return fail(
5792 cache,
5793 format!(
5794 "draft plane rows {pos} exceed scratch capacity {}",
5795 scratch.cap
5796 ),
5797 );
5798 }
5799 let kb = pos * draft_k_tok_bytes;
5800 let vb = pos * draft_v_tok_bytes;
5801 if draft_k.len() < kb || draft_v.len() < vb {
5802 return fail(
5803 cache,
5804 format!(
5805 "truncated draft plane: K {} < {kb} or V {} < {vb} bytes",
5806 draft_k.len(),
5807 draft_v.len(),
5808 ),
5809 );
5810 }
5811 if kb > 0 {
5812 if let Err(err) = e.copy_u8_into(&mut scratch.kv.k, 0, draft_k, kb) {
5813 return fail(cache, format!("draft K restore copy failed: {err}"));
5814 }
5815 }
5816 if vb > 0 {
5817 if let Err(err) = e.copy_u8_into(&mut scratch.kv.v, 0, draft_v, vb) {
5818 return fail(cache, format!("draft V restore copy failed: {err}"));
5819 }
5820 }
5821 if let Err(err) = scratch.set_len(e, pos) {
5822 return fail(cache, format!("draft scratch len set failed: {err}"));
5823 }
5824 let mut last_h_dev = if last_h.len() == self.cfg.n_embd as usize {
5825 // anchor upload failure is acceptance-only when a suffix feed follows (fill
5826 // row-0 falls back to zeros) but FATAL for an empty-suffix continuation (the
5827 // burst entry asserts committed + last_h + next_pred) — the caller says which.
5828 e.htod(last_h).ok()
5829 } else {
5830 None
5831 };
5832 if require_anchor && last_h_dev.is_none() {
5833 return fail(
5834 cache,
5835 "empty-suffix continuation requires the entry's boundary hidden anchor".into(),
5836 );
5837 }
5838 let mut committed = prefix;
5839 let mut next_pred = None;
5840 if !suffix.is_empty() {
5841 // ---- SUFFIX FEED, mirroring prefill_tick's program selection exactly ----
5842 // From here on the trunk cache mutates: failures return Err((None, _)) and
5843 // the worker serves the request cold-plain instead of reusing the carrier.
5844 let dirty =
5845 |msg: String| -> Result<SpecSession, (Option<Cache>, String)> { Err((None, msg)) };
5846 let n_embd = self.cfg.n_embd as usize;
5847 let t = suffix.len();
5848 let mut h_rows = match e.uninit(t * n_embd) {
5849 Ok(b) => b,
5850 Err(err) => return fail(cache, format!("suffix hidden buffer alloc: {err}")),
5851 };
5852 let mut feed_logits = Vec::new();
5853 let batched = t >= crate::hybrid_forward::PRIME_MIN_T
5854 && std::env::var("MEMRA_PRIME_TOKENWISE").is_err()
5855 && !e.frozen_cpu_experts_prefer_tokenwise_prime();
5856 if batched {
5857 // prefill_tick's prime arm: one request-level prime_cache call.
5858 match self.prime_cache(e, suffix, &mut cache, 0) {
5859 Ok((l, _h_seed, hiddens)) => {
5860 if let Err(err) = e.copy_into(&mut h_rows, 0, &hiddens, t * n_embd) {
5861 return dirty(format!("suffix hidden copy: {err}"));
5862 }
5863 feed_logits = l;
5864 }
5865 Err(err) => return dirty(format!("suffix prime failed: {err}")),
5866 }
5867 } else {
5868 // prefill_tick's tokenwise arm: eager decode_step, one token at a time.
5869 for (i, &tok) in suffix.iter().enumerate() {
5870 match self.decode_step_h(e, tok, &mut cache) {
5871 Ok((l, h)) => {
5872 if let Err(err) = e.copy_into(&mut h_rows, i * n_embd, &h, n_embd) {
5873 return dirty(format!("suffix hidden copy: {err}"));
5874 }
5875 feed_logits = l;
5876 }
5877 Err(err) => return dirty(format!("suffix decode_step failed: {err}")),
5878 }
5879 }
5880 }
5881 // Draft-scratch fill for the suffix rows, predecessor-paired: row `pos` reads
5882 // the entry's boundary anchor (zeros fallback — acceptance-only), row `pos+i`
5883 // reads h_rows[i-1]. Chunked like the generate path's fill (transients scale
5884 // with T). Fill failures are acceptance-only — truncate to the restored rows
5885 // and continue; the burst's own set_len keeps the invariant.
5886 let mtp = self.mtp.as_ref().expect("mtp checked above");
5887 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
5888 let embd_gpu = if spec_host_embd() {
5889 None
5890 } else {
5891 Some(
5892 self.embd_gpu
5893 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
5894 )
5895 };
5896 let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
5897 let fill_chunk = 4096usize;
5898 let mut filled = true;
5899 let mut start = 0usize;
5900 'fill: while start < t {
5901 let end = (start + fill_chunk).min(t);
5902 let tc = end - start;
5903 let Ok(mut phs) = e.zeros(tc * n_embd) else {
5904 filled = false;
5905 break 'fill;
5906 };
5907 let (src_lo, dst_off, n_copy) = if start == 0 {
5908 (0, n_embd, (tc - 1) * n_embd)
5909 } else {
5910 ((start - 1) * n_embd, 0, tc * n_embd)
5911 };
5912 if start == 0 {
5913 if let Some(lh) = last_h_dev.as_ref() {
5914 if e.copy_into(&mut phs, 0, lh, n_embd).is_err() {
5915 filled = false;
5916 break 'fill;
5917 }
5918 }
5919 }
5920 if n_copy > 0
5921 && e.copy_view_into(
5922 &mut phs,
5923 dst_off,
5924 &h_rows.slice(src_lo..src_lo + n_copy),
5925 n_copy,
5926 )
5927 .is_err()
5928 {
5929 filled = false;
5930 break 'fill;
5931 }
5932 if self
5933 .mtp_kv_fill(
5934 e,
5935 mtp,
5936 &suffix[start..end],
5937 &phs,
5938 pos + start,
5939 &mut scratch,
5940 embd_dev,
5941 )
5942 .is_err()
5943 {
5944 filled = false;
5945 break 'fill;
5946 }
5947 start = end;
5948 }
5949 if !filled {
5950 // acceptance-only: drafts over missing suffix rows are cheap and wrong,
5951 // so keep only the restored rows resident and let verify arbitrate.
5952 if let Err(err) = scratch.set_len(e, pos) {
5953 return dirty(format!("scratch truncation after failed fill: {err}"));
5954 }
5955 }
5956 // continuation seed: the feed's boundary logits ARE the plain path's boundary
5957 // logits (same program), so this argmax is plain's first emitted token.
5958 next_pred = Some(argmax(&feed_logits) as u32);
5959 let mut lh = match e.uninit(n_embd) {
5960 Ok(b) => b,
5961 Err(err) => return dirty(format!("boundary hidden alloc: {err}")),
5962 };
5963 if let Err(err) = e.copy_view_into(
5964 &mut lh,
5965 0,
5966 &h_rows.slice((t - 1) * n_embd..t * n_embd),
5967 n_embd,
5968 ) {
5969 return dirty(format!("boundary hidden copy: {err}"));
5970 }
5971 last_h_dev = Some(lh);
5972 committed.extend_from_slice(suffix);
5973 }
5974 Ok(SpecSession {
5975 cache,
5976 scratch,
5977 committed,
5978 last_h: last_h_dev,
5979 next_pred,
5980 sctr: 0,
5981 uctr: 0,
5982 draft_ctx: None,
5983 pending_tok: None,
5984 turn_ckpt: None,
5985 telem: SpecTelemetryCounters::default(),
5986 capture_at: None,
5987 boundary_capture: None,
5988 })
5989 }
5990
5991 /// Forced-gate exact state comparison. This intentionally reads the real live prefixes from
5992 /// their owning PP devices: matching emitted ids alone would miss a stale `len_d`, recurrent
5993 /// snapshot, or draft-KV row that only corrupts the following round.
5994 pub fn optipipe_compare_session_state(
5995 &self,
5996 e: &Engine,
5997 reference: &SpecSession,
5998 candidate: &SpecSession,
5999 ) -> Result<OptiForkStateIdentity, Box<dyn std::error::Error>> {
6000 fn fail(what: &str) -> Box<dyn std::error::Error> {
6001 format!("optipipe state mismatch: {what}").into()
6002 }
6003 fn same_f32(a: &[f32], b: &[f32]) -> bool {
6004 a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.to_bits() == y.to_bits())
6005 }
6006 fn compare_layers(
6007 es: &Engine,
6008 range: std::ops::Range<usize>,
6009 reference: &SpecSession,
6010 candidate: &SpecSession,
6011 report: &mut OptiForkStateIdentity,
6012 ) -> Result<(), Box<dyn std::error::Error>> {
6013 for il in range {
6014 match (&reference.cache.kv[il], &candidate.cache.kv[il]) {
6015 (Some(a), Some(b)) => {
6016 if a.len != b.len {
6017 return Err(fail(&format!(
6018 "layer {il} host KV len {} != {}",
6019 a.len, b.len
6020 )));
6021 }
6022 let ad = es.dtoh_i32(&a.len_d)?;
6023 let bd = es.dtoh_i32(&b.len_d)?;
6024 if ad != bd || ad.first().copied() != Some(a.len as i32) {
6025 return Err(fail(&format!(
6026 "layer {il} device KV len {ad:?} != {bd:?} (host={})",
6027 a.len,
6028 )));
6029 }
6030 let kb = a.len * a.k_tok_bytes;
6031 let vb = a.len * a.v_tok_bytes;
6032 if kb > 0 {
6033 let ak = es.dtoh_u8_view(&a.k.slice(0..kb))?;
6034 let bk = es.dtoh_u8_view(&b.k.slice(0..kb))?;
6035 if ak != bk {
6036 let at = ak.iter().zip(&bk).position(|(x, y)| x != y).unwrap();
6037 return Err(fail(&format!(
6038 "layer {il} K bytes at byte {at} row {} offset {}: {} != {}",
6039 at / a.k_tok_bytes,
6040 at % a.k_tok_bytes,
6041 ak[at],
6042 bk[at],
6043 )));
6044 }
6045 }
6046 if vb > 0 {
6047 let av = es.dtoh_u8_view(&a.v.slice(0..vb))?;
6048 let bv = es.dtoh_u8_view(&b.v.slice(0..vb))?;
6049 if av != bv {
6050 let at = av.iter().zip(&bv).position(|(x, y)| x != y).unwrap();
6051 return Err(fail(&format!(
6052 "layer {il} V bytes at byte {at} row {} offset {}: {} != {}",
6053 at / a.v_tok_bytes,
6054 at % a.v_tok_bytes,
6055 av[at],
6056 bv[at],
6057 )));
6058 }
6059 }
6060 report.trunk_kv_bytes += kb + vb;
6061 }
6062 (None, None) => {}
6063 _ => return Err(fail(&format!("layer {il} KV presence"))),
6064 }
6065 match (&reference.cache.recur[il], &candidate.cache.recur[il]) {
6066 (Some(a), Some(b)) => {
6067 let ac = es.dtoh(&a.conv_state)?;
6068 let bc = es.dtoh(&b.conv_state)?;
6069 if !same_f32(&ac, &bc) {
6070 return Err(fail(&format!("layer {il} conv state")));
6071 }
6072 let as_ = es.dtoh(&a.ssm_state)?;
6073 let bs = es.dtoh(&b.ssm_state)?;
6074 if !same_f32(&as_, &bs) {
6075 return Err(fail(&format!("layer {il} SSM state")));
6076 }
6077 report.recurrent_bytes += (ac.len() + as_.len()) * 4;
6078 }
6079 (None, None) => {}
6080 _ => return Err(fail(&format!("layer {il} recurrent presence"))),
6081 }
6082 }
6083 Ok(())
6084 }
6085
6086 if reference.committed != candidate.committed {
6087 return Err(fail("committed token ids"));
6088 }
6089 if reference.cache.pos != candidate.cache.pos
6090 || reference.cache.max_ctx != candidate.cache.max_ctx
6091 {
6092 return Err(fail("cache pos/capacity"));
6093 }
6094 if reference.pending_tok != candidate.pending_tok
6095 || reference.next_pred != candidate.next_pred
6096 || reference.sctr != candidate.sctr
6097 || reference.uctr != candidate.uctr
6098 {
6099 return Err(fail("pending/prediction/counter tail"));
6100 }
6101
6102 let mut report = OptiForkStateIdentity::default();
6103 if let Some(fence) = crate::pp::pp_cuts(self.layers.len()) {
6104 let rt = crate::pp::PpNRt::get(e)?;
6105 for stage in 0..rt.n_stages() {
6106 let _scope = rt.enter(stage);
6107 compare_layers(
6108 rt.engine(stage, e),
6109 fence[stage]..fence[stage + 1],
6110 reference,
6111 candidate,
6112 &mut report,
6113 )?;
6114 }
6115 } else {
6116 compare_layers(e, 0..self.layers.len(), reference, candidate, &mut report)?;
6117 }
6118
6119 let (a, b) = (&reference.scratch.kv, &candidate.scratch.kv);
6120 if a.len != b.len || e.dtoh_i32(&a.len_d)? != e.dtoh_i32(&b.len_d)? {
6121 return Err(fail("draft scratch length"));
6122 }
6123 let kb = a.len * a.k_tok_bytes;
6124 let vb = a.len * a.v_tok_bytes;
6125 if kb > 0 && e.dtoh_u8_view(&a.k.slice(0..kb))? != e.dtoh_u8_view(&b.k.slice(0..kb))? {
6126 return Err(fail("draft scratch K bytes"));
6127 }
6128 if vb > 0 && e.dtoh_u8_view(&a.v.slice(0..vb))? != e.dtoh_u8_view(&b.v.slice(0..vb))? {
6129 return Err(fail("draft scratch V bytes"));
6130 }
6131 report.scratch_kv_bytes = kb + vb;
6132
6133 match (&reference.last_h, &candidate.last_h) {
6134 (Some(a), Some(b)) => {
6135 let ah = e.dtoh(a)?;
6136 let bh = e.dtoh(b)?;
6137 if !same_f32(&ah, &bh) {
6138 return Err(fail("last hidden/seed bytes"));
6139 }
6140 report.hidden_bytes = ah.len() * 4;
6141 }
6142 (None, None) => {}
6143 _ => return Err(fail("last hidden/seed presence")),
6144 }
6145 Ok(report)
6146 }
6147
6148 /// SESSION-AFFINITY REWIND (lane/session-affinity, 2026-08-05): roll `sess` back to its
6149 /// retained prompt-end checkpoint, so a request whose prompt matches
6150 /// `committed[..rewind_pos()]` exactly can resume there and prime only its own delta.
6151 ///
6152 /// EXACTNESS. After this returns, the session is byte-for-byte the state it was in AT that
6153 /// boundary: full-attn KV truncated to it (append-only, position-addressed), GDN conv/ssm
6154 /// restored from the device copy taken there, draft scratch length reset, `committed`
6155 /// truncated, `last_h` = the boundary's predecessor anchor. That is precisely the state a
6156 /// fresh prime of `committed[..pos]` would have produced, so the following suffix prime and
6157 /// every burst after it are identical to a cold run of the same token stream — the
6158 /// committed-tokens-authoritative contract.
6159 ///
6160 /// `next_pred` and `pending_tok` are CLEARED: both describe generation past the boundary,
6161 /// which the rewind discards. The caller therefore must supply a non-empty suffix (a
6162 /// rewound session cannot serve an empty-suffix continuation burst — there is nothing to
6163 /// continue). The persistent draft graph survives: it bakes only session-stable pointers
6164 /// (the scratch KV, the resident embedding), none of which the rewind moves.
6165 ///
6166 /// The checkpoint is CONSUMED (`turn_ckpt` taken): its snapshot buffers are freed here, and
6167 /// this turn's own prime installs a fresh one at the new prompt end. Returns the position
6168 /// rewound to, or `None` when the session holds no checkpoint (caller: full re-prime).
6169 pub fn spec_rewind_to_checkpoint(
6170 &self,
6171 e: &Engine,
6172 sess: &mut SpecSession,
6173 ) -> Result<Option<usize>, Box<dyn std::error::Error>> {
6174 if sess.turn_ckpt.as_ref().is_some_and(|ckpt| {
6175 !sess.cache.can_rollback(&ckpt.snap, 0) || !sess.scratch.can_rewind_to(ckpt.pos)
6176 }) {
6177 return Err(
6178 "SWA ring rewind checkpoint has been lapped; full re-prime required".into(),
6179 );
6180 }
6181 let Some(ckpt) = sess.turn_ckpt.take() else {
6182 return Ok(None);
6183 };
6184 assert!(
6185 ckpt.pos <= sess.committed.len(),
6186 "checkpoint past committed ({} > {})",
6187 ckpt.pos,
6188 sess.committed.len()
6189 );
6190 // Restore through each layer's owning engine. A single primary-engine rollback is not
6191 // sufficient when the serving cache is stage-owned under cross-device PP.
6192 crate::pp::restore_cache_checkpoint(e, &self.cfg, None, &mut sess.cache, &ckpt.snap)?;
6193 debug_assert_eq!(
6194 sess.cache.pos, ckpt.pos,
6195 "rollback landed off the checkpoint"
6196 );
6197 sess.scratch.set_len(e, ckpt.pos)?;
6198 sess.committed.truncate(ckpt.pos);
6199 sess.last_h = Some(ckpt.last_h);
6200 sess.next_pred = None;
6201 sess.pending_tok = None;
6202 Ok(Some(ckpt.pos))
6203 }
6204
6205 /// Grow a parked speculative session to `target_cap` and rewind it to its retained turn
6206 /// checkpoint without re-priming the checkpoint prefix.
6207 ///
6208 /// The trunk cache is restored exactly like a plain grown cache: append-only full-attention
6209 /// KV rows come from the parked cache, while recurrent state comes from the checkpoint's
6210 /// owned snapshot. The MTP scratch is also context-linear and its rows below the checkpoint
6211 /// remain authoritative, so they are copied into a fresh larger scratch before its length is
6212 /// truncated. Pointer-baking draft graphs are dropped and recaptured on the next burst.
6213 ///
6214 /// All fallible work completes before `sess` is mutated. A failed allocation or copy leaves
6215 /// the parked session intact, allowing the caller one reclaim-and-retry attempt.
6216 pub fn spec_grow_and_rewind_to_checkpoint(
6217 &self,
6218 e: &Engine,
6219 sess: &mut SpecSession,
6220 target_cap: usize,
6221 ) -> Result<Option<usize>, Box<dyn std::error::Error>> {
6222 if target_cap <= sess.cache.max_ctx {
6223 return self.spec_rewind_to_checkpoint(e, sess);
6224 }
6225 let Some(ckpt) = sess.turn_ckpt.as_ref() else {
6226 return Ok(None);
6227 };
6228 if ckpt.pos == 0 || ckpt.pos > sess.committed.len() {
6229 return Err(format!(
6230 "checkpoint pos {} outside committed length {}",
6231 ckpt.pos,
6232 sess.committed.len(),
6233 )
6234 .into());
6235 }
6236 if ckpt.pos > target_cap {
6237 return Err(format!(
6238 "checkpoint pos {} exceeds grown capacity {target_cap}",
6239 ckpt.pos,
6240 )
6241 .into());
6242 }
6243
6244 let mut grown_cache = crate::pp::new_cache(e, &self.cfg, target_cap)?;
6245 let mut grown_scratch = MtpScratch::new(
6246 e,
6247 &self.cfg,
6248 target_cap,
6249 self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
6250 )?;
6251 crate::pp::restore_cache_checkpoint(
6252 e,
6253 &self.cfg,
6254 Some(&sess.cache),
6255 &mut grown_cache,
6256 &ckpt.snap,
6257 )?;
6258
6259 let src = &sess.scratch.kv;
6260 let dst = &mut grown_scratch.kv;
6261 if ckpt.pos > src.len
6262 || src.kv_dim_k != dst.kv_dim_k
6263 || src.kv_dim_v != dst.kv_dim_v
6264 || src.k_tok_bytes != dst.k_tok_bytes
6265 || src.v_tok_bytes != dst.v_tok_bytes
6266 {
6267 return Err(format!(
6268 "checkpoint draft layout mismatch (pos {}, source len {})",
6269 ckpt.pos, src.len,
6270 )
6271 .into());
6272 }
6273 let kb = ckpt.pos * src.k_tok_bytes;
6274 let vb = ckpt.pos * src.v_tok_bytes;
6275 if kb > 0 {
6276 e.copy_u8_into(&mut dst.k, 0, &src.k, kb)?;
6277 }
6278 if vb > 0 {
6279 e.copy_u8_into(&mut dst.v, 0, &src.v, vb)?;
6280 }
6281 grown_scratch.set_len(e, ckpt.pos)?;
6282 // The old scratch is dropped immediately after publication below. Bound its D2D reads
6283 // first; growth happens once per rewritten turn, outside the decode hot loop.
6284 e.stream().synchronize()?;
6285
6286 let ckpt = sess
6287 .turn_ckpt
6288 .take()
6289 .expect("checkpoint remained present through transactional grow");
6290 let pos = ckpt.pos;
6291 sess.cache = grown_cache;
6292 sess.scratch = grown_scratch;
6293 sess.committed.truncate(pos);
6294 sess.last_h = Some(ckpt.last_h);
6295 sess.next_pred = None;
6296 sess.pending_tok = None;
6297 sess.draft_ctx = None;
6298 debug_assert_eq!(sess.cache.pos, pos, "grown rewind landed off checkpoint");
6299 debug_assert_eq!(
6300 sess.scratch.kv.len, pos,
6301 "grown draft rewind landed off checkpoint"
6302 );
6303 Ok(Some(pos))
6304 }
6305
6306 /// Commit a carried pending bonus (see SpecSession::pending_tok): one T=1 trunk pass
6307 /// (its logits' argmax becomes next_pred) + the draft-KV fill at the carried anchor —
6308 /// byte-identical to the pre-carry session tail. Required before a non-empty-suffix
6309 /// prime, a sampled turn, or parking a session for pool reuse. No-op without a pending.
6310 pub fn spec_flush_pending(
6311 &self,
6312 e: &Engine,
6313 sess: &mut SpecSession,
6314 ) -> Result<(), Box<dyn std::error::Error>> {
6315 let Some(b) = sess.pending_tok.take() else {
6316 return Ok(());
6317 };
6318 let mtp = self
6319 .mtp
6320 .as_ref()
6321 .expect("pending carry requires an MTP head");
6322 let n_embd = self.cfg.n_embd as usize;
6323 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
6324 let embd_gpu = if spec_host_embd() {
6325 None
6326 } else {
6327 Some(
6328 self.embd_gpu
6329 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
6330 )
6331 };
6332 let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
6333 let pos_b = sess.cache.pos;
6334 sess.scratch.set_len(e, pos_b)?;
6335 let (lg_b, hb) = self.spec_target_step_h(e, b, &mut sess.cache)?;
6336 sess.next_pred = Some(argmax(&lg_b) as u32);
6337 let anchor = sess
6338 .last_h
6339 .as_ref()
6340 .expect("pending carry requires last_h (the predecessor-row anchor)");
6341 self.mtp_kv_fill(e, mtp, &[b], anchor, pos_b, &mut sess.scratch, embd_dev)?;
6342 sess.last_h = Some(hb);
6343 sess.committed.push(b);
6344 Ok(())
6345 }
6346
6347 /// Solo target feed used only at speculative round boundaries. Step35 serving made its
6348 /// staged batched B=1 graph authoritative, so a speculative session must enter and leave
6349 /// rounds through that same graph. Other model families keep their eager T=1 contract.
6350 fn spec_target_step_h(
6351 &self,
6352 e: &Engine,
6353 token: u32,
6354 cache: &mut Cache,
6355 ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
6356 if self.cfg.step35.is_none() && !self.qwen35_serving_class() {
6357 return self.decode_step_h(e, token, cache);
6358 }
6359 let pos0 = cache.pos;
6360 let (logits, hidden) = self.decode_step_t_core(e, &[token], pos0, cache, None, None)?;
6361 Ok((e.dtoh(&logits)?, hidden))
6362 }
6363
6364 /// The archs whose LIVE B=1 serving runs the generic BATCHED numeric class (decode_step_batch
6365 /// walk + batched head), so their spec verify must run the SAME class. MoE learned this
6366 /// 2026-08-14 AM (4b777ccc5); the dense hybrid reproduced the identical near-tie flip class
6367 /// the same day on Qwen3.8-27B — eager-class verify logits drift from batched-class serving
6368 /// logits ("1 ULP at layer 2 → 2.3e-1 logit maxdiff at the head"), and the GDN recurrence
6369 /// carries the drift until a near-tie flips deep in generation. One predicate so the five
6370 /// dispatch sites cannot drift apart again.
6371 fn qwen35_serving_class(&self) -> bool {
6372 matches!(
6373 self.cfg.arch,
6374 memra_gguf::config::Arch::Qwen35 | memra_gguf::config::Arch::Qwen35Moe
6375 )
6376 }
6377
6378 /// Reduced-matrix admission for increment 1. This deliberately does not change the PP-2
6379 /// serving policy: the worker calls it only after `MEMRA_SPEC_PIPE=1` and an explicit spec
6380 /// session already exist.
6381 pub fn spec_pipe_available(&self, e: &Engine) -> bool {
6382 if std::env::var("MEMRA_SPEC_PIPE").as_deref() != Ok("1")
6383 || !spec_devacc()
6384 || spec_replay_env_enabled()
6385 || spec_stream()
6386 || std::env::var("MEMRA_SPEC_ADAPT").as_deref() == Ok("1")
6387 || std::env::var("MEMRA_SPEC_PMIN0").as_deref() == Ok("1")
6388 || std::env::var("MEMRA_SPEC_PP_ANATOMY").as_deref() == Ok("1")
6389 || std::env::var("MEMRA_SPEC_PMIN")
6390 .ok()
6391 .and_then(|v| v.parse::<f32>().ok())
6392 .unwrap_or(0.0)
6393 > 0.0
6394 || self.is_gemma4_e4b()
6395 || self.cfg.gemma4.is_some()
6396 || self.mtp.is_none()
6397 {
6398 return false;
6399 }
6400 let Some(cuts) = crate::pp::pp_cuts(self.layers.len()) else {
6401 return false;
6402 };
6403 if cuts.len() != 3 || crate::pp::pp2_streams_off() || !crate::pp::spec_pp_on() {
6404 return false;
6405 }
6406 crate::pp::PpNRt::get(e)
6407 .map(|rt| rt.n_stages() == 2 && rt.cross_device())
6408 .unwrap_or(false)
6409 }
6410
6411 /// Two warm greedy continuation bursts over one PP-2 interval coordinator. The two existing
6412 /// `generate_spec_inner2` call stacks own all per-session round locals; only phase issue order
6413 /// changes. No callback is accepted in increment 1 — the worker publishes each completed burst.
6414 #[allow(clippy::too_many_arguments)]
6415 pub fn generate_spec_session_pair(
6416 &self,
6417 e: &Engine,
6418 sess_a: &mut SpecSession,
6419 max_new_a: usize,
6420 k_a: usize,
6421 sess_b: &mut SpecSession,
6422 max_new_b: usize,
6423 k_b: usize,
6424 ) -> Result<((Vec<u32>, usize, usize), (Vec<u32>, usize, usize)), Box<dyn std::error::Error>>
6425 {
6426 if !self.spec_pipe_available(e) {
6427 return Err("two-session speculative pipeline is outside its reduced matrix".into());
6428 }
6429 if max_new_a == 0 || max_new_b == 0 || k_a == 0 || k_b == 0 {
6430 return Err(
6431 "two-session speculative pipeline requires non-empty positive-K bursts".into(),
6432 );
6433 }
6434 for sess in [&*sess_a, &*sess_b] {
6435 if sess.committed.is_empty()
6436 || sess.last_h.is_none()
6437 || (sess.next_pred.is_none() && sess.pending_tok.is_none())
6438 {
6439 return Err("two-session speculative pipeline requires warm continuations".into());
6440 }
6441 }
6442
6443 let mtp_dense = self
6444 .mtp
6445 .as_ref()
6446 .map(|m| matches!(m.ffn, crate::hybrid::Ffn::Dense { .. }))
6447 .unwrap_or(false);
6448 let trunk_dense = self
6449 .layers
6450 .iter()
6451 .all(|l| matches!(l.ffn, crate::hybrid::Ffn::Dense { .. }));
6452 let graph_ok = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
6453 && !spec_host_embd()
6454 && mtp_dense
6455 && trunk_dense
6456 && !crate::model::full_prec_enabled();
6457 let graph_a = graph_ok && k_a + 2 < 96;
6458 let graph_b = graph_ok && k_b + 2 < 96;
6459 let was_tracking = e.ctx().is_event_tracking();
6460 if (graph_a || graph_b) && was_tracking {
6461 unsafe {
6462 e.ctx().disable_event_tracking();
6463 }
6464 }
6465
6466 static LOGGED: std::sync::Once = std::sync::Once::new();
6467 LOGGED.call_once(|| {
6468 eprintln!("[spec-pipe] two-session PP-2 continuation pipeline engaged");
6469 });
6470 let sync = std::sync::Arc::new(SpecPipeSync::new());
6471 let lane_a = SpecPipeLane {
6472 sync: sync.clone(),
6473 lane: 0,
6474 };
6475 let lane_b = SpecPipeLane { sync, lane: 1 };
6476 let mut sess_b_ptr = SpecPipeSessionPtr(sess_b as *mut SpecSession);
6477 let (result_a, result_b) = std::thread::scope(|scope| {
6478 let b = scope.spawn(move || {
6479 let mut finish = SpecPipeFinish::new(&lane_b);
6480 let sess_b = unsafe { sess_b_ptr.get_mut() };
6481 let result = e
6482 .ctx()
6483 .bind_to_thread()
6484 .map_err(|err| err.to_string())
6485 .and_then(|_| {
6486 self.generate_spec_inner2(
6487 e,
6488 &[],
6489 max_new_b,
6490 k_b,
6491 graph_b,
6492 Some(sess_b),
6493 None,
6494 None,
6495 None,
6496 None,
6497 Some(&lane_b),
6498 )
6499 .map_err(|err| err.to_string())
6500 });
6501 finish.close(result.is_err());
6502 result
6503 });
6504 let mut finish = SpecPipeFinish::new(&lane_a);
6505 let result_a = self.generate_spec_inner2(
6506 e,
6507 &[],
6508 max_new_a,
6509 k_a,
6510 graph_a,
6511 Some(sess_a),
6512 None,
6513 None,
6514 None,
6515 None,
6516 Some(&lane_a),
6517 );
6518 finish.close(result_a.is_err());
6519 let result_b = b
6520 .join()
6521 .map_err(|_| "paired speculative session B panicked".to_string())
6522 .and_then(|r| r);
6523 (result_a, result_b)
6524 });
6525
6526 if (graph_a || graph_b) && was_tracking {
6527 unsafe {
6528 e.ctx().enable_event_tracking();
6529 }
6530 }
6531 let result_a = result_a?;
6532 let result_b = result_b.map_err(|err| -> Box<dyn std::error::Error> { err.into() })?;
6533 Ok((result_a, result_b))
6534 }
6535
6536 /// One spec-decode turn on a live session. `suffix` = the NEW tokens only (turn N+1's user
6537 /// message rendered through the chat template continuation). Returns (new tokens emitted,
6538 /// drafted, accepted); session.committed grows by suffix + emitted.
6539 pub fn generate_spec_session(
6540 &self,
6541 e: &Engine,
6542 sess: &mut SpecSession,
6543 suffix: &[u32],
6544 max_new: usize,
6545 k: usize,
6546 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
6547 self.generate_spec_session_sampled(e, sess, suffix, max_new, k, None, None)
6548 }
6549
6550 /// Serve-path sampled spec: routes the burst through the rejection-sampling verify with
6551 /// per-SESSION Philox continuity (sess.sctr/uctr). None = env-driven (CLI) or greedy.
6552 /// Filters (top-k/p/min-p) apply SYMMETRICALLY to draft q and verify p — distribution-exact
6553 /// for the filtered target (feat/filtered-spec).
6554 ///
6555 /// `on_commit` (sse-cadence, 2026-08-05): called with each newly-emitted slice of the
6556 /// output — once right after the prime's first token, then once per round commit — so a
6557 /// streaming caller can flush text at round cadence instead of once per burst. The slices
6558 /// are disjoint, in order, and concatenate to exactly the returned token vec. Emission-
6559 /// timing only: token bytes, session state, and exactness are untouched.
6560 ///
6561 /// The returned bool is a CONTINUE-VERDICT (admission yield, 2026-08-06): `false` ends
6562 /// the burst at the current round boundary, exactly as if `max_new` had been reached —
6563 /// the caller's scheduler regains control without waiting the burst out. Burst size is
6564 /// content-neutral (spec-levers battery), so an early exit moves WHEN the burst returns,
6565 /// never what tokens say. The slice may be EMPTY (a poll-only boundary — round-stream
6566 /// drains and the defensive tail flush can land with nothing new committed).
6567 #[allow(clippy::too_many_arguments)]
6568 pub fn generate_spec_session_sampled(
6569 &self,
6570 e: &Engine,
6571 sess: &mut SpecSession,
6572 suffix: &[u32],
6573 max_new: usize,
6574 k: usize,
6575 sampling: Option<SpecSampling>,
6576 on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
6577 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
6578 self.generate_spec_session_sampled_prime_split(
6579 e, sess, suffix, max_new, k, sampling, None, on_commit,
6580 )
6581 }
6582
6583 /// Serve-only cold-prime segmentation twin. `prime_split` is the same stable boundary the
6584 /// plain worker would honor before entering its sub-floor tokenwise tail; warm continuations
6585 /// pass `None` and stay on the existing zero-prime path.
6586 #[allow(clippy::too_many_arguments)]
6587 pub fn generate_spec_session_sampled_prime_split(
6588 &self,
6589 e: &Engine,
6590 sess: &mut SpecSession,
6591 suffix: &[u32],
6592 max_new: usize,
6593 k: usize,
6594 sampling: Option<SpecSampling>,
6595 prime_split: Option<usize>,
6596 on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
6597 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
6598 self.generate_spec_session_constrained_prime_split(
6599 e,
6600 sess,
6601 suffix,
6602 max_new,
6603 k,
6604 sampling,
6605 None,
6606 prime_split,
6607 on_commit,
6608 )
6609 }
6610
6611 /// `generate_spec_session_sampled` + GRAMMAR (constrained decoding, 2026-08-03): the
6612 /// hook truncates acceptance at the first grammar-illegal token AFTER the exactness
6613 /// verify (grammar is an extra rejection rule, ordering like the batched-verify twins)
6614 /// and replaces an illegal bonus with the MASKED argmax of the target's own verify
6615 /// column — token-identical to constrained plain greedy decode. GREEDY only (the
6616 /// worker routes sampled constrained to plain decode). Acceptance under tight grammars
6617 /// may drop (drafter is unconstrained); that is measured, not hidden.
6618 #[allow(clippy::too_many_arguments)]
6619 pub fn generate_spec_session_constrained(
6620 &self,
6621 e: &Engine,
6622 sess: &mut SpecSession,
6623 suffix: &[u32],
6624 max_new: usize,
6625 k: usize,
6626 sampling: Option<SpecSampling>,
6627 constraint: Option<&mut dyn SpecConstraint>,
6628 on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
6629 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
6630 self.generate_spec_session_constrained_prime_split(
6631 e, sess, suffix, max_new, k, sampling, constraint, None, on_commit,
6632 )
6633 }
6634
6635 #[allow(clippy::too_many_arguments)]
6636 pub fn generate_spec_session_constrained_prime_split(
6637 &self,
6638 e: &Engine,
6639 sess: &mut SpecSession,
6640 suffix: &[u32],
6641 max_new: usize,
6642 k: usize,
6643 sampling: Option<SpecSampling>,
6644 constraint: Option<&mut dyn SpecConstraint>,
6645 prime_split: Option<usize>,
6646 on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
6647 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
6648 if constraint.is_some() && sampling.is_some_and(|s| s.temp > 0.0) {
6649 return Err(
6650 "constrained spec decode is greedy-only (worker routes sampled \
6651 constrained to plain decode)"
6652 .into(),
6653 );
6654 }
6655 // PENDING-CARRY entry flush: a carried bonus precedes any new suffix in the sequence,
6656 // so it must commit BEFORE the suffix primes; the sampled path doesn't carry (its
6657 // round-0 accept needs the commit pass's logits). Empty-suffix greedy bursts — the
6658 // serve continuation case — consume the carry in-loop with zero solo passes.
6659 if sess.pending_tok.is_some()
6660 && (!suffix.is_empty() || sampling.map_or(false, |s| s.temp > 0.0))
6661 {
6662 self.spec_flush_pending(e, sess)?;
6663 }
6664 let mtp_dense = self
6665 .mtp
6666 .as_ref()
6667 .map(|m| matches!(m.ffn, crate::hybrid::Ffn::Dense { .. }))
6668 .unwrap_or(false);
6669 let trunk_dense = self
6670 .layers
6671 .iter()
6672 .all(|l| matches!(l.ffn, crate::hybrid::Ffn::Dense { .. }));
6673 // FULL_PREC forces the EAGER draft: the graph capture would enclose cuBLASLt f32 GEMV
6674 // (the FloatBf16 else-branches) and a bf16_to_f32 dequant alloc — neither is stream-capture
6675 // safe. Eager rides matmul/matmul_decode_exact, which dequant FloatBf16 on use. (§item 2.)
6676 let graph_draft = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
6677 && !spec_host_embd()
6678 && mtp_dense
6679 && trunk_dense
6680 && k + 2 < 96
6681 && !crate::model::full_prec_enabled();
6682 let was_tracking = e.ctx().is_event_tracking();
6683 if graph_draft && was_tracking {
6684 unsafe {
6685 e.ctx().disable_event_tracking();
6686 }
6687 }
6688 let r = self.generate_spec_inner2(
6689 e,
6690 suffix,
6691 max_new,
6692 k,
6693 graph_draft,
6694 Some(sess),
6695 sampling,
6696 constraint,
6697 on_commit,
6698 prime_split,
6699 None,
6700 );
6701 if graph_draft && was_tracking {
6702 unsafe {
6703 e.ctx().enable_event_tracking();
6704 }
6705 }
6706 let (out, d, a) = r?;
6707 Ok((out, d, a))
6708 }
6709
6710 pub fn generate_spec(
6711 &self,
6712 e: &Engine,
6713 prompt: &[u32],
6714 max_new: usize,
6715 k: usize,
6716 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
6717 let mtp_dense = self
6718 .mtp
6719 .as_ref()
6720 .map(|m| matches!(m.ffn, crate::hybrid::Ffn::Dense { .. }))
6721 .unwrap_or(false);
6722 let trunk_dense = self
6723 .layers
6724 .iter()
6725 .all(|l| matches!(l.ffn, crate::hybrid::Ffn::Dense { .. }));
6726 // FULL_PREC forces eager (see generate_spec_session note): CUDA graph capture cannot
6727 // enclose cuBLASLt f32 GEMV or the bf16_to_f32 dequant alloc the FloatBf16 path needs.
6728 let graph_draft = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
6729 && !spec_host_embd()
6730 && mtp_dense
6731 && trunk_dense
6732 && k + 2 < 96
6733 && !crate::model::full_prec_enabled();
6734 if !graph_draft {
6735 return self.generate_spec_inner2(
6736 e, prompt, max_new, k, false, None, None, None, None, None, None,
6737 );
6738 }
6739 let was_tracking = e.ctx().is_event_tracking();
6740 if was_tracking {
6741 unsafe {
6742 e.ctx().disable_event_tracking();
6743 }
6744 }
6745 let r = self.generate_spec_inner2(
6746 e, prompt, max_new, k, true, None, None, None, None, None, None,
6747 );
6748 if was_tracking {
6749 unsafe {
6750 e.ctx().enable_event_tracking();
6751 }
6752 }
6753 r
6754 }
6755
6756 fn generate_spec_inner2(
6757 &self,
6758 e: &Engine,
6759 prompt: &[u32],
6760 max_new: usize,
6761 k: usize,
6762 graph_draft: bool,
6763 mut sess: Option<&mut SpecSession>,
6764 sampling: Option<SpecSampling>,
6765 mut constraint: Option<&mut dyn SpecConstraint>,
6766 mut on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
6767 prime_split: Option<usize>,
6768 pipe: Option<&SpecPipeLane>,
6769 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
6770 assert!(k >= 1, "k must be >= 1");
6771 if let Some(p) = pipe {
6772 p.setup_begin()?;
6773 }
6774 // sse-cadence flush cursor: everything in out[..flushed] has been handed to on_commit.
6775 let mut flushed = 0usize;
6776 // admission yield (2026-08-06): on_commit's continue-verdict; false = end the burst
6777 // at the next round boundary (same exit as max_new reached — the session tail runs).
6778 // Initialized by the unconditional post-prime flush below.
6779 let mut keep_going;
6780 let mtp = self
6781 .mtp
6782 .as_ref()
6783 .expect("generate_spec requires an MTP head (nextn_predict_layers>0)");
6784 let n_vocab = self.output.out_features();
6785 // FR-Spec: the draft head may be TRIMMED (fewer rows than n_vocab); the draft argmax runs
6786 // over the draft vocab and the winning index maps through d2t to a TARGET token id.
6787 // Everything downstream (verify/accept/commit) sees target ids only — exactness unchanged.
6788 let d_vocab = mtp
6789 .shared_head_head
6790 .as_ref()
6791 .unwrap_or(&self.output)
6792 .out_features();
6793 let n_embd = self.cfg.n_embd as usize;
6794 // SESSION MODE: reuse the live cache/scratch, prime only the suffix. `base` = tokens
6795 // already committed (their state is in the caches); 0 = fresh single-shot call.
6796 let session_mode = sess.is_some();
6797 let max_ctx = match sess.as_ref() {
6798 Some(s) => s.cache.max_ctx,
6799 None => prompt.len() + max_new + k + 8,
6800 };
6801 let mut own_cache;
6802 let mut own_scratch;
6803 // PREFIX-CACHE capture request threaded out of the session (lane/spec-prefix-cache):
6804 // (requested split, destination slot). Single-shot per burst; fresh calls have none.
6805 let mut sess_capture: Option<(Option<usize>, &mut Option<SpecBoundaryCapture>)> = None;
6806 let (
6807 cache,
6808 scratch,
6809 mut sess_tail,
6810 mut sess_draft_slot,
6811 mut sess_pending_slot,
6812 sess_ckpt_slot,
6813 sess_telem,
6814 ): (
6815 &mut Cache,
6816 &mut MtpScratch,
6817 Option<(
6818 &mut Vec<u32>,
6819 &mut Option<CudaSlice<f32>>,
6820 &mut Option<u32>,
6821 &mut u32,
6822 &mut u32,
6823 )>,
6824 Option<&mut Option<DraftGraphCtx>>,
6825 Option<&mut Option<u32>>,
6826 Option<&mut Option<SpecCheckpoint>>,
6827 Option<&SpecTelemetryCounters>,
6828 ) = match sess.take() {
6829 Some(sr) => {
6830 let SpecSession {
6831 cache,
6832 scratch,
6833 committed,
6834 last_h,
6835 next_pred,
6836 sctr: s_sctr,
6837 uctr: s_uctr,
6838 draft_ctx,
6839 pending_tok,
6840 turn_ckpt,
6841 telem,
6842 capture_at,
6843 boundary_capture,
6844 } = sr;
6845 sess_capture = Some((capture_at.take(), boundary_capture));
6846 (
6847 cache,
6848 scratch,
6849 Some((committed, last_h, next_pred, s_sctr, s_uctr)),
6850 Some(draft_ctx),
6851 Some(pending_tok),
6852 Some(turn_ckpt),
6853 Some(telem),
6854 )
6855 }
6856 None => {
6857 // STAGE-OWNED KV (lane/pp2-spec 2026-08-06) — see `new_session`. Door shut =
6858 // `Cache::new` verbatim.
6859 own_cache = crate::pp::new_cache(e, &self.cfg, max_ctx)?;
6860 // Persistent scratch = max_ctx rows (~2KB/token quantized).
6861 own_scratch = MtpScratch::new(
6862 e,
6863 &self.cfg,
6864 max_ctx,
6865 self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
6866 )?;
6867 (
6868 &mut own_cache,
6869 &mut own_scratch,
6870 None,
6871 None,
6872 None,
6873 None,
6874 None,
6875 )
6876 }
6877 };
6878 let base = cache.pos;
6879 // PENDING-CARRY consume (2026-08-01): a carried bonus reaches here only on the
6880 // empty-suffix GREEDY continuation path (generate_spec_session_sampled flushed every
6881 // other case). It enters the round loop as round-0's pending — verify col 0 — exactly
6882 // like a mid-burst full-accept boundary: no init feed, no tail commit pass.
6883 let carried_pending: Option<u32> = sess_pending_slot.as_mut().and_then(|s| s.take());
6884 // PERSISTENT DRAFT KV (the only mode since 2026-07-08 — the legacy round-local scratch,
6885 // MEMRA_SPEC_KVLOCAL, measured -35 acceptance pts on the 27B p3 sweep and was removed;
6886 // acceptance-only — exactness is verify's job either way).
6887 // HIDDEN-PAIRING CONVENTION (DEFAULT = predecessor-row, 2026-07-04 — the 27B acceptance
6888 // unlock, +16pts): the MTP head is TRAINED on rows pairing token x_p with the trunk
6889 // hidden of its PREDECESSOR h_{p-1} (the reference engine's mtp_update shifts the target
6890 // hiddens right by one; its draft step 0 feeds (id_last, TRUE hidden of the row id_last
6891 // was sampled from)). memra's historical convention paired SAME-ROW (x_p, h_p) in the fill
6892 // and seeded chain step 0 through an extra MTP pass on a duplicated token (the
6893 // pseudo-seed) — measured 27B p2 K=3 acceptance 0.569 vs 0.731, p3 0.445 vs 0.63+, and
6894 // the chain steps j>=1 were already predecessor-shaped, so ONLY the fill + step-0 seed
6895 // move. The fill shifts by one and the chain seeds from the predecessor's true hidden
6896 // DIRECTLY (vh_seed / vx[j-1]) — the pseudo pass disappears (one MTP-block pass saved
6897 // per round on top of the acceptance win). Draft-quality-only: exactness stays the
6898 // verify's job either way. (The legacy same-row pairing seam, MEMRA_SPEC_HSAME, and its
6899 // pseudo-seed passes were removed 2026-07-08 — predecessor pairing won by +16 acc pts;
6900 // the legacy round-local scratch, MEMRA_SPEC_KVLOCAL, went with it.)
6901 // REPLAY-FREE PARTIAL ACCEPT (default, 2026-07-03): partial rounds keep the verify's own
6902 // bit-identical committed-prefix state (KV truncate + recur rebuild from the VerifyCkpt)
6903 // and leave the bonus PENDING — no duplicate trunk pass (profiled ~0.54 extra full weight
6904 // reads/round at long ctx). MEMRA_SPEC_REPLAY=1 restores the legacy rollback+replay (A/B
6905 // + fallback seam).
6906 // Qwen35-MoE stays on the correctness reference path until its retained verify-state
6907 // commit is proven equivalent to sequential serving on the long-prompt gate. Replaying
6908 // every accepted round through the serving-class verifier is slower, but prevents a
6909 // numerically exact verify result from carrying a drifted recurrent cache into the next
6910 // round. DENSE qwen35 runs replay-free: its verify already executes the serving batched
6911 // class (qwen35_verify_batch_layers), and the serving-class replay loop below steps
6912 // per-row T=1 (replay.len() full weight reads/round — measured 69 -> 30 tok/s on
6913 // Qwen3.8-27B, 2026-08-15); the replay-free VerifyCkpt commit is gated bit-identical by
6914 // the spec-serve battery before release.
6915 let spec_replay = spec_replay_env_enabled()
6916 || matches!(self.cfg.arch, memra_gguf::config::Arch::Qwen35Moe);
6917 if constraint.is_some() && spec_replay {
6918 return Err(
6919 "constrained spec decode does not support MEMRA_SPEC_REPLAY=1 \
6920 (legacy replay commits an unmasked bonus)"
6921 .into(),
6922 );
6923 }
6924 // TRUE-HIDDEN REFRESH (default in persistent-draft-KV mode): every round overwrites the
6925 // committed positions' scratch entries from the verify's exact hiddens (mtp_kv_fill batch)
6926 // instead of keeping chain-approximate entries. MEMRA_SPEC_NOREFRESH=1 = legacy (A/B seam).
6927 let refresh = std::env::var("MEMRA_SPEC_NOREFRESH").is_err();
6928
6929 // prime: BATCHED cache prime (prime_cache — the measured #1 e2e gap: tokenwise primed at
6930 // ~102/38 tok/s vs the engine's ~2000-5900 tok/s batched prefill). prime_cache returns the
6931 // full pre-output_norm hidden stack [T, n_embd], which IS prompt_h (the persistent-draft-KV
6932 // mtp_kv_fill input) — no per-token collection needed. Prompts below PRIME_MIN_T, and
6933 // MEMRA_PRIME_TOKENWISE=1, and frozen Hy3 CPU/GPU expert splits take the tokenwise
6934 // decode_step_h loop. The latter avoids transient GPU staging of the spilled expert bank.
6935 // EMPTY-SUFFIX CONTINUATION (serve bursts): a session turn with NO new tokens resumes
6936 // generation exactly where the last turn stopped — no prime at all. The stashed
6937 // `next_pred` plays prime_logits' argmax role (it IS the argmax of the logits after
6938 // committed.last()); `last_h` seeds the predecessor pairing below. Fresh calls and
6939 // non-empty suffixes take the normal path.
6940 let continuation = prompt.is_empty();
6941 if continuation {
6942 assert!(session_mode, "empty prompt requires a session");
6943 assert!(
6944 sess_tail
6945 .as_ref()
6946 .map_or(false, |(c, lh, np, _, _)| !c.is_empty()
6947 && lh.is_some()
6948 && (np.is_some() || carried_pending.is_some())),
6949 "empty-suffix continuation needs a primed session (committed + last_h + next_pred|pending)"
6950 );
6951 }
6952 let mut prime_logits;
6953 let mut prompt_h: Option<CudaSlice<f32>> = None;
6954 let t_prime = std::time::Instant::now();
6955 let batched_prime = !continuation
6956 && prompt.len() >= crate::hybrid_forward::PRIME_MIN_T
6957 && std::env::var("MEMRA_PRIME_TOKENWISE").is_err()
6958 && !e.frozen_cpu_experts_prefer_tokenwise_prime();
6959 let prime_split = prime_split.filter(|&split| split > 0 && split < prompt.len());
6960 if prime_split.is_some() && (continuation || base != 0) {
6961 return Err("spec prime split is cold-session-only".into());
6962 }
6963 if continuation {
6964 prime_logits = Vec::new();
6965 } else if let Some(split) = prime_split {
6966 if split < crate::hybrid_forward::PRIME_MIN_T {
6967 return Err(format!(
6968 "spec prime split {split} is below PRIME_MIN_T {}",
6969 crate::hybrid_forward::PRIME_MIN_T,
6970 )
6971 .into());
6972 }
6973 // Mirror the plain worker's affinity boundary exactly. The prefix is a request-level
6974 // prime (`queued_after` keeps Step35 arm selection independent of this stop); a tail
6975 // below PRIME_MIN_T then takes the same eager tokenwise continuation as prefill_tick.
6976 // Retain every hidden row so the draft scratch fill remains one coherent prompt.
6977 let mut h_all = e.uninit(prompt.len() * n_embd)?;
6978 let (l, _, h_prefix) =
6979 self.prime_cache(e, &prompt[..split], &mut *cache, prompt.len() - split)?;
6980 e.copy_into(&mut h_all, 0, &h_prefix, split * n_embd)?;
6981 prime_logits = l;
6982 // PREFIX-CACHE BOUNDARY CAPTURE (lane/spec-prefix-cache): the GDN conv/ssm states
6983 // are about to be advanced in place by the tail prime, so this is the ONLY moment
6984 // the boundary's recurrent state exists. Capture iff the worker requested exactly
6985 // this split. cache.pos == split here (the prefix prime just finished). A failed
6986 // snapshot is silent (turn_ckpt convention) — publication is an optimization,
6987 // never a correctness dependency.
6988 if let Some((requested, slot)) = sess_capture.as_mut() {
6989 if *requested == Some(split) {
6990 debug_assert_eq!(cache.pos, split, "boundary capture off the prime split");
6991 if let Ok(snap) = cache.snapshot(e) {
6992 **slot = Some(SpecBoundaryCapture {
6993 snap,
6994 pos: split,
6995 logits: prime_logits.clone(),
6996 // rows [0..split) of h_all are the prefix prime's hiddens — copied
6997 // just above, before the tail prime overwrites nothing (append-only).
6998 last_h: capture_boundary_hidden(e, &h_all, split, n_embd),
6999 });
7000 }
7001 }
7002 }
7003 let tail = &prompt[split..];
7004 if tail.len() >= crate::hybrid_forward::PRIME_MIN_T
7005 && std::env::var("MEMRA_PRIME_TOKENWISE").is_err()
7006 && !e.frozen_cpu_experts_prefer_tokenwise_prime()
7007 {
7008 let (l, _, h_tail) = self.prime_cache(e, tail, &mut *cache, 0)?;
7009 e.copy_into(&mut h_all, split * n_embd, &h_tail, tail.len() * n_embd)?;
7010 prime_logits = l;
7011 } else {
7012 for (i, &tok) in tail.iter().enumerate() {
7013 let (l, h) = self.decode_step_h(e, tok, &mut *cache)?;
7014 e.copy_into(&mut h_all, (split + i) * n_embd, &h, n_embd)?;
7015 prime_logits = l;
7016 }
7017 }
7018 if std::env::var("MEMRA_SPEC_STATS").as_deref() == Ok("1") {
7019 eprintln!("[spec-prime] affinity split={split} tail={}", tail.len());
7020 }
7021 prompt_h = Some(h_all);
7022 } else if batched_prime {
7023 let (l, _h_seed, hiddens) = self.prime_cache(e, prompt, &mut *cache, 0)?;
7024 prime_logits = l;
7025 prompt_h = Some(hiddens);
7026 } else {
7027 prime_logits = Vec::new();
7028 prompt_h = Some(e.uninit(prompt.len() * n_embd)?);
7029 for (i, &tok) in prompt.iter().enumerate() {
7030 let (l, h) = self.spec_target_step_h(e, tok, &mut *cache)?;
7031 if let Some(ph) = prompt_h.as_mut() {
7032 e.copy_into(ph, i * n_embd, &h, n_embd)?;
7033 }
7034 prime_logits = l;
7035 }
7036 }
7037 e.stream().synchronize()?;
7038 // PREFIX-CACHE SEED CAPTURE (lane/spec-prefix-cache): boundary == prompt end (the seed
7039 // case — no shared-prefix split, publish the whole prompt). The prime just finished, so
7040 // cache.pos == base + prompt.len() and the recurrent state IS the boundary state;
7041 // prime_logits are the boundary logits. Cold sessions only (base == 0) — same law as
7042 // prime_split. The mid-prompt capture above already consumed the request if it matched.
7043 if !continuation && base == 0 {
7044 if let Some((requested, slot)) = sess_capture.as_mut() {
7045 if *requested == Some(prompt.len()) && slot.is_none() {
7046 debug_assert_eq!(cache.pos, prompt.len(), "seed capture off prompt end");
7047 if let Ok(snap) = cache.snapshot(e) {
7048 **slot = Some(SpecBoundaryCapture {
7049 snap,
7050 pos: prompt.len(),
7051 logits: prime_logits.clone(),
7052 last_h: prompt_h
7053 .as_ref()
7054 .map(|ph| capture_boundary_hidden(e, ph, prompt.len(), n_embd))
7055 .unwrap_or_default(),
7056 });
7057 }
7058 }
7059 }
7060 }
7061 // Harness timing contract (see crate::PRIME_NANOS): gen-only throughput without the
7062 // prime-subtraction hack.
7063 crate::PRIME_NANOS.store(
7064 t_prime.elapsed().as_nanos() as u64,
7065 std::sync::atomic::Ordering::Relaxed,
7066 );
7067
7068 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
7069 // Resident table is fastest when it fits. Large spill deployments can preserve that HBM
7070 // for expert-cache slots and gather only the exact rows needed by MTP/verify from host.
7071 let host_embd = spec_host_embd();
7072 let embd_gpu = if host_embd {
7073 None
7074 } else {
7075 Some(
7076 self.embd_gpu
7077 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
7078 )
7079 };
7080 let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
7081 if host_embd {
7082 eprintln!(
7083 "[spec] host-row embedding: {} bytes kept off HBM",
7084 self.embd.raw.len()
7085 );
7086 }
7087 let mut out: Vec<u32> = Vec::with_capacity(max_new);
7088 let mut total_drafted = 0usize;
7089 let mut total_accepted = 0usize;
7090
7091 // First generated token = argmax of the prompt's last logits (== greedy's first token).
7092 // Emit it, then FEED it to establish the loop invariant below.
7093 // PENDING-CARRY: the carried bonus was already emitted by the LAST burst — it becomes
7094 // last_token WITHOUT re-emission, and round 0 consumes it as pending (no init feed).
7095 // CONSTRAINED entry rules: the first emitted token is the MASKED argmax of the
7096 // prompt's last logits (plain constrained-greedy identity); a continuation without
7097 // a carried pending would emit an UNMASKED stashed next_pred — refused loudly (the
7098 // worker never resumes constrained sessions from the pool, so this cannot fire).
7099 if let Some(c) = constraint.as_deref_mut() {
7100 if continuation && carried_pending.is_none() {
7101 return Err("constrained spec continuation requires a carried pending \
7102 (pool resume is unconstrained-only)"
7103 .into());
7104 }
7105 if !continuation {
7106 c.mask_logits(&mut prime_logits)
7107 .map_err(|e2| format!("constraint: {e2}"))?;
7108 }
7109 }
7110 let mut last_token = if let Some(b) = carried_pending {
7111 b
7112 } else if continuation {
7113 sess_tail.as_ref().unwrap().2.unwrap()
7114 } else {
7115 argmax(&prime_logits) as u32
7116 };
7117 if carried_pending.is_none() {
7118 out.push(last_token);
7119 // grammar advances with every emitted token (carried pendings were consumed
7120 // by the burst that emitted them).
7121 if let Some(c) = constraint.as_deref_mut() {
7122 c.consume(last_token)
7123 .map_err(|e2| format!("constraint: {e2}"))?;
7124 }
7125 }
7126 if continuation {
7127 // draft-KV invariant: entries [0..base) are the session's exact fills; truncate any
7128 // overhang so the chain's first append lands at slot base (== committed.len()).
7129 scratch.set_len(e, base)?;
7130 }
7131 // sse-cadence: hand the caller every not-yet-flushed token (disjoint in-order slices
7132 // concatenating to the full `out`). Called after the prime's first token and after each
7133 // round commit — emission timing only, token bytes untouched. The slice may be EMPTY
7134 // (poll-only boundary: zero-round folds commit nothing new); returns the caller's
7135 // continue-verdict (admission yield, 2026-08-06) — false ends the burst at this round.
7136 fn flush_commit(
7137 cb: &mut Option<&mut dyn FnMut(&[u32]) -> bool>,
7138 out: &[u32],
7139 flushed: &mut usize,
7140 ) -> bool {
7141 if let Some(f) = cb.as_mut() {
7142 let keep = f(&out[*flushed..]);
7143 *flushed = out.len();
7144 keep
7145 } else {
7146 true
7147 }
7148 }
7149 keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
7150 // INVARIANT at loop top: `last_token` is the most-recently-committed/emitted token, its
7151 // KV+recur state IS in `cache` (cache.pos = position right AFTER last_token), `last_pred`
7152 // is the greedy ARGMAX of the logits that predict the token FOLLOWING last_token, and
7153 // `h_seed` = last_token's pre-output_norm hidden. Establish it by feeding last_token once
7154 // (mirrors plain greedy). DEVICE-ARGMAX lever: the accept walk only ever consumes the
7155 // argmax of those logits — never the full vector — so a host u32 replaces the Vec<f32>.
7156 // --- SAMPLED SPEC (MEMRA_SPEC_TEMP>0, research/sampled-spec-impl-map.md): rejection-
7157 // sampling verify (Leviathan/Chen) — accept draft x at u < p(x)/q(x), resample from
7158 // norm(max(0,p-q)) on reject, bonus sampled from p on full accept. Counter-based Philox
7159 // everywhere (seed, event) -> reproducible. temp==0/unset = the greedy path, untouched.
7160 let sp = sampling.unwrap_or_else(|| SpecSampling {
7161 temp: std::env::var("MEMRA_SPEC_TEMP")
7162 .ok()
7163 .and_then(|v| v.parse().ok())
7164 .unwrap_or(0.0),
7165 seed: std::env::var("MEMRA_SEED")
7166 .ok()
7167 .and_then(|v| v.parse().ok())
7168 .unwrap_or(42),
7169 top_k: std::env::var("MEMRA_TOP_K")
7170 .ok()
7171 .and_then(|v| v.parse().ok())
7172 .unwrap_or(0),
7173 top_p: std::env::var("MEMRA_TOP_P")
7174 .ok()
7175 .and_then(|v| v.parse().ok())
7176 .unwrap_or(1.0),
7177 min_p: std::env::var("MEMRA_MIN_P")
7178 .ok()
7179 .and_then(|v| v.parse().ok())
7180 .unwrap_or(0.0),
7181 penalty_last_n: std::env::var("MEMRA_PENALTY_LAST_N")
7182 .ok()
7183 .and_then(|v| v.parse().ok())
7184 .unwrap_or(0),
7185 penalty_repeat: std::env::var("MEMRA_PENALTY_REPEAT")
7186 .ok()
7187 .and_then(|v| v.parse().ok())
7188 .unwrap_or(1.0),
7189 penalty_freq: std::env::var("MEMRA_PENALTY_FREQ")
7190 .ok()
7191 .and_then(|v| v.parse().ok())
7192 .unwrap_or(0.0),
7193 penalty_present: std::env::var("MEMRA_PENALTY_PRESENT")
7194 .ok()
7195 .and_then(|v| v.parse().ok())
7196 .unwrap_or(0.0),
7197 });
7198 let (sp_temp, sp_seed) = (sp.temp, sp.seed);
7199 let sampled = sp_temp > 0.0;
7200 // Trimmed heads: q lives on the trimmed vocab; accept gathers use the TRIMMED index and
7201 // the residual scatters q into target-id space (q=-inf off-trim — the head cannot propose
7202 // those, so their residual mass is p(x), correct by construction).
7203 let d2t_dev: Option<CudaSlice<u32>> = if sampled || crate::spec::spec_stream() {
7204 match &mtp.d2t {
7205 Some(map) => Some(e.htod_u32_v(map)?),
7206 None => None,
7207 }
7208 } else {
7209 None
7210 };
7211 let mut q_full_buf: Option<CudaSlice<f32>> = None;
7212 // Counters resume from the session (burst continuity: randomness must never repeat
7213 // across generate_spec_session calls); one-shot callers start at (0,0). Read through
7214 // sess_tail — `sess` was take()n into it above, so sess.as_ref() here is always None.
7215 let mut sctr: u32 = sess_tail.as_ref().map(|(_, _, _, s, _)| **s).unwrap_or(0);
7216 let mut uctr: u32 = sess_tail.as_ref().map(|(_, _, _, _, u)| **u).unwrap_or(0);
7217 // host Philox4x32-10 (mirrors spec_sample.cu; independent stream via ctr_lo tag)
7218 let host_u01 = |seed: u64, ctr: u32| -> f32 {
7219 let (m0, m1) = (0xD2511F53u32, 0xCD9E8D57u32);
7220 let (mut c0, mut c1, mut c2, mut c3) = (0xFFFF_FFFEu32, ctr, 0u32, 0u32);
7221 let (mut k0, mut k1) = ((seed & 0xFFFF_FFFF) as u32, (seed >> 32) as u32);
7222 for _ in 0..10 {
7223 let (h0, l0) = (((m0 as u64 * c0 as u64) >> 32) as u32, m0.wrapping_mul(c0));
7224 let (h1, l1) = (((m1 as u64 * c2 as u64) >> 32) as u32, m1.wrapping_mul(c2));
7225 let (n0, n1, n2, n3) = (h1 ^ c1 ^ k0, l1, h0 ^ c3 ^ k1, l0);
7226 c0 = n0;
7227 c1 = n1;
7228 c2 = n2;
7229 c3 = n3;
7230 k0 = k0.wrapping_add(0x9E3779B9);
7231 k1 = k1.wrapping_add(0xBB67AE85);
7232 }
7233 (c0 as f32 + 1.0) * (1.0 / 4294967296.0)
7234 };
7235 let mut draft_logits: Vec<CudaSlice<f32>> = Vec::new(); // retained head logits (q), per slot
7236 let mut draft_stats: Vec<(f32, f32, f32)> = Vec::new(); // (row_max, th_e, z_e) per slot
7237 let mut perturb_buf: Option<CudaSlice<f32>> = None; // gumbel scratch (max(n_vocab,d_vocab))
7238 let mut sample_tok = e.alloc_u32_zeroed(1)?; // residual/bonus sample out
7239 let mut col_buf: Option<CudaSlice<f32>> = None; // materialized verify column
7240 // Penalties (v2.1): applied to COPIES of q rows and p columns symmetrically (exactness
7241 // for the penalized+filtered target). History = generated tokens, host-tracked window.
7242 let pen_on = sampled
7243 && sp.penalty_last_n > 0
7244 && (sp.penalty_repeat != 1.0 || sp.penalty_freq != 0.0 || sp.penalty_present != 0.0);
7245 let mut pen_hist: Vec<u32> = if pen_on {
7246 prompt.iter().rev().take(64).rev().cloned().collect() // llama-parity: history spans prompt tail too
7247 } else {
7248 Vec::new()
7249 };
7250 let mut pen_hist_d: Option<CudaSlice<u32>> = None;
7251 let mut pcol_buf: Option<CudaSlice<f32>> = None; // penalized p-column scratch
7252 // MEMRA_SPEC_SETUP_TRACE=1 (diagnostics): per-call wall decomposition of the burst
7253 // SETUP + TAIL segments (the round loop's internals are MEMRA_SPEC_PHASE's job) —
7254 // built to pin the serve per-burst fixed cost (research/spec-serving-20260801).
7255 let setup_trace = std::env::var("MEMRA_SPEC_SETUP_TRACE").as_deref() == Ok("1");
7256 let t_ent = std::time::Instant::now();
7257
7258 // SESSION-AFFINITY TURN CHECKPOINT (lane/session-affinity, 2026-08-05): capture the
7259 // PROMPT-END boundary state so a LATER turn can rewind here and re-prime only its own
7260 // delta instead of the whole conversation. See `SpecCheckpoint` for why this boundary is
7261 // the one that matters (a history-rewriting client mutates what the session GENERATED,
7262 // so the next turn's prompt agrees with this one up to exactly here).
7263 //
7264 // WHERE — AND WHY THIS EXACT LINE. Right after the trunk prime, BEFORE the init feed
7265 // (`decode_step_h(last_token)`) and before round 0: the last instant at which the caches
7266 // hold exactly `base + prompt.len()` rows and nothing generated.
7267 //
7268 // This was WRONG in the first cut of this lane: the capture sat after the draft-KV fill,
7269 // which is also after the init feed, so `cache.pos` was `base + prompt.len() + 1` — the
7270 // boundary included the FIRST GENERATED TOKEN. That token is the first thing inside the
7271 // `<think>` block the client strips, so every later turn's diff diverged exactly one
7272 // token below the checkpoint and affinity declined 100% of the time. Measured on the
7273 // owner regime: "history diverged at 12233 of checkpoint 12234". The off-by-one made the
7274 // whole mechanism inert while looking, from the outside, like a working
7275 // correctness-declines-safely path — hence the decline log carries the offsets.
7276 //
7277 // The full-attn planes are `len`-truncatable so the snapshot copies only the GDN conv/ssm
7278 // state (the reason a spec session could not rewind before). The draft scratch needs no
7279 // copy: rows below the boundary are rewritten by the next turn's own fill.
7280 //
7281 // WHEN: non-empty prime only. An empty-suffix continuation burst adds no prompt boundary
7282 // (its "prompt end" IS the previous checkpoint's, already held), so it keeps the existing
7283 // checkpoint rather than replacing it with a strictly worse one.
7284 //
7285 // FAILURE IS SILENT BY DESIGN: on a VRAM-tight rig the snapshot alloc can fail. That
7286 // costs the NEXT turn its rewind (it re-primes fully, today's behavior) and must never
7287 // fail the burst that is already running — so the error is swallowed, loud only under
7288 // MEMRA_DEBUG_SPEC.
7289 if let Some(slot) = sess_ckpt_slot {
7290 if !continuation {
7291 let pos = cache.pos;
7292 debug_assert_eq!(
7293 pos,
7294 base + prompt.len(),
7295 "turn checkpoint must sit at the prompt end, before the init feed"
7296 );
7297 let anchor: Result<CudaSlice<f32>, Box<dyn std::error::Error>> =
7298 if let Some(ph) = &prompt_h {
7299 // hidden of the LAST primed row = the predecessor anchor at this
7300 // boundary (exactly what a fresh prime of committed[..pos] leaves in
7301 // last_h, and what the next prime's fill reads for its first row).
7302 let np = prompt.len();
7303 e.uninit(n_embd).and_then(|mut a| {
7304 e.copy_view_into(
7305 &mut a,
7306 0,
7307 &ph.slice((np - 1) * n_embd..np * n_embd),
7308 n_embd,
7309 )?;
7310 Ok(a)
7311 })
7312 } else {
7313 Err("no prompt hiddens".into())
7314 };
7315 match (cache.snapshot(e), anchor) {
7316 (Ok(snap), Ok(last_h)) => {
7317 *slot = Some(SpecCheckpoint { snap, pos, last_h });
7318 }
7319 (s, a) => {
7320 *slot = None; // a stale checkpoint would rewind to the WRONG boundary
7321 if std::env::var("MEMRA_DEBUG_SPEC").is_ok() {
7322 let err = s
7323 .err()
7324 .map(|e| e.to_string())
7325 .or_else(|| a.err().map(|e| e.to_string()))
7326 .unwrap_or_default();
7327 eprintln!(
7328 "[spec] turn checkpoint skipped ({err}); \
7329 next turn re-primes in full"
7330 );
7331 }
7332 }
7333 }
7334 }
7335 }
7336 // INIT FEED — skipped on a pending carry: last_token (the carried bonus) is NOT in the
7337 // caches and must NOT be fed solo; round 0's batched verify commits it as col 0. Its
7338 // seed/anchor hidden is the carried last_h (copied below); last_pred is dead in the
7339 // pending path (t_pred reads verify col 0 — the accept walk overwrites it).
7340 let mut last_pred = 0u32;
7341 let mut last_col_logits: Option<CudaSlice<f32>> = None;
7342 // CONSTRAINED: the init feed's logits back the (n_acc==0, base==0) masked-argmax
7343 // recompute in the grammar-truncation walk — retained host-side, round 0 only.
7344 let mut init_logits_host: Option<Vec<f32>> = None;
7345 let h_seed0: CudaSlice<f32> = if carried_pending.is_none() {
7346 let (init_logits, h) = self.spec_target_step_h(e, last_token, &mut *cache)?;
7347 last_pred = argmax(&init_logits) as u32;
7348 if constraint.is_some() {
7349 init_logits_host = Some(init_logits.clone());
7350 }
7351 // sampled mode: p-distribution after last_token, for the j==0/base==0 accept test.
7352 if sampled {
7353 last_col_logits = Some(e.htod(&init_logits)?);
7354 }
7355 h
7356 } else {
7357 // predecessor-row anchor: hidden of the last COMMITTED row (the carry contract).
7358 let lh = sess_tail
7359 .as_ref()
7360 .unwrap()
7361 .1
7362 .as_ref()
7363 .expect("pending carry requires last_h");
7364 e.clone_dtod(lh)?
7365 };
7366 let t_init = t_ent.elapsed();
7367 let mut last_col_stats: Option<(f32, f32, f32)> = None;
7368 // PERSISTENT h_seed buffer (allocated BEFORE any graph capture so no captured scratch can
7369 // alias it): every path that updates the round seed copies INTO it — no per-round allocs,
7370 // stable pointer for the graph-draft round-start copy.
7371 let mut h_seed_buf = e.clone_dtod(&h_seed0)?;
7372 // Predecessor-pairing trackers: `fill_prev` = trunk hidden AT the last COMMITTED row (the
7373 // predecessor of the next verify's col 0 — the reference's carried pending-h analogue;
7374 // also the predecessor-row hidden for the round-0 legacy-replay seed). At round 0 that
7375 // row is last_token's own (h_seed0). The chain step-0 seed under the pairing default =
7376 // hidden of the row BEFORE last_token = the prompt's last row at round 0 (h_seed_buf
7377 // overwritten below).
7378 let mut fill_prev = e.clone_dtod(&h_seed0)?;
7379 {
7380 if let Some(ph) = &prompt_h {
7381 let np = prompt.len();
7382 e.copy_view_into(
7383 &mut h_seed_buf,
7384 0,
7385 &ph.slice((np - 1) * n_embd..np * n_embd),
7386 n_embd,
7387 )?;
7388 } else if continuation {
7389 if let Some((_, lh, _, _, _)) = sess_tail.as_ref() {
7390 if let Some(lh) = lh.as_ref() {
7391 e.copy_into(&mut h_seed_buf, 0, lh, n_embd)?;
7392 }
7393 }
7394 }
7395 }
7396 // Persistent device prediction slots for the accept walk (max k+1 verify columns).
7397 let mut preds_d = e.alloc_u32_zeroed(k + 2)?;
7398
7399 let debug_spec = std::env::var("MEMRA_DEBUG_SPEC").is_ok();
7400 let fork_mode = OptiForkGateMode::configured();
7401 // MEMRA_SPEC_STATS=1: per-slot accept histogram + draft-length histogram, printed once at
7402 // the end. Metric normalization vs the reference engine: BOTH engines count
7403 // accepted/drafted where the chain stopped at p-min and the sub-threshold token is
7404 // discarded uncounted — per-slot decay + chain-length mix are the extra dimensions.
7405 let spec_stats = std::env::var("MEMRA_SPEC_STATS").is_ok();
7406 let mut st_drafted = vec![0usize; k];
7407 let mut st_accepted = vec![0usize; k];
7408 let mut st_len_hist = vec![0usize; k + 1];
7409 let mut st_full = 0usize;
7410 // P-MIN CONFIDENCE GATE (MEMRA_SPEC_PMIN, the serve script's --spec-draft-p-min mechanism):
7411 // stop the draft chain early when the head's softmax confidence in its own pick drops
7412 // below p_min. Hoisted above the loop: the graph capture bakes the prob kernels iff on.
7413 static PMIN: std::sync::OnceLock<f32> = std::sync::OnceLock::new();
7414 let p_min = *PMIN.get_or_init(|| {
7415 std::env::var("MEMRA_SPEC_PMIN")
7416 .ok()
7417 .and_then(|v| v.parse().ok())
7418 .unwrap_or(0.0)
7419 });
7420 // ZERO-DRAFT ROUNDS (MEMRA_SPEC_PMIN0=1, vendored from llama.cpp's draft gating): let the
7421 // p-min gate apply at j==0 too, so a low-confidence round drafts NOTHING and the verify
7422 // batch is just the pending bonus (m=1 = a plain decode step). llama's 35B win rides
7423 // exactly this — draft acceptance 76% at mean len 2.5 because unpredictable stretches
7424 // never pay draft+verify overhead. Only legal when a pending bonus exists (an empty
7425 // verify batch is not); the j==0 exemption stays for pending-less rounds.
7426 let pmin0 = std::env::var("MEMRA_SPEC_PMIN0")
7427 .map(|v| v == "1")
7428 .unwrap_or(false);
7429
7430 // --- GRAPH DRAFT setup: persistent I/O buffers + ONE capture (2 warmups inside). The
7431 // warmups mutate scratch len_d / pos / tok / seed — all reset at every round start, so the
7432 // only restore needed is the scratch counter. Capture failure (e.g. a non-capturable
7433 // cuBLAS path in an exotic head) falls back to the eager draft chain.
7434 // PER-SESSION PERSISTENCE (2026-08-01): session calls reuse the DraftGraphCtx parked on
7435 // the SpecSession — the capture (2 warmup head forwards + instantiate) ran ONCE at the
7436 // session's first burst, not per burst (measured ~16ms/burst fixed cost on H100 q27,
7437 // research/spec-serving-20260801). Reuse is pointer-exact: the graph bakes the session's
7438 // own scratch KV (never realloc'd), the model's resident embedding, the OnceLock p_min,
7439 // and the g_* buffers carried in the ctx — replay dispatch is identical to a fresh
7440 // capture, so draft tokens are bit-identical (drafts never decide exactness anyway; the
7441 // verify arbitrates). Single-shot calls (sess=None) build a fresh ctx and drop it.
7442 let mut dctx: DraftGraphCtx = match sess_draft_slot.as_mut().and_then(|s| s.take()) {
7443 Some(c) => c,
7444 None => DraftGraphCtx::new(e, n_embd, if sampled { d_vocab } else { 1 })?,
7445 };
7446 // A session that ran greedy bursts first sized g_q/g_perturb at 1; a sampled resume
7447 // needs d_vocab. Realloc is legal exactly while graph_s is None (nothing baked them).
7448 if sampled && dctx.g_q.len() < d_vocab {
7449 dctx.g_q = e.zeros(d_vocab)?;
7450 dctx.g_perturb = e.zeros(d_vocab)?;
7451 }
7452 // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask, 2026-08-04): the drafter samples the
7453 // grammar's legal set, so proposals are legal BY CONSTRUCTION and the verify-side
7454 // truncation (the correctness backstop) stops cutting every tight-schema round.
7455 // The mask is one node inside the captured draft chain — presence is a CAPTURE-TIME
7456 // shape, so a parked graph of the other shape is dropped and recaptured.
7457 let dmask_on = constraint
7458 .as_deref()
7459 .is_some_and(|c| c.draft_mask_enabled());
7460 let dmask_words = if dmask_on { d_vocab.div_ceil(32) } else { 0 };
7461 if dmask_on && dctx.g_dmask.len() < dmask_words {
7462 dctx.g_dmask = e.alloc_u32_zeroed(dmask_words)?;
7463 dctx.graph = None; // the old capture baked the old (or no) mask pointer
7464 dctx.failed.clear_greedy();
7465 dctx.keeper.clear();
7466 }
7467 if dctx.graph.is_some() && dctx.graph_masked != dmask_on {
7468 dctx.graph = None;
7469 dctx.failed.clear_greedy();
7470 dctx.keeper.clear();
7471 }
7472 if graph_draft && !sampled && dctx.graph.is_none() && !dctx.failed.greedy_failed() {
7473 let DraftGraphCtx {
7474 g_tok,
7475 g_pos,
7476 g_seed,
7477 g_p,
7478 g_dmask,
7479 ..
7480 } = &mut dctx;
7481 // capture-time contents: ALL-ONES (ban nothing). A replay only ever runs after the
7482 // host uploads the position's real words, so the warmups stay grammar-free.
7483 if dmask_on {
7484 e.htod_u32_into(g_dmask, &vec![u32::MAX; dmask_words])?;
7485 }
7486 let g_dmask_ro: &CudaSlice<u32> = &*g_dmask;
7487 // CAPTURE-RETAIN (#68 fix): the warmup transients' pool addresses are baked into the
7488 // captured graph; the keeper pins them for the graph's lifetime. capture_graph (non-
7489 // retained) freed them at exit — safe for one-shot generate_spec (nothing else touches
7490 // the pool between replays) but WRONG for sessions: burst-boundary prime/fill/commit
7491 // passes (and, in serve, other sessions) recycle those addresses and the replay then
7492 // clobbers live buffers — the ST serve-spec corruption (research/serve-st-20260803).
7493 let cap_res = e.capture_graph_retained(|e| {
7494 self.mtp_head_forward_cap(
7495 e,
7496 mtp,
7497 g_tok,
7498 g_pos,
7499 g_seed,
7500 g_p,
7501 &mut *scratch,
7502 p_min > 0.0 || fork_mode == OptiForkGateMode::Controller,
7503 true,
7504 embd_gpu.expect("graph draft requires resident embedding"),
7505 embd_qt,
7506 embd_rb,
7507 d_vocab,
7508 None,
7509 None,
7510 if dmask_on {
7511 Some((g_dmask_ro, dmask_words))
7512 } else {
7513 None
7514 },
7515 )
7516 });
7517 match cap_res {
7518 Ok((g, keep)) => {
7519 scratch.set_len(e, base)?;
7520 dctx.graph = Some(g);
7521 dctx.graph_masked = dmask_on;
7522 dctx.keeper = keep;
7523 }
7524 Err(err) => {
7525 scratch.set_len(e, base)?;
7526 // LOUD flip (audit Q2): a dropped draft graph is a coverage loss, never
7527 // silent. Once per flip — mark returns None on an already-failed ctx.
7528 if let Some(line) = dctx.failed.mark_greedy(&err.to_string()) {
7529 eprintln!("{line}");
7530 }
7531 }
7532 }
7533 }
7534 // --- SAMPLED GRAPH DRAFT setup (step 3 of the sampled-spec arc): a SECOND capture, own
7535 // graph object, built only when sampled && graph-eligible — the greedy capture above is
7536 // untouched (and skipped when sampled: its graph would never be launched). Same head
7537 // forward, but the in-graph argmax reads GUMBEL-PERTURBED logits; the Philox event
7538 // counter lives in the persistent device g_ctr (bumped in-graph, host-seeded from sctr
7539 // once per round); the raw head logits land in the persistent g_q for the host's
7540 // per-replay async D2D into the round's q slot (q_slots, K x d_vocab, allocated once).
7541 // seed/temp are capture-time constants — baked into graph_s, so a pool-resumed request
7542 // with a different (seed, temp, k) drops the parked sampled graph and recaptures.
7543 // COST OF THE FRESH-SEED SERVE DEFAULT (dogfood F4, 2026-08-04): omitting `seed` on a
7544 // serve request now draws fresh per-request entropy (it used to default to a pinned 0),
7545 // so a seed-omitting request that RESUMES a parked spec session finds an s_key baked
7546 // with the PREVIOUS request's seed and pays one recapture. Bounded, and it does not
7547 // reopen the ~16ms/burst regression the persistent ctx exists to fix: a session's seed
7548 // is fixed for its whole lifetime (worker.rs reads s.sampler.seed() per burst), so
7549 // this compare misses at most ONCE per resumed request — the first burst recaptures
7550 // and every later burst in that request replays. A client that wants the parked graph
7551 // AND reproducibility supplies an explicit `seed`, honored exactly, which keeps s_key
7552 // stable across its whole conversation.
7553 // COMPOSITION RULE (fspec x gsd merge): the in-graph chain samples from the RAW
7554 // softmax — it can hold neither per-row filter stats nor the varying penalty history.
7555 // The sampled graph therefore engages only in the PURE-TEMP regime; filters/penalties
7556 // force the eager draft (which computes stats/penalties per row).
7557 let pure_temp = sp.top_k == 0 && sp.top_p >= 1.0 && sp.min_p <= 0.0 && !pen_on;
7558 let s_key = (sp_seed, sp_temp.to_bits(), k);
7559 if sampled && dctx.s_key.is_some_and(|old| old != s_key) {
7560 dctx.graph_s = None;
7561 dctx.failed.clear_sampled();
7562 dctx.s_key = None;
7563 dctx.q_slots.clear();
7564 dctx.keeper_s.clear();
7565 }
7566 if graph_draft
7567 && sampled
7568 && pure_temp
7569 && dctx.graph_s.is_none()
7570 && !dctx.failed.sampled_failed()
7571 {
7572 let DraftGraphCtx {
7573 g_tok,
7574 g_pos,
7575 g_seed,
7576 g_p,
7577 g_ctr,
7578 g_perturb,
7579 g_q,
7580 ..
7581 } = &mut dctx;
7582 // CAPTURE-RETAIN (#68 fix): same keeper contract as the greedy capture above.
7583 let cap_res = e.capture_graph_retained(|e| {
7584 self.mtp_head_forward_cap(
7585 e,
7586 mtp,
7587 g_tok,
7588 g_pos,
7589 g_seed,
7590 g_p,
7591 &mut *scratch,
7592 p_min > 0.0,
7593 true,
7594 embd_gpu.expect("graph draft requires resident embedding"),
7595 embd_qt,
7596 embd_rb,
7597 d_vocab,
7598 Some((g_ctr, g_perturb, g_q, sp_seed, sp_temp)),
7599 None,
7600 None, // constrained spec is greedy-only — sampled never carries a hook
7601 )
7602 });
7603 match cap_res {
7604 Ok((g, keep)) => {
7605 scratch.set_len(e, base)?;
7606 for _ in 0..k {
7607 dctx.q_slots.push(e.zeros(d_vocab)?);
7608 }
7609 dctx.graph_s = Some(g);
7610 dctx.s_key = Some(s_key);
7611 dctx.keeper_s = keep;
7612 }
7613 Err(err) => {
7614 scratch.set_len(e, base)?;
7615 // LOUD flip (audit Q2): same contract as the greedy capture above.
7616 if let Some(line) = dctx.failed.mark_sampled(&err.to_string()) {
7617 eprintln!("{line}");
7618 }
7619 }
7620 }
7621 }
7622 let t_cap = t_ent.elapsed();
7623 // PERSISTENT DRAFT KV: fill the MTP block's K/V for every prompt position from the exact
7624 // trunk hiddens collected during prime — ONE batched K/V-only pass (overwrites any
7625 // capture-warmup garbage; capture left len at 0). last_token (the init feed) needs no
7626 // fill: the first chain step processes it and appends its entry at slot prompt.len().
7627 if let Some(ph) = &prompt_h {
7628 // SESSION: rows [0..base) are the previous turns' exact fills (refresh overwrote them
7629 // with true verify hiddens) — truncate any draft overhang, fill ONLY the suffix at
7630 // global positions [base..base+tp). Fresh call: base==0, identical to before.
7631 scratch.set_len(e, base)?;
7632 // CHUNKED FILL (long-ctx OOM fix, 2026-07-05): mtp_kv_fill's transients scale with its
7633 // T (concat = T*2*n_embd*4B — 1.5GB at 40k) and its concat loop is 2*T launches. The
7634 // fill is a pure sequential append, so chunking is exact: each chunk appends its rows
7635 // at pos0=base+start with the identical per-row math. Same knob as the trunk prime.
7636 let tp = prompt.len();
7637 let fill_chunk: usize = if crate::cache::swa_ring_on() {
7638 crate::hybrid_forward::prime_chunk_tokens(tp, self.layers.len())
7639 } else {
7640 // Preserve the flag-OFF schedule byte-for-byte, including the legacy zero value
7641 // meaning one monolithic fill.
7642 std::env::var("MEMRA_PRIME_CHUNK")
7643 .ok()
7644 .and_then(|v| v.parse().ok())
7645 .unwrap_or(4096)
7646 };
7647 let fill_chunk = if fill_chunk == 0 { tp } else { fill_chunk };
7648 let mut start = 0usize;
7649 while start < tp {
7650 let end = (start + fill_chunk).min(tp);
7651 let tc = end - start;
7652 {
7653 // PREDECESSOR pairing: row i gets h[i-1]; global row 0 a zeros row (the
7654 // reference engine's initial pending-h is zeroed too); a session turn's row 0
7655 // gets the PREVIOUS turn's last committed hidden (sess.last_h). Per chunk:
7656 // rows start..end read h[start-1..end-1] — one dtod into a chunk buffer.
7657 let mut phs = e.zeros(tc * n_embd)?;
7658 let (src_lo, dst_off) = if start == 0 {
7659 (0, n_embd)
7660 } else {
7661 ((start - 1) * n_embd, 0)
7662 };
7663 let n_copy = if start == 0 {
7664 (tc - 1) * n_embd
7665 } else {
7666 tc * n_embd
7667 };
7668 if start == 0 {
7669 if let Some((_, lh, _, _, _)) = sess_tail.as_ref() {
7670 if let Some(lh) = lh.as_ref() {
7671 e.copy_into(&mut phs, 0, lh, n_embd)?;
7672 }
7673 }
7674 }
7675 if n_copy > 0 {
7676 e.copy_view_into(
7677 &mut phs,
7678 dst_off,
7679 &ph.slice(src_lo..src_lo + n_copy),
7680 n_copy,
7681 )?;
7682 }
7683 self.mtp_kv_fill(
7684 e,
7685 mtp,
7686 &prompt[start..end],
7687 &phs,
7688 base + start,
7689 &mut *scratch,
7690 embd_dev,
7691 )?;
7692 }
7693 start = end;
7694 }
7695 }
7696 // MEMRA_PROFILE_SPEC=2: profiler capture starts HERE — after the prime, so an
7697 // `nsys -c cudaProfilerApi` capture contains ONLY the round loop (draft/verify/commit).
7698 // (=1 brackets the whole call in run_spec.rs, prime included.)
7699 if std::env::var("MEMRA_PROFILE_SPEC").as_deref() == Ok("2") {
7700 unsafe extern "C" {
7701 fn cudaProfilerStart() -> i32;
7702 }
7703 unsafe {
7704 cudaProfilerStart();
7705 }
7706 }
7707 // ROUND-STREAM stage (c) 4 (MEMRA_SPEC_STREAM=1, experimental): pre-issued M-round
7708 // bursts with ZERO per-round host readbacks — the accept/seed/rollback/ring kernels
7709 // consume each other's device outputs; the host drains the ring every M rounds. v1
7710 // constraints: greedy, !spec_replay, single-shot, batched-linear layers, no refresh
7711 // fills (acceptance effect A/B-arbitrated), enters from round 1 (pending guaranteed).
7712 // NOTE: not gated on the caller's graph_draft (its trunk_dense conjunct turns the 35B
7713 // MoE off) — the stream capture encloses ONLY the dense MTP head; the head-dense /
7714 // full-prec / k gates are re-derived here and a failed capture degrades to stream-off.
7715 let stream_on = crate::spec::spec_stream()
7716 && !sampled
7717 && !spec_replay
7718 && constraint.is_none()
7719 && !session_mode
7720 && embd_gpu.is_some()
7721 && !crate::model::full_prec_enabled()
7722 && k + 2 < 96;
7723 let mut stream_graph: Option<cudarc::driver::CudaGraph> = None;
7724 let mut g_tokp2k = e.alloc_u32_zeroed(2 * k.max(1))?;
7725 if stream_on {
7726 let cap = e.capture_graph(|e| {
7727 for j in 0..k.max(1) {
7728 self.mtp_head_forward_cap(
7729 e,
7730 mtp,
7731 &mut dctx.g_tok,
7732 &mut dctx.g_pos,
7733 &mut dctx.g_seed,
7734 &mut dctx.g_p,
7735 &mut *scratch,
7736 true,
7737 true,
7738 embd_gpu.expect("round stream requires resident embedding"),
7739 embd_qt,
7740 embd_rb,
7741 d_vocab,
7742 None,
7743 Some((&mut g_tokp2k, j, d2t_dev.as_ref())),
7744 None, // round-stream requires constraint.is_none() (see stream_on)
7745 )?;
7746 }
7747 Ok(())
7748 });
7749 match cap {
7750 Ok(g) => {
7751 scratch.set_len(e, 0)?;
7752 stream_graph = Some(g);
7753 }
7754 Err(err) => {
7755 scratch.set_len(e, 0)?;
7756 if debug_spec {
7757 eprintln!("[spec] stream-graph capture failed ({err}); stream off");
7758 }
7759 }
7760 }
7761 }
7762 let stream_active = stream_on && stream_graph.is_some();
7763 if debug_spec {
7764 eprintln!(
7765 "[spec] stream_on={stream_on} env={} samp={sampled} dg={} captured={} active={stream_active} session={session_mode} replay={spec_replay}",
7766 crate::spec::spec_stream(),
7767 dctx.graph.is_some(),
7768 stream_graph.is_some()
7769 );
7770 }
7771 let t_v_s = k + 1;
7772 // ROUND-STREAM buffers + ptr tables now live in the model-generic round_stream
7773 // module (extracted 2026-07-12; the gemma burst reuses them).
7774 let sb = crate::round_stream::StreamBufs::new(e, k, crate::spec::spec_stream_m())?;
7775 let crate::round_stream::StreamBufs {
7776 mut vtok_d,
7777 mut brk_d,
7778 mut pend_d,
7779 last_pred_d,
7780 mut pos_ctr,
7781 mut pos_start_d,
7782 mut ring_d,
7783 acc_d: mut stream_acc,
7784 m_rounds,
7785 k: _,
7786 } = sb;
7787 let stream_ptrs: Option<CudaSlice<u64>> = if stream_active {
7788 Some(crate::round_stream::kv_len_ptr_table(
7789 e,
7790 cache,
7791 Some(&pos_ctr),
7792 )?)
7793 } else {
7794 None
7795 };
7796
7797 let t_fill = t_ent.elapsed();
7798 let mut round = 0usize;
7799 // ADAPTIVE DRAFT LENGTH (MEMRA_SPEC_ADAPT=1, opt-in — the gemma_spec accepted-run law,
7800 // ported 2026-08-01): next round's draft depth = last round's accepted run + 1, clamped
7801 // to [floor(pos), k_cap] — a miss shrinks the next draft to the miss point + 1,
7802 // full-accept streaks re-deepen one step per round. NOT the 2026-07-07 acceptance-EMA
7803 // (that arm measured an HONEST LOSS to static per-class optima — 115.0/85.8/73.4 vs
7804 // 121.6/92.7/75.6, EMA lag — and was removed 2026-07-08; rig5090.jsonl has the record).
7805 // The gemma law has no lag class: it reacts within one round, and was worth +7-20% on
7806 // the gemma cells at unchanged exactness (2026-07-10 flip; floor sweep 2026-07-25;
7807 // position key 2026-07-26). Signal = n_acc from the round's EXISTING accept readback —
7808 // zero new syncs; the draft graph is a SINGLE-STEP capture replayed per drafted token,
7809 // so a per-round depth needs no re-capture (unlike gemma's whole-chain graphs). qwen's
7810 // in-round p-min cut already shortens chains mid-round, so gemma's one-round-late p-min
7811 // fold into kc is unnecessary here — the accepted-run law sees the cut via n_acc.
7812 // Exactness is the verify's job at ANY depth (same contract as p-min variable rounds).
7813 // DEFAULT OFF on the qwen path until its cells gate a flip (gemma's is default-on).
7814 // MEASURED 2026-08-01 (H100 GPU-3, interleaved x3, NGEN=256, same-invocation plain
7815 // denominators; research/qwen-adaptive-k-20260801/): REFUTED on the tuned qwen configs.
7816 // q27 K=3+HPOST+PMIN=0.3: short +0.8% (noise; law ~idles, len_hist identical), board
7817 // -1.9%, agentic -0.5%; board PMIN=0 -2.1% (not p-min shadowing — the law itself);
7818 // floor=1 -2.8% (gemma's floor-collapse, reproduced). q35 K=2 board: -6.4% (52/136
7819 // rounds shrink to depth 1; no depth to reclaim at K=2). The gemma direction DOES
7820 // appear at untuned depth-K — q27 K=6 floor=4 +1.5% over fixed K=6 — but stays -3.7%
7821 // below fixed K=3: same verdict class as the retired EMA arm (honest loss to static
7822 // per-class optima). Acceptance-rate rises under the law while tokens/round falls —
7823 // it buys accept-% by adding rounds, and a round's fixed draft+verify cost wins.
7824 // K=1..8 self-consistency PASS both models with the law ON (exactness held).
7825 let adapt = std::env::var("MEMRA_SPEC_ADAPT").as_deref() == Ok("1");
7826 // floor: per-model default keyed on n_embd (gemma's tiering — models with an expensive
7827 // verify keep deep drafts after a miss); MEMRA_SPEC_ADAPT_FLOOR pins it everywhere.
7828 let adapt_floor_env: Option<usize> = std::env::var("MEMRA_SPEC_ADAPT_FLOOR")
7829 .ok()
7830 .and_then(|v| v.parse().ok());
7831 let adapt_floor_default: usize = if self.cfg.n_embd as usize >= 3500 {
7832 4
7833 } else if self.cfg.n_embd as usize >= 2500 {
7834 2
7835 } else {
7836 1
7837 };
7838 let adapt_floor: usize = adapt_floor_env.unwrap_or(adapt_floor_default);
7839 // position key: past floor_ctx a HIGH floor (>=4) relaxes to 1 — forced-deep drafts
7840 // turn net-negative at depth (gemma 31B d1736 evidence); MEMRA_SPEC_FLOOR_CTX moves
7841 // the boundary, an explicit MEMRA_SPEC_ADAPT_FLOOR pins the floor everywhere.
7842 let floor_ctx: usize = std::env::var("MEMRA_SPEC_FLOOR_CTX")
7843 .ok()
7844 .and_then(|v| v.parse().ok())
7845 .unwrap_or(1024);
7846 let floor_at = |pos: usize| -> usize {
7847 if adapt_floor_env.is_some() || pos < floor_ctx {
7848 adapt_floor
7849 } else if adapt_floor >= 4 {
7850 1
7851 } else {
7852 adapt_floor
7853 }
7854 };
7855 // cap: MEMRA_SPEC_CAPMAX (gemma semantics, default 7). Binds only under adapt — the
7856 // fixed-K default path is untouched by this whole block.
7857 let cap_max: usize = std::env::var("MEMRA_SPEC_CAPMAX")
7858 .ok()
7859 .and_then(|v| v.parse().ok())
7860 .unwrap_or(7);
7861 let k_cap = k.min(cap_max).max(1);
7862 let mut kc = k_cap;
7863 let mut opti_fork: Option<OptiForkState> = None;
7864 let mut fork_snapshot: Option<crate::cache::CacheSnapshot> = None;
7865 if fork_mode != OptiForkGateMode::Disabled {
7866 let fence = crate::pp::pp_cuts(self.layers.len());
7867 let refusal = if !session_mode {
7868 Some("not-session")
7869 } else if k != 1 || adapt {
7870 Some("requires-fixed-k1")
7871 } else if sampled || constraint.is_some() || spec_replay {
7872 Some("sampled-constrained-or-replay")
7873 } else if pipe.is_some() {
7874 Some("two-session-pipeline")
7875 } else if !spec_devacc() {
7876 Some("requires-device-accept")
7877 } else if stream_active || crate::spec::spec_stream() {
7878 Some("round-stream")
7879 } else if crate::cache::swa_ring_on() || cache.has_swa_ring() {
7880 Some("swa-ring")
7881 } else if crate::pp::pp_host_bounce_active() {
7882 Some("host-bounce")
7883 } else if fork_mode == OptiForkGateMode::Controller
7884 && cache.recur.iter().any(Option::is_some)
7885 {
7886 Some("controller-requires-zero-recurrent-state")
7887 } else if fence.as_ref().is_none_or(|f| f.len() != 3) {
7888 Some("requires-pp2")
7889 } else {
7890 None
7891 };
7892 if let Some(reason) = refusal {
7893 OPTI_FORK_REFUSALS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7894 eprintln!("[opti-fork] refused reason={reason}");
7895 } else {
7896 let fence = fence.expect("validated PP-2 fence");
7897 let rt = crate::pp::PpNRt::get(e)?;
7898 let primary_stage0 = rt.engine(0, e).ctx().ordinal() == e.ctx().ordinal();
7899 let primary_stage1 = rt.engine(1, e).ctx().ordinal() == e.ctx().ordinal();
7900 let primary_supported =
7901 primary_stage0 || (fork_mode == OptiForkGateMode::Controller && primary_stage1);
7902 if !rt.cross_device() || !primary_supported {
7903 OPTI_FORK_REFUSALS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7904 eprintln!("[opti-fork] refused reason=requires-supported-primary-cross-device");
7905 } else {
7906 // Both recurrent snapshots and both seed generations are allocated before
7907 // the first fork, each through its owning PP stage. Allocation failure
7908 // therefore happens before any optimistic state mutation can occur.
7909 let current_snapshot = opti_snapshot_stage_owned(e, cache, rt, &fence)?;
7910 let alternate_snapshot = opti_snapshot_stage_owned(e, cache, rt, &fence)?;
7911 let fork = OptiForkState::new(
7912 e,
7913 cache,
7914 fork_mode,
7915 alternate_snapshot,
7916 &h_seed_buf,
7917 &fill_prev,
7918 rt,
7919 fence[1],
7920 self.layers.len(),
7921 )?;
7922 eprintln!(
7923 "[opti-fork] armed mode={fork_mode:?} snapshots=2 seeds=2 split={} \
7924 payload_dev0={} payload_dev1={} q_threshold={:.3}",
7925 fence[1],
7926 fork.logical_payload_bytes[0],
7927 fork.logical_payload_bytes[1],
7928 fork.controller.map_or(0.0, |policy| policy.threshold),
7929 );
7930 fork_snapshot = Some(current_snapshot);
7931 opti_fork = Some(fork);
7932 }
7933 }
7934 }
7935 // Persistent snapshot buffers are allocated once and refreshed in place. The fork arm
7936 // uses stage-owned snapshots; refused/disabled arms retain the existing generic helper.
7937 let mut snap = match fork_snapshot {
7938 Some(snapshot) => snapshot,
7939 None => cache.snapshot(e)?,
7940 };
7941 let mut carried_opti: Option<OptiControllerTicket> = None;
7942 // ROUND-STREAM stage (b) 3a: device table of per-layer kvl.len_d pointers (stable — the
7943 // cache never reallocates len_d; see cache.rs "stable pointer" note). 0 = no KV layer.
7944 let kv_len_ptrs: Option<CudaSlice<u64>> = if spec_devacc() && !spec_replay {
7945 Some(crate::round_stream::kv_len_ptr_table(e, cache, None)?)
7946 } else {
7947 None
7948 };
7949 // BONUS FOLD (2026-07-04): after a FULL accept the bonus token is NOT committed with a
7950 // separate T=1 trunk pass (a full weight read per round). It stays PENDING and rides as
7951 // column 0 of the NEXT round's verify batch. Under predecessor pairing the next chain
7952 // seeds from the bonus's predecessor's TRUE verify hidden (free — no extra
7953 // pass of any kind). Verify still
7954 // checks every emitted token against the target -> exactness holds by construction; only
7955 // DRAFT QUALITY can shift, which the acceptance numbers arbitrate.
7956 // bonus emitted but not yet committed to cache. A carried pending (see SpecSession::
7957 // pending_tok) enters round 0 directly — the burst boundary becomes a plain round edge.
7958 let mut pending: Option<u32> = carried_pending;
7959 // MEMRA_SPEC_PHASE=1: per-round wall decomposition (draft / verify / accept+commit) —
7960 // no tracing, no extra syncs (each phase is naturally sync-bounded: draft readbacks,
7961 // the verify accept readback). Printed once at loop end via spec-stats.
7962 let anatomy_on = std::env::var("MEMRA_SPEC_PP_ANATOMY").as_deref() == Ok("1");
7963 let phase_on = anatomy_on || std::env::var("MEMRA_SPEC_PHASE").as_deref() == Ok("1");
7964 // DRAFT-MASK receipt (lane/draft-mask): speculative-clone wall + rounds, printed with
7965 // spec-stats. The clone is the one cost the design adds per round — measured, not assumed.
7966 let (mut dm_clone_ns, mut dm_rounds) = (0u128, 0usize);
7967 // grammar-truncation counters: how many rounds the verify-side cut fired and how many
7968 // already-verified tokens it threw away. THIS is the quantity draft masking targets.
7969 let (mut dm_cuts, mut dm_cut_tokens) = (0usize, 0usize);
7970 let (mut ph_draft, mut ph_verify, mut ph_rest) = (0f64, 0f64, 0f64);
7971 let mut ph_wait = 0f64;
7972 let mut ph_commit = 0f64;
7973 let mut ph_t = std::time::Instant::now();
7974 let mut ph_mark = |acc: &mut f64, on: bool| {
7975 if on {
7976 let now = std::time::Instant::now();
7977 *acc += (now - ph_t).as_secs_f64();
7978 ph_t = now;
7979 }
7980 };
7981 if let Some(p) = pipe {
7982 p.setup_end();
7983 }
7984 while keep_going && out.len() < max_new {
7985 // ROUND-STREAM BURST: from round 1 (pending guaranteed by every non-replay arm),
7986 // issue M rounds with zero readbacks, then drain the ring + reconcile mirrors.
7987 if let (true, Some(sg), Some(ptrs)) = (
7988 stream_active && round >= 1 && pending.is_some(),
7989 &stream_graph,
7990 &stream_ptrs,
7991 ) {
7992 if debug_spec {
7993 static ONCE: std::sync::Once = std::sync::Once::new();
7994 ONCE.call_once(|| {
7995 eprintln!("[memra] ROUND-STREAM burst engaged (M={m_rounds} k={k})")
7996 });
7997 }
7998 e.set_i32_one(&mut pos_ctr, cache.pos as i32)?;
7999 e.set_u32_one(&mut pend_d, pending.unwrap())?;
8000 e.set_u32_one(&mut ring_d, 0)?; // ring count = 0 (writes element 0)
8001 for _mi in 0..m_rounds {
8002 e.i32_copy_add(&pos_ctr, &mut pos_start_d, 0)?;
8003 cache.snapshot_into(e, &mut snap)?; // device D2Ds, stream-ordered
8004 e.i32_copy_add(&pos_ctr, &mut scratch.kv.len_d, 0)?; // draft-KV rollback
8005 e.i32_copy_add(&pos_ctr, &mut dctx.g_pos, 1)?; // rope pos = pos + base
8006 e.u32_copy(&pend_d, &mut dctx.g_tok)?;
8007 e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
8008 sg.launch()?;
8009 e.spec_assemble_verify(
8010 &g_tokp2k,
8011 &pend_d,
8012 d2t_dev.as_ref(),
8013 &mut vtok_d,
8014 &mut brk_d,
8015 p_min,
8016 k,
8017 pmin0,
8018 )?;
8019 let mut ck = VerifyCkpt::new(self.layers.len());
8020 let dummy = vec![0u32; t_v_s];
8021 let (tl_d, vx) = self.decode_step_t_core_stream(
8022 e,
8023 &dummy,
8024 0,
8025 &mut *cache,
8026 embd_dev,
8027 Some(&mut ck),
8028 Some((&vtok_d, &pos_ctr)),
8029 None,
8030 )?;
8031 for j in 0..t_v_s {
8032 e.argmax_token_device_col(&tl_d, j, n_vocab, &mut preds_d, j)?;
8033 }
8034 e.spec_accept_greedy_dc(
8035 &preds_d,
8036 &vtok_d,
8037 &last_pred_d,
8038 &brk_d,
8039 &mut stream_acc,
8040 )?;
8041 e.spec_seed_gather(&vx, &fill_prev, &stream_acc, &mut h_seed_buf, 1, n_embd)?;
8042 e.copy_into(&mut fill_prev, 0, &h_seed_buf, n_embd)?;
8043 self.commit_verified_prefix_stream(
8044 e,
8045 &mut *cache,
8046 &snap,
8047 &ck,
8048 &stream_acc,
8049 1,
8050 t_v_s,
8051 )?;
8052 e.spec_rollback_stream(
8053 ptrs,
8054 &pos_start_d,
8055 &stream_acc,
8056 1,
8057 self.layers.len() + 1,
8058 )?;
8059 e.spec_ring_commit(&vtok_d, &stream_acc, &brk_d, &mut ring_d, &mut pend_d)?;
8060 }
8061 e.stream().synchronize()?;
8062 let ring_h = e.dtoh_u32(&ring_d)?;
8063 let cnt = ring_h[0] as usize;
8064 for i in 0..cnt {
8065 if out.len() < max_new {
8066 out.push(ring_h[1 + i]);
8067 }
8068 }
8069 let pos_h = e.dtoh_i32(&pos_ctr)?[0] as usize;
8070 for il in 0..self.layers.len() {
8071 if let Some(kvl) = cache.kv[il].as_mut() {
8072 kvl.len = pos_h;
8073 }
8074 }
8075 cache.pos = pos_h;
8076 scratch.kv.len = pos_h;
8077 pending = Some(ring_h[cnt]); // last drained token = the live bonus
8078 last_token = ring_h[cnt];
8079 total_drafted += k * m_rounds; // upper bound (p-min breaks uncounted)
8080 total_accepted += cnt.saturating_sub(m_rounds);
8081 if let Some(t) = sess_telem {
8082 // totals only — the burst's per-round accept counts stayed on device
8083 // (that is the point of the round-stream arm). pos_* untouched.
8084 t.record_totals(m_rounds, k * m_rounds, cnt.saturating_sub(m_rounds));
8085 }
8086 round += m_rounds;
8087 // sse-cadence: the drained ring is committed — flush it at burst-drain cadence.
8088 keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
8089 continue;
8090 }
8091 let pipe_draft = match pipe {
8092 Some(p) => Some(p.draft_begin(round)?),
8093 None => None,
8094 };
8095 let pos = cache.pos; // #tokens committed (EXCLUDES a pending bonus)
8096 let mut current_opti = carried_opti.take();
8097 let mut fork_generation = if current_opti.is_none() && pending.is_some() {
8098 match opti_fork.as_mut() {
8099 Some(fork) if fork.mode.is_forced() => Some(fork.reserve(&mut snap)?),
8100 None => None,
8101 Some(_) => None,
8102 }
8103 } else {
8104 None
8105 };
8106 if current_opti.is_none() {
8107 if let Some(fork) = opti_fork.as_ref() {
8108 opti_snapshot_stage_owned_into(e, cache, fork.rt, &fork.fence, &mut snap)?;
8109 } else {
8110 cache.snapshot_into(e, &mut snap)?;
8111 }
8112 } else if snap.pos != pos {
8113 return Err(format!(
8114 "optipipe carried snapshot pos {} != current pos {pos}",
8115 snap.pos
8116 )
8117 .into());
8118 } // §C: snapshot BEFORE draft+verify (already retained for a carried successor)
8119 ph_mark(&mut ph_rest, phase_on);
8120
8121 // --- 1. DRAFT k tokens with the NextN head (autoregressive, T=1 each) ---
8122 // p-min semantics (both paths): stop the chain early when the head's confidence in
8123 // its own pick drops below p_min — the just-drafted token is DISCARDED, but its
8124 // scratch append stands (identical to the eager chain's ordering). j==0 always drafts.
8125 let base0 = if pending.is_some() { 1usize } else { 0usize };
8126 // fixed draft length by default; MEMRA_SPEC_ADAPT=1 drafts at last round's
8127 // accepted run + 1 (the gemma law — see the setup block above the loop).
8128 let k_this = if adapt { kc } else { k };
8129 let mut draft: Vec<u32> = Vec::with_capacity(k);
8130 let mut draft_idx: Vec<u32> = Vec::with_capacity(k); // trimmed-vocab ids (== draft when untrimmed)
8131 let mut controller_draft_prob: Option<f32> = None;
8132 let mut controller_eager_state: Option<(u32, CudaSlice<f32>)> = None;
8133 if let Some(ticket) = current_opti.as_mut() {
8134 let carried_pending = pending.ok_or("optipipe carried successor lost pending")?;
8135 if ticket.verify_tokens[0] != carried_pending {
8136 return Err(format!(
8137 "optipipe carried pending mismatch: ticket={} live={carried_pending}",
8138 ticket.verify_tokens[0],
8139 )
8140 .into());
8141 }
8142 draft.push(ticket.verify_tokens[1]);
8143 controller_draft_prob = Some(ticket.draft_prob);
8144 controller_eager_state = ticket
8145 .take_eager_seed()
8146 .map(|seed| (ticket.verify_tokens[1], seed));
8147 } else {
8148 // Round-start draft-KV sync (BOTH paths). Persistent: truncate/align to the committed
8149 // history — slots 0..P hold entries for the tokens before last_token@P (P = pos +
8150 // base0 - 1); this single set_len IS the draft-side rollback (drops last round's
8151 // rejected drafts and p-min extras via the len mechanism).
8152 scratch.set_len(e, pos + base0 - 1)?;
8153 if pen_on {
8154 let w0 = pen_hist.len().saturating_sub(sp.penalty_last_n);
8155 pen_hist_d = Some(e.htod_u32_v(&pen_hist[w0..])?);
8156 }
8157 if sampled {
8158 draft_logits.clear();
8159 draft_stats.clear();
8160 }
8161 // DRAFT-SIDE GRAMMAR MASK: clone the committed grammar state ONCE per round; each
8162 // position's mask is computed on that clone and advanced by the PROPOSED token. The
8163 // real state moves only on emission (verify's job), so the emitted stream is
8164 // unchanged — the mask only removes tokens the verify would have truncated anyway.
8165 let mut dmask_live = dmask_on;
8166 if dmask_live {
8167 let t_c = std::time::Instant::now();
8168 constraint
8169 .as_deref_mut()
8170 .unwrap()
8171 .draft_begin()
8172 .map_err(|e2| format!("constraint: {e2}"))?;
8173 dm_clone_ns += t_c.elapsed().as_nanos();
8174 dm_rounds += 1;
8175 }
8176 if let (false, Some(gr)) = (sampled || pen_on, &dctx.graph) {
8177 // GRAPH DRAFT: one dispatch per drafted token. The chain feeds itself on-device
8178 // (in-graph argmax -> tok_d -> next replay's embed; h_nextn -> h_seed_d; pos_d
8179 // inc'd in-graph); the host only reads 4B token (+4B p) and decides the break.
8180 e.set_i32_one(&mut dctx.g_pos, (pos + base0) as i32)?;
8181 e.set_u32_one(&mut dctx.g_tok, last_token)?;
8182 e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
8183 for j in 0..k_this {
8184 // per-position mask upload (contents only — the graph's baked pointer is
8185 // dctx.g_dmask). All-ones once masking goes dead mid-chain, so the captured
8186 // mask node degrades to a no-op ban instead of needing a second graph.
8187 if dmask_live
8188 && !upload_draft_mask(
8189 e,
8190 constraint.as_deref_mut().unwrap(),
8191 &mut dctx.g_dmask,
8192 mtp.d2t.as_ref(),
8193 d_vocab,
8194 dmask_words,
8195 )?
8196 {
8197 // no draft-vocab row is grammar-legal here (a trimmed FR-Spec head can
8198 // genuinely miss the legal set): neutralize the captured mask node and
8199 // finish the chain UNMASKED — exactly pre-lane behaviour, never worse.
8200 e.htod_u32_into(&mut dctx.g_dmask, &vec![u32::MAX; dmask_words])?;
8201 dmask_live = false;
8202 }
8203 gr.launch()?;
8204 scratch.kv.len += 1; // host mirror (len_d advanced in-graph)
8205 let idx = e.dtoh_u32_one(&dctx.g_tok)?;
8206 // #87 SENTINEL TRAP: an all-NaN head-logits row leaves the device argmax's
8207 // init sentinel (0x7FFFFFFF) in g_tok — feeding it onward dereferences
8208 // embed_row(sentinel) = table + ~4.6TB (never mapped) inside the NEXT graph
8209 // replay's embed node, and the MMU fault kills the CUDA context for the
8210 // whole process (research/pp2spec-crash-20260807: 3 coredumps, byte-exact
8211 // VA arithmetic). Refuse loudly instead; the diagnostics name the first-NaN
8212 // buffer (g_seed = the verify-side handoff vs head-side compute).
8213 if (idx as usize) >= d_vocab {
8214 // g_seed is SELF-FED (the replay writes h_nextn back into it), so it
8215 // reads as the head's OUTPUT at j; h_seed_buf is the round's INPUT
8216 // seed, untouched since the round-start copy — the pair discriminates
8217 // "seed arrived poisoned" from "head forward produced NaN".
8218 let seed_h = e.dtoh(&dctx.g_seed)?;
8219 let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
8220 let in_h = e.dtoh(&h_seed_buf)?;
8221 let in_nan = in_h.iter().filter(|v| v.is_nan()).count();
8222 return Err(format!(
8223 "draft(graph) argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab} at \
8224 round {round} j={j} pos={pos}: head-out NaN {seed_nan}/{n_embd}, \
8225 round-input-seed NaN {in_nan}/{n_embd} — refusing to dereference \
8226 the embed row (#87 trap)"
8227 )
8228 .into());
8229 }
8230 // trimmed draft vocab -> target token id (identity when no d2t map)
8231 let d = match &mtp.d2t {
8232 Some(map) => map[idx as usize],
8233 None => idx,
8234 };
8235 let draft_p = if p_min > 0.0
8236 || opti_fork
8237 .as_ref()
8238 .is_some_and(|fork| fork.controller.is_some())
8239 {
8240 Some(e.dtoh(&dctx.g_p)?[0])
8241 } else {
8242 None
8243 };
8244 if j == 0 {
8245 controller_draft_prob = draft_p;
8246 }
8247 if let Some(p) = draft_p.filter(|_| p_min > 0.0) {
8248 if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
8249 break;
8250 }
8251 }
8252 draft.push(d);
8253 // with a trimmed head the NEXT embed must read the TARGET id, not the draft
8254 // index the argmax wrote — patch the persistent token buffer (4B htod).
8255 if d != idx {
8256 e.set_u32_one(&mut dctx.g_tok, d)?;
8257 }
8258 // advance the SPECULATIVE state with the proposal; a dead chain drops to
8259 // unmasked drafting for the remaining positions (verify still arbitrates).
8260 // speculative advance; a chain the grammar can no longer follow (EOS
8261 // proposed) ends here. The captured mask node always runs, so a dead chain
8262 // leaves the buffer NEUTRAL (all-ones = ban nothing) before it exits.
8263 if dmask_live
8264 && !constraint
8265 .as_deref_mut()
8266 .unwrap()
8267 .draft_advance(d)
8268 .map_err(|e2| format!("constraint: {e2}"))?
8269 {
8270 e.htod_u32_into(&mut dctx.g_dmask, &vec![u32::MAX; dmask_words])?;
8271 break;
8272 }
8273 }
8274 } else if let (true, Some(gr)) = (sampled, &dctx.graph_s) {
8275 // SAMPLED GRAPH DRAFT: one replay per drafted token — head forward + gumbel +
8276 // argmax in ONE dispatch; the host reads 4B token (+4B p), D2Ds q into slot j,
8277 // and decides the break. Event-counter continuity: g_ctr is host-seeded to
8278 // sctr-1 ONCE per round (outside the graph); the in-graph bump runs BEFORE the
8279 // perturb, so replay j consumes counter sctr+j — exactly the eager arm's Philox
8280 // stream. Host sctr advances in lockstep (computed, no readback needed).
8281 e.set_i32_one(&mut dctx.g_pos, (pos + base0) as i32)?;
8282 e.set_u32_one(&mut dctx.g_tok, last_token)?;
8283 e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
8284 e.set_u32_one(&mut dctx.g_ctr, sctr.wrapping_sub(1))?;
8285 for j in 0..k_this {
8286 gr.launch()?;
8287 scratch.kv.len += 1; // host mirror (len_d advanced in-graph)
8288 sctr += 1; // mirrors the in-graph g_ctr bump (eager parity:
8289 // counts the p-min-discarded token too)
8290 // q retention: ONE async D2D of the persistent head-logits buffer into this
8291 // round's slot j (stream-ordered after the replay, before the next one).
8292 e.copy_into(&mut dctx.q_slots[j], 0, &dctx.g_q, d_vocab)?;
8293 let idx = e.dtoh_u32_one(&dctx.g_tok)?;
8294 // #87 SENTINEL TRAP (see the greedy graph arm above).
8295 if (idx as usize) >= d_vocab {
8296 let seed_h = e.dtoh(&dctx.g_seed)?;
8297 let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
8298 return Err(format!(
8299 "draft(graph-sampled) argmax sentinel 0x{idx:08x} >= d_vocab \
8300 {d_vocab} at round {round} j={j} pos={pos}: round-seed NaN \
8301 {seed_nan}/{n_embd} — refusing to dereference the embed row \
8302 (#87 trap)"
8303 )
8304 .into());
8305 }
8306 let d = match &mtp.d2t {
8307 Some(map) => map[idx as usize],
8308 None => idx,
8309 };
8310 draft_idx.push(idx);
8311 if p_min > 0.0 {
8312 let p = e.dtoh(&dctx.g_p)?[0];
8313 if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
8314 break;
8315 }
8316 }
8317 draft.push(d);
8318 // trimmed head: the NEXT embed must read the TARGET id (see the greedy arm).
8319 if d != idx {
8320 e.set_u32_one(&mut dctx.g_tok, d)?;
8321 }
8322 }
8323 // uniform accept path: fill draft_stats per used slot (pure-temp regime — the
8324 // stats degenerate to th=0 / full-Z; one filter_stats launch per slot, tiny).
8325 for j in 0..draft.len().max(draft_idx.len()) {
8326 let rows0 = e.htod_i32(&[0])?;
8327 let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
8328 e.filter_stats(
8329 &dctx.q_slots[j],
8330 d_vocab,
8331 &rows0,
8332 &mut th_d,
8333 &mut z_d,
8334 &mut mx_d,
8335 d_vocab,
8336 1,
8337 sp_temp,
8338 sp.top_k,
8339 sp.top_p,
8340 sp.min_p,
8341 )?;
8342 draft_stats.push((e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0]));
8343 }
8344 } else {
8345 // EAGER DRAFT (fallback: MoE head/trunk, huge k, MEMRA_SPEC_NOGRAPH, capture fail).
8346 let mut e_tok = last_token;
8347 let mut d_seed = e.clone_dtod(&h_seed_buf)?;
8348 for j in 0..k_this {
8349 // GPU-ARGMAX DRAFT (2026-07-03): device logits + device argmax + 4-byte token
8350 // read instead of the ~600KB full-vocab dtoh + host argmax per draft token.
8351 let mtp_pos = pos + base0 + j;
8352 // draft-side grammar mask (eager twin of the graph arm's in-graph node).
8353 // A position with no legal draft-vocab row drops to unmasked drafting for
8354 // the rest of the chain (pre-lane behaviour; verify still arbitrates).
8355 if dmask_live {
8356 dmask_live = upload_draft_mask(
8357 e,
8358 constraint.as_deref_mut().unwrap(),
8359 &mut dctx.g_dmask,
8360 mtp.d2t.as_ref(),
8361 d_vocab,
8362 dmask_words,
8363 )?;
8364 }
8365 let (dl_d, h_nextn) = self.mtp_head_forward_dev(
8366 e,
8367 mtp,
8368 e_tok,
8369 &d_seed,
8370 &mut *scratch,
8371 mtp_pos,
8372 embd_dev,
8373 if dmask_live {
8374 Some((&dctx.g_dmask, dmask_words))
8375 } else {
8376 None
8377 },
8378 )?;
8379 let tok_d = if sampled {
8380 // FILTERED Gumbel-max: stats -> masked perturb -> argmax = one draw from
8381 // the filtered softmax (filters off => th=0, exact v1 semantics).
8382 if perturb_buf.is_none() {
8383 perturb_buf = Some(e.zeros(d_vocab.max(n_vocab))?);
8384 }
8385 let mut q_row = e.clone_dtod(&dl_d)?; // retained q (penalized when on)
8386 if pen_on {
8387 let h = pen_hist_d.as_ref().unwrap();
8388 let nh = h.len();
8389 e.penalize_logits(
8390 &mut q_row,
8391 h,
8392 nh,
8393 sp.penalty_repeat,
8394 sp.penalty_freq,
8395 sp.penalty_present,
8396 d_vocab,
8397 )?;
8398 }
8399 let rows0 = e.htod_i32(&[0])?;
8400 let (mut th_d, mut z_d, mut mx_d) =
8401 (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
8402 e.filter_stats(
8403 &q_row, d_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, d_vocab,
8404 1, sp_temp, sp.top_k, sp.top_p, sp.min_p,
8405 )?;
8406 let (th, z, mx) =
8407 (e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0], e.dtoh(&mx_d)?[0]);
8408 let pb = perturb_buf.as_mut().unwrap();
8409 e.gumbel_perturb_filtered(
8410 &q_row, pb, d_vocab, sp_seed, sctr, sp_temp, mx, th,
8411 )?;
8412 sctr += 1;
8413 draft_logits.push(q_row);
8414 draft_stats.push((mx, th, z));
8415 e.argmax_token_device(pb, d_vocab)?
8416 } else {
8417 e.argmax_token_device(&dl_d, d_vocab)?
8418 };
8419 let idx = e.dtoh_u32_one(&tok_d)?;
8420 // #87 SENTINEL TRAP (eager twin — see the graph arm). Extra diagnostics
8421 // here because the eager chain's operands are all readable: dl_d (the head
8422 // logits row) and d_seed (this step's h_seed) name the first-NaN buffer.
8423 if (idx as usize) >= d_vocab {
8424 let dl_h = e.dtoh(&dl_d)?;
8425 let dl_nan = dl_h.iter().filter(|v| v.is_nan()).count();
8426 let seed_h = e.dtoh(&d_seed)?;
8427 let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
8428 return Err(format!(
8429 "draft(eager) argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab} at \
8430 round {round} j={j} pos={pos}: head-logits NaN {dl_nan}/{d_vocab}, \
8431 step-seed NaN {seed_nan}/{n_embd} — refusing to dereference the \
8432 embed row (#87 trap)"
8433 )
8434 .into());
8435 }
8436 let d = match &mtp.d2t {
8437 Some(map) => map[idx as usize],
8438 None => idx,
8439 };
8440 if sampled {
8441 draft_idx.push(idx);
8442 }
8443 let draft_p = if p_min > 0.0
8444 || opti_fork
8445 .as_ref()
8446 .is_some_and(|fork| fork.controller.is_some())
8447 {
8448 let p_d = e.prob_of_token_device(&dl_d, &tok_d, d_vocab)?;
8449 Some(e.dtoh(&p_d)?[0])
8450 } else {
8451 None
8452 };
8453 if j == 0 {
8454 controller_draft_prob = draft_p;
8455 }
8456 if let Some(p) = draft_p.filter(|_| p_min > 0.0) {
8457 if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
8458 break;
8459 }
8460 }
8461 draft.push(d);
8462 e_tok = d;
8463 d_seed = h_nextn;
8464 // speculative advance; a chain the grammar can no longer follow (EOS
8465 // proposed) ends here — the prefix already proposed still rides verify.
8466 if dmask_live
8467 && !constraint
8468 .as_deref_mut()
8469 .unwrap()
8470 .draft_advance(d)
8471 .map_err(|e2| format!("constraint: {e2}"))?
8472 {
8473 break;
8474 }
8475 }
8476 if opti_fork
8477 .as_ref()
8478 .is_some_and(|fork| fork.controller.is_some())
8479 {
8480 controller_eager_state = Some((e_tok, d_seed));
8481 }
8482 }
8483 }
8484 let k_round = draft.len();
8485 if let Some(p) = pipe {
8486 p.draft_end(round);
8487 }
8488 drop(pipe_draft);
8489
8490 ph_mark(&mut ph_draft, phase_on);
8491 // --- 2. VERIFY: one batched target forward. With a pending bonus, it rides as col 0
8492 // (committing its KV/recur inside the SAME weight read); drafts follow. ---
8493 let verify_tokens: Vec<u32> = match pending {
8494 Some(b) => {
8495 let mut v = Vec::with_capacity(k_round + 1);
8496 v.push(b);
8497 v.extend_from_slice(&draft);
8498 v
8499 }
8500 None => draft.clone(),
8501 };
8502 let base = if pending.is_some() { 1 } else { 0 };
8503 // ckpt (REPLAY-FREE partial accept): retain per-layer state-rebuild inputs alongside
8504 // the verify. Pure buffer keep-alives + dtod clones — kernel work is unchanged.
8505 let mut ckpt = if let Some(ticket) = current_opti.as_mut() {
8506 Some(ticket.take_ckpt())
8507 } else if spec_replay {
8508 None
8509 } else {
8510 Some(VerifyCkpt::new(self.layers.len()))
8511 };
8512 let controller_can_probe = base == 1
8513 && k_round == 1
8514 && out.len().saturating_add(2) < max_new
8515 && controller_draft_prob.is_some()
8516 && opti_fork
8517 .as_ref()
8518 .and_then(|fork| fork.controller.as_ref())
8519 .is_some_and(|policy| !policy.breaker_tripped);
8520 let mut successor_attempt: Option<OptiControllerTicket> = None;
8521 let mut rejected_probe: Option<(f32, u32)> = None;
8522 let mut controller_prepared: Option<OptiControllerPrepared> = None;
8523 if controller_can_probe {
8524 // Prepare d2/q and, on admission, d3 before either current verify half is
8525 // issued. N stage 0 can then be followed immediately by N+1 stage 0; once N's
8526 // boundary fires, those dev0 launches overlap N stage 1 on dev1. Preparing on
8527 // the primary stream after N stage 1 would serialize the supposed pipeline.
8528 let eager_pos = scratch.kv.len + 1;
8529 let (optimistic_pending, pending_probability) = self.opti_controller_draft_step(
8530 e,
8531 mtp,
8532 &mut dctx,
8533 &mut *scratch,
8534 d_vocab,
8535 &mut controller_eager_state,
8536 eager_pos,
8537 embd_dev,
8538 )?;
8539 let first_probability = controller_draft_prob
8540 .ok_or("optipipe controller probe lost first-token probability")?;
8541 let q_proxy = first_probability * pending_probability;
8542 OPTI_GATE_CHECKS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8543 OPTI_SHADOW_DRAFT_TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8544 let admitted = opti_fork
8545 .as_ref()
8546 .and_then(|fork| fork.controller.as_ref())
8547 .ok_or("optipipe controller policy disappeared")?
8548 .admit(q_proxy);
8549 if admitted {
8550 OPTI_GATE_ADMITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8551 let eager_pos = scratch.kv.len + 1;
8552 let (optimistic_draft, optimistic_draft_probability) = self
8553 .opti_controller_draft_step(
8554 e,
8555 mtp,
8556 &mut dctx,
8557 &mut *scratch,
8558 d_vocab,
8559 &mut controller_eager_state,
8560 eager_pos,
8561 embd_dev,
8562 )?;
8563 OPTI_SHADOW_DRAFT_TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8564 let eager_seed = controller_eager_state.take().map(|(token, seed)| {
8565 debug_assert_eq!(token, optimistic_draft);
8566 seed
8567 });
8568 controller_prepared = Some(OptiControllerPrepared {
8569 verify_tokens: [optimistic_pending, optimistic_draft],
8570 draft_prob: optimistic_draft_probability,
8571 eager_seed,
8572 q_proxy,
8573 scratch_len: scratch.kv.len,
8574 });
8575 } else {
8576 OPTI_GATE_REJECTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8577 OPTI_WASTED_DRAFT_TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8578 rejected_probe = Some((q_proxy, optimistic_pending));
8579 eprintln!(
8580 "[opti-controller] reject q={q_proxy:.6} threshold={:.3}",
8581 opti_fork
8582 .as_ref()
8583 .and_then(|fork| fork.controller.as_ref())
8584 .expect("controller policy")
8585 .threshold,
8586 );
8587 }
8588 }
8589 let fork_attempt = match fork_generation.take() {
8590 Some(generation) if base == 1 && k_round == 1 => Some(generation),
8591 Some(generation) => {
8592 opti_fork
8593 .as_mut()
8594 .expect("fork generation without fork state")
8595 .retire(generation)?;
8596 None
8597 }
8598 None => None,
8599 };
8600 let (tlogits_d, vx) = if let Some(p) = pipe {
8601 self.decode_step_t_core_pipelined(
8602 e,
8603 &verify_tokens,
8604 pos,
8605 &mut *cache,
8606 embd_dev,
8607 ckpt.as_mut(),
8608 p,
8609 round,
8610 )?
8611 } else if controller_can_probe {
8612 let fence = opti_fork
8613 .as_ref()
8614 .ok_or("optipipe controller probe lost fork state")?
8615 .fence;
8616 let boundary = match current_opti.as_mut() {
8617 Some(ticket) => ticket.take_boundary(),
8618 None => self.verify_stage0_issue(
8619 e,
8620 &verify_tokens,
8621 pos,
8622 &mut *cache,
8623 embd_dev,
8624 ckpt.as_mut(),
8625 None,
8626 &fence,
8627 Some(true),
8628 None,
8629 )?,
8630 };
8631 if let Some(prepared) = controller_prepared.take() {
8632 let generation = {
8633 let fork = opti_fork
8634 .as_mut()
8635 .ok_or("optipipe controller admission lost fork state")?;
8636 let generation = fork.reserve_successor()?;
8637 let rt = fork.rt;
8638 let snapshot_fence = fork.fence;
8639 opti_snapshot_one_stage_owned_into(
8640 e,
8641 cache,
8642 rt,
8643 &snapshot_fence,
8644 0,
8645 fork.successor_snapshot_mut(),
8646 )?;
8647 generation
8648 };
8649 let mut successor_ckpt = VerifyCkpt::new(self.layers.len());
8650 let successor_boundary = self.verify_stage0_issue(
8651 e,
8652 &prepared.verify_tokens,
8653 pos + verify_tokens.len(),
8654 &mut *cache,
8655 embd_dev,
8656 Some(&mut successor_ckpt),
8657 None,
8658 &fence,
8659 Some(false),
8660 None,
8661 )?;
8662 OPTI_FORK_ATTEMPTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8663 let fork = opti_fork
8664 .as_ref()
8665 .ok_or("optipipe controller ticket lost fork state")?;
8666 successor_attempt = Some(fork.controller_ticket(
8667 generation,
8668 successor_boundary,
8669 successor_ckpt,
8670 prepared.verify_tokens,
8671 prepared.draft_prob,
8672 prepared.eager_seed,
8673 prepared.q_proxy,
8674 prepared.scratch_len,
8675 ));
8676 eprintln!(
8677 "[opti-controller] issue generation={} q={:.6} threshold={:.3} \
8678 verify={:?}",
8679 generation.id,
8680 prepared.q_proxy,
8681 fork.controller.expect("controller policy").threshold,
8682 prepared.verify_tokens,
8683 );
8684 }
8685 let result = self.verify_stage1_finish(
8686 e,
8687 boundary,
8688 &mut *cache,
8689 ckpt.as_mut(),
8690 None,
8691 &fence,
8692 successor_attempt.is_none(),
8693 )?;
8694 if let Some(ticket) = current_opti.as_mut() {
8695 ticket.settle();
8696 }
8697 if successor_attempt.is_some() {
8698 let fork = opti_fork
8699 .as_mut()
8700 .ok_or("optipipe successor snapshot lost fork state")?;
8701 let rt = fork.rt;
8702 let snapshot_fence = fork.fence;
8703 opti_snapshot_one_stage_owned_into(
8704 e,
8705 cache,
8706 rt,
8707 &snapshot_fence,
8708 1,
8709 fork.successor_snapshot_mut(),
8710 )?;
8711 // Publish N only after both independent successor-state queues are complete.
8712 fork.rt.publish_to(1, &e.stream())?;
8713 }
8714 result
8715 } else if let Some(ticket) = current_opti.as_mut() {
8716 let fork = opti_fork
8717 .as_mut()
8718 .ok_or("optipipe carried controller ticket lost fork state")?;
8719 let boundary = ticket.take_boundary();
8720 let result = self.verify_stage1_finish(
8721 e,
8722 boundary,
8723 &mut *cache,
8724 ckpt.as_mut(),
8725 None,
8726 &fork.fence,
8727 true,
8728 )?;
8729 ticket.settle();
8730 result
8731 } else if let Some(generation) = fork_attempt {
8732 let fork = opti_fork
8733 .as_mut()
8734 .expect("fork generation without fork state");
8735 fork.capture_seed(e, generation, &h_seed_buf, &fill_prev, scratch.kv.len)?;
8736 let action = fork.mode.action(generation.id);
8737 let boundary = self.verify_stage0_issue(
8738 e,
8739 &verify_tokens,
8740 pos,
8741 &mut *cache,
8742 embd_dev,
8743 ckpt.as_mut(),
8744 None,
8745 &fork.fence,
8746 Some(true),
8747 None,
8748 )?;
8749 OPTI_FORK_ATTEMPTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8750 let mut ticket = fork.ticket(generation, boundary);
8751 if action == OptiForkAction::Abort {
8752 return Err(format!(
8753 "optipipe forced abort with generation {} stage0 in flight",
8754 generation.id,
8755 )
8756 .into());
8757 }
8758 fork.reconcile(
8759 e,
8760 &mut *cache,
8761 &mut *scratch,
8762 &snap,
8763 &mut h_seed_buf,
8764 &mut fill_prev,
8765 generation,
8766 action,
8767 verify_tokens[0],
8768 )?;
8769 let result = if action == OptiForkAction::Hit {
8770 let boundary = ticket.take_boundary();
8771 self.verify_stage1_finish(
8772 e,
8773 boundary,
8774 &mut *cache,
8775 ckpt.as_mut(),
8776 None,
8777 &fork.fence,
8778 true,
8779 )?
8780 } else {
8781 // The optimistic boundary slot has no reader. Re-run the unchanged serial
8782 // verify only after E_restart published the restored stage-0 state.
8783 self.decode_step_t_core(
8784 e,
8785 &verify_tokens,
8786 pos,
8787 &mut *cache,
8788 embd_dev,
8789 ckpt.as_mut(),
8790 )?
8791 };
8792 ticket.settle();
8793 debug_assert_eq!(ticket.generation, generation);
8794 fork.retire(generation)?;
8795 result
8796 } else {
8797 self.decode_step_t_core(
8798 e,
8799 &verify_tokens,
8800 pos,
8801 &mut *cache,
8802 embd_dev,
8803 ckpt.as_mut(),
8804 )?
8805 };
8806 let pipe_accept = match pipe {
8807 Some(p) => Some(p.accept_begin(round)?),
8808 None => None,
8809 };
8810
8811 ph_mark(&mut ph_verify, phase_on);
8812 // --- 3. GREEDY ACCEPT (walk prefix, stop at first mismatch) ---
8813 // DEVICE-ARGMAX ACCEPT: argmax every verify column ON DEVICE (same 2-pass kernels +
8814 // smallest-index tie-break as host argmax, argmax_gate-validated) and read back ONE
8815 // [T] u32 — replaces the T x n_vocab f32 dtoh + T host argmaxes per round.
8816 // t_pred[j] = target's greedy prediction for the slot after draft[j-1] (j>=1) or after
8817 // last_token (j==0). With a pending bonus, col 0 IS the prediction after last_token
8818 // (== the bonus), so every index shifts by `base` and last_pred is unused.
8819 let t_v = verify_tokens.len();
8820 let mut preds: Vec<u32> = Vec::new();
8821 if !sampled {
8822 for j in 0..t_v {
8823 e.argmax_token_device_col(&tlogits_d, j, n_vocab, &mut preds_d, j)?;
8824 }
8825 preds = e.dtoh_u32(&preds_d)?; // <- the verify-GPU wait lands here
8826 // #87 SENTINEL TRAP, verify side: a sentinel pred becomes the round's bonus =
8827 // next round's last_token = the next chain's embed lookup. Catch it at the
8828 // source with the column named — an all-NaN VERIFY column implicates the
8829 // stage-split trunk (decode_step_t_core_ppn), not the draft head.
8830 if let Some(bad) = preds[..t_v].iter().position(|&p| (p as usize) >= n_vocab) {
8831 let col = &tlogits_d.slice(bad * n_vocab..(bad + 1) * n_vocab);
8832 let mut probe = e.zeros(n_vocab)?;
8833 e.copy_view_into(&mut probe, 0, col, n_vocab)?;
8834 let col_h = e.dtoh(&probe)?;
8835 let col_nan = col_h.iter().filter(|v| v.is_nan()).count();
8836 return Err(format!(
8837 "verify argmax sentinel 0x{:08x} >= n_vocab {n_vocab} at round {round} \
8838 col {bad}/{t_v} pos={pos}: verify-logits col NaN {col_nan}/{n_vocab} \
8839 — the stage-split verify produced a poisoned column (#87 trap)",
8840 preds[bad]
8841 )
8842 .into());
8843 }
8844 }
8845 ph_mark(&mut ph_wait, phase_on);
8846 let t_pred = |j: usize| -> u32 {
8847 if j == 0 && base == 0 {
8848 last_pred
8849 } else {
8850 preds[base + j - 1]
8851 }
8852 };
8853 let mut devacc_seeded = false;
8854 let mut devacc_acc: Option<CudaSlice<u32>> = None;
8855 let (n_acc, bonus) = if !sampled {
8856 // ROUND-STREAM stage (a) (MEMRA_SPEC_DEVACC=1 opt-in): the walk runs ON DEVICE
8857 // (spec_accept_greedy, verbatim rule) and the host reads back 8B (n_acc, bonus)
8858 // instead of the [T] preds. Same sync count — machinery for stages (b)/(c),
8859 // gated on token identity vs the host walk (the arms below are bit-equal rules).
8860 if crate::spec::spec_devacc() && k_round > 0 && !spec_replay && constraint.is_none()
8861 {
8862 let draft_d = e.htod_u32_v(&draft)?;
8863 let mut acc_out = e.alloc_u32_zeroed(2)?;
8864 e.spec_accept_greedy(
8865 &preds_d,
8866 &draft_d,
8867 last_pred,
8868 base,
8869 k_round,
8870 &mut acc_out,
8871 )?;
8872 devacc_acc = Some(acc_out.clone());
8873 // stage (b): next-round seed gathered ON DEVICE from acc_out before the host
8874 // ever reads n_acc (j=base+n_acc -> vx col j-1; j==0 -> fill_prev). The three
8875 // non-replay commit arms skip their host-offset seed copies (guarded below);
8876 // the legacy spec_replay arm keeps its own rx-based seeding (excluded here).
8877 // NOTE: fill_prev is NOT updated here — the commit arms' TRUE-HIDDEN
8878 // REFRESH reads the OLD fill_prev (predecessor of this round's verify batch);
8879 // the update lands after the arms (devacc_seeded guard below).
8880 e.spec_seed_gather(&vx, &fill_prev, &acc_out, &mut h_seed_buf, base, n_embd)?;
8881 // 3a: KV lens roll back on device (len = saved + base + n_acc, all arms'
8882 // unified rule; full accept rewrites the verify-left value). Host mirrors
8883 // update after the readback; commit_verified_prefix skips its len_d writes.
8884 if let Some(successor) = successor_attempt.as_ref() {
8885 opti_fork
8886 .as_mut()
8887 .ok_or("optipipe successor reconcile lost fork state")?
8888 .queue_actual_reconcile(
8889 e,
8890 &snap,
8891 &acc_out,
8892 successor.verify_tokens[0],
8893 base,
8894 )?;
8895 } else if let Some(ptrs) = &kv_len_ptrs {
8896 let saved: Vec<i32> = (0..self.layers.len())
8897 .map(|il| snap.kv_len[il].map(|v| v as i32).unwrap_or(0))
8898 .collect();
8899 let saved_d = e.htod_i32(&saved)?;
8900 e.spec_rollback_kv(ptrs, &saved_d, &acc_out, base, self.layers.len())?;
8901 }
8902 devacc_seeded = true;
8903 let ab = e.dtoh_u32(&acc_out)?;
8904 (ab[0] as usize, ab[1])
8905 } else {
8906 let mut n_acc = 0usize;
8907 for j in 0..k_round {
8908 if t_pred(j) == draft[j] {
8909 n_acc += 1;
8910 } else {
8911 break;
8912 }
8913 }
8914 // bonus = target's own token at the first non-accepted slot. n_acc in 0..=k; t_pred
8915 // is defined for j in 0..=k (j==0 -> last_logits, j>=1 -> col j-1, last col = k-1).
8916 (n_acc, t_pred(n_acc))
8917 }
8918 } else {
8919 // --- SAMPLED ACCEPT (rejection sampling): u_j < p_j(x_j)/q_j(x_j) walk ---
8920 if col_buf.is_none() {
8921 col_buf = Some(e.zeros(n_vocab)?);
8922 }
8923 // FILTERED p_j: per-verify-col stats (one batched filter_stats call), then the
8924 // filtered gather. j==0&&base==0 reads last_col (its own stats row appended).
8925 let mut pj = vec![0f32; k_round.max(1)];
8926 let mut col_stats: Vec<(f32, f32, f32)> = Vec::new(); // (max, th, z) per verify col used
8927 if k_round > 0 {
8928 let mut ids: Vec<u32> = Vec::new();
8929 let mut rows: Vec<i32> = Vec::new();
8930 for j in 0..k_round {
8931 if j > 0 || base == 1 {
8932 ids.push(draft[j]);
8933 rows.push((base + j) as i32 - 1);
8934 }
8935 }
8936 if !ids.is_empty() {
8937 let nr = rows.len();
8938 // penalties: materialize the used columns into one contiguous penalized
8939 // buffer (rows remapped 0..nr) so stats+gathers see the penalized p.
8940 // penalties: materialize used columns contiguously, penalize all rows in
8941 // one launch, and point stats+gathers at the penalized buffer (rows 0..nr).
8942 let p_rows: Vec<i32> = if pen_on {
8943 (0..nr as i32).collect()
8944 } else {
8945 rows.clone()
8946 };
8947 if pen_on {
8948 if pcol_buf.as_ref().map(|b| b.len()).unwrap_or(0) < nr * n_vocab {
8949 pcol_buf = Some(e.zeros(nr * n_vocab)?);
8950 }
8951 let pc = pcol_buf.as_mut().unwrap();
8952 for (i2, &r) in rows.iter().enumerate() {
8953 let c = r as usize;
8954 e.copy_view_into(
8955 pc,
8956 i2 * n_vocab,
8957 &tlogits_d.slice(c * n_vocab..(c + 1) * n_vocab),
8958 n_vocab,
8959 )?;
8960 }
8961 let h = pen_hist_d.as_ref().unwrap();
8962 let nh = h.len();
8963 e.penalize_logits_rows(
8964 pc,
8965 h,
8966 nh,
8967 sp.penalty_repeat,
8968 sp.penalty_freq,
8969 sp.penalty_present,
8970 n_vocab,
8971 nr,
8972 )?;
8973 }
8974 let p_src: &CudaSlice<f32> = if pen_on {
8975 pcol_buf.as_ref().unwrap()
8976 } else {
8977 &tlogits_d
8978 };
8979 let rowsd = e.htod_i32(&p_rows)?;
8980 let (mut th_d, mut z_d, mut mx_d) =
8981 (e.zeros(nr)?, e.zeros(nr)?, e.zeros(nr)?);
8982 e.filter_stats(
8983 p_src, n_vocab, &rowsd, &mut th_d, &mut z_d, &mut mx_d, n_vocab, nr,
8984 sp_temp, sp.top_k, sp.top_p, sp.min_p,
8985 )?;
8986 let idsd = e.htod_u32_v(&ids)?;
8987 let mut outd = e.zeros(nr)?;
8988 e.softmax_gather_filtered(
8989 p_src, n_vocab, &idsd, &rowsd, &th_d, &z_d, &mut outd, n_vocab, nr,
8990 sp_temp,
8991 )?;
8992 let outv = e.dtoh(&outd)?;
8993 let (thv, zv, mxv) = (e.dtoh(&th_d)?, e.dtoh(&z_d)?, e.dtoh(&mx_d)?);
8994 let mut oi = 0usize;
8995 for j in 0..k_round {
8996 if j > 0 || base == 1 {
8997 pj[j] = outv[oi];
8998 oi += 1;
8999 }
9000 }
9001 col_stats = (0..nr).map(|i| (mxv[i], thv[i], zv[i])).collect();
9002 }
9003 if base == 0 {
9004 let lc: &CudaSlice<f32> = if pen_on {
9005 if col_buf.is_none() {
9006 col_buf = Some(e.zeros(n_vocab)?);
9007 }
9008 let cb = col_buf.as_mut().unwrap();
9009 e.copy_into(
9010 cb,
9011 0,
9012 last_col_logits
9013 .as_ref()
9014 .expect("sampled: last_col_logits unset"),
9015 n_vocab,
9016 )?;
9017 let h = pen_hist_d.as_ref().unwrap();
9018 let nh = h.len();
9019 e.penalize_logits(
9020 cb,
9021 h,
9022 nh,
9023 sp.penalty_repeat,
9024 sp.penalty_freq,
9025 sp.penalty_present,
9026 n_vocab,
9027 )?;
9028 col_buf.as_ref().unwrap()
9029 } else {
9030 last_col_logits
9031 .as_ref()
9032 .expect("sampled: last_col_logits unset")
9033 };
9034 let rows0 = e.htod_i32(&[0])?;
9035 let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
9036 e.filter_stats(
9037 lc, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1,
9038 sp_temp, sp.top_k, sp.top_p, sp.min_p,
9039 )?;
9040 let idsd = e.htod_u32_v(&[draft[0]])?;
9041 let mut outd = e.zeros(1)?;
9042 e.softmax_gather_filtered(
9043 lc, n_vocab, &idsd, &rows0, &th_d, &z_d, &mut outd, n_vocab, 1, sp_temp,
9044 )?;
9045 pj[0] = e.dtoh(&outd)?[0];
9046 last_col_stats =
9047 Some((e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0]));
9048 }
9049 }
9050 // q source: the graph arm retained the head logits in the persistent q_slots;
9051 // the eager arm in per-round draft_logits clones. Same raw-logit values either way.
9052 // FILTERED q_j: stats from draft_stats (eager pushes in-chain; the graph arm
9053 // computes them post-replay — graph engages only filter/penalty-free, so the
9054 // stats degenerate to th=0/full-Z there, keeping ONE accept path).
9055 let q_bufs: &[CudaSlice<f32>] = if dctx.graph_s.is_some() {
9056 &dctx.q_slots
9057 } else {
9058 &draft_logits
9059 };
9060 let mut n_acc = 0usize;
9061 for j in 0..k_round {
9062 let (qmx, qth, qz) = draft_stats[j];
9063 let idsd = e.htod_u32_v(&[draft_idx[j]])?;
9064 let rowsd = e.htod_i32(&[0])?;
9065 let thd = e.htod(&[qth])?;
9066 let zd = e.htod(&[qz])?;
9067 let _ = qmx;
9068 let mut outd = e.zeros(1)?;
9069 e.softmax_gather_filtered(
9070 &q_bufs[j], d_vocab, &idsd, &rowsd, &thd, &zd, &mut outd, d_vocab, 1,
9071 sp_temp,
9072 )?;
9073 let qj = e.dtoh(&outd)?[0];
9074 let u = host_u01(sp_seed, uctr);
9075 uctr += 1;
9076 if (u as f64) * (qj as f64) < pj[j] as f64 {
9077 n_acc += 1;
9078 } else {
9079 break;
9080 }
9081 }
9082 let bonus = if n_acc == k_round {
9083 // FULL ACCEPT: bonus ~ FILTERED softmax at the last verify column.
9084 let col = base + k_round - 1;
9085 let cb = col_buf.as_mut().unwrap();
9086 e.copy_view_into(
9087 cb,
9088 0,
9089 &tlogits_d.slice(col * n_vocab..(col + 1) * n_vocab),
9090 n_vocab,
9091 )?;
9092 if pen_on {
9093 let h = pen_hist_d.as_ref().unwrap();
9094 let nh = h.len();
9095 e.penalize_logits(
9096 cb,
9097 h,
9098 nh,
9099 sp.penalty_repeat,
9100 sp.penalty_freq,
9101 sp.penalty_present,
9102 n_vocab,
9103 )?;
9104 }
9105 if perturb_buf.is_none() {
9106 perturb_buf = Some(e.zeros(d_vocab.max(n_vocab))?);
9107 }
9108 // STATS MUST COME FROM THIS COLUMN (bug fix 2026-08-05, lane/sampler-
9109 // truncation-fix; receipts research/sampfix-20260805/). The old code reused
9110 // `col_stats.last()` here, which is ALWAYS the wrong row: the gathered set
9111 // covers verify columns 0..=(base+k_round-2) (rows pushed as base+j-1), while
9112 // the full-accept bonus samples column base+k_round-1 — exactly ONE PAST the
9113 // last gathered column, in both base arms. `th` is a threshold in e-units of
9114 // its OWN row's max, so feeding a neighbour's (row_max, th) into
9115 // gumbel_perturb_filtered mis-scales every e0 = exp((x-row_max)/T). When the
9116 // donor column's peak is higher by more than T*ln(1/th), EVERY id fails
9117 // `e0 >= th`, the whole perturbed row becomes -3.4e38, and the 2-pass argmax
9118 // falls through to its smallest-index tie-break => token id 0 ("!") spliced
9119 // mid-word. Fragility is ordered by how large th is: min_p pins th = min_p
9120 // (0.05 => trigger at delta > 2.4 at T=0.8, fires constantly), top_p's
9121 // mass-boundary th is smaller, top_k's k-th-largest th smaller still — which
9122 // is why the head-to-head matrix saw min_p and top_p corrupt while top_k-only
9123 // stayed clean. The pure-temp default regime is immune (th == 0 masks nothing,
9124 // and row_max is unused once nothing is masked), so this fix is a byte-level
9125 // no-op for the untruncated serve default. One extra one-block filter_stats
9126 // per full-accept round is the whole cost.
9127 let (mx, th) = {
9128 let rows0 = e.htod_i32(&[0])?;
9129 let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
9130 let cb0 = col_buf.as_ref().unwrap();
9131 e.filter_stats(
9132 cb0, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1,
9133 sp_temp, sp.top_k, sp.top_p, sp.min_p,
9134 )?;
9135 (e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0])
9136 };
9137 let pb = perturb_buf.as_mut().unwrap();
9138 let cb2 = col_buf.as_ref().unwrap();
9139 e.gumbel_perturb_filtered(cb2, pb, n_vocab, sp_seed, sctr, sp_temp, mx, th)?;
9140 sctr += 1;
9141 let td = e.argmax_token_device(pb, n_vocab)?;
9142 e.dtoh_u32_one(&td)?
9143 } else {
9144 // REJECT at n_acc: bonus ~ norm(max(0, softmax_T(p) - softmax_T(q))).
9145 let cb = col_buf.as_mut().unwrap();
9146 if n_acc > 0 || base == 1 {
9147 let col = base + n_acc - 1;
9148 e.copy_view_into(
9149 cb,
9150 0,
9151 &tlogits_d.slice(col * n_vocab..(col + 1) * n_vocab),
9152 n_vocab,
9153 )?;
9154 } else {
9155 let lc = last_col_logits.as_ref().unwrap();
9156 e.copy_into(cb, 0, lc, n_vocab)?;
9157 }
9158 if pen_on {
9159 let h = pen_hist_d.as_ref().unwrap();
9160 let nh = h.len();
9161 e.penalize_logits(
9162 cb,
9163 h,
9164 nh,
9165 sp.penalty_repeat,
9166 sp.penalty_freq,
9167 sp.penalty_present,
9168 n_vocab,
9169 )?;
9170 }
9171 let cb2 = col_buf.as_ref().unwrap();
9172 let sc = sctr;
9173 sctr += 1;
9174 // p-stats for the reject column: from col_stats when the col was gathered,
9175 // else (j==0&&base==0) from last_col_stats.
9176 let p_stats = if n_acc > 0 || base == 1 {
9177 // col index within the gathered set == number of gathered cols before n_acc
9178 let gi = if base == 1 { n_acc } else { n_acc - 1 };
9179 col_stats.get(gi).copied().unwrap_or_else(|| {
9180 (0.0, 0.0, 1.0) // unreachable: gathered cols always cover the reject slot
9181 })
9182 } else {
9183 last_col_stats.expect("sampled: last_col_stats unset at reject")
9184 };
9185 let q_stats = draft_stats[n_acc];
9186 if let Some(map) = &d2t_dev {
9187 if q_full_buf.is_none() {
9188 q_full_buf = Some(e.zeros(n_vocab)?);
9189 }
9190 let qf = q_full_buf.as_mut().unwrap();
9191 e.scatter_trim_logits(&q_bufs[n_acc], map, qf, d_vocab, n_vocab)?;
9192 let qf2 = q_full_buf.as_ref().unwrap();
9193 e.residual_sample_filtered(
9194 cb2,
9195 Some(qf2),
9196 n_vocab,
9197 sp_temp,
9198 sp_seed,
9199 sc,
9200 p_stats,
9201 q_stats,
9202 &mut sample_tok,
9203 )?;
9204 } else {
9205 e.residual_sample_filtered(
9206 cb2,
9207 Some(&q_bufs[n_acc]),
9208 n_vocab,
9209 sp_temp,
9210 sp_seed,
9211 sc,
9212 p_stats,
9213 q_stats,
9214 &mut sample_tok,
9215 )?;
9216 }
9217 e.dtoh_u32(&sample_tok)?[0]
9218 };
9219 (n_acc, bonus)
9220 };
9221 // --- 3b. GRAMMAR TRUNCATION (constrained spec, 2026-08-03): the grammar is
9222 // an extra rejection rule AFTER the exactness verify (the batched-verify-twins
9223 // ordering). Walk the accepted drafts through the grammar in commit order; the
9224 // first illegal token truncates acceptance at its slot, and that slot's emission
9225 // is recomputed as the MASKED argmax of the target's own verify column — token-
9226 // identical to constrained plain greedy decode (an unmasked argmax that is
9227 // grammar-legal IS the masked argmax: masking only removes competitors). The
9228 // column D2H (~1MB) is paid only when a cut fires — the tight-grammar cost,
9229 // measured in acceptance numbers, never hidden.
9230 let (n_acc, bonus) = match constraint.as_deref_mut() {
9231 None => (n_acc, bonus),
9232 Some(c) => {
9233 fn ce(e2: String) -> Box<dyn std::error::Error> {
9234 format!("constraint: {e2}").into()
9235 }
9236 let mut na = n_acc;
9237 let mut cut = false;
9238 for (j, &d) in draft.iter().enumerate().take(n_acc) {
9239 if c.is_allowed(d).map_err(ce)? {
9240 c.consume(d).map_err(ce)?;
9241 } else {
9242 na = j;
9243 cut = true;
9244 dm_cut_tokens += n_acc - j;
9245 break;
9246 }
9247 }
9248 if cut {
9249 dm_cuts += 1;
9250 }
9251 let mut bo = bonus;
9252 if cut || !c.is_allowed(bo).map_err(ce)? {
9253 let mut row = if na == 0 && base == 0 {
9254 init_logits_host
9255 .clone()
9256 .ok_or("constraint: init logits missing (round-0 cut)")?
9257 } else {
9258 e.dtoh_view(
9259 &tlogits_d.slice((base + na - 1) * n_vocab..(base + na) * n_vocab),
9260 )?
9261 };
9262 c.mask_logits(&mut row).map_err(ce)?;
9263 bo = argmax(&row) as u32;
9264 }
9265 c.consume(bo).map_err(ce)?;
9266 (na, bo)
9267 }
9268 };
9269 let mut successor_valid = false;
9270 if let Some((q_proxy, expected_d2)) = rejected_probe {
9271 let v_n = n_acc == 1 && bonus == expected_d2;
9272 eprintln!(
9273 "[opti-controller] shadow q={q_proxy:.6} admitted=false v_n={v_n} \
9274 expected_d2={expected_d2} n_acc={n_acc} bonus={bonus}",
9275 );
9276 }
9277 if let Some(successor) = successor_attempt.as_ref() {
9278 successor_valid = n_acc == 1 && bonus == successor.verify_tokens[0];
9279 let generation = successor.generation;
9280 let q_proxy = successor.q_proxy;
9281 let expected_pending = successor.verify_tokens[0];
9282 let resolution_ms = successor.issued_at.elapsed().as_secs_f64() * 1e3;
9283 let fork = opti_fork
9284 .as_mut()
9285 .ok_or("optipipe successor resolution lost fork state")?;
9286 fork.finish_actual_reconcile(e, &mut *cache, &snap, n_acc, base, successor_valid)?;
9287 if successor_valid {
9288 OPTI_FORK_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9289 } else {
9290 OPTI_FORK_MISSES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9291 OPTI_RECONCILES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9292 OPTI_WASTED_DRAFT_TOKENS.fetch_add(2, std::sync::atomic::Ordering::Relaxed);
9293 }
9294 let breaker_tripped = fork
9295 .controller
9296 .as_mut()
9297 .expect("controller policy")
9298 .resolve(successor_valid);
9299 if breaker_tripped {
9300 OPTI_BREAKER_TRIPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9301 }
9302 eprintln!(
9303 "[opti-controller] resolve generation={} hit={} q={q_proxy:.6} \
9304 expected_pending={expected_pending} n_acc={n_acc} bonus={bonus} \
9305 resolution_ms={resolution_ms:.3} reconcile={} breaker={}",
9306 generation.id, successor_valid, !successor_valid, breaker_tripped,
9307 );
9308 if !successor_valid {
9309 let mut successor = successor_attempt
9310 .take()
9311 .expect("controller successor disappeared on miss");
9312 successor.settle();
9313 fork.retire(generation)?;
9314 }
9315 }
9316 total_drafted += k_round;
9317 total_accepted += n_acc;
9318 if let Some(t) = sess_telem {
9319 // Greedy, rejection-sampling, and grammar truncation all converge here after
9320 // the accept decision is already on host. Fixed-size relaxed atomics only.
9321 t.record_round(k_round, n_acc);
9322 }
9323 if spec_stats {
9324 st_len_hist[k_round] += 1;
9325 for j in 0..k_round {
9326 st_drafted[j] += 1;
9327 }
9328 for j in 0..n_acc {
9329 st_accepted[j] += 1;
9330 }
9331 if n_acc == k_round {
9332 st_full += 1;
9333 }
9334 }
9335
9336 if debug_spec {
9337 eprintln!(
9338 "[R{round}] pos={pos} out_len={} last_tok={last_token} draft={draft:?} n_acc={n_acc} bonus={bonus} t_pred0={}",
9339 out.len(),
9340 t_pred(0)
9341 );
9342 }
9343
9344 // --- 4. COMMIT: draft[0..n_acc] then bonus (n_acc + 1 tokens) ---
9345 let commit_started = std::time::Instant::now();
9346 // SESSION MODE: every accepted column is already in the CACHE — `out` must carry all
9347 // of them (overshoot past max_new included) or `committed` under-counts the cache rows
9348 // and the next turn's continuation seeds one token off (gate-caught 2026-07-05). The
9349 // single-shot path keeps the cap (its caller truncates + drops the cache anyway).
9350 for j in 0..n_acc {
9351 if !session_mode && out.len() >= max_new {
9352 break;
9353 }
9354 out.push(draft[j]);
9355 }
9356 if pen_on {
9357 pen_hist.extend_from_slice(&draft[0..n_acc]);
9358 pen_hist.push(bonus);
9359 }
9360 let bonus_emitted = session_mode || out.len() < max_new;
9361 if bonus_emitted {
9362 out.push(bonus);
9363 }
9364 last_token = bonus;
9365
9366 // --- 5. ROLLBACK + advance (§C) ---
9367 if n_acc == k_round && !spec_replay {
9368 // FULL ACCEPT, BONUS FOLD: all verify columns (pending? + drafts) are committed in
9369 // cache; the NEW bonus stays PENDING for the next round's verify batch — NO extra
9370 // T=1 trunk pass. The next draft chain seeds from the MTP block's h_nextn at the
9371 // bonus position: one MTP-block pass (~1/33 trunk cost) replaces the trunk read.
9372 // last_pred is dead in the pending path (t_pred reads verify col 0).
9373 //
9374 // PERSISTENT DRAFT KV, full-accept fill: the chain covered last_token +
9375 // draft[0..k_round-2] as INPUTS (slots P..P'-2); draft[k_round-1] (slot P'-1) was
9376 // only ever an output, so its entry is MISSING. Fill it from vh_seed — its EXACT
9377 // trunk hidden (the last verify column). set_len first: a p-min break may have
9378 // left one extra chain append at that slot. Partial accepts need NO fill (the
9379 // chain already covered every accepted position; round-start set_len truncates).
9380 let mut vh_seed = e.zeros(n_embd)?;
9381 e.copy_view_into(
9382 &mut vh_seed,
9383 0,
9384 &vx.slice((t_v - 1) * n_embd..t_v * n_embd),
9385 n_embd,
9386 )?;
9387 if refresh {
9388 // TRUE-HIDDEN REFRESH (2026-07-03, the HANDOVER-listed acceptance lever):
9389 // overwrite ALL committed positions' scratch entries with K/V from their EXACT
9390 // verify hiddens — the reference engine's mtp_update fills from true hiddens;
9391 // the full stack (vx) is already resident from the verify. Replaces both the
9392 // chain-approximate entries AND the old last-token-only fill. Acceptance-only
9393 // (draft attention quality); exactness stays the verify's job.
9394 scratch.set_len(e, pos)?;
9395 // PREDECESSOR pairing: row i gets vx[i-1]; row 0 the carried fill_prev
9396 // (hidden of the last committed row before this verify batch).
9397 let mut vxs = e.zeros(t_v * n_embd)?;
9398 e.copy_into(&mut vxs, 0, &fill_prev, n_embd)?;
9399 if t_v > 1 {
9400 e.copy_view_into(
9401 &mut vxs,
9402 n_embd,
9403 &vx.slice(0..(t_v - 1) * n_embd),
9404 (t_v - 1) * n_embd,
9405 )?;
9406 }
9407 self.mtp_kv_fill(e, mtp, &verify_tokens, &vxs, pos, &mut *scratch, embd_dev)?;
9408 } else {
9409 scratch.set_len(e, pos + base + k_round - 1)?;
9410 // predecessor of the last draft = verify col t_v-2 (or fill_prev at t_v==1)
9411 let mut hp = e.zeros(n_embd)?;
9412 if t_v >= 2 {
9413 e.copy_view_into(
9414 &mut hp,
9415 0,
9416 &vx.slice((t_v - 2) * n_embd..(t_v - 1) * n_embd),
9417 n_embd,
9418 )?;
9419 } else {
9420 e.copy_into(&mut hp, 0, &fill_prev, n_embd)?;
9421 }
9422 self.mtp_kv_fill(
9423 e,
9424 mtp,
9425 &[draft[k_round - 1]],
9426 &hp,
9427 pos + base + k_round - 1,
9428 &mut *scratch,
9429 embd_dev,
9430 )?;
9431 }
9432 // REFERENCE SEEDING: no pseudo pass — the next chain's step 0 IS the
9433 // reference's (id_last, h_prev) draft row; it appends the bonus's scratch
9434 // entry itself. Seed = TRUE hidden of the bonus's predecessor (last verify
9435 // col). Saves one MTP-block pass per round on top of the pairing fix.
9436 if !devacc_seeded {
9437 e.copy_into(&mut h_seed_buf, 0, &vh_seed, n_embd)?;
9438 e.copy_into(&mut fill_prev, 0, &vh_seed, n_embd)?;
9439 }
9440 pending = Some(bonus);
9441 if debug_spec {
9442 eprintln!(" -> FULL ACCEPT (bonus pending, prev-h seed)");
9443 }
9444 } else if !spec_replay && base + n_acc >= 1 {
9445 // PARTIAL ACCEPT, REPLAY-FREE (2026-07-03 — the profiled #1 long-ctx spec cost):
9446 // the verify's first j = base+n_acc columns ARE the committed sequence, computed
9447 // bit-identically to eager (decode-exact contract) — so KEEP them: KV truncates to
9448 // pos+j, recurrent state rebuilds from the VerifyCkpt (same-kernel gdn prefix
9449 // re-run / pure state-clone restore), and the bonus stays PENDING exactly like the
9450 // full-accept path — the legacy duplicate trunk replay is gone. The next chain
9451 // seeds from the MTP pseudo-hidden of the bonus, whose seed = the TRUE verify
9452 // hidden of its predecessor (col j-1) — same one-hop pseudo structure as full
9453 // accept (never compounds: the next verify recomputes true hiddens for all
9454 // committed columns).
9455 let j = base + n_acc;
9456 self.commit_verified_prefix(
9457 e,
9458 &mut *cache,
9459 &snap,
9460 ckpt.as_ref().unwrap(),
9461 j,
9462 devacc_seeded,
9463 if devacc_seeded {
9464 devacc_acc.as_ref().map(|a| (a, base, t_v))
9465 } else {
9466 None
9467 },
9468 )?;
9469 let mut seed = e.zeros(n_embd)?;
9470 e.copy_view_into(
9471 &mut seed,
9472 0,
9473 &vx.slice((j - 1) * n_embd..j * n_embd),
9474 n_embd,
9475 )?;
9476 // Draft scratch: TRUE-HIDDEN REFRESH of the committed prefix (see the full-accept
9477 // branch); without it the chain entries stand and only the tail truncates. Either
9478 // way len ends at pos+j so the pseudo append lands at the bonus's slot pos+j
9479 // (persistent mode), rope pos+j+1 (chain convention).
9480 if refresh {
9481 scratch.set_len(e, pos)?;
9482 let mut vxs = e.zeros(j * n_embd)?;
9483 e.copy_into(&mut vxs, 0, &fill_prev, n_embd)?;
9484 if j > 1 {
9485 e.copy_view_into(
9486 &mut vxs,
9487 n_embd,
9488 &vx.slice(0..(j - 1) * n_embd),
9489 (j - 1) * n_embd,
9490 )?;
9491 }
9492 self.mtp_kv_fill(
9493 e,
9494 mtp,
9495 &verify_tokens[0..j],
9496 &vxs,
9497 pos,
9498 &mut *scratch,
9499 embd_dev,
9500 )?;
9501 } else {
9502 scratch.set_len(e, pos + j)?;
9503 }
9504 // REFERENCE SEEDING (see the full-accept branch): seed = TRUE hidden of the
9505 // bonus's predecessor (verify col j-1); no pseudo pass.
9506 if !devacc_seeded {
9507 e.copy_into(&mut h_seed_buf, 0, &seed, n_embd)?;
9508 e.copy_into(&mut fill_prev, 0, &seed, n_embd)?;
9509 }
9510 pending = Some(bonus);
9511 if debug_spec {
9512 eprintln!(" -> PARTIAL(replay-free j={j}, bonus pending, prev-h seed)");
9513 }
9514 } else if !spec_replay {
9515 // ZERO ROUND FOLD (2026-07-10, verify-cost target #3): base+n_acc == 0 — a
9516 // pending-less round where nothing was accepted (PMIN0 zero-draft chains after a
9517 // replay/commit, or plain 0-accept rounds at round 0). The old path replayed
9518 // [bonus] through a FULL m=1 trunk+head forward (the 489us full-vocab head pass
9519 // measured at ~0.75/round on PMIN0 configs). Instead: restore the pre-round
9520 // snapshot and let the bonus ride the NEXT round's verify as col 0 — the existing
9521 // base=1 pending machinery, bit-identical by the decode-exact verify contract.
9522 // Seed: the bonus's predecessor is the last COMMITTED token, whose hidden
9523 // fill_prev already carries (same seeding as the 1-token-replay case it replaces).
9524 cache.rollback(e, &snap, 0)?;
9525 scratch.set_len(e, pos)?;
9526 e.copy_into(&mut h_seed_buf, 0, &fill_prev, n_embd)?;
9527 pending = Some(bonus);
9528 if debug_spec {
9529 eprintln!(" -> ZERO-ROUND FOLD (bonus pending, fill_prev seed)");
9530 }
9531 } else {
9532 // PARTIAL ACCEPT, LEGACY REPLAY (seam MEMRA_SPEC_REPLAY=1 — or j==0: nothing of
9533 // this round survives, only possible before the first pending exists, ~round 0):
9534 // restore EVERYTHING to the pre-round snapshot (KV truncate to pos + recur
9535 // restore), then replay the committed prefix pending? ++ draft[0..n_acc] ++
9536 // [bonus] as ONE batched T forward — single weight read, bit-identical to greedy
9537 // (the verify-all-columns path is the same math). Commits the bonus with a TRUE
9538 // trunk hidden.
9539 cache.rollback(e, &snap, 0)?; // accept_len=0: KV len = pos, recur = snapshot
9540 let mut replay: Vec<u32> = Vec::with_capacity(base + n_acc + 1);
9541 if let Some(b) = pending.take() {
9542 replay.push(b);
9543 }
9544 replay.extend_from_slice(&draft[0..n_acc]);
9545 replay.push(bonus);
9546 // Full-stack forward (decode_step_t_core = decode_step_t_h_emb_dev's body):
9547 // Predecessor pairing seeds from the PREDECESSOR row (col len-2) — the same-row path takes the
9548 // last col exactly as before (byte-identical to the old _h_emb_dev call).
9549 let (rl_d, rx) = if self.qwen35_serving_class() {
9550 let mut logits = Vec::with_capacity(replay.len() * n_vocab);
9551 let mut hidden = e.uninit(replay.len() * n_embd)?;
9552 for (row, &token) in replay.iter().enumerate() {
9553 let (row_logits, row_hidden) =
9554 self.spec_target_step_h(e, token, &mut *cache)?;
9555 logits.extend_from_slice(&row_logits);
9556 e.dtod_copy_into(&row_hidden, &mut hidden, row * n_embd)?;
9557 }
9558 (e.htod(&logits)?, hidden)
9559 } else {
9560 self.decode_step_t_core(e, &replay, pos, &mut *cache, embd_dev, None)?
9561 };
9562 // last_pred = argmax of the LAST column's logits (predicts the token after `bonus`)
9563 // — device argmax + one 4-byte read instead of the full-vocab column dtoh.
9564 e.argmax_token_device_col(&rl_d, replay.len() - 1, n_vocab, &mut preds_d, 0)?;
9565 last_pred = e.dtoh_u32(&preds_d)?[0];
9566 if sampled {
9567 let lr0 = replay.len();
9568 let lc = last_col_logits
9569 .as_mut()
9570 .expect("sampled: last_col_logits unset");
9571 e.copy_view_into(
9572 lc,
9573 0,
9574 &rl_d.slice((lr0 - 1) * n_vocab..lr0 * n_vocab),
9575 n_vocab,
9576 )?;
9577 }
9578 let lr = replay.len();
9579 if lr >= 2 {
9580 e.copy_view_into(
9581 &mut h_seed_buf,
9582 0,
9583 &rx.slice((lr - 2) * n_embd..(lr - 1) * n_embd),
9584 n_embd,
9585 )?;
9586 } else {
9587 // 1-token replay (round-0 miss): the bonus's predecessor is the OLD
9588 // last_token, whose own-row hidden fill_prev still holds.
9589 e.copy_into(&mut h_seed_buf, 0, &fill_prev, n_embd)?;
9590 }
9591 // the bonus is COMMITTED here — it becomes the last committed row.
9592 let mut rh_last = e.zeros(n_embd)?;
9593 e.copy_view_into(
9594 &mut rh_last,
9595 0,
9596 &rx.slice((lr - 1) * n_embd..lr * n_embd),
9597 n_embd,
9598 )?;
9599 e.copy_into(&mut fill_prev, 0, &rh_last, n_embd)?;
9600 if debug_spec {
9601 eprintln!(" -> PARTIAL(replay={replay:?}), next_pred={last_pred}");
9602 }
9603 }
9604 if devacc_seeded {
9605 // stage (b) epilogue: fill_prev takes the gathered seed AFTER the refresh fills
9606 // consumed the old value (both slots carry the same value in every non-replay arm).
9607 e.copy_into(&mut fill_prev, 0, &h_seed_buf, n_embd)?;
9608 }
9609 if successor_valid {
9610 let optimistic_scratch_len = successor_attempt
9611 .as_ref()
9612 .expect("valid controller successor disappeared")
9613 .scratch_len;
9614 // The normal current-round commit refreshed/truncated the logical scratch tail.
9615 // Its optimistic successor row was already written physically, so restoring only
9616 // the retained logical length makes that row live for the carried round.
9617 scratch.set_len(e, optimistic_scratch_len)?;
9618 }
9619 if let Some(current) = current_opti.take() {
9620 opti_fork
9621 .as_mut()
9622 .ok_or("optipipe current retirement lost fork state")?
9623 .retire(current.generation)?;
9624 }
9625 if successor_valid {
9626 let successor = successor_attempt
9627 .take()
9628 .expect("valid controller successor disappeared before promotion");
9629 let generation = successor.generation;
9630 opti_fork
9631 .as_mut()
9632 .ok_or("optipipe successor promotion lost fork state")?
9633 .promote_successor_snapshot(&mut snap, generation);
9634 carried_opti = Some(successor);
9635 }
9636 if anatomy_on {
9637 // Commit/rollback is normally asynchronous on the primary/head stream. Bound it
9638 // only for this diagnostic so it does not disappear into the following draft's
9639 // first token readback.
9640 e.stream().synchronize()?;
9641 ph_commit += commit_started.elapsed().as_secs_f64();
9642 }
9643 // adaptive-K update (host math, zero syncs): next round drafts accepted-run + 1,
9644 // clamped to [floor(pos), k_cap]. cache.pos is post-rollback here (the round's
9645 // final position — the floor's position key reads the committed depth). Burst
9646 // rounds (`continue` above) draft the captured fixed depth and skip this, exactly
9647 // like gemma's burst arm.
9648 if adapt {
9649 let fl_now = floor_at(cache.pos);
9650 kc = (n_acc + 1).clamp(fl_now.min(k_cap), k_cap);
9651 }
9652 ph_mark(&mut ph_rest, phase_on);
9653 if let Some(p) = pipe {
9654 p.accept_end(round);
9655 }
9656 drop(pipe_accept);
9657 round += 1;
9658 // sse-cadence: this round's accepted drafts + bonus are committed (out is
9659 // append-only past step 4) — flush at round cadence.
9660 keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
9661 }
9662 if let Some(mut ticket) = carried_opti.take() {
9663 opti_fork
9664 .as_mut()
9665 .ok_or("optipipe tail drain lost fork state")?
9666 .cancel_controller_ticket(e, &mut *cache, &mut *scratch, &snap, &mut ticket)?;
9667 }
9668 // sse-cadence: nothing below appends to `out`; flush any remainder (defensive).
9669 // (verdict ignored — the burst is over either way; the session tail runs unchanged.)
9670 let _ = flush_commit(&mut on_commit, &out, &mut flushed);
9671
9672 if spec_stats {
9673 let per_slot: Vec<String> = (0..k)
9674 .map(|j| {
9675 if st_drafted[j] > 0 {
9676 format!(
9677 "{}/{}={:.3}",
9678 st_accepted[j],
9679 st_drafted[j],
9680 st_accepted[j] as f64 / st_drafted[j] as f64
9681 )
9682 } else {
9683 "0/0".into()
9684 }
9685 })
9686 .collect();
9687 let acc = if total_drafted > 0 {
9688 total_accepted as f64 / total_drafted as f64
9689 } else {
9690 0.0
9691 };
9692 eprintln!(
9693 "[spec-stats] rounds={round} full_accept={st_full} len_hist={st_len_hist:?} \
9694 per_slot=[{}] total={total_accepted}/{total_drafted}={acc:.3} \
9695 tok_per_round={:.3}",
9696 per_slot.join(" "),
9697 (total_accepted + round) as f64 / round.max(1) as f64
9698 );
9699 }
9700 if constraint.is_some() {
9701 eprintln!(
9702 "[draft-mask] mask_rounds={dm_rounds} clone_total={:.3}ms \
9703 clone_per_round={:.4}ms gram_cuts={dm_cuts}/{round} cut_tokens={dm_cut_tokens}",
9704 dm_clone_ns as f64 / 1e6,
9705 dm_clone_ns as f64 / 1e6 / dm_rounds.max(1) as f64
9706 );
9707 }
9708 if phase_on {
9709 let tot = ph_draft + ph_verify + ph_wait + ph_rest;
9710 eprintln!(
9711 "[spec-phase] draft={:.1}ms ({:.1}%) verify-issue={:.1}ms ({:.1}%) verify-wait={:.1}ms ({:.1}%) commit-host={:.1}ms ({:.1}%) rounds={round}",
9712 ph_draft * 1e3,
9713 ph_draft / tot * 100.0,
9714 ph_verify * 1e3,
9715 ph_verify / tot * 100.0,
9716 ph_wait * 1e3,
9717 ph_wait / tot * 100.0,
9718 ph_rest * 1e3,
9719 ph_rest / tot * 100.0
9720 );
9721 }
9722 if anatomy_on {
9723 let rounds_f = round.max(1) as f64;
9724 let other = (ph_rest - ph_commit).max(0.0);
9725 eprintln!(
9726 "[spec-anatomy] per-round draft={:.3}ms pp-verify={:.3}ms \
9727 verify-accept={:.3}ms commit-rollback={:.3}ms other={:.3}ms rounds={round}",
9728 ph_draft * 1e3 / rounds_f,
9729 ph_verify * 1e3 / rounds_f,
9730 ph_wait * 1e3 / rounds_f,
9731 ph_commit * 1e3 / rounds_f,
9732 other * 1e3 / rounds_f,
9733 );
9734 }
9735 let _pipe_tail = pipe.map(|p| p.primary());
9736 // SESSION TAIL: leave the session in the exact invariant the next turn's suffix prime
9737 // expects — every row in `committed` has trunk KV/recur state AND an exact draft-KV row.
9738 // Park the draft-graph ctx back on the session (the serve-burst fixed-cost fix): the next
9739 // burst replays instead of recapturing. Error paths (`?` above) drop it — recaptured then.
9740 if let Some(slot) = sess_draft_slot.take() {
9741 *slot = Some(dctx);
9742 }
9743 let t_rounds = t_ent.elapsed();
9744 if let Some((committed, last_h, next_pred_slot, sctr_slot, uctr_slot)) = sess_tail.take() {
9745 *sctr_slot = sctr;
9746 *uctr_slot = uctr;
9747 *next_pred_slot = Some(last_pred);
9748 let mut stashed_pending = false;
9749 if let Some(b) = pending.take() {
9750 if !sampled {
9751 // PENDING-CARRY (2026-08-01): stash the bonus on the session instead of
9752 // committing it with a solo T=1 pass — the next empty-suffix greedy burst
9753 // consumes it as round-0 verify col 0 (a plain round edge; the old tail
9754 // commit + next burst's init feed were 11.6+11.5ms solo trunk passes per
9755 // burst on H100 q27, [spec-setup] trace). b stays in `out` (emitted) but
9756 // OUT of `committed` (cache rows == committed); the consuming call
9757 // prepends it once its verify commits the row. next_pred is unknowable
9758 // without the commit pass — None; callers gate on pending_tok too.
9759 debug_assert_eq!(out.last(), Some(&b), "pending must be the last emitted");
9760 if let Some(slot) = sess_pending_slot.take() {
9761 *slot = Some(b);
9762 }
9763 *next_pred_slot = None;
9764 // fill_prev = hidden of the last COMMITTED row (b's predecessor) — the
9765 // exact chain-seed/fill anchor the consuming burst (or a flush) needs.
9766 *last_h = Some(e.clone_dtod(&fill_prev)?);
9767 stashed_pending = true;
9768 } else {
9769 // SAMPLED tail (unchanged): commit the bonus (one T=1 pass) + draft fill —
9770 // the sampled round-0 accept needs this pass's logits (last_col_logits).
9771 let pos_b = cache.pos;
9772 scratch.set_len(e, pos_b)?;
9773 let (lg_b, hb) = self.spec_target_step_h(e, b, &mut *cache)?;
9774 // after a FULL-accept exit `last_pred` is STALE (it predicted the bonus
9775 // itself — the prediction AFTER the bonus never materialized; it would have
9776 // been the next round's verify col 0). The commit's logits ARE that
9777 // prediction.
9778 *next_pred_slot = Some(argmax(&lg_b) as u32);
9779 self.mtp_kv_fill(e, mtp, &[b], &fill_prev, pos_b, &mut *scratch, embd_dev)?;
9780 *last_h = Some(hb);
9781 }
9782 } else {
9783 // fill_prev tracks the hidden of the last COMMITTED row throughout the loop.
9784 *last_h = Some(e.clone_dtod(&fill_prev)?);
9785 }
9786 committed.extend_from_slice(prompt);
9787 if let Some(cb) = carried_pending {
9788 // the consumed carry's cache row landed in round 0's verify (every pending
9789 // round commits col 0) — it joins `committed` here, in sequence order.
9790 committed.push(cb);
9791 }
9792 if stashed_pending {
9793 // ZERO-EMIT BURST (2026-08-06 c=8 serve panic, pre-existing since b4aea184):
9794 // `out.len() - 1` underflowed on an EMPTY `out` — "range end index
9795 // 18446744073709551615 out of range for slice of length 0", killing the
9796 // memra-gpu-worker and failing 31 of 32 concurrent requests with "worker closed
9797 // stream". Reachable because `pending` starts as `carried_pending` (a bonus
9798 // stashed by the PREVIOUS burst) while `out` starts empty, and the carry is
9799 // deliberately NOT pushed to `out` (line ~3239: the burst that emitted it already
9800 // did). So a burst that stashes a pending without emitting anything of its own —
9801 // the round loop exits before a push, e.g. the ring drain's `out.len() < max_new`
9802 // guard skipping every token under a tight budget — arrives here with
9803 // out.len() == 0 and stashed_pending == true.
9804 //
9805 // The invariant is unchanged: `committed` gets every emitted token EXCEPT the
9806 // stashed bonus. With nothing emitted, that is nothing — and the carry pushed
9807 // just above is already accounted. Saturating, not a min/assert: an empty `out`
9808 // here is a legitimate burst shape, not a corrupt state.
9809 let emitted = out.len().saturating_sub(1);
9810 committed.extend_from_slice(&out[..emitted]);
9811 } else {
9812 committed.extend_from_slice(&out); // FULL out incl. overshoot — all committed
9813 }
9814 debug_assert_eq!(
9815 cache.pos,
9816 committed.len(),
9817 "session invariant: cache rows == committed tokens"
9818 );
9819 if setup_trace {
9820 e.stream().synchronize()?; // bound the async tail fill in the trace
9821 let t_tail = t_ent.elapsed();
9822 eprintln!(
9823 "[spec-setup] init={:.2}ms cap={:.2}ms fill={:.2}ms rounds={:.2}ms tail={:.2}ms total={:.2}ms out={} cont={}",
9824 t_init.as_secs_f64() * 1e3,
9825 (t_cap - t_init).as_secs_f64() * 1e3,
9826 (t_fill - t_cap).as_secs_f64() * 1e3,
9827 (t_rounds - t_fill).as_secs_f64() * 1e3,
9828 (t_tail - t_rounds).as_secs_f64() * 1e3,
9829 t_tail.as_secs_f64() * 1e3,
9830 out.len(),
9831 continuation
9832 );
9833 }
9834 return Ok((out, total_drafted, total_accepted));
9835 }
9836 out.truncate(max_new);
9837 Ok((out, total_drafted, total_accepted))
9838 }
9839
9840 /// Anchor-bounded DSpark target extraction. The trunk sees the exact generated token tape;
9841 /// only requested hidden rows and target-logit rows cross PCIe. An anchor token at p pairs
9842 /// with the pre-output-norm h[p-1] carrier, exactly as the existing replay/NextN path does.
9843 pub fn extract_dspark_anchors(
9844 &self,
9845 e: &Engine,
9846 tokens: &[u32],
9847 anchor_positions: &[usize],
9848 gamma: usize,
9849 top_k: usize,
9850 chunk: usize,
9851 temperature: f32,
9852 ) -> Result<Vec<DsparkAnchorRecord>, Box<dyn std::error::Error>> {
9853 if tokens.len() < gamma + 2 || gamma == 0 || chunk < 2 {
9854 return Err("DSpark extraction token tape/gamma/chunk is invalid".into());
9855 }
9856 if anchor_positions.windows(2).any(|pair| pair[0] >= pair[1]) {
9857 return Err("DSpark anchor positions must be sorted and unique".into());
9858 }
9859 for &position in anchor_positions {
9860 if position == 0 || position + gamma >= tokens.len() {
9861 return Err(format!(
9862 "DSpark anchor {position} has no predecessor or cannot cover gamma={gamma} in {} tokens",
9863 tokens.len()
9864 )
9865 .into());
9866 }
9867 }
9868
9869 let n_vocab = self.output.out_features();
9870 let n_embd = self.cfg.n_embd as usize;
9871 let mut cache = crate::pp::new_cache(e, &self.cfg, tokens.len() + gamma + 8)?;
9872 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
9873 let embd_gpu = if spec_host_embd() {
9874 None
9875 } else {
9876 Some(
9877 self.embd_gpu
9878 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
9879 )
9880 };
9881 let embd_dev = embd_gpu.map(|gpu| (gpu, embd_qt, embd_rb));
9882
9883 struct PendingRecord {
9884 position: usize,
9885 hidden: Option<Vec<f32>>,
9886 tokens: Vec<u32>,
9887 target_top_ids: Vec<Option<Vec<u32>>>,
9888 target_top_logits: Vec<Option<Vec<f32>>>,
9889 target_top_probs: Vec<Option<Vec<f32>>>,
9890 target_tail_probs: Vec<Option<f32>>,
9891 }
9892
9893 let mut pending: Vec<PendingRecord> = anchor_positions
9894 .iter()
9895 .map(|&position| PendingRecord {
9896 position,
9897 hidden: None,
9898 tokens: tokens[position..=position + gamma].to_vec(),
9899 target_top_ids: vec![None; gamma],
9900 target_top_logits: vec![None; gamma],
9901 target_top_probs: vec![None; gamma],
9902 target_tail_probs: vec![None; gamma],
9903 })
9904 .collect();
9905
9906 let mut start = 0usize;
9907 while start < tokens.len() {
9908 let end = (start + chunk).min(tokens.len());
9909 let chunk_tokens = &tokens[start..end];
9910 let (target_logits, hidden_rows) =
9911 self.decode_step_t_core(e, chunk_tokens, start, &mut cache, embd_dev, None)?;
9912 for record in &mut pending {
9913 let hidden_position = record.position - 1;
9914 if hidden_position >= start && hidden_position < end {
9915 let local = hidden_position - start;
9916 record.hidden = Some(
9917 e.dtoh_view(&hidden_rows.slice(local * n_embd..(local + 1) * n_embd))?,
9918 );
9919 }
9920 for slot in 0..gamma {
9921 let target_row = record.position + slot;
9922 if target_row < start || target_row >= end {
9923 continue;
9924 }
9925 let local = target_row - start;
9926 let logits =
9927 e.dtoh_view(&target_logits.slice(local * n_vocab..(local + 1) * n_vocab))?;
9928 let (ids, top_logits, probs, tail) =
9929 dspark_sparse_softmax_topk(&logits, top_k, temperature)?;
9930 record.target_top_ids[slot] = Some(ids);
9931 record.target_top_logits[slot] = Some(top_logits);
9932 record.target_top_probs[slot] = Some(probs);
9933 record.target_tail_probs[slot] = Some(tail);
9934 }
9935 }
9936 start = end;
9937 }
9938
9939 pending
9940 .into_iter()
9941 .map(|record| {
9942 let hidden = record
9943 .hidden
9944 .ok_or_else(|| format!("missing DSpark hidden at {}", record.position))?;
9945 let target_top_ids =
9946 flatten_dspark_rows(record.target_top_ids, record.position, "target ids")?;
9947 let target_top_logits = flatten_dspark_rows(
9948 record.target_top_logits,
9949 record.position,
9950 "target logits",
9951 )?;
9952 let target_top_probs =
9953 flatten_dspark_rows(record.target_top_probs, record.position, "target probs")?;
9954 let target_tail_probs = record
9955 .target_tail_probs
9956 .into_iter()
9957 .enumerate()
9958 .map(|(slot, value)| {
9959 value.ok_or_else(|| {
9960 format!("missing DSpark tail at {} slot {slot}", record.position)
9961 })
9962 })
9963 .collect::<Result<Vec<_>, _>>()?;
9964 Ok(DsparkAnchorRecord {
9965 position: record.position,
9966 hidden,
9967 tokens: record.tokens,
9968 target_top_ids,
9969 target_top_logits,
9970 target_top_probs,
9971 target_tail_probs,
9972 })
9973 })
9974 .collect()
9975 }
9976
9977 /// TEACHER-FORCED REPLAY ACCEPTANCE (hqmtp MTP-heal protocol): walk a FIXED token
9978 /// sequence and, at sampled positions, compare the MTP head's K-token draft chain against
9979 /// the trunk's own teacher-forced greedy predictions. Nothing is generated — the context is
9980 /// the corpus text itself, so (a) degenerate self-generated loops cannot inflate acceptance
9981 /// and (b) two arms (bf16 ceiling vs NVFP4) score on IDENTICAL contexts, isolating the
9982 /// quant-induced head/hidden-state mismatch from text drift.
9983 ///
9984 /// Per eval position p (context = tokens[0..=p], predecessor pairing as in spec decode):
9985 /// draft_j = chain token j from (tokens[p], h_{p-1}), then its own drafts — the exact
9986 /// eager spec-decode chain (same mtp_head_forward_dev, same rope positions).
9987 /// target_j = teacher-forced greedy pick for position p+1+j (argmax of the trunk logits
9988 /// at forced context tokens[0..p+j]). For j==0 this equals live spec
9989 /// acceptance; for j>=1 live verify would condition on the drafts, here it
9990 /// conditions on the corpus — deterministic and arm-comparable by design.
9991 ///
9992 /// Returns (rows, bg): one (p, drafts[k], targets[k]) row per eval position (ascending p),
9993 /// plus the full teacher-forced greedy track bg (bg[i] = greedy pick for position i, i>=1)
9994 /// so harnesses can cross-check runs (e.g. different chunk sizes must give identical bg).
9995 ///
9996 /// `hdump`: when Some, every position's pre-output_norm trunk hidden (the exact rows the
9997 /// draft-KV fill pairs from) streams to the file as little-endian f32 [t_total, n_embd] —
9998 /// the head-distillation extraction (hqmtp): the ENGINE is the source of truth for trunk
9999 /// hiddens (HF torch reproductions of the hybrid trunk measured only ~0.5 greedy
10000 /// agreement vs this path — not usable as a training-data source).
10001 pub fn replay_acceptance(
10002 &self,
10003 e: &Engine,
10004 tokens: &[u32],
10005 k: usize,
10006 stride: usize,
10007 chunk: usize,
10008 mut hdump: Option<&mut std::fs::File>,
10009 ) -> Result<(Vec<(usize, Vec<u32>, Vec<u32>)>, Vec<u32>), Box<dyn std::error::Error>> {
10010 assert!(k >= 1 && stride >= 1 && chunk >= 2);
10011 let mtp = self
10012 .mtp
10013 .as_ref()
10014 .expect("replay_acceptance requires an MTP head");
10015 let n_vocab = self.output.out_features();
10016 let d_vocab = mtp
10017 .shared_head_head
10018 .as_ref()
10019 .unwrap_or(&self.output)
10020 .out_features();
10021 let n_embd = self.cfg.n_embd as usize;
10022 let t_total = tokens.len();
10023 assert!(t_total >= 8, "corpus too short ({t_total} tokens)");
10024 // STAGE-OWNED KV (lane/pp2-spec 2026-08-06) — see `new_session`. Door shut = `Cache::new`.
10025 let mut cache = crate::pp::new_cache(e, &self.cfg, t_total + k + 8)?;
10026 let mut scratch = MtpScratch::new(
10027 e,
10028 &self.cfg,
10029 t_total + k + 8,
10030 self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
10031 )?;
10032 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
10033 let embd_gpu = if spec_host_embd() {
10034 None
10035 } else {
10036 Some(
10037 self.embd_gpu
10038 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
10039 )
10040 };
10041 let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
10042
10043 // bg[i] = the trunk's greedy pick for position i under the forced context (i >= 1).
10044 let mut bg: Vec<u32> = vec![0; t_total + 1];
10045 let mut rows: Vec<(usize, Vec<u32>, Vec<u32>)> = Vec::new();
10046 let mut prev_last_h = e.zeros(n_embd)?; // predecessor hidden entering the chunk
10047 let mut seed_buf = e.zeros(n_embd)?;
10048 let mut preds_d = e.alloc_u32_zeroed(chunk)?;
10049 let nll_on = std::env::var("MEMRA_REPLAY_NLL").as_deref() == Ok("1");
10050 let (mut nll_sum, mut nll_cnt) = (0f64, 0u64);
10051 let mut s = 0usize;
10052 while s < t_total {
10053 let cend = (s + chunk).min(t_total);
10054 let tc = cend - s;
10055 let ch = &tokens[s..cend];
10056 // 1. forced trunk pass — verify path (decode-exact contract): all-column logits +
10057 // the chunk's true hiddens.
10058 let (tl_d, vx) = self.decode_step_t_core(e, ch, s, &mut cache, embd_dev, None)?;
10059 for j in 0..tc {
10060 e.argmax_token_device_col(&tl_d, j, n_vocab, &mut preds_d, j)?;
10061 }
10062 let preds = e.dtoh_u32(&preds_d)?;
10063 for j in 0..tc {
10064 bg[s + j + 1] = preds[j];
10065 }
10066 // MEMRA_REPLAY_NLL=1: teacher-forced NLL/perplexity over the same forced pass — the
10067 // checkpoint-quality metric (position j's logits score the GOLD next token).
10068 if nll_on {
10069 let jmax = if cend < t_total { tc } else { tc - 1 }; // last pos has no gold next
10070 if jmax > 0 {
10071 let ids: Vec<u32> = (0..jmax).map(|j| tokens[s + j + 1]).collect();
10072 let rows: Vec<i32> = (0..jmax as i32).collect();
10073 let idsd = e.htod_u32_v(&ids)?;
10074 let rowsd = e.htod_i32(&rows)?;
10075 let mut outd = e.zeros(jmax)?;
10076 e.softmax_gather(&tl_d, n_vocab, &idsd, &rowsd, &mut outd, n_vocab, jmax, 1.0)?;
10077 for pr in e.dtoh(&outd)? {
10078 nll_sum += -((pr.max(1e-30)) as f64).ln();
10079 nll_cnt += 1;
10080 }
10081 }
10082 }
10083 if let Some(f) = hdump.as_deref_mut() {
10084 use std::io::Write;
10085 let host: Vec<f32> = e.dtoh(&vx)?;
10086 // bf16 round-to-nearest-even — f32 doubled the disk bill at bulk
10087 // extraction scale (20M tokens x 4096 = 320GB f32 vs 160GB bf16).
10088 let mut bytes = Vec::with_capacity(tc * n_embd * 2);
10089 for v in &host[..tc * n_embd] {
10090 let b = v.to_bits();
10091 let r = b.wrapping_add(0x7FFF + ((b >> 16) & 1));
10092 bytes.extend_from_slice(&((r >> 16) as u16).to_le_bytes());
10093 }
10094 f.write_all(&bytes)?;
10095 }
10096 // CHAINLESS extraction (stride > corpus, the bulk-hdump mode): no chunk ever
10097 // drafts, so the draft-KV fills are pure waste — skip them (2 MTP-block passes
10098 // per token saved; the forced trunk pass + hdump is all the mode needs).
10099 let chainless = stride > t_total;
10100 if chainless {
10101 e.copy_view_into(
10102 &mut prev_last_h,
10103 0,
10104 &vx.slice((tc - 1) * n_embd..tc * n_embd),
10105 n_embd,
10106 )?;
10107 s = cend;
10108 continue;
10109 }
10110 // 2. TRUE predecessor-paired draft-KV fill for the chunk (row i carries h_{i-1};
10111 // row s reads the previous chunk's last true hidden, zeros at corpus start).
10112 let mut vxs = e.zeros(tc * n_embd)?;
10113 e.copy_into(&mut vxs, 0, &prev_last_h, n_embd)?;
10114 if tc > 1 {
10115 e.copy_view_into(
10116 &mut vxs,
10117 n_embd,
10118 &vx.slice(0..(tc - 1) * n_embd),
10119 (tc - 1) * n_embd,
10120 )?;
10121 }
10122 scratch.set_len(e, s)?;
10123 self.mtp_kv_fill(e, mtp, ch, &vxs, s, &mut scratch, embd_dev)?;
10124 // 3. draft chains at sampled positions, DESCENDING: a chain reads only slots
10125 // [0..p) (true fills) and appends at >= p; the next (smaller-p) chain's set_len
10126 // truncates those approximate appends before they can ever be read.
10127 let ps: Vec<usize> = (s..cend)
10128 .filter(|p| *p >= 1 && *p % stride == 0 && *p + k <= t_total)
10129 .collect();
10130 for &p in ps.iter().rev() {
10131 scratch.set_len(e, p)?;
10132 if p == s {
10133 e.copy_into(&mut seed_buf, 0, &prev_last_h, n_embd)?;
10134 } else {
10135 e.copy_view_into(
10136 &mut seed_buf,
10137 0,
10138 &vx.slice((p - 1 - s) * n_embd..(p - s) * n_embd),
10139 n_embd,
10140 )?;
10141 }
10142 let mut e_tok = tokens[p];
10143 let mut d_seed = e.clone_dtod(&seed_buf)?;
10144 let mut drafts: Vec<u32> = Vec::with_capacity(k);
10145 for j in 0..k {
10146 let (dl_d, h_nextn) = self.mtp_head_forward_dev(
10147 e,
10148 mtp,
10149 e_tok,
10150 &d_seed,
10151 &mut scratch,
10152 p + 1 + j,
10153 embd_dev,
10154 None, // acceptance-oracle walk: no grammar
10155 )?;
10156 let tok_d = e.argmax_token_device(&dl_d, d_vocab)?;
10157 let idx = e.dtoh_u32_one(&tok_d)?;
10158 let d = match &mtp.d2t {
10159 Some(map) => map[idx as usize],
10160 None => idx,
10161 };
10162 drafts.push(d);
10163 e_tok = d;
10164 d_seed = h_nextn;
10165 }
10166 // targets may live in a LATER chunk's bg — resolved after the walk.
10167 rows.push((p, drafts, Vec::new()));
10168 }
10169 // 4. restore TRUE entries for the whole chunk (the next chunk's chains and fills
10170 // expect scratch.len == cend with exact rows).
10171 scratch.set_len(e, s)?;
10172 self.mtp_kv_fill(e, mtp, ch, &vxs, s, &mut scratch, embd_dev)?;
10173 e.copy_view_into(
10174 &mut prev_last_h,
10175 0,
10176 &vx.slice((tc - 1) * n_embd..tc * n_embd),
10177 n_embd,
10178 )?;
10179 s = cend;
10180 }
10181 for (p, drafts, targets) in rows.iter_mut() {
10182 for j in 0..drafts.len() {
10183 targets.push(bg[*p + 1 + j]);
10184 }
10185 }
10186 rows.sort_by_key(|r| r.0);
10187 if nll_cnt > 0 {
10188 let mean = nll_sum / nll_cnt as f64;
10189 println!(
10190 "[replay-nll] tokens={nll_cnt} nll/token={mean:.5} ppl={:.4}",
10191 mean.exp()
10192 );
10193 }
10194 Ok((rows, bg))
10195 }
10196}
10197
10198#[cfg(test)]
10199mod dspark_sparse_tests {
10200 use super::dspark_sparse_softmax_topk;
10201
10202 #[test]
10203 fn topk_keeps_full_softmax_mass_and_stable_ties() {
10204 let logits = [1.0f32, 3.0, 3.0, -2.0];
10205 let (ids, top_logits, probs, tail) = dspark_sparse_softmax_topk(&logits, 2, 1.0).unwrap();
10206 assert_eq!(ids, vec![1, 2]);
10207 assert_eq!(top_logits, vec![3.0, 3.0]);
10208 let denominator = logits.iter().map(|value| (value - 3.0).exp()).sum::<f32>();
10209 let expected = 1.0 / denominator;
10210 assert!((probs[0] - expected).abs() < 1.0e-6);
10211 assert!((probs[1] - expected).abs() < 1.0e-6);
10212 assert!((tail - (1.0 - 2.0 * expected)).abs() < 1.0e-6);
10213 assert!((probs.iter().sum::<f32>() + tail - 1.0).abs() < 1.0e-6);
10214 }
10215}
10216
10217#[cfg(test)]
10218mod spec_replay_env_tests {
10219 use super::spec_replay_env_on;
10220
10221 #[test]
10222 fn replay_requires_literal_one() {
10223 assert!(!spec_replay_env_on(None));
10224 assert!(!spec_replay_env_on(Some("")));
10225 assert!(!spec_replay_env_on(Some("0")));
10226 assert!(!spec_replay_env_on(Some("true")));
10227 assert!(!spec_replay_env_on(Some("2")));
10228 assert!(spec_replay_env_on(Some("1")));
10229 }
10230}
10231
10232#[cfg(test)]
10233mod telem_tests {
10234 use super::{SPEC_TELEM_POS, SpecTelemetry, SpecTelemetryCounters};
10235
10236 #[test]
10237 fn synthetic_accept_masks_produce_tau_and_position_histogram() {
10238 let counters = SpecTelemetryCounters::default();
10239 for mask in [
10240 [true, true, true],
10241 [true, true, false],
10242 [true, false, false],
10243 [false, false, false],
10244 ] {
10245 let accepted = mask.iter().take_while(|&&value| value).count();
10246 counters.record_round(mask.len(), accepted);
10247 }
10248
10249 let snapshot = counters.snapshot();
10250 assert_eq!(
10251 (snapshot.rounds, snapshot.drafted, snapshot.accepted),
10252 (4, 12, 6)
10253 );
10254 assert_eq!(&snapshot.pos_drafted[..3], &[4, 4, 4]);
10255 assert_eq!(&snapshot.pos_accepted[..3], &[3, 2, 1]);
10256 assert_eq!(snapshot.tau(), 1.5);
10257 assert_eq!(snapshot.pos_drafted[3..], [0; SPEC_TELEM_POS - 3]);
10258 assert_eq!(snapshot.pos_accepted[3..], [0; SPEC_TELEM_POS - 3]);
10259 }
10260
10261 /// The worker's per-burst pattern: stash, accumulate, diff — the delta must isolate
10262 /// exactly the burst's contribution (pool-resumed sessions carry prior requests' counts).
10263 #[test]
10264 fn delta_isolates_burst_contribution() {
10265 let mut t = SpecTelemetry::default();
10266 // "previous request": 2 rounds of k=3, accepts 3 then 1.
10267 for (kr, na) in [(3usize, 3usize), (3, 1)] {
10268 t.rounds += 1;
10269 t.drafted += kr as u64;
10270 t.accepted += na as u64;
10271 for j in 0..kr {
10272 t.pos_drafted[j] += 1;
10273 }
10274 for j in 0..na {
10275 t.pos_accepted[j] += 1;
10276 }
10277 }
10278 let before = t;
10279 // "this burst": 1 round k=3, accepts 2.
10280 t.rounds += 1;
10281 t.drafted += 3;
10282 t.accepted += 2;
10283 for j in 0..3 {
10284 t.pos_drafted[j] += 1;
10285 }
10286 for j in 0..2 {
10287 t.pos_accepted[j] += 1;
10288 }
10289 let d = t.delta_since(&before);
10290 assert_eq!((d.rounds, d.drafted, d.accepted), (1, 3, 2));
10291 assert_eq!(&d.pos_drafted[..3], &[1, 1, 1]);
10292 assert_eq!(&d.pos_accepted[..3], &[1, 1, 0]);
10293 assert_eq!(d.pos_drafted[3..], [0; SPEC_TELEM_POS - 3]);
10294 }
10295
10296 /// merge(delta) then merge(delta2) equals accumulating both — the per-model /metrics
10297 /// aggregation invariant.
10298 #[test]
10299 fn merge_accumulates_fieldwise() {
10300 let mut agg = SpecTelemetry::default();
10301 let mut d1 = SpecTelemetry {
10302 rounds: 2,
10303 drafted: 6,
10304 accepted: 4,
10305 ..Default::default()
10306 };
10307 d1.pos_drafted[0] = 2;
10308 d1.pos_accepted[0] = 2;
10309 let mut d2 = SpecTelemetry {
10310 rounds: 1,
10311 drafted: 3,
10312 accepted: 1,
10313 ..Default::default()
10314 };
10315 d2.pos_drafted[0] = 1;
10316 d2.pos_accepted[0] = 1;
10317 d2.pos_drafted[1] = 1;
10318 agg.merge(&d1);
10319 agg.merge(&d2);
10320 assert_eq!((agg.rounds, agg.drafted, agg.accepted), (3, 9, 5));
10321 assert_eq!(agg.pos_drafted[0], 3);
10322 assert_eq!(agg.pos_accepted[0], 3);
10323 assert_eq!(agg.pos_drafted[1], 1);
10324 assert_eq!(agg.pos_accepted[1], 0);
10325 }
10326
10327 /// Wrong-snapshot diff saturates to zero instead of wrapping — the counters feed a
10328 /// public metrics surface and must never publish a u64-wrapped garbage value.
10329 #[test]
10330 fn delta_saturates_never_wraps() {
10331 let small = SpecTelemetry {
10332 rounds: 1,
10333 drafted: 2,
10334 accepted: 1,
10335 ..Default::default()
10336 };
10337 let big = SpecTelemetry {
10338 rounds: 5,
10339 drafted: 15,
10340 accepted: 9,
10341 ..Default::default()
10342 };
10343 let d = small.delta_since(&big);
10344 assert_eq!((d.rounds, d.drafted, d.accepted), (0, 0, 0));
10345 }
10346}
10347
10348#[cfg(test)]
10349mod opti_fork_tests {
10350 use super::{
10351 OptiControllerPolicy, OptiForkAction, OptiForkGateMode, OptiForkGenerationTracker,
10352 };
10353
10354 #[test]
10355 fn controller_threshold_and_three_miss_breaker_are_exact() {
10356 let mut policy = OptiControllerPolicy {
10357 threshold: 0.7,
10358 consecutive_misses: 0,
10359 breaker_tripped: false,
10360 };
10361 assert!(!policy.admit(0.699_999));
10362 assert!(policy.admit(0.7));
10363 assert!(!policy.resolve(false));
10364 assert!(!policy.resolve(false));
10365 assert!(policy.resolve(false));
10366 assert!(policy.breaker_tripped);
10367 assert!(!policy.admit(1.0));
10368 assert!(
10369 !policy.resolve(true),
10370 "a resolved hit cannot re-arm a tripped request"
10371 );
10372 assert!(policy.breaker_tripped);
10373 }
10374
10375 #[test]
10376 fn zero_threshold_is_the_true_unconditional_measurement_arm() {
10377 let mut policy = OptiControllerPolicy {
10378 threshold: 0.0,
10379 consecutive_misses: 0,
10380 breaker_tripped: false,
10381 };
10382 for _ in 0..16 {
10383 assert!(policy.admit(0.0));
10384 assert!(!policy.resolve(false));
10385 }
10386 for invalid in [f32::NAN, f32::INFINITY, -0.01, 1.01] {
10387 assert!(
10388 !policy.admit(invalid),
10389 "invalid q proxy must fail closed: {invalid}"
10390 );
10391 }
10392 assert!(!policy.breaker_tripped);
10393 assert_eq!(policy.consecutive_misses, 0);
10394 }
10395
10396 #[test]
10397 fn alternating_mode_flips_by_generation_not_round_parity() {
10398 assert_eq!(OptiForkGateMode::Alternate.action(0), OptiForkAction::Hit);
10399 assert_eq!(OptiForkGateMode::Alternate.action(1), OptiForkAction::Miss);
10400 assert_eq!(OptiForkGateMode::Alternate.action(8), OptiForkAction::Hit);
10401 assert_eq!(OptiForkGateMode::Alternate.action(9), OptiForkAction::Miss);
10402 }
10403
10404 #[test]
10405 fn live_generation_cannot_be_overwritten() {
10406 let mut tracker = OptiForkGenerationTracker::default();
10407 let g0 = tracker.reserve().unwrap();
10408 let g1 = tracker.reserve().unwrap();
10409 let err = tracker.reserve().unwrap_err().to_string();
10410 assert!(
10411 err.contains("still owns generation 0"),
10412 "unexpected error: {err}"
10413 );
10414 tracker.retire(g0).unwrap();
10415 let g2 = tracker.reserve().unwrap();
10416 assert_eq!((g2.id, g2.slot), (2, 0));
10417 tracker.retire(g1).unwrap();
10418 tracker.retire(g2).unwrap();
10419 }
10420
10421 #[test]
10422 fn teardown_rejects_a_stale_generation_tag() {
10423 let mut tracker = OptiForkGenerationTracker::default();
10424 let g0 = tracker.reserve().unwrap();
10425 tracker.retire(g0).unwrap();
10426 let err = tracker.retire(g0).unwrap_err().to_string();
10427 assert!(err.contains("teardown mismatch"), "unexpected error: {err}");
10428 }
10429}
10430
10431#[cfg(test)]
10432mod draft_graph_fallback_tests {
10433 use super::DraftGraphFallback;
10434
10435 /// The Q2 contract, part (a): a fallback flip is LOUD — exactly once per flip.
10436 #[test]
10437 fn flip_is_loud_once_and_memoized_after() {
10438 let mut f = DraftGraphFallback::default();
10439 let line = f
10440 .mark_greedy("out of memory")
10441 .expect("first flip must return the warn line");
10442 assert!(
10443 line.contains("WARN"),
10444 "flip line must be warn-level: {line}"
10445 );
10446 assert!(
10447 line.contains("out of memory"),
10448 "flip line must carry the reason: {line}"
10449 );
10450 assert!(f.greedy_failed());
10451 // re-marking an already-failed graph is the memoization: quiet, still failed.
10452 assert!(f.mark_greedy("out of memory").is_none());
10453 assert!(f.greedy_failed());
10454 // the two graphs' flags are independent (greedy flip leaves sampled capturable).
10455 assert!(!f.sampled_failed());
10456 let line_s = f
10457 .mark_sampled("capture unsupported")
10458 .expect("sampled flip is its own flip");
10459 assert!(
10460 line_s.contains("sampled"),
10461 "sampled flip names itself: {line_s}"
10462 );
10463 assert!(f.mark_sampled("capture unsupported").is_none());
10464 }
10465
10466 /// The Q2 contract, part (b): resume-from-pool RESETS both flags (fresh capture chance),
10467 /// and says so exactly when there was something to reset.
10468 #[test]
10469 fn reset_on_resume_clears_flags_and_logs_once() {
10470 let mut f = DraftGraphFallback::default();
10471 // clean session: resume is silent, nothing to reset.
10472 assert!(f.reset_on_resume().is_none());
10473 f.mark_greedy("oom").unwrap();
10474 f.mark_sampled("oom").unwrap();
10475 let note = f
10476 .reset_on_resume()
10477 .expect("a set flag must produce the reset note");
10478 assert!(
10479 note.contains("greedy+sampled"),
10480 "note names what was reset: {note}"
10481 );
10482 assert!(
10483 !f.greedy_failed() && !f.sampled_failed(),
10484 "both flags cleared"
10485 );
10486 // and the NEXT failure after a reset is a fresh flip — loud again.
10487 assert!(f.mark_greedy("oom again").is_some());
10488 let note2 = f.reset_on_resume().expect("greedy-only reset");
10489 assert!(note2.contains("(greedy)"), "single-flag note: {note2}");
10490 }
10491
10492 /// Shape-change clears (dmask realloc / mask-shape mismatch / s_key change) stay silent —
10493 /// they precede a fresh capture attempt whose own failure re-flips loudly.
10494 #[test]
10495 fn shape_change_clears_are_silent() {
10496 let mut f = DraftGraphFallback::default();
10497 f.mark_greedy("oom").unwrap();
10498 f.clear_greedy();
10499 assert!(!f.greedy_failed());
10500 f.mark_sampled("oom").unwrap();
10501 f.clear_sampled();
10502 assert!(!f.sampled_failed());
10503 // after a silent clear there is nothing left for resume to report.
10504 assert!(f.reset_on_resume().is_none());
10505 }
10506}