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/// Engine-bundle slice 2 (DSF-ROUNDCOST-20260820 §1.1 host/device round trips + §2 rows 2-3),
179/// DEFAULT ON (`MEMRA_DSPARK_DEFER_READBACK=0` reverts): the dspark round's draft-chain DtoH
180/// is DEFERRED past verify dispatch and merged with the verify-argmax readback into ONE host
181/// sync (2 blocking DtoH/round -> 1). Verify embeds DEVICE tokens (`chain_d`) through the
182/// resident embed table — `embed_gather_u32_t`, bit-identical rows to the host gather by its
183/// own pinned contract. The host therefore dispatches snap + the whole verify while the DRAFT
184/// is still executing, instead of blocking ~1.7 ms on the chain and letting the device drain.
185/// Ladder arm only: the confidence policies size vt from a pre-verify head readback (their
186/// chain readback merges into that same sync instead). Exactness unchanged BY CONSTRUCTION —
187/// same tokens, same kernels, same order; E2E + accept-bank gates arbitrate.
188pub(crate) fn dspark_defer_readback_on() -> bool {
189 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
190 *ON.get_or_init(|| {
191 std::env::var("MEMRA_DSPARK_DEFER_READBACK")
192 .map(|v| v != "0")
193 .unwrap_or(true)
194 })
195}
196/// Engine-bundle slice 1 (DSF-ROUNDCOST-20260820 §1.1, lane/dspark-engine-bundle-20260820),
197/// DEFAULT ON (`MEMRA_STATE_COPY_BATCH=0` reverts): batch the dspark round's GDN state
198/// snapshot and partial-accept restore into single `copy_batch_uniform_f32` launches
199/// instead of ~2 memcpy dispatches (+2 alloc_zeros on the snap side) per linear layer per
200/// round — measured 0.67 ms/round snap + 0.25 ms/round commit of pure dispatch on the q38
201/// route. Launch-structure only: bytes, buffers and stream order are unchanged, so
202/// acceptance and streams stay bit-identical (E2E-gated on the B1 packs).
203pub(crate) fn state_copy_batch_on() -> bool {
204 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
205 *ON.get_or_init(|| {
206 std::env::var("MEMRA_STATE_COPY_BATCH")
207 .map(|v| v != "0")
208 .unwrap_or(true)
209 })
210}
211/// Engine-bundle slice 3 + fa-execupdate slice 4c (DSF-ROUNDCOST-20260820 §5 rank 1),
212/// DEFAULT OFF — `MEMRA_DSPARK_VERIFY_GRAPH=1` opts in: per-(segment, vt) CUDA graphs
213/// for the LINEAR-layer runs, plus the full-verify single graph per (vt, rung) when a
214/// round's rows all ride one seqs rung — see [`DsparkVerifyGraphs`]. Requires the
215/// slice-2 deferred path (device tokens); the eager walk is the byte-identical fallback.
216///
217/// MEASURED disposition (box6 card0, agentic pack, 2026-08-20, both slices): exactness
218/// holds everywhere (ALL EXACT, accept lines byte-match the banks, ckpt-gate oracle
219/// green over the graph + slab-commit paths). Slice-3's AUTO_FREE launch-scan limiter
220/// (25.6 us x 16 launches ≈ 0.41 ms/round) is FIXED — the captured bodies' alloc nodes
221/// are balanced by in-graph frees (census 84/84 per segment, 1776/1776 full) so graphs
222/// instantiate USE_NODE_PRIORITY and the scan is gone. What remains at gate scale:
223/// segment graphs +0.1 tok/s over the batched-rows default (114.4 vs 114.3 x5
224/// interleaved — the linear launch overhead was only ~0.1 ms); the FULL-verify graph is
225/// NET NEGATIVE at gate scale (110.6 vs 114.2: ~14-21 (vt, rung) captures/process at
226/// 2 full-walk executions + ~2.9k-node instantiate each eat far more than the ~0.2-0.3
227/// ms/round of remaining launch overhead). The orchestration ceiling of §1.3 is spent —
228/// the fa/append recovery landed DEFAULT-ON as the batched rows arm
229/// (`dspark_fa_rows_on`), not as a graph. Stays opt-in until a serve-lifetime cell
230/// shows the capture toll amortizing across a long-lived session (graphs persist on
231/// the model), re-gated by the same battery.
232pub(crate) fn dspark_verify_graph_on() -> bool {
233 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
234 *ON.get_or_init(|| std::env::var("MEMRA_DSPARK_VERIFY_GRAPH").as_deref() == Ok("1"))
235}
236/// Engine-bundle slice 4 (fa-execupdate lane, DSF-ROUNDCOST-20260820 §6 close: "the
237/// residual gap lives in the FULL-ATTENTION per-row section"), DEFAULT ON —
238/// `MEMRA_DSPARK_FA_ROWS=0` reverts to the per-row loop: when every row of a verify
239/// round takes the v4-seqs arm on ONE `fa_split_keys` rung (the straddle law, evaluated
240/// at the round's first and last t_kv — both eligibility gates are intervals in t_kv),
241/// the qwen35 t-parallel verify's per-row KV-append + fa-decode loop collapses into the
242/// z-batched serving twins: ONE `append_quantize_kv_q8_0_q5_1_seqs` + ONE
243/// `fa_decode_vec_q_seqs_v4` + ONE combine per full-attention layer, replacing
244/// T x (4 dtod row copies + append + 3 memsets + main + combine) launches. Bytes are
245/// pinned by the batched-tick increment-2 kernel-check (seqs-vs-per-seq-loop bit
246/// identity: per-row T_kv derives in-kernel from pos_seq[z]; splits >= ns_eff write the
247/// empty partial the combine never reads, so the shared n_splits_max stride changes no
248/// bytes) and re-gated e2e by this lane's battery.
249pub(crate) fn dspark_fa_rows_on() -> bool {
250 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
251 *ON.get_or_init(|| {
252 std::env::var("MEMRA_DSPARK_FA_ROWS")
253 .map(|v| v != "0")
254 .unwrap_or(true)
255 })
256}
257
258/// `t_pred0` for the `MEMRA_DEBUG_SPEC` per-round print, sampled-safe.
259///
260/// `generate_spec_inner2` fills its `preds` vector ONLY on the greedy path (`if !sampled`), and
261/// the per-round debug print was the sole consumer in the sampled arm: `t_pred(0)` survives round
262/// 0 (`base == 0` returns `last_pred`) and from round 1 (`base == 1`, a pending bonus) indexes an
263/// EMPTY vector — `index out of bounds: the len is 0 but the index is 0`, in the GPU worker
264/// thread, which then respawns and reloads weights while the request dies. So any sampled spec
265/// request longer than one round used to kill the worker whenever `MEMRA_DEBUG_SPEC` was set:
266/// the flag crashed precisely the regime it exists to investigate.
267///
268/// Fixed at the print site, not inside the closure, so the greedy accept walk keeps its strict
269/// indexing (an out-of-range pred there is a real bug and must still be loud).
270fn debug_t_pred0(sampled: bool, base: usize, last_pred: u32, preds: &[u32]) -> String {
271 if base == 0 {
272 return last_pred.to_string();
273 }
274 match preds.get(base - 1) {
275 Some(p) => p.to_string(),
276 // sampled: the greedy per-column argmax was never run for this round.
277 None => {
278 debug_assert!(
279 sampled,
280 "greedy spec: preds[{}] missing at base {base}",
281 base - 1
282 );
283 "n/a".to_string()
284 }
285 }
286}
287
288/// `MEMRA_SKEY_PROBE=1` — sampled-draft-graph key probe (lane/graph-s-key-exactness-20260819).
289///
290/// Reports, per burst and per round, which draft chain the sampled arm chose and under which
291/// filter regime, plus the ONE observable that separates a legal filtered draft from a stale
292/// pure-temp graph replayed under filters: an accept test whose gathered `q` is exactly 0.
293/// A draft token sampled from the FILTERED softmax can never gather q=0 (it was drawn from the
294/// kept set), so `q=0` in the verify means the draft came from a distribution the verify does
295/// not believe in — and `u * 0 < p` then accepts it unconditionally.
296///
297/// Its own env var, deliberately NOT `MEMRA_DEBUG_SPEC`: that flag panicked the GPU worker on
298/// any sampled spec request past round 0 until this lane fixed it (§2 of the bank note).
299pub(crate) fn skey_probe() -> bool {
300 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
301 *ON.get_or_init(|| std::env::var("MEMRA_SKEY_PROBE").as_deref() == Ok("1"))
302}
303
304/// GRAMMAR HOOK for constrained spec decode (lane/constrained-full, 2026-08-03). The engine
305/// stays llguidance-agnostic: the server adapts its per-session grammar state behind this
306/// trait. CONTRACT (the verify-side truncation rule — token-identical to constrained plain
307/// greedy decode): the exactness walk runs UNMASKED first; the hook then (a) truncates
308/// acceptance at the first grammar-illegal accepted token, and (b) when the truncation fired
309/// or the bonus is illegal, the engine recomputes that slot as the MASKED argmax of the
310/// target's own verify column (an unmasked argmax that is grammar-legal IS the masked argmax
311/// — masking only removes tokens — so the common case pays nothing). `consume` advances the
312/// state with each EMITTED token in order; EOS handling is the implementor's job (skip).
313pub trait SpecConstraint {
314 /// -inf the current state's banned ids on a HOST logits row (prompt-tail / init-feed
315 /// masked argmax).
316 fn mask_logits(&mut self, logits: &mut [f32]) -> Result<(), String>;
317 /// Packed 32-bit bitset words of the CURRENT state's allowed set (device-mask form).
318 fn mask_words(&mut self) -> Result<Vec<u32>, String>;
319 /// Is `tok` consumable in the CURRENT state?
320 fn is_allowed(&mut self, tok: u32) -> Result<bool, String>;
321 /// Advance the state with an emitted token.
322 fn consume(&mut self, tok: u32) -> Result<(), String>;
323
324 // --- DRAFT-SIDE MASKING (lane/draft-mask, 2026-08-04) ---
325 // The drafter proposed grammar-illegal tokens under tight schemas, so verify-side
326 // truncation cut nearly every round (measured acceptance 0.467-0.513 tight vs 0.62-0.82
327 // loose, research/constrained-full-20260803). These three methods let the engine mask the
328 // DRAFT model's own sampling with the grammar's legal set, so proposals are legal by
329 // construction. The state they walk is a SPECULATIVE CLONE of the session matcher — the
330 // real state is advanced only by `consume` (emitted tokens), so verify-side truncation
331 // stays the correctness backstop and the emitted stream is unchanged by construction
332 // (an accepted draft is the target's unmasked argmax AND grammar-legal, hence the masked
333 // argmax; a cut slot is recomputed as the masked argmax either way).
334 // Default impls = feature OFF (pre-lane behaviour: unmasked drafts).
335
336 /// Is draft-side masking available on this hook? Probed ONCE per burst, before the draft
337 /// graph is captured (the mask is an in-graph node — its presence is a capture-time shape).
338 fn draft_mask_enabled(&self) -> bool {
339 false
340 }
341 /// Start a draft chain: clone the CURRENT (committed) grammar state into the speculative
342 /// slot. Called once per spec round, before the first draft position.
343 fn draft_begin(&mut self) -> Result<(), String> {
344 Ok(())
345 }
346 /// Packed 32-bit bitset words of the SPECULATIVE state's allowed set (target-vocab ids),
347 /// for the draft position about to be sampled. `None` = draft masking off (no-op).
348 fn draft_mask_words(&mut self) -> Result<Option<Vec<u32>>, String> {
349 Ok(None)
350 }
351 /// Advance the SPECULATIVE state with a PROPOSED draft token. `false` = the chain cannot
352 /// continue (EOS proposed, or an unmasked position proposed something illegal) — the
353 /// engine stops drafting; the token already pushed still goes through verify.
354 fn draft_advance(&mut self, _tok: u32) -> Result<bool, String> {
355 Ok(false)
356 }
357}
358
359/// DRAFT-MASK UPLOAD (lane/draft-mask): pull the speculative state's allowed set (TARGET-id
360/// space) from the hook, project it into the DRAFT head's vocab space, and upload it into the
361/// stable device buffer the draft chain reads. Returns false when the chain must stop drafting:
362/// the hook handed out no mask, or NO draft-vocab row is grammar-legal at this position (a
363/// trimmed FR-Spec head genuinely cannot propose a legal token there — masking it would leave
364/// a fully-banned row whose argmax is meaningless, so the round drafts fewer tokens and the
365/// verify emits the masked argmax as usual).
366fn upload_draft_mask(
367 e: &Engine,
368 c: &mut dyn SpecConstraint,
369 dst: &mut CudaSlice<u32>,
370 d2t: Option<&Vec<u32>>,
371 d_vocab: usize,
372 words: usize,
373) -> Result<bool, Box<dyn std::error::Error>> {
374 let Some(tw) = c
375 .draft_mask_words()
376 .map_err(|e2| format!("constraint: {e2}"))?
377 else {
378 return Ok(false);
379 };
380 let bit = |t: usize| -> bool {
381 let w = t >> 5;
382 w < tw.len() && (tw[w] >> (t & 31)) & 1 == 1
383 };
384 let mut buf = vec![0u32; words];
385 match d2t {
386 // TRIMMED draft head: row i proposes target id d2t[i] — permute the mask accordingly.
387 Some(map) => {
388 for (i, &t) in map.iter().enumerate().take(d_vocab) {
389 if bit(t as usize) {
390 buf[i >> 5] |= 1u32 << (i & 31);
391 }
392 }
393 }
394 // UNTRIMMED: draft ids ARE target ids; the packed words transfer verbatim (a short
395 // mask leaves the padded tail zeroed == banned, same rule as constrained::apply_mask).
396 None => {
397 let n = tw.len().min(words);
398 buf[..n].copy_from_slice(&tw[..n]);
399 }
400 }
401 if buf.iter().all(|w| *w == 0) {
402 return Ok(false);
403 }
404 e.htod_u32_into(dst, &buf)?;
405 Ok(true)
406}
407
408/// Keep the full token-embedding table in host memory and upload only the rows needed by each
409/// MTP/verify step. This is an exact memory-capacity seam for very large BF16 vocab tables: host
410/// gather expands the same source bits to f32, and only O(T*n_embd) bytes cross PCIe per step.
411/// CUDA-graph/round-stream draft paths require device token ids and therefore stay disabled.
412pub(crate) fn spec_host_embd() -> bool {
413 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
414 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_HOST_EMBD").as_deref() == Ok("1"))
415}
416
417/// VERIFY-TIER TRUNK LAUNCH-FUSION (default ON since 2026-07-09; MEMRA_SPEC_FUSED_T=0 reverts — lane/close35b): extend
418/// the t=1 fused2/fused3 Q8_0 trunk launches to the batched verify tier (t=2-4, the K=1..3
419/// verify shapes). At t>1 the trunk pairs/triples (35B wqkv+wqkv_gate, wq/wk/wv,
420/// gate_shexp+up_shexp) each run a separate `matmul_decode_exact` — one q8_1 re-quantize of the
421/// SAME activation plus one _b2/_b4 launch per tensor. The fused twins share ONE quantize and
422/// ONE launch per group; per (tensor,token,row) the kernel body is q8_0_mmvq_batched verbatim
423/// with the identical row mapping -> BIT-IDENTICAL by construction (kernel-check pins it,
424/// run-spec K=1..8 + acceptance identity arbitrate e2e).
425pub(crate) fn spec_fused_t() -> bool {
426 static F: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
427 // DEFAULT ON since 2026-07-09 (MEMRA_SPEC_FUSED_T=0 reverts): verify t=2-4 trunk launch-fusion
428 // (fused2/fused3 Q8_0 batched twins, bit-identical by construction — m=1 block-offset split on
429 // the batched body). m=2 marginal token 2117->1762us; 35B daily: p3 +3.7% (crosses llama), p2 +5%.
430 *F.get_or_init(|| {
431 std::env::var("MEMRA_SPEC_FUSED_T")
432 .map(|v| v != "0")
433 .unwrap_or(true)
434 })
435}
436
437/// zeros/uninit switch for verify-path buffers that are FULLY OVERWRITTEN before any read.
438/// Only call this on such buffers — the lean contract is "identical bytes by construction".
439fn vbuf(e: &Engine, n: usize) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
440 if spec_lean() { e.uninit(n) } else { e.zeros(n) }
441}
442
443/// Scratch KV for the MTP block (one full-attn layer).
444///
445/// PERSISTENT MODE (default, 2026-07-03 — the acceptance lever): sized cap = max_ctx and kept in
446/// sync with the COMMITTED sequence — slot p holds the MTP block's K/V for committed token p
447/// (roped p+1, the chain's rope convention), so the draft chain's self-attention sees the FULL
448/// committed history instead of only the current round's 1..K+1 chain tokens (the reference
449/// engine's "mtp_update" design). Entries come from two sources:
450/// - chain appends: accepted positions KEEP their chain-computed entries (embedding exact,
451/// hidden chain-approximate — the reference engine accepts the same);
452/// - `mtp_kv_fill` batches: prompt positions + the last-draft position on full accept, computed
453/// from EXACT trunk hiddens (K/V-only MTP-block pass, no attention/FFN/lm_head).
454/// Rejected drafts / p-min extras / pseudo-seed appends are all discarded by the round-start
455/// `set_len` truncation (the KvLayer len mechanism — §C rollback for the draft side).
456/// Multi-turn spec-decode session (2026-07-05): trunk Cache + persistent MTP draft scratch +
457/// the committed token list, alive across generate_spec_session calls. Turn N+1 primes ONLY its
458/// suffix (chunked continuation prime over the quantized past) and mtp_kv_fill's its suffix rows,
459/// then the round loop runs unchanged. `last_h` carries the pre-output_norm hidden of the last
460/// committed row across turns (the predecessor-pairing seed + fill anchor).
461/// Per-request sampling config for the sampled-spec serve path.
462#[derive(Clone, Copy, Debug)]
463pub struct SpecSampling {
464 pub temp: f32,
465 pub seed: u64,
466 pub top_k: i32, // 0 = off
467 pub top_p: f32, // 1.0 = off
468 pub min_p: f32, // 0.0 = off
469 pub penalty_last_n: usize, // 0 = penalties off
470 pub penalty_repeat: f32,
471 pub penalty_freq: f32,
472 pub penalty_present: f32,
473}
474
475/// Host Philox4x32-10 uniform in (0,1) — mirrors spec_sample.cu's `philox4`/`u01` with the
476/// ctr_lo tag 0xFFFF_FFFE, so the host accept-test stream never collides with any device
477/// sampling event (device Gumbel uses (i>>2, stream_pos); device residual uses 0xFFFF_FFFD).
478/// One value per (seed, ctr) EVENT; callers own the counter discipline. Extracted verbatim
479/// from generate_spec_inner2's closure for the dspark sampled-admission walk (the two paths
480/// MUST consume the identical stream construction — two ad-hoc Philox copies drifting apart
481/// is a distributional bug, not a style problem).
482pub(crate) fn host_u01(seed: u64, ctr: u32) -> f32 {
483 let (m0, m1) = (0xD2511F53u32, 0xCD9E8D57u32);
484 let (mut c0, mut c1, mut c2, mut c3) = (0xFFFF_FFFEu32, ctr, 0u32, 0u32);
485 let (mut k0, mut k1) = ((seed & 0xFFFF_FFFF) as u32, (seed >> 32) as u32);
486 for _ in 0..10 {
487 let (h0, l0) = (((m0 as u64 * c0 as u64) >> 32) as u32, m0.wrapping_mul(c0));
488 let (h1, l1) = (((m1 as u64 * c2 as u64) >> 32) as u32, m1.wrapping_mul(c2));
489 let (n0, n1, n2, n3) = (h1 ^ c1 ^ k0, l1, h0 ^ c3 ^ k1, l0);
490 c0 = n0;
491 c1 = n1;
492 c2 = n2;
493 c3 = n3;
494 k0 = k0.wrapping_add(0x9E3779B9);
495 k1 = k1.wrapping_add(0xBB67AE85);
496 }
497 (c0 as f32 + 1.0) * (1.0 / 4294967296.0)
498}
499
500/// Tracked draft positions for [`SpecTelemetry`] (serve K defaults to 3; the run-spec gate
501/// sweeps K=1..8, and MEMRA_SPEC_CAPMAX defaults to 7 — 8 covers every tuned config).
502pub const SPEC_TELEM_POS: usize = 8;
503
504/// Always-on per-draft-position acceptance telemetry (lane/accept-telemetry, 2026-08-05 —
505/// the llama.cpp #26389 / vLLM spec-decode counter schema, upstream-sweeps 2026-08-05).
506/// Lives on the [`SpecSession`] and accumulates across bursts; the serve worker diffs a
507/// stashed copy per burst for its per-model /metrics aggregation and per-request usage.
508/// Same normalization as the `[spec-stats]` line: p-min-discarded chain tokens are counted
509/// in NEITHER drafted nor accepted.
510#[derive(Clone, Copy, Default, Debug)]
511pub struct SpecTelemetry {
512 /// verify rounds completed (a round-stream burst counts each of its M rounds).
513 pub rounds: u64,
514 /// tokens drafted / accepted across all rounds.
515 pub drafted: u64,
516 pub accepted: u64,
517 /// how often draft position j (0-based within a round's chain) was offered / accepted.
518 /// Positions >= SPEC_TELEM_POS are untracked (totals still count them). The opt-in
519 /// round-stream arm (MEMRA_SPEC_STREAM=1) reads back only totals, so under it these
520 /// arrays cover the standard-path rounds only and their sums may undercount the totals.
521 pub pos_drafted: [u64; SPEC_TELEM_POS],
522 pub pos_accepted: [u64; SPEC_TELEM_POS],
523}
524
525impl SpecTelemetry {
526 /// Fieldwise `self - prev` — the worker's per-burst delta off a copy stashed before the
527 /// burst call. Saturating: a caller diffing against the wrong snapshot gets zeros, not
528 /// a wrapped counter.
529 pub fn delta_since(&self, prev: &SpecTelemetry) -> SpecTelemetry {
530 let mut d = SpecTelemetry {
531 rounds: self.rounds.saturating_sub(prev.rounds),
532 drafted: self.drafted.saturating_sub(prev.drafted),
533 accepted: self.accepted.saturating_sub(prev.accepted),
534 ..Default::default()
535 };
536 for j in 0..SPEC_TELEM_POS {
537 d.pos_drafted[j] = self.pos_drafted[j].saturating_sub(prev.pos_drafted[j]);
538 d.pos_accepted[j] = self.pos_accepted[j].saturating_sub(prev.pos_accepted[j]);
539 }
540 d
541 }
542 /// Fieldwise `self += d` — the worker's per-model aggregation.
543 pub fn merge(&mut self, d: &SpecTelemetry) {
544 self.rounds += d.rounds;
545 self.drafted += d.drafted;
546 self.accepted += d.accepted;
547 for j in 0..SPEC_TELEM_POS {
548 self.pos_drafted[j] += d.pos_drafted[j];
549 self.pos_accepted[j] += d.pos_accepted[j];
550 }
551 }
552
553 /// Mean accepted draft-prefix length per verify round (tau).
554 pub fn tau(&self) -> f64 {
555 if self.rounds > 0 {
556 self.accepted as f64 / self.rounds as f64
557 } else {
558 0.0
559 }
560 }
561}
562
563/// Session-lifetime atomic acceptance counters. The verifier records only after the greedy or
564/// rejection-sampling walk has resolved on the host, so these relaxed increments add no GPU
565/// launch, synchronization, allocation, or ordering dependency to the numeric path.
566struct SpecTelemetryCounters {
567 rounds: AtomicU64,
568 drafted: AtomicU64,
569 accepted: AtomicU64,
570 pos_drafted: [AtomicU64; SPEC_TELEM_POS],
571 pos_accepted: [AtomicU64; SPEC_TELEM_POS],
572}
573
574impl Default for SpecTelemetryCounters {
575 fn default() -> Self {
576 Self {
577 rounds: AtomicU64::new(0),
578 drafted: AtomicU64::new(0),
579 accepted: AtomicU64::new(0),
580 pos_drafted: std::array::from_fn(|_| AtomicU64::new(0)),
581 pos_accepted: std::array::from_fn(|_| AtomicU64::new(0)),
582 }
583 }
584}
585
586impl SpecTelemetryCounters {
587 fn record_round(&self, drafted: usize, accepted: usize) {
588 debug_assert!(accepted <= drafted);
589 self.rounds.fetch_add(1, Ordering::Relaxed);
590 self.drafted.fetch_add(drafted as u64, Ordering::Relaxed);
591 self.accepted.fetch_add(accepted as u64, Ordering::Relaxed);
592 for counter in self.pos_drafted.iter().take(drafted) {
593 counter.fetch_add(1, Ordering::Relaxed);
594 }
595 for counter in self.pos_accepted.iter().take(accepted) {
596 counter.fetch_add(1, Ordering::Relaxed);
597 }
598 }
599
600 /// Round-stream keeps each round's accept length on device; retain exact scalar totals while
601 /// leaving the per-position arrays untouched, matching the pre-existing telemetry contract.
602 fn record_totals(&self, rounds: usize, drafted: usize, accepted: usize) {
603 self.rounds.fetch_add(rounds as u64, Ordering::Relaxed);
604 self.drafted.fetch_add(drafted as u64, Ordering::Relaxed);
605 self.accepted.fetch_add(accepted as u64, Ordering::Relaxed);
606 }
607
608 fn snapshot(&self) -> SpecTelemetry {
609 SpecTelemetry {
610 rounds: self.rounds.load(Ordering::Relaxed),
611 drafted: self.drafted.load(Ordering::Relaxed),
612 accepted: self.accepted.load(Ordering::Relaxed),
613 pos_drafted: std::array::from_fn(|j| self.pos_drafted[j].load(Ordering::Relaxed)),
614 pos_accepted: std::array::from_fn(|j| self.pos_accepted[j].load(Ordering::Relaxed)),
615 }
616 }
617}
618
619pub struct SpecSession {
620 pub(crate) cache: Cache,
621 pub(crate) scratch: MtpScratch,
622 /// Every token whose state the caches hold, in order (prompt turns + generated), INCLUDING
623 /// overshoot: spec commits accepted drafts past max_new; those rows are in the caches, so the
624 /// session must count them. Callers render output from this, not from their own echo.
625 pub committed: Vec<u32>,
626 /// Pre-output_norm hidden of the LAST committed row (device). None before the first turn.
627 pub(crate) last_h: Option<CudaSlice<f32>>,
628 /// Greedy argmax predicting the token AFTER committed.last() (from the last turn's final
629 /// logits). Fuels empty-suffix continuation bursts (serve): the next turn emits this token
630 /// first, feeds it, and the round loop resumes without any prime. None before the first turn.
631 pub next_pred: Option<u32>,
632 /// SAMPLED-SPEC stream continuity across bursts: Philox event counters persist here so a
633 /// session's randomness never repeats between generate_spec_session calls. (0,0) at admit.
634 pub sctr: u32,
635 pub uctr: u32,
636 /// PERSISTENT DRAFT-GRAPH CONTEXT (2026-08-01, the serve-burst fixed-cost fix): the captured
637 /// draft graph(s) + every device I/O buffer they bake, carried ACROSS generate_spec_session
638 /// calls. Before this, every serve burst re-captured the draft graph (2 warmup forwards +
639 /// instantiate) — measured ~16ms/burst on H100 q27 (MEMRA_SPEC_BURST sweep,
640 /// research/spec-serving-20260801). None before the first turn; error paths drop it
641 /// (next burst recaptures — serve retires errored sessions anyway).
642 pub(crate) draft_ctx: Option<DraftGraphCtx>,
643 /// PENDING-CARRY across bursts (2026-08-01, the serve burst-boundary fix): the bonus token
644 /// emitted by the last round but NOT committed to the caches. The old tail committed it with
645 /// a solo T=1 trunk pass (+ draft fill), and the next burst's setup fed the stashed next_pred
646 /// with ANOTHER solo pass — 2x ~11.5ms/burst measured on H100 q27 ([spec-setup] trace).
647 /// Carrying it lets the next empty-suffix greedy burst consume it as round-0 verify col 0,
648 /// exactly like a mid-burst full-accept boundary (no solo passes). INVARIANT: when set,
649 /// `committed` (== cache rows) EXCLUDES this token although it was already emitted in the
650 /// last burst's output, and `last_h` holds the hidden of the last COMMITTED row (its
651 /// predecessor — the chain-seed/fill anchor). `next_pred` is None (unknown without the
652 /// commit pass). Non-empty-suffix or sampled turns must flush first (spec_flush_pending);
653 /// generate_spec_session_sampled does this at entry, and serve parks only flushed sessions.
654 pub pending_tok: Option<u32>,
655 /// SESSION-AFFINITY TURN CHECKPOINT (lane/session-affinity, 2026-08-05): the state at this
656 /// turn's PROMPT-END boundary, retained so a later turn can REWIND here. See
657 /// [`SpecCheckpoint`]. Refreshed by every non-empty prime; None until the first one, and on
658 /// a rig too tight to hold it (a failed capture is silent — resume just isn't available).
659 pub(crate) turn_ckpt: Option<SpecCheckpoint>,
660 /// Session-lifetime acceptance telemetry. Relaxed atomics update at the host-side round
661 /// accounting the loop already does — no syncs, no allocation. NOTE a
662 /// pool-resumed session carries the PREVIOUS requests' counts; per-request consumers
663 /// diff with [`SpecTelemetry::delta_since`] around each burst.
664 telem: SpecTelemetryCounters,
665 /// PREFIX-CACHE publication request (lane/spec-prefix-cache): worker sets this to the
666 /// miss-LCP boundary before a cold burst; the prime captures at exactly that split (it must
667 /// coincide with the burst's `prime_split` or no capture happens). One-shot: consumed by the
668 /// prime, result lands in `boundary_captures`.
669 pub capture_at: Option<usize>,
670 /// The captures the last prime produced (see [`SpecBoundaryCapture`]). Worker drains them
671 /// post-burst to assemble prefix entries. A failed capture is silent, like `turn_ckpt` —
672 /// publication just isn't available for that request. Plural since
673 /// lane/frspec-multiturn-cache (2026-08-21): a cold burst can capture BOTH the miss-LCP
674 /// split (the shared-prefix class) and the stable pre-generation boundary (the
675 /// next-turn re-render class) — one entry per stop, exactly the boundary set the plain
676 /// prefill tick publishes/checkpoints.
677 pub boundary_captures: Vec<SpecBoundaryCapture>,
678 /// STABLE-BOUNDARY TURN CHECKPOINT REQUEST (lane/frspec-multiturn-cache, 2026-08-21): the
679 /// ABSOLUTE committed-length position the next non-empty prime should capture `turn_ckpt`
680 /// at, instead of prompt-end. The worker sets it to the STABLE PRE-GENERATION boundary
681 /// (`plain_checkpoint_boundary` — before the live generation header the client rewrites),
682 /// porting the 2026-08-09 plain-tier fix: a prompt-end spec checkpoint includes the
683 /// template's live assistant-generation header (`<|im_start|>assistant\n<think>\n`), which
684 /// the NEXT turn's re-render replaces, so `affinity_match` diverged a couple tokens below
685 /// the checkpoint and the spec pool declined 100% of multi-turn agent traffic (measured:
686 /// `spec-affinity: declined (history diverged at 6811 of checkpoint 6813)`,
687 /// research/multiturn-cache-20260821 B4). One-shot, `capture_at` convention; None = legacy
688 /// prompt-end capture.
689 pub ckpt_at: Option<usize>,
690}
691impl SpecSession {
692 /// Context capacity of the session's caches (the server's ContextFull guard).
693 pub fn cache_max_ctx(&self) -> usize {
694 self.cache.max_ctx
695 }
696 /// Read access to the live trunk cache (lane/spec-prefix-cache): the worker slices
697 /// full-attn KV rows `[0..capture.pos)` out of it when publishing a boundary capture —
698 /// those rows are append-only for the session's lifetime (rollbacks never truncate below
699 /// the prime boundary), so no copy was taken at prime time.
700 pub fn cache_ref(&self) -> &Cache {
701 &self.cache
702 }
703 /// Read access to the persistent draft-scratch plane (lane/spec-on-cache-hit): the
704 /// worker slices rows `[0..capture.pos)` when publishing a boundary capture, exactly
705 /// like the trunk KV — draft rows below the prompt end are append-only for the
706 /// session's lifetime (the prime fill wrote them once; rollbacks reset `len_d` to the
707 /// committed length, never below the prime boundary, and the true-hidden refresh
708 /// rewrites generated positions only). Returns `(k, v, k_tok_bytes, v_tok_bytes)`.
709 /// None when the scratch is ring-backed (Step35 SWA — physical rows are not
710 /// prefix-addressable; the prefix cache already refuses that class end to end).
711 pub fn draft_plane_ref(&self) -> Option<(&CudaSlice<u8>, &CudaSlice<u8>, usize, usize)> {
712 if self.scratch.kv.ring.is_some() {
713 return None;
714 }
715 Some((
716 &self.scratch.kv.k,
717 &self.scratch.kv.v,
718 self.scratch.kv.k_tok_bytes,
719 self.scratch.kv.v_tok_bytes,
720 ))
721 }
722 /// Snapshot the session's process-local acceptance counters for per-burst diffing.
723 pub fn telemetry(&self) -> SpecTelemetry {
724 self.telem.snapshot()
725 }
726 /// Committed position this session can REWIND to (its retained prompt-end boundary), if any.
727 /// A request whose prompt matches `committed[..pos]` exactly can resume from here — see
728 /// `spec_rewind_to_checkpoint`.
729 pub fn rewind_pos(&self) -> Option<usize> {
730 self.turn_ckpt.as_ref().map(|c| c.pos)
731 }
732 /// Whether every ring-backed trunk/draft row needed by the retained checkpoint is resident.
733 pub fn rewind_is_resident(&self) -> bool {
734 self.turn_ckpt.as_ref().is_some_and(|ckpt| {
735 self.cache.can_rollback(&ckpt.snap, 0) && self.scratch.can_rewind_to(ckpt.pos)
736 })
737 }
738 /// Is this session in the DEMOTION-READY shape (see [`SpecSession::into_demoted`])?
739 /// `false` means a carried pending must be flushed first (`spec_flush_pending`), or the
740 /// session has never run a turn and has no prediction to hand over.
741 pub fn demote_ready(&self) -> bool {
742 self.pending_tok.is_none() && self.next_pred.is_some()
743 }
744 /// Does this session hold a carried pending bonus (flush required before a handoff/park)?
745 pub fn has_pending(&self) -> bool {
746 self.pending_tok.is_some()
747 }
748 /// Committed row count == cache rows (the session invariant), for the caller's own
749 /// `fed`-length cross-check at a handoff boundary.
750 pub fn committed_len(&self) -> usize {
751 self.committed.len()
752 }
753 /// DEMOTION HANDOFF (lane/spec-gate, 2026-08-07): consume this session and hand its trunk
754 /// cache + next-token prediction to the plain batched-decode path.
755 ///
756 /// WHY THIS IS EXACT (greedy). The invariant at a burst boundary is `cache.pos ==
757 /// committed.len()`: every committed row has trunk KV + recurrent state, exactly as a plain
758 /// tokenwise prime of the same `committed` sequence would have left it (that is the
759 /// session-tail contract, and the same property `spec_rewind_to_checkpoint` and the reuse
760 /// pool already rely on). `next_pred` is the argmax of the verify's logits for the LAST
761 /// committed row — and verify-column logits are bit-identical to plain decode's logits at
762 /// that position, because `matmul_decode_exact` bit-identity IS the basis of the greedy
763 /// accept walk. So handing (cache, next_pred) to the batched path continues the stream from
764 /// a state indistinguishable from one the batched path produced itself: the batched tick
765 /// emits `next_pred`, feeds it into this same cache, and decodes on.
766 ///
767 /// `None` when the session is not in the handoff shape — a carried pending (its bonus row is
768 /// NOT in the cache, so `spec_flush_pending` must commit it first) or no `next_pred` yet
769 /// (never bursted). Callers must not force it: a half-committed cache handed to the batched
770 /// path would silently skip a token.
771 ///
772 /// The MTP draft scratch, the persistent draft-graph context and the turn checkpoint are
773 /// DROPPED here (freeing their VRAM): the batched path never drafts, and this handoff is
774 /// one-way by design — there is no cheap symmetric re-promotion (rebuilding the draft KV
775 /// would mean an `mtp_kv_fill` over the whole committed history).
776 pub fn into_demoted(self) -> Option<(Cache, u32)> {
777 if self.pending_tok.is_some() {
778 return None;
779 }
780 let np = self.next_pred?;
781 debug_assert_eq!(
782 self.cache.pos,
783 self.committed.len(),
784 "demotion handoff: cache rows != committed tokens"
785 );
786 Some((self.cache, np))
787 }
788 /// Pool-resume hook (audit Q2): clear the parked draft-graph failure memoization so a
789 /// NEW request resuming this session gets one fresh capture chance — a transient-pressure
790 /// capture failure must not persist for the pool's whole lifetime (the TRT #16072 class).
791 /// Logs once iff a flag was actually set; a no-fallback resume is silent and free.
792 pub fn reset_graph_fallback_on_resume(&mut self) {
793 if let Some(line) = self
794 .draft_ctx
795 .as_mut()
796 .and_then(|c| c.failed.reset_on_resume())
797 {
798 eprintln!("{line}");
799 }
800 }
801}
802
803/// A session's PROMPT-END boundary state, the rewind target for session-affinity resume.
804///
805/// WHY THIS BOUNDARY, AND WHY IT IS THE ONLY ONE WORTH KEEPING. The rewrite class this lane
806/// exists for (a client that strips `<think>` blocks out of prior assistant turns) mutates the
807/// text the session GENERATED, never the prompt it was given. So turn N's prompt agrees with
808/// turn N-1's committed tokens up to almost exactly where turn N-1's generation began — the
809/// prompt-end boundary. Keeping a checkpoint there means the next turn re-primes only its own
810/// delta (the rewritten answer + the new user turn) instead of the whole conversation.
811///
812/// WHAT IT MUST HOLD. Full-attn KV is append-only and position-addressed, so rewinding it is a
813/// `len` truncation (no data). Linear-attn (GDN) conv/ssm state is mutated IN PLACE with no
814/// position index, so it must be a real device COPY — that copy is the entire reason a spec
815/// session could not previously rewind. The MTP draft scratch needs no copy either: its rows
816/// below the boundary were written by this turn's fill and are never revisited (the per-round
817/// true-hidden refresh only rewrites the CURRENT burst's committed positions), so rewinding it
818/// is also just a `len` reset. `last_h` is the hidden of the last row below the boundary — the
819/// predecessor-pairing anchor the next prime's fill reads for its first row.
820///
821/// COST: one `Cache::snapshot` per TURN, on a code path that already takes one per ROUND.
822pub(crate) struct SpecCheckpoint {
823 snap: crate::cache::CacheSnapshot,
824 /// Committed length at the boundary (== cache.pos there, the session invariant).
825 pos: usize,
826 /// Pre-output_norm hidden of row `pos - 1`.
827 last_h: CudaSlice<f32>,
828}
829
830/// PREFIX-CACHE BOUNDARY CAPTURE (lane/spec-prefix-cache, 2026-08-14): the state a spec session
831/// records at its cold-prime split so the WORKER can publish a cross-request prefix entry —
832/// the commit-gated-publication port (research/cache-spec-design-20260814/PORT-PLAN.md item 1).
833/// Only the pieces that are DESTROYED by continuing the prime need copies here: the in-place
834/// GDN conv/ssm states (via `Cache::snapshot`, same mechanism as [`SpecCheckpoint`]) and the
835/// boundary logits. Full-attn KV rows `[0..pos)` and draft-scratch rows `[0..pos)` are
836/// append-only for the session's lifetime (rollbacks never truncate below the prime boundary),
837/// so the worker slices those from the live caches post-burst instead of copying at prime time.
838pub struct SpecBoundaryCapture {
839 pub snap: crate::cache::CacheSnapshot,
840 /// Token boundary (== cache.pos at capture; == the worker's miss-LCP split).
841 pub pos: usize,
842 /// Full-vocab logits after the prefix prime — the entry's boundary logits.
843 pub logits: Vec<f32>,
844 /// Pre-output_norm trunk hidden of row `pos - 1` (lane/spec-on-cache-hit): the
845 /// predecessor-pairing anchor a RESTORED spec session's first suffix-fill row reads
846 /// (the `SpecSession::last_h` convention). Empty = unavailable (capture stays valid;
847 /// the fill's zeros row-0 fallback covers it at a bounded acceptance cost).
848 pub last_h: Vec<f32>,
849}
850
851/// D2H one hidden row out of a `[T, n_embd]` prime hidden stack — the boundary anchor a
852/// spec boundary capture carries for later restored-session fills. Failure is silent
853/// (`turn_ckpt` convention): the capture publishes without an anchor.
854fn capture_boundary_hidden(
855 e: &Engine,
856 h_rows: &CudaSlice<f32>,
857 pos: usize,
858 n_embd: usize,
859) -> Vec<f32> {
860 if pos == 0 || h_rows.len() < pos * n_embd {
861 return Vec::new();
862 }
863 let Ok(mut row) = e.uninit(n_embd) else {
864 return Vec::new();
865 };
866 if e.copy_view_into(
867 &mut row,
868 0,
869 &h_rows.slice((pos - 1) * n_embd..pos * n_embd),
870 n_embd,
871 )
872 .is_err()
873 {
874 return Vec::new();
875 }
876 e.dtoh(&row).unwrap_or_default()
877}
878
879/// ROLLBACK DOOR for sampled BOUNDARY tokens (lane/sampled-spec-quality, 2026-08-19).
880/// Default ON: the token a burst emits at its own boundary is drawn from the request's
881/// sampler. `MEMRA_SPEC_SAMPLED_BOUNDARY=0` restores the pre-lane posture (an ARGMAX at
882/// every boundary) without touching greedy, which is byte-unaffected either way.
883pub fn spec_sampled_boundary_on() -> bool {
884 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
885 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_SAMPLED_BOUNDARY").as_deref() != Ok("0"))
886}
887
888/// ROLLBACK DOOR for SESSION-SPANNING penalty history (lane/sampled-spec-quality).
889/// Default ON: `pen_hist` is seeded from the session's committed tail, so repetition /
890/// frequency / presence penalties see the whole stream. `MEMRA_SPEC_PEN_SESSION=0`
891/// restores the pre-lane posture (each burst restarts the window from its own prompt
892/// slice, i.e. from NOTHING on a continuation burst) — and with the door shut the worker
893/// must keep refusing penalized sampled prefix-cache restores, because the restored
894/// session's continuation burst is handed no prompt slice at all.
895pub fn spec_pen_session_on() -> bool {
896 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
897 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_PEN_SESSION").as_deref() != Ok("0"))
898}
899
900/// ROLLBACK DOOR for extended-entry publication from a RESTORED session
901/// (lane/sampled-spec-quality, Item 3). Default ON: a converted prefix-cache hit that fed a
902/// suffix captures its own prompt-end boundary so the NEXT turn can hit a longer prefix.
903/// `MEMRA_SPEC_RESTORE_REPUBLISH=0` restores the pre-lane posture (a namespace learns exactly
904/// one boundary and never advances it). Whole-entry semantics only — the boundary is the
905/// restored session's own prompt end, so `entry_pos != fed_len` still refuses on the way in.
906pub fn spec_restore_republish_on() -> bool {
907 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
908 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_RESTORE_REPUBLISH").as_deref() != Ok("0"))
909}
910
911/// Diagnostics: name every boundary token on stderr (`MEMRA_SPEC_BOUNDARY_TRACE=1`), with
912/// the argmax the pre-lane code would have emitted from the same row. This is how the
913/// lane MEASURES the boundary rate and the deviation rate instead of estimating them.
914fn spec_boundary_trace() -> bool {
915 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
916 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_BOUNDARY_TRACE").as_deref() == Ok("1"))
917}
918
919/// llama-parity floor for the penalty window when the request does not ask for a bigger
920/// one (`repeat_last_n` default). The serve API arms `penalty_last_n = usize::MAX` for any
921/// non-identity penalty, so this floor only matters to explicit small windows and to the
922/// CLI env path.
923const PEN_WINDOW_FLOOR: usize = 64;
924
925/// CEILING on the penalty window, and it is a COST bound, not a semantic preference.
926/// `penalize_logits_f32` (cu/spec_sample.cu) dedups on device by having thread `i` scan
927/// `hist[0..i]`, so a pass is O(n_hist²) and it runs ~3x per verify round (the q rows, the
928/// p column, the bonus column). The serve API arms `penalty_last_n = usize::MAX` for ANY
929/// non-identity penalty — "the whole context", llama's `repeat_last_n = -1` — so an
930/// uncapped session window would put a 128k-token history through that kernel: ~1.7e10
931/// comparisons per pass, tens of ms per round, i.e. penalties would silently destroy decode
932/// throughput on exactly the long-context requests that most want them. 8192 keeps a pass
933/// at ~7e7 comparisons (tens of microseconds) while still being **128x wider than the
934/// pre-lane effective window** (64 prompt-tail tokens + whatever the current burst had
935/// generated). A request that genuinely needs a window beyond this wants host-side dedup +
936/// counts through a new kernel signature — a follow-up lane, named here rather than hidden.
937const PEN_WINDOW_MAX: usize = 8192;
938
939/// Seed a penalty window over the SESSION, not the burst (lane/sampled-spec-quality,
940/// Item 2). The window is the last `max(penalty_last_n, 64)` tokens of
941/// `session_committed ++ burst_prompt` — for a cold turn-1 burst (`session_committed`
942/// empty, default `penalty_last_n`) that is byte-identically the pre-lane
943/// `prompt.iter().rev().take(64).rev()`; for a continuation burst it is the stream the
944/// client actually asked us to penalize, where the pre-lane code had NOTHING.
945fn pen_window_seed(
946 session_committed: &[u32],
947 burst_prompt: &[u32],
948 penalty_last_n: usize,
949) -> Vec<u32> {
950 let win = penalty_last_n.clamp(PEN_WINDOW_FLOOR, PEN_WINDOW_MAX);
951 let take_prompt = burst_prompt.len().min(win);
952 let take_sess = (win - take_prompt).min(session_committed.len());
953 let mut hist = Vec::with_capacity(take_sess + take_prompt);
954 hist.extend_from_slice(&session_committed[session_committed.len() - take_sess..]);
955 hist.extend_from_slice(&burst_prompt[burst_prompt.len() - take_prompt..]);
956 hist
957}
958
959/// Draw a BOUNDARY token from the target distribution the request asked for
960/// (lane/sampled-spec-quality, Item 1) — the fix for "sampled spec emits an ARGMAX token at
961/// every burst boundary".
962///
963/// WHY THIS EXISTS. A spec burst's first emitted token is not produced by the accept walk:
964/// it comes off a logits row that already exists (the prime's last row on a cold burst; the
965/// row after the last committed token on a continuation burst; the prefix-cache entry's
966/// boundary row on a restored one). Pre-lane that token was `argmax` in BOTH sampling
967/// regimes, so a sampled stream took a greedy token once per burst — measured, not
968/// estimated, in research/spec-cache-20260818/SAMPLED-QUALITY.md. At temperature > 0 the
969/// customer asked for a sampled token, so this draws one.
970///
971/// THE PROGRAM IS THE FULL-ACCEPT BONUS'S PROGRAM, deliberately: penalize the row (over the
972/// session's window), take this row's OWN filter stats (the sampfix-20260805 law — stats
973/// from a neighbour row mis-scale every `e0` and can wipe the row to token 0), gumbel-perturb
974/// with the session's Philox stream at `*sctr`, argmax the perturbed row. Reusing the bonus's
975/// composition means `sample_check`'s distributional oracle covers this draw too, and the
976/// boundary token is drawn from the same filtered/penalized `p` the accept walk targets.
977///
978/// THE STREAM IS THE SESSION'S, NOT A FRESH ONE. `sctr` is the caller's live counter and is
979/// advanced by exactly one, so a boundary draw consumes the next value in the same Philox
980/// stream the accept walk uses — never a second, independently seeded stream (which would be
981/// a new distributional bug: two streams from one seed correlate wherever their counters
982/// collide). That also makes a restored session's boundary draw at `sctr == 0` bit-identical
983/// to the cold session's own first draw from the same logits row, which is what preserves the
984/// sampled-hit lane's per-seed hit==cold byte identity.
985#[allow(clippy::too_many_arguments)]
986pub fn sample_boundary_token_dev(
987 e: &Engine,
988 logits: &CudaSlice<f32>,
989 n_vocab: usize,
990 sp: &SpecSampling,
991 pen_hist: &[u32],
992 sctr: &mut u32,
993 site: &str,
994) -> Result<u32, Box<dyn std::error::Error>> {
995 debug_assert!(
996 sp.temp > 0.0,
997 "boundary sampling is the sampled regime only"
998 );
999 // Own copy: penalize_logits mutates in place and the caller's row is live state
1000 // (prime_logits back the constrained recompute; last_col_logits backs round 0's accept).
1001 let mut col = e.zeros(n_vocab)?;
1002 e.copy_into(&mut col, 0, logits, n_vocab)?;
1003 let pen_on = sp.penalty_last_n > 0
1004 && (sp.penalty_repeat != 1.0 || sp.penalty_freq != 0.0 || sp.penalty_present != 0.0);
1005 if pen_on && !pen_hist.is_empty() {
1006 // window trim mirrors the round loop's own upload (`pen_hist[w0..]`), cap included.
1007 let w0 = pen_hist
1008 .len()
1009 .saturating_sub(sp.penalty_last_n.min(PEN_WINDOW_MAX));
1010 let hist = &pen_hist[w0..];
1011 let hd = e.htod_u32_v(hist)?;
1012 e.penalize_logits(
1013 &mut col,
1014 &hd,
1015 hist.len(),
1016 sp.penalty_repeat,
1017 sp.penalty_freq,
1018 sp.penalty_present,
1019 n_vocab,
1020 )?;
1021 }
1022 let rows0 = e.htod_i32(&[0])?;
1023 let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
1024 e.filter_stats(
1025 &col, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1, sp.temp, sp.top_k,
1026 sp.top_p, sp.min_p,
1027 )?;
1028 let (th, mx) = (e.dtoh(&th_d)?[0], e.dtoh(&mx_d)?[0]);
1029 let mut perturb = e.zeros(n_vocab)?;
1030 e.gumbel_perturb_filtered(&col, &mut perturb, n_vocab, sp.seed, *sctr, sp.temp, mx, th)?;
1031 *sctr = sctr.wrapping_add(1);
1032 let td = e.argmax_token_device(&perturb, n_vocab)?;
1033 let tok = e.dtoh_u32_one(&td)?;
1034 if spec_boundary_trace() {
1035 // the pre-lane token, from the SAME row, so the deviation rate is measurable.
1036 let raw = e.argmax_token_device(logits, n_vocab)?;
1037 let greedy = e.dtoh_u32_one(&raw)?;
1038 eprintln!(
1039 "[spec-boundary] site={site} sampled={tok} argmax={greedy} \
1040 deviates={} temp={} sctr={}",
1041 (tok != greedy) as u8,
1042 sp.temp,
1043 sctr.wrapping_sub(1),
1044 );
1045 }
1046 Ok(tok)
1047}
1048
1049/// Host-row twin of [`sample_boundary_token_dev`] (the prime / feed / entry rows arrive as
1050/// host `Vec<f32>`).
1051#[allow(clippy::too_many_arguments)]
1052pub fn sample_boundary_token(
1053 e: &Engine,
1054 logits: &[f32],
1055 sp: &SpecSampling,
1056 pen_hist: &[u32],
1057 sctr: &mut u32,
1058 site: &str,
1059) -> Result<u32, Box<dyn std::error::Error>> {
1060 let n_vocab = logits.len();
1061 let d = e.htod(logits)?;
1062 sample_boundary_token_dev(e, &d, n_vocab, sp, pen_hist, sctr, site)
1063}
1064
1065struct SpecPipeTraceClock {
1066 pair: usize,
1067 started: std::time::Instant,
1068}
1069
1070#[derive(Clone)]
1071struct SpecPipeTraceCtx {
1072 clock: std::sync::Arc<SpecPipeTraceClock>,
1073 round: usize,
1074 lane: usize,
1075}
1076
1077struct SpecPipeTraceMarker {
1078 trace: SpecPipeTraceCtx,
1079 phase: &'static str,
1080 edge: &'static str,
1081 slot: Option<usize>,
1082}
1083
1084unsafe extern "C" fn spec_pipe_trace_marker(raw: *mut std::ffi::c_void) {
1085 let marker = unsafe { Box::from_raw(raw.cast::<SpecPipeTraceMarker>()) };
1086 let lane = if marker.trace.lane == 0 { "A" } else { "B" };
1087 let slot = marker
1088 .slot
1089 .map(|v| v.to_string())
1090 .unwrap_or_else(|| "-".into());
1091 let t_ms = marker.trace.clock.started.elapsed().as_secs_f64() * 1e3;
1092 use std::io::Write as _;
1093 let stderr = std::io::stderr();
1094 let mut stderr = stderr.lock();
1095 let _ = writeln!(
1096 stderr,
1097 "[spec-pipe-timeline] pair={} round={} lane={lane} phase={} edge={} \
1098 slot={slot} t_ms={t_ms:.3}",
1099 marker.trace.clock.pair, marker.trace.round, marker.phase, marker.edge,
1100 );
1101}
1102
1103fn enqueue_spec_pipe_trace_marker(
1104 stream: &cudarc::driver::CudaStream,
1105 trace: Option<&SpecPipeTraceCtx>,
1106 phase: &'static str,
1107 edge: &'static str,
1108 slot: Option<usize>,
1109) -> Result<(), Box<dyn std::error::Error>> {
1110 let Some(trace) = trace else {
1111 return Ok(());
1112 };
1113 let marker = Box::new(SpecPipeTraceMarker {
1114 trace: trace.clone(),
1115 phase,
1116 edge,
1117 slot,
1118 });
1119 let raw = Box::into_raw(marker);
1120 let result = unsafe {
1121 cudarc::driver::result::stream::launch_host_function(
1122 stream.cu_stream(),
1123 spec_pipe_trace_marker,
1124 raw.cast(),
1125 )
1126 };
1127 if let Err(err) = result {
1128 unsafe {
1129 drop(Box::from_raw(raw));
1130 }
1131 return Err(err.into());
1132 }
1133 Ok(())
1134}
1135
1136#[derive(Default)]
1137struct SpecPipeProgress {
1138 setup_done: [bool; 2],
1139 draft_done: [usize; 2],
1140 stage0_done: [usize; 2],
1141 verify_done: [usize; 2],
1142 accept_done: [usize; 2],
1143 finished: [bool; 2],
1144 aborted: bool,
1145}
1146
1147/// Host-side issue coordinator for the reduced two-session speculative pipeline. Each session
1148/// keeps its existing call stack and round locals; this object only orders phase entry. The
1149/// primary mutex spans whole draft/accept/tail issue regions so Engine's single-stream scratch
1150/// cannot be interleaved by the two host threads.
1151struct SpecPipeSync {
1152 progress: std::sync::Mutex<SpecPipeProgress>,
1153 changed: std::sync::Condvar,
1154 primary: std::sync::Mutex<()>,
1155 trace: Option<std::sync::Arc<SpecPipeTraceClock>>,
1156}
1157
1158impl SpecPipeSync {
1159 fn new() -> Self {
1160 static TRACE_PAIR: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1161 let trace = (std::env::var("MEMRA_SPEC_PIPE_TRACE").as_deref() == Ok("1")).then(|| {
1162 std::sync::Arc::new(SpecPipeTraceClock {
1163 pair: TRACE_PAIR.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1,
1164 started: std::time::Instant::now(),
1165 })
1166 });
1167 Self {
1168 progress: std::sync::Mutex::new(SpecPipeProgress::default()),
1169 changed: std::sync::Condvar::new(),
1170 primary: std::sync::Mutex::new(()),
1171 trace,
1172 }
1173 }
1174}
1175
1176#[derive(Clone)]
1177struct SpecPipeLane {
1178 sync: std::sync::Arc<SpecPipeSync>,
1179 lane: usize,
1180}
1181
1182impl SpecPipeLane {
1183 fn peer(&self) -> usize {
1184 1 - self.lane
1185 }
1186
1187 fn aborted() -> Box<dyn std::error::Error> {
1188 "paired speculative peer aborted".into()
1189 }
1190
1191 fn trace(&self, round: usize) -> Option<SpecPipeTraceCtx> {
1192 self.sync.trace.as_ref().map(|clock| SpecPipeTraceCtx {
1193 clock: clock.clone(),
1194 round,
1195 lane: self.lane,
1196 })
1197 }
1198
1199 fn setup_begin(&self) -> Result<(), Box<dyn std::error::Error>> {
1200 let mut p = self.sync.progress.lock().unwrap();
1201 while !p.aborted && self.lane == 1 && !p.setup_done[0] && !p.finished[0] {
1202 p = self.sync.changed.wait(p).unwrap();
1203 }
1204 if p.aborted {
1205 Err(Self::aborted())
1206 } else {
1207 Ok(())
1208 }
1209 }
1210
1211 fn setup_end(&self) {
1212 let mut p = self.sync.progress.lock().unwrap();
1213 p.setup_done[self.lane] = true;
1214 self.sync.changed.notify_all();
1215 }
1216
1217 fn draft_begin(
1218 &self,
1219 round: usize,
1220 ) -> Result<std::sync::MutexGuard<'_, ()>, Box<dyn std::error::Error>> {
1221 let peer = self.peer();
1222 let mut p = self.sync.progress.lock().unwrap();
1223 loop {
1224 if p.aborted {
1225 return Err(Self::aborted());
1226 }
1227 let setup_ready =
1228 (p.setup_done[0] || p.finished[0]) && (p.setup_done[1] || p.finished[1]);
1229 let prior_ready = p.accept_done[self.lane] >= round
1230 && (p.accept_done[peer] >= round || p.finished[peer]);
1231 let turn_ready = if self.lane == 0 {
1232 true
1233 } else {
1234 p.draft_done[0] > round || p.finished[0]
1235 };
1236 if setup_ready && prior_ready && turn_ready {
1237 break;
1238 }
1239 p = self.sync.changed.wait(p).unwrap();
1240 }
1241 drop(p);
1242 Ok(self.sync.primary.lock().unwrap())
1243 }
1244
1245 fn draft_end(&self, round: usize) {
1246 let mut p = self.sync.progress.lock().unwrap();
1247 p.draft_done[self.lane] = round + 1;
1248 self.sync.changed.notify_all();
1249 }
1250
1251 /// Admit stage 0 and return whether this lane owns the interval's one reverse fence.
1252 /// Lane B releases as soon as lane A has issued its boundary TX, not after A's full body.
1253 fn stage0_begin(&self, round: usize) -> Result<bool, Box<dyn std::error::Error>> {
1254 let peer = self.peer();
1255 let mut p = self.sync.progress.lock().unwrap();
1256 loop {
1257 if p.aborted {
1258 return Err(Self::aborted());
1259 }
1260 let ready = if self.lane == 0 {
1261 p.draft_done[0] > round && (p.draft_done[1] > round || p.finished[1])
1262 } else {
1263 p.draft_done[1] > round && (p.stage0_done[0] > round || p.finished[0])
1264 };
1265 if ready {
1266 return Ok(self.lane == 0 || p.finished[peer]);
1267 }
1268 p = self.sync.changed.wait(p).unwrap();
1269 }
1270 }
1271
1272 fn stage0_end(&self, round: usize) {
1273 let mut p = self.sync.progress.lock().unwrap();
1274 p.stage0_done[self.lane] = round + 1;
1275 self.sync.changed.notify_all();
1276 }
1277
1278 /// Stage 1 is single-owner per engine. A proceeds immediately after its own ticket; B waits
1279 /// for A's full stage1/head issue so only A.S1 and B.S0 can overlap.
1280 fn stage1_begin(&self, round: usize) -> Result<(), Box<dyn std::error::Error>> {
1281 let mut p = self.sync.progress.lock().unwrap();
1282 while !p.aborted
1283 && !(p.stage0_done[self.lane] > round
1284 && (self.lane == 0 || p.verify_done[0] > round || p.finished[0]))
1285 {
1286 p = self.sync.changed.wait(p).unwrap();
1287 }
1288 if p.aborted {
1289 Err(Self::aborted())
1290 } else {
1291 Ok(())
1292 }
1293 }
1294
1295 fn verify_end(&self, round: usize) {
1296 let mut p = self.sync.progress.lock().unwrap();
1297 p.verify_done[self.lane] = round + 1;
1298 self.sync.changed.notify_all();
1299 }
1300
1301 fn accept_begin(
1302 &self,
1303 round: usize,
1304 ) -> Result<std::sync::MutexGuard<'_, ()>, Box<dyn std::error::Error>> {
1305 let mut p = self.sync.progress.lock().unwrap();
1306 loop {
1307 if p.aborted {
1308 return Err(Self::aborted());
1309 }
1310 let ready = if self.lane == 0 {
1311 p.verify_done[0] > round && (p.verify_done[1] > round || p.finished[1])
1312 } else {
1313 p.verify_done[1] > round && (p.accept_done[0] > round || p.finished[0])
1314 };
1315 if ready {
1316 break;
1317 }
1318 p = self.sync.changed.wait(p).unwrap();
1319 }
1320 drop(p);
1321 Ok(self.sync.primary.lock().unwrap())
1322 }
1323
1324 fn accept_end(&self, round: usize) {
1325 let mut p = self.sync.progress.lock().unwrap();
1326 p.accept_done[self.lane] = round + 1;
1327 self.sync.changed.notify_all();
1328 }
1329
1330 fn primary(&self) -> std::sync::MutexGuard<'_, ()> {
1331 self.sync.primary.lock().unwrap()
1332 }
1333
1334 fn finish(&self, failed: bool) {
1335 let mut p = self.sync.progress.lock().unwrap();
1336 p.finished[self.lane] = true;
1337 p.aborted |= failed;
1338 self.sync.changed.notify_all();
1339 }
1340}
1341
1342struct SpecPipeFinish<'a> {
1343 lane: &'a SpecPipeLane,
1344 closed: bool,
1345}
1346
1347impl<'a> SpecPipeFinish<'a> {
1348 fn new(lane: &'a SpecPipeLane) -> Self {
1349 Self {
1350 lane,
1351 closed: false,
1352 }
1353 }
1354
1355 fn close(&mut self, failed: bool) {
1356 self.lane.finish(failed);
1357 self.closed = true;
1358 }
1359}
1360
1361impl Drop for SpecPipeFinish<'_> {
1362 fn drop(&mut self) {
1363 if !self.closed {
1364 self.lane.finish(true);
1365 }
1366 }
1367}
1368
1369/// Scoped transfer of one exclusively-borrowed session to the second host issue thread.
1370/// `CudaGraph` is not marked Send by cudarc because its raw driver handles carry no automatic
1371/// trait. CUDA driver graph handles are context-scoped rather than OS-thread-affine; the caller
1372/// binds that context before touching the session, joins before returning, and never aliases the
1373/// pointer. Keep this exception local to the experimental pair call instead of marking the public
1374/// session type Send.
1375struct SpecPipeSessionPtr(*mut SpecSession);
1376
1377unsafe impl Send for SpecPipeSessionPtr {}
1378
1379impl SpecPipeSessionPtr {
1380 unsafe fn get_mut(&mut self) -> &mut SpecSession {
1381 unsafe { &mut *self.0 }
1382 }
1383}
1384
1385/// Per-session persistent draft-graph context: the captured CUDA graph(s) plus the device
1386/// buffers whose POINTERS the capture bakes. Reuse legality: the greedy capture bakes only
1387/// session-stable pointers (the session's own MtpScratch KV — allocated once, never realloc'd;
1388/// the model's resident embedding; the process-wide OnceLock p_min) and the g_* buffers held
1389/// HERE — so one capture serves the session's whole lifetime. The sampled capture additionally
1390/// bakes (seed, temp) as capture-time constants and needs k q-slots — keyed by `s_key`, dropped
1391/// and recaptured when a pool-resumed request changes them. `*_failed` memoizes a failed capture
1392/// so the eager fallback doesn't pay a doomed capture attempt every burst.
1393/// Capture identity of the parked SAMPLED draft graph (`DraftGraphCtx::graph_s`).
1394///
1395/// EXACTNESS, not perf (lane/graph-s-key-exactness-20260819; receipts
1396/// `research/spec-cache-20260818/GRAPH-S-KEY.md`). Two classes of field live here, both
1397/// load-bearing:
1398///
1399/// - **Baked constants.** `seed` and `temp` are capture-time constants INSIDE the graph and `k`
1400/// sizes the q slots its replays write. A resumed request changing any of them must recapture.
1401/// This is all the key used to carry.
1402/// - **Regime fields.** `top_k`/`top_p`/`min_p`/`pen_on` are not baked, but they decide whether
1403/// the captured graph is a legal draft chain AT ALL. The in-graph draw is one gumbel-max over
1404/// the RAW softmax (`gumbel_perturb_ctr`, unfiltered by construction), while the verify builds
1405/// the accept test's `q` from `filter_stats(q_slots, top_k, top_p, min_p)`. If those disagree
1406/// the accept test evaluates a distribution the draft was never sampled from: a draft token
1407/// below the filter threshold gathers `q = 0` (`softmax_gather_filtered_f32`,
1408/// `cu/spec_sample.cu`) and `u * 0 < p` accepts it UNCONDITIONALLY.
1409///
1410/// Omitting the regime fields was reachable — not through the prefix-cache spec restore (that
1411/// path is greedy-only, `memra-server` `spec_restore_convertible`), but through WHOLE-SESSION
1412/// spec reuse: a parked `SpecSession` carries this `DraftGraphCtx`, and the pool-resume probe
1413/// applies no sampler predicate at all. Turn 1 pure-temp parks a graph; turn 2 of the same
1414/// conversation, same explicit seed and temperature, adds `top_p`/`top_k` and inherits it.
1415#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1416pub(crate) struct SampledGraphKey {
1417 seed: u64,
1418 temp_bits: u32,
1419 k: usize,
1420 top_k: i32,
1421 top_p_bits: u32,
1422 min_p_bits: u32,
1423 pen_on: bool,
1424}
1425
1426impl SampledGraphKey {
1427 pub(crate) fn new(
1428 seed: u64,
1429 temp: f32,
1430 k: usize,
1431 top_k: i32,
1432 top_p: f32,
1433 min_p: f32,
1434 pen_on: bool,
1435 ) -> Self {
1436 SampledGraphKey {
1437 seed,
1438 temp_bits: temp.to_bits(),
1439 k,
1440 top_k,
1441 top_p_bits: top_p.to_bits(),
1442 min_p_bits: min_p.to_bits(),
1443 pen_on,
1444 }
1445 }
1446
1447 /// The one regime the in-graph sampled chain may stand in for the eager one: nothing but
1448 /// temperature shapes `q`. Computed FROM THE KEY so the capture guard, the launch guard and
1449 /// the key can never drift apart (they were three separate expressions before this lane, and
1450 /// the launch site simply forgot to ask).
1451 pub(crate) fn pure_temp(&self) -> bool {
1452 self.top_k == 0
1453 && f32::from_bits(self.top_p_bits) >= 1.0
1454 && f32::from_bits(self.min_p_bits) <= 0.0
1455 && !self.pen_on
1456 }
1457}
1458
1459pub(crate) struct DraftGraphCtx {
1460 g_tok: CudaSlice<u32>,
1461 g_pos: CudaSlice<i32>,
1462 g_seed: CudaSlice<f32>,
1463 g_p: CudaSlice<f32>,
1464 g_ctr: CudaSlice<u32>,
1465 g_q: CudaSlice<f32>,
1466 g_perturb: CudaSlice<f32>,
1467 q_slots: Vec<CudaSlice<f32>>,
1468 /// DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): packed allowed-set words over the DRAFT
1469 /// head's vocab, at a STABLE address so the captured draft graph's mask node reads the
1470 /// per-position contents the host re-uploads before each replay (the graph-promote
1471 /// pattern from decode.rs). Empty unless the session drafts under a grammar.
1472 g_dmask: CudaSlice<u32>,
1473 /// was `graph` captured WITH the mask node? A parked graph of the wrong shape is dropped.
1474 graph_masked: bool,
1475 graph: Option<cudarc::driver::CudaGraph>,
1476 graph_s: Option<cudarc::driver::CudaGraph>,
1477 /// Failed-capture memoization for both graphs — LOUD on flip, cleared on pool resume
1478 /// (audit Q2, the TRT #16072 silent-permanent-coverage-loss class).
1479 failed: DraftGraphFallback,
1480 /// Capture identity of `graph_s` — see [`SampledGraphKey`]. `None` iff no sampled graph is
1481 /// parked; a request whose key differs drops the parked graph (and its q slots/keeper).
1482 s_key: Option<SampledGraphKey>,
1483 /// CAPTURE-RETAIN keepers (#68 root cause, 2026-08-04): the warmup-run transients whose
1484 /// pool addresses the captured graph(s) bake. Without these, the transients return to the
1485 /// pool at capture-body exit and later work (burst-boundary prime/fill/commit passes, or a
1486 /// co-served session in the worker) reuses those addresses — the persisted graph's replay
1487 /// then reads/writes live unrelated buffers (exactness corruption, first seen as the ST
1488 /// serve-spec 4B graph-arm corruption; one-shot CLI calls never re-shuffled the pool, which
1489 /// is why run-spec K=1..8 passed on the same checkpoint). Same fix class as
1490 /// capture_graph_retained's gemma/decode.rs sites — hold as long as the graph replays.
1491 keeper: Vec<Box<dyn std::any::Any + Send>>,
1492 keeper_s: Vec<Box<dyn std::any::Any + Send>>,
1493}
1494
1495/// Failed-capture memoization for the two draft graphs (audit Q2, 2026-08-05 — the
1496/// TRT #16072 trap class: pressure-triggered, silent, long-lived coverage loss).
1497///
1498/// Three contracts:
1499/// - LOUD FLIP: `mark_*` returns the warn line exactly on the false→true transition
1500/// (returned, not printed, so the once-per-flip contract is unit-testable); the caller
1501/// `eprintln!`s it UNCONDITIONALLY — a dropped draft graph is never silent. Re-marking
1502/// an already-failed graph returns None (the per-burst memoization that keeps the eager
1503/// fallback from paying a doomed capture attempt every burst).
1504/// - RESET ON RESUME: `reset_on_resume` clears both flags — a parked session resumed by a
1505/// NEW request gets one fresh capture chance instead of carrying a transient-pressure
1506/// failure for the pool's whole lifetime. Returns the note line only when a flag was
1507/// actually set (quiet on the common clean-resume path).
1508/// - Shape-change clears (`clear_*`) stay silent, exactly as before: they precede a fresh
1509/// capture attempt whose own failure would re-flip loudly.
1510#[derive(Default)]
1511pub(crate) struct DraftGraphFallback {
1512 greedy: bool,
1513 sampled: bool,
1514}
1515impl DraftGraphFallback {
1516 fn mark_greedy(&mut self, reason: &str) -> Option<String> {
1517 if self.greedy {
1518 return None;
1519 }
1520 self.greedy = true;
1521 Some(format!(
1522 "[spec] WARN: draft-graph capture failed ({reason}); eager fallback until session resume"
1523 ))
1524 }
1525 fn mark_sampled(&mut self, reason: &str) -> Option<String> {
1526 if self.sampled {
1527 return None;
1528 }
1529 self.sampled = true;
1530 Some(format!(
1531 "[spec] WARN: sampled draft-graph capture failed ({reason}); eager fallback until session resume"
1532 ))
1533 }
1534 fn greedy_failed(&self) -> bool {
1535 self.greedy
1536 }
1537 fn sampled_failed(&self) -> bool {
1538 self.sampled
1539 }
1540 fn clear_greedy(&mut self) {
1541 self.greedy = false;
1542 }
1543 fn clear_sampled(&mut self) {
1544 self.sampled = false;
1545 }
1546 /// Pool-resume reset: both graphs get a fresh capture chance. Some(note) iff any flag
1547 /// was set (so clean resumes stay quiet).
1548 pub(crate) fn reset_on_resume(&mut self) -> Option<String> {
1549 if !self.greedy && !self.sampled {
1550 return None;
1551 }
1552 let which = match (self.greedy, self.sampled) {
1553 (true, true) => "greedy+sampled",
1554 (true, false) => "greedy",
1555 _ => "sampled",
1556 };
1557 self.greedy = false;
1558 self.sampled = false;
1559 Some(format!(
1560 "[spec] draft-graph fallback reset on session resume ({which}); recapture eligible"
1561 ))
1562 }
1563}
1564
1565impl DraftGraphCtx {
1566 fn new(e: &Engine, n_embd: usize, qlen: usize) -> Result<Self, Box<dyn std::error::Error>> {
1567 Ok(DraftGraphCtx {
1568 g_tok: e.alloc_u32_zeroed(1)?,
1569 g_pos: e.htod_i32(&[0])?,
1570 g_seed: e.zeros(n_embd)?,
1571 g_p: e.zeros(1)?,
1572 g_ctr: e.alloc_u32_zeroed(1)?,
1573 g_q: e.zeros(qlen)?,
1574 g_perturb: e.zeros(qlen)?,
1575 q_slots: Vec::new(),
1576 g_dmask: e.alloc_u32_zeroed(1)?,
1577 graph_masked: false,
1578 graph: None,
1579 graph_s: None,
1580 failed: DraftGraphFallback::default(),
1581 s_key: None,
1582 keeper: Vec::new(),
1583 keeper_s: Vec::new(),
1584 })
1585 }
1586}
1587
1588pub(crate) struct MtpScratch {
1589 kv: KvLayer,
1590 /// Logical row capacity. On the graph/DC draft path it also doubles as fa_decode_dc's
1591 /// bucket_max: n_splits is sized from it ONCE, so the graph captured at round 0 stays valid
1592 /// for every later t_kv. Step35 refuses that path and may back this logical extent with the
1593 /// smaller host-indexed SWA ring instead.
1594 cap: usize,
1595}
1596
1597fn mtp_scratch_layout(
1598 cfg: &memra_gguf::config::ModelConfig,
1599 geom: Option<&crate::hybrid::DraftGeom>,
1600) -> (usize, usize, usize, usize) {
1601 // Student draft heads carry fewer KV heads (head_dim unchanged) -> smaller scratch rows.
1602 let n_head_kv = geom.map(|g| g.n_head_kv).unwrap_or(cfg.n_head_kv as usize);
1603 let head_dim_k = cfg.head_dim_k as usize;
1604 let head_dim_v = cfg.head_dim_v as usize;
1605 assert!(
1606 head_dim_k % 32 == 0 && head_dim_v % 32 == 0,
1607 "KVQUANT requires head_dim%32==0 (MTP scratch)"
1608 );
1609 let kv_dim_k = head_dim_k * n_head_kv;
1610 let kv_dim_v = head_dim_v * n_head_kv;
1611 // The fp8-KV arm deliberately does not reach the draft scratch; keep the exact format
1612 // policy shared with `MtpScratch::new` so admission scales the same allocation.
1613 let (kbb, vbb) = crate::kv_blk_bytes();
1614 let k_tok_bytes = (kv_dim_k / 32) * kbb;
1615 let v_tok_bytes = (kv_dim_v / 32) * vbb;
1616 (kv_dim_k, kv_dim_v, k_tok_bytes, v_tok_bytes)
1617}
1618
1619impl MtpScratch {
1620 fn new(
1621 e: &Engine,
1622 cfg: &memra_gguf::config::ModelConfig,
1623 cap: usize,
1624 geom: Option<&crate::hybrid::DraftGeom>,
1625 ) -> Result<Self, Box<dyn std::error::Error>> {
1626 // env-selected KV formats (default 34/24). The fp8-KV arm (MEMRA_KV_FP8) deliberately
1627 // does NOT reach the draft scratch: fp8 drafts drifted acceptance 69-88% -> 46%
1628 // (2026-07-12 A/B); the scratch is tiny, so it keeps baseline q8_0/q5_1 numerics
1629 // while the TRUNK cache carries the fp8 depth win. Scratch append/fa pass g=false.
1630 let (kv_dim_k, kv_dim_v, k_tok_bytes, v_tok_bytes) = mtp_scratch_layout(cfg, geom);
1631 let ring = if crate::cache::swa_ring_on() && cfg.arch.is_step35() {
1632 let window = cfg.step35.as_ref().unwrap().sliding_window as usize;
1633 Some(crate::cache::KvRing::new(
1634 crate::cache::swa_ring_rows(window, cap),
1635 window,
1636 ))
1637 } else {
1638 None
1639 };
1640 let alloc_rows = ring.as_ref().map(crate::cache::KvRing::rows).unwrap_or(cap);
1641 Ok(MtpScratch {
1642 kv: KvLayer {
1643 k: e.alloc_u8(alloc_rows * k_tok_bytes)?,
1644 v: e.alloc_u8(alloc_rows * v_tok_bytes)?,
1645 kv_dim_k,
1646 kv_dim_v,
1647 k_tok_bytes,
1648 v_tok_bytes,
1649 len: 0,
1650 ring,
1651 len_d: e.htod_i32(&[0])?,
1652 },
1653 cap,
1654 })
1655 }
1656 /// Set BOTH length counters: the host mirror AND the device len_d the captured append/fa read
1657 /// (a 4-byte in-place htod — the counter pointer is baked into the graph, never realloc'd).
1658 /// This is the ONLY truncation/rollback mechanism the persistent draft KV needs.
1659 fn set_len(&mut self, e: &Engine, n: usize) -> Result<(), Box<dyn std::error::Error>> {
1660 if self
1661 .kv
1662 .ring
1663 .as_ref()
1664 .is_some_and(|ring| !ring.can_rewind_to(n))
1665 {
1666 return Err("SWA ring MTP checkpoint has been lapped; full re-prime required".into());
1667 }
1668 self.kv.len = n;
1669 e.set_i32_one(&mut self.kv.len_d, n as i32)
1670 }
1671
1672 fn can_rewind_to(&self, n: usize) -> bool {
1673 self.kv
1674 .ring
1675 .as_ref()
1676 .is_none_or(|ring| ring.can_rewind_to(n))
1677 }
1678}
1679
1680/// Retained verify intermediates for the REPLAY-FREE partial accept (2026-07-03, the profiled
1681/// #1 spec cost at long ctx: the partial-accept replay was a DUPLICATE trunk pass — ~0.54 extra
1682/// full weight reads per round — recomputing columns the verify had already produced
1683/// bit-identically). Holds, per linear layer, everything needed to rebuild its recurrent state
1684/// to "after the first j verify columns" WITHOUT re-running the trunk:
1685/// - BATCHED-path layers (`gdn`): the exact token-major inputs the round's ONE gdn_scan
1686/// consumed. A prefix re-run of the SAME kernel (t=j) from the snapshot state is bit-identical
1687/// to the first j iterations of the verify's scan — the kernel's t-loop carries state in
1688/// registers and iteration t never depends on T. `qkv_mixed` (the conv input) feeds the
1689/// pure-copy ring rebuild.
1690/// - PER-COLUMN-path layers (`cols`): dtod clones of (conv_state, ssm_state) taken after each
1691/// column 0..t-2 — pure copies of the actual chain states (the last column is never a rebuild
1692/// target: j <= t-1).
1693/// Full-attn layers need nothing: their verify KV rows are bit-identical to eager's (the
1694/// decode-exact contract; verify-probe pins it), so rollback = len truncation.
1695struct GdnStash {
1696 qkv_mixed: CudaSlice<f32>, // [t, conv_dim] token-major (conv input)
1697 q_l2: CudaSlice<f32>,
1698 k_l2: CudaSlice<f32>,
1699 v_g: CudaSlice<f32>, // [t, num_v, d_state]
1700 g_log: CudaSlice<f32>,
1701 beta: CudaSlice<f32>, // [t, num_v]
1702}
1703pub(crate) struct VerifyCkpt {
1704 gdn: Vec<Option<GdnStash>>, // [n_layer], Some iff batched linear path ran
1705 cols: Vec<Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>>>, // [n_layer][col] = (conv, ssm) after col
1706}
1707/// Opaque handle for the dspark round (dflash.rs) — VerifyCkpt stays spec-private.
1708pub(crate) struct DsparkVerifyCkpt(VerifyCkpt);
1709
1710/// Engine-bundle slice 3 (DSF-ROUNDCOST-20260820 §2 row 4 / §5 rank 1): bucketed CUDA
1711/// graphs for the dspark verify's LINEAR-layer segments. The measured verify is ~2,800
1712/// eager launches whose residual cost is DEVICE-side per-launch overhead (slice 2 proved
1713/// host dispatch is not the binder: fully-deferred dispatch bought ~0 wall). The 48 GDN
1714/// layers between full-attention layers are shape-static given vt — no positions, no
1715/// t_kv, state addressed through pointer tables — so runs of them capture per
1716/// (segment, vt) and replay as ONE graph launch each. Full-attention layers stay eager
1717/// (their per-row append/fa arm picks are t_kv-driven — the exec-update extension).
1718///
1719/// Per round out-of-graph: one pointer-table refresh (gdn ping-pong moves the canonical
1720/// handles), one input-staging copy per segment, host parity bookkeeping. Captured via
1721/// `capture_graph_retained` (2 warmups + capture, keeper retains warmup transients so
1722/// pool addresses stay stable); the warmups EXECUTE, so segment conv/ssm state is saved
1723/// before and restored after — the graph's first real launch starts from the exact
1724/// pre-round state. The ckpt column stash rides persistent slabs (written inside the
1725/// graph as memcpy nodes); commit reads them via `dspark_commit_prefix_slab`.
1726/// `MEMRA_DSPARK_VERIFY_GRAPH=0` reverts to the eager walk (byte-identical body).
1727pub(crate) struct DsparkVerifyGraphs {
1728 /// Linear-attention layer indices ascending; `lin_pos[il]` = index into the vecs.
1729 lin: Vec<usize>,
1730 lin_pos: std::collections::HashMap<usize, usize>,
1731 /// [n_lin x 6] pointer table (conv, s0, s1, conv, s1, s0 per layer), refreshed per
1732 /// verify from the live handles; layer il's slice starts at lin_pos[il]*6.
1733 table_all: CudaSlice<u64>,
1734 host_table: Vec<u64>,
1735 /// Persistent per-layer ckpt stash slabs: row r of the verify at slab offset
1736 /// r*words. Shared by every (segment, vt) bucket — one verify runs at a time.
1737 stash_conv: Vec<CudaSlice<f32>>,
1738 stash_ssm: Vec<CudaSlice<f32>>,
1739 conv_words: usize,
1740 ssm_words: usize,
1741 /// Per-vt input/output staging (stable addresses the graphs bake).
1742 stage: std::collections::HashMap<usize, (CudaSlice<f32>, CudaSlice<f32>)>,
1743 /// Per-vt dflash tap-sink buffers — the captured segments bake the tap dst address,
1744 /// so the sink buffer must live (and persist) with the graphs, not with the round.
1745 pub(crate) tap_bufs: std::collections::HashMap<usize, CudaSlice<f32>>,
1746 graphs: std::collections::HashMap<(usize, usize), DsparkSegGraph>,
1747 /// Warmup-corruption guard scratch: pre-capture conv/ssm of every linear layer
1748 /// (sized n_lin — the slice-4c full-verify warmups execute the whole walk).
1749 save_conv: CudaSlice<f32>,
1750 save_ssm: CudaSlice<f32>,
1751 max_run: usize,
1752 n_embd: usize,
1753 /// Set by the verify walk: this round's linear ckpt lives in the slabs (the caller
1754 /// commits through `dspark_commit_prefix_slab` instead of the cols arm).
1755 pub(crate) round_slab: bool,
1756 // ---- slice 4c: full-verify single graph per (vt, rung) ----
1757 /// Full-attention layer indices ascending; `fa_pos[il]` = index into the vec.
1758 fa: Vec<usize>,
1759 fa_pos: std::collections::HashMap<usize, usize>,
1760 /// [n_fa x 2 x t_cap] interleaved (k,v) base-pointer pairs, refreshed per verify;
1761 /// layer il's slice starts at `fa_pos[il] * 2 * t_cap` (the seqs twins read pairs
1762 /// [2z], z < t <= t_cap, so one t_cap-sized table serves every vt).
1763 fa_table: CudaSlice<u64>,
1764 fa_host_table: Vec<u64>,
1765 t_cap: usize,
1766 /// Per-vt position staging for the captured bodies — contents refreshed per round
1767 /// (rope reads row r; the seqs twins derive append slot and T_kv per z from it).
1768 pos_stage: std::collections::HashMap<usize, CudaSlice<i32>>,
1769 /// Full-verify graphs keyed (vt, rung_end, hi).
1770 full: std::collections::HashMap<(usize, usize, usize), DsparkSegGraph>,
1771 /// Largest n with every layer in [0, n) linear or full-attention (walk coverage).
1772 covered: usize,
1773 /// Every layer in [0, n) is linear or full-attention (no MLA/unknown mixers) — the
1774 /// full-verify capture walks all of them.
1775 walk_uniform: bool,
1776}
1777
1778struct DsparkSegGraph {
1779 graph: cudarc::driver::CudaGraph,
1780 _keeper: Vec<Box<dyn std::any::Any + Send>>,
1781}
1782
1783/// Per-call arguments of [`HybridModel::qwen35_tparallel_fa_layer`] — one struct so the
1784/// eager walk and the slice-4c captured full-verify graphs hand the SAME body its two
1785/// modes without a second copy of the math.
1786pub(crate) struct FaLayerArgs<'a> {
1787 /// [T] per-row positions (device): rope reads them row-indexed; the seqs twins read
1788 /// them per-z (append slot = pos, T_kv = pos + 1).
1789 pub pos_d: &'a CudaSlice<i32>,
1790 /// Verify-level lazy per-row 1-element position buffers — only the per-row fallback
1791 /// arm builds/uses them (graph mode refuses that arm).
1792 pub pos_rows: &'a mut Option<Vec<CudaSlice<i32>>>,
1793 pub pos0: usize,
1794 pub seqs_append: bool,
1795 pub batch_fa_on: bool,
1796 /// Some((kv pointer table, offset-in-u64s, rung_end)) = captured-graph mode.
1797 pub graph_cap: Option<(&'a CudaSlice<u64>, usize, usize)>,
1798 /// ROUND-STREAM (lane/draftcost-moe, v0.100 train merge): Some((token stream, device
1799 /// round counter)) routes the FA attend through the dc rows kernels and the Linear
1800 /// mixer through `linear_attn_verify_t` (the stream arms the old inline body carried).
1801 /// Never armed together with `graph_cap` (the verify-level merge guard refuses).
1802 pub stream: Option<(&'a CudaSlice<u32>, &'a CudaSlice<i32>)>,
1803 /// VerifyCkpt for the stream-Linear arm's GdnStash install; None in graph mode and
1804 /// for FA layers that never touch it.
1805 pub ckpt: Option<&'a mut VerifyCkpt>,
1806}
1807
1808// SAFETY: `CudaGraph` is not marked Send by cudarc because its raw driver handles carry
1809// no automatic trait; CUDA driver graph handles are context-scoped rather than
1810// OS-thread-affine (the SpecPipeSessionPtr precedent above). The ctx lives in
1811// `HybridModel::dspark_vgraphs` behind a Mutex and every touch happens on the engine's
1812// single decode-stream thread.
1813unsafe impl Send for DsparkVerifyGraphs {}
1814
1815impl DsparkVerifyGraphs {
1816 /// Build for this cache's shape. None when there are no linear layers, sizes are
1817 /// non-uniform, or the trunk keeps a gemma4 config (never on the qwen35 family).
1818 pub(crate) fn new(
1819 e: &Engine,
1820 cache: &Cache,
1821 t_max: usize,
1822 n_embd: usize,
1823 ) -> Result<Option<Self>, Box<dyn std::error::Error>> {
1824 let lin: Vec<usize> = (0..cache.recur.len())
1825 .filter(|&il| cache.recur[il].is_some())
1826 .collect();
1827 if lin.is_empty() || t_max < 2 {
1828 return Ok(None);
1829 }
1830 let first = cache.recur[lin[0]].as_ref().unwrap();
1831 let (conv_words, ssm_words) = (first.conv_state.len(), first.ssm_state.len());
1832 for &il in &lin {
1833 let rl = cache.recur[il].as_ref().unwrap();
1834 if rl.conv_state.len() != conv_words || rl.ssm_state.len() != ssm_words {
1835 return Ok(None);
1836 }
1837 }
1838 let n = lin.len();
1839 let mut lin_pos = std::collections::HashMap::with_capacity(n);
1840 for (k, &il) in lin.iter().enumerate() {
1841 lin_pos.insert(il, k);
1842 }
1843 // longest run of consecutive linear layers (save-scratch sizing)
1844 let mut max_run = 1usize;
1845 let mut run = 1usize;
1846 for w in lin.windows(2) {
1847 if w[1] == w[0] + 1 {
1848 run += 1;
1849 max_run = max_run.max(run);
1850 } else {
1851 run = 1;
1852 }
1853 }
1854 let rows = t_max - 1;
1855 let mut stash_conv = Vec::with_capacity(n);
1856 let mut stash_ssm = Vec::with_capacity(n);
1857 for _ in 0..n {
1858 stash_conv.push(e.uninit(rows * conv_words)?);
1859 stash_ssm.push(e.uninit(rows * ssm_words)?);
1860 }
1861 let host_table = vec![0u64; n * 6];
1862 let table_all = e.htod_u64(&host_table)?;
1863 // slice 4c: full-attention census for the full-verify graphs.
1864 let fa: Vec<usize> = (0..cache.kv.len())
1865 .filter(|&il| cache.kv[il].is_some())
1866 .collect();
1867 let mut fa_pos = std::collections::HashMap::with_capacity(fa.len());
1868 for (k, &il) in fa.iter().enumerate() {
1869 fa_pos.insert(il, k);
1870 }
1871 let n_layers = cache.kv.len().max(cache.recur.len());
1872 // exactly one of (linear state, kv cache) per layer — no MLA/unknown mixers.
1873 let walk_uniform = (0..n_layers).all(|il| {
1874 cache.recur.get(il).is_some_and(|r| r.is_some())
1875 != cache.kv.get(il).is_some_and(|k| k.is_some())
1876 });
1877 // Contiguous covered prefix: the largest n such that every layer in [0, n) is
1878 // linear or full-attention. The TRUNK walk is [0, layers.len()) and the cache
1879 // vecs can carry EXTRA state slots past it (the q38 export keeps the MTP head
1880 // layer's kv at the tail — hi == lin+fa never held, the s4c battery's zero
1881 // 'full' captures). The full-graph guard is walk coverage, not slot arithmetic.
1882 let covered = (0..n_layers)
1883 .take_while(|il| lin_pos.contains_key(il) || fa_pos.contains_key(il))
1884 .count();
1885 let t_cap = t_max;
1886 let fa_host_table = vec![0u64; fa.len() * 2 * t_cap];
1887 let fa_table = e.htod_u64(&fa_host_table)?;
1888 Ok(Some(Self {
1889 lin,
1890 lin_pos,
1891 table_all,
1892 host_table,
1893 stash_conv,
1894 stash_ssm,
1895 conv_words,
1896 ssm_words,
1897 stage: std::collections::HashMap::new(),
1898 tap_bufs: std::collections::HashMap::new(),
1899 graphs: std::collections::HashMap::new(),
1900 save_conv: e.uninit(n * conv_words)?,
1901 save_ssm: e.uninit(n * ssm_words)?,
1902 max_run,
1903 n_embd,
1904 round_slab: false,
1905 fa,
1906 fa_pos,
1907 fa_table,
1908 fa_host_table,
1909 t_cap,
1910 pos_stage: std::collections::HashMap::new(),
1911 full: std::collections::HashMap::new(),
1912 covered,
1913 walk_uniform,
1914 }))
1915 }
1916
1917 /// Rebuild the pointer tables from the live handles (once per verify — the gdn
1918 /// ping-pong swaps the canonical/alt handles between rounds; a fresh generation's
1919 /// cache buffers land at new addresses; a stale table would read the wrong state).
1920 pub(crate) fn refresh_tables(
1921 &mut self,
1922 e: &Engine,
1923 cache: &Cache,
1924 ) -> Result<(), Box<dyn std::error::Error>> {
1925 use cudarc::driver::DevicePtr;
1926 {
1927 let s = &e.gpu.stream();
1928 for (k, &il) in self.lin.iter().enumerate() {
1929 let rl = cache.recur[il].as_ref().unwrap();
1930 let (pc, _g0) = rl.conv_state.device_ptr(s);
1931 let (p0, _g1) = rl.ssm_state.device_ptr(s);
1932 let (p1, _g2) = rl.ssm_state_alt.device_ptr(s);
1933 let o = k * 6;
1934 self.host_table[o] = pc as u64;
1935 self.host_table[o + 1] = p0 as u64;
1936 self.host_table[o + 2] = p1 as u64;
1937 self.host_table[o + 3] = pc as u64;
1938 self.host_table[o + 4] = p1 as u64;
1939 self.host_table[o + 5] = p0 as u64;
1940 }
1941 for (k, &il) in self.fa.iter().enumerate() {
1942 let kvl = cache.kv[il].as_ref().unwrap();
1943 let (pk, _g0) = kvl.k.device_ptr(s);
1944 let (pv, _g1) = kvl.v.device_ptr(s);
1945 let o = k * 2 * self.t_cap;
1946 for z in 0..self.t_cap {
1947 self.fa_host_table[o + 2 * z] = pk as u64;
1948 self.fa_host_table[o + 2 * z + 1] = pv as u64;
1949 }
1950 }
1951 }
1952 e.htod_u64_into(&self.host_table, &mut self.table_all)?;
1953 if !self.fa_host_table.is_empty() {
1954 e.htod_u64_into(&self.fa_host_table, &mut self.fa_table)?;
1955 }
1956 Ok(())
1957 }
1958
1959 /// Slice 4c eligibility: Some(rung_end) when this round can replay (or capture) a
1960 /// full-verify graph — the whole walk [lo, hi) is covered, every layer is linear or
1961 /// full-attention, and ALL of the round's per-row t_kv values take the v4-seqs arm
1962 /// on ONE `fa_split_keys` ladder step that the rung also sits on (the straddle law;
1963 /// both gates are t_kv intervals, so ends-inside means all-inside). The rung is the
1964 /// round's next power of two — grid/partial sizing only (`n_splits_max` is pure
1965 /// stride; splits >= ns_eff write the empty partial the combine never reads), so one
1966 /// captured graph is bit-identical for every round the rung covers.
1967 #[allow(clippy::too_many_arguments)]
1968 pub(crate) fn full_rung(
1969 &self,
1970 model: &crate::hybrid::HybridModel,
1971 cache: &Cache,
1972 lo: usize,
1973 hi: usize,
1974 t: usize,
1975 seqs_arms_on: bool,
1976 ) -> Option<usize> {
1977 if std::env::var("MEMRA_DSPARK_FULLG_DEBUG").as_deref() == Ok("1") {
1978 static ONCE: std::sync::Once = std::sync::Once::new();
1979 let len0 = self
1980 .fa
1981 .first()
1982 .and_then(|&il| cache.kv[il].as_ref())
1983 .map(|k| k.len);
1984 ONCE.call_once(|| {
1985 eprintln!(
1986 "[fullg-debug] walk_uniform={} covered={} seqs_arms_on={} fa_rows_on={} t={} lo={} hi={} lin={} fa={} t_cap={} len0={:?}",
1987 self.walk_uniform, self.covered, seqs_arms_on, dspark_fa_rows_on(), t, lo, hi,
1988 self.lin.len(), self.fa.len(), self.t_cap, len0
1989 );
1990 });
1991 }
1992 if !self.walk_uniform
1993 || !seqs_arms_on
1994 || !dspark_fa_rows_on()
1995 || t < 2
1996 || lo != 0
1997 || hi > self.covered
1998 || t > self.t_cap
1999 || self.fa.is_empty()
2000 {
2001 return None;
2002 }
2003 let cfg = &model.cfg;
2004 let head_dim_global = cfg.head_dim_k as usize;
2005 let nkv = cfg.n_head_kv as usize;
2006 let kvl0 = cache.kv[self.fa[0]].as_ref().unwrap();
2007 // the z-batched twins read stacked rows at the cache's kv dims — must equal the
2008 // projection stride (the body's guard, hoisted so ineligible models fall back
2009 // instead of refusing mid-capture).
2010 let geom = cfg.full_attention_geometry_at(self.fa[0] as u32);
2011 let kv_dim = geom.n_head_kv as usize * geom.head_dim_k as usize;
2012 if kvl0.kv_dim_k != kv_dim || kvl0.kv_dim_v != kv_dim {
2013 return None;
2014 }
2015 let len0 = kvl0.len;
2016 let (t_kv_first, t_kv_last) = (len0 + 1, len0 + t);
2017 if !crate::fa_seqs_eligible(t_kv_first, head_dim_global)
2018 || !crate::fa_seqs_eligible(t_kv_last, head_dim_global)
2019 || crate::fa_split_keys(t_kv_first, nkv) != crate::fa_split_keys(t_kv_last, nkv)
2020 {
2021 return None;
2022 }
2023 let rung = t_kv_last.next_power_of_two().max(256);
2024 if crate::fa_split_keys(rung, nkv) != crate::fa_split_keys(t_kv_last, nkv) {
2025 return None;
2026 }
2027 Some(rung)
2028 }
2029
2030 /// Run the WHOLE verify walk [lo, hi) as one captured graph at (vt=t, rung): stage
2031 /// the residual + refresh the per-vt position staging, capture on first encounter
2032 /// (2 executing warmups bracketed by a full linear-state save/restore; KV warmup
2033 /// appends write the exact slots the replay writes — idempotent), launch, then apply
2034 /// the host bookkeeping the captured body skipped (per-linear-layer parity swap for
2035 /// odd t, per-fa-layer len bump). Returns the fresh residual.
2036 #[allow(clippy::too_many_arguments)]
2037 pub(crate) fn run_full(
2038 &mut self,
2039 model: &crate::hybrid::HybridModel,
2040 e: &Engine,
2041 lo: usize,
2042 hi: usize,
2043 x: &CudaSlice<f32>,
2044 t: usize,
2045 pos0: usize,
2046 rung: usize,
2047 cache: &mut Cache,
2048 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2049 let n_embd = self.n_embd;
2050 if !self.stage.contains_key(&t) {
2051 let xin = e.uninit(t * n_embd)?;
2052 let xout = e.uninit(t * n_embd)?;
2053 self.stage.insert(t, (xin, xout));
2054 }
2055 if !self.pos_stage.contains_key(&t) {
2056 self.pos_stage.insert(t, e.htod_i32(&vec![0i32; t])?);
2057 }
2058 // Per-round refresh: position contents + input staging (both addresses are baked
2059 // by the captured bodies; only their CONTENTS change round to round).
2060 {
2061 let pos_host: Vec<i32> = (0..t).map(|r| (pos0 + r) as i32).collect();
2062 let pb = self.pos_stage.get_mut(&t).unwrap();
2063 e.htod_i32_into(pb, &pos_host)?;
2064 let (xin, _) = self.stage.get_mut(&t).unwrap();
2065 e.copy_into(xin, 0, x, t * n_embd)?;
2066 }
2067 let key = (t, rung, hi);
2068 if !self.full.contains_key(&key) {
2069 // The warmups EXECUTE the whole walk on live state — save every linear
2070 // layer's conv + canonical ssm first, restore after (KV needs no restore:
2071 // graph mode never bumps host lens and the appends write this round's own
2072 // slots).
2073 for (k, &il) in self.lin.iter().enumerate() {
2074 let rl = cache.recur[il].as_ref().unwrap();
2075 e.copy_into(
2076 &mut self.save_conv,
2077 k * self.conv_words,
2078 &rl.conv_state,
2079 self.conv_words,
2080 )?;
2081 e.copy_into(
2082 &mut self.save_ssm,
2083 k * self.ssm_words,
2084 &rl.ssm_state,
2085 self.ssm_words,
2086 )?;
2087 }
2088 let (graph, keeper) = {
2089 let table_all = &self.table_all;
2090 let lin_pos = &self.lin_pos;
2091 let fa_pos = &self.fa_pos;
2092 let fa_table = &self.fa_table;
2093 let t_cap = self.t_cap;
2094 let stash_conv = &mut self.stash_conv;
2095 let stash_ssm = &mut self.stash_ssm;
2096 let pos_d: &CudaSlice<i32> = &self.pos_stage[&t];
2097 let (xin, xout) = self
2098 .stage
2099 .get_mut(&t)
2100 .map(|(a, b)| (&*a, b))
2101 .expect("stage bucket created above");
2102 let cache_ref: &mut Cache = cache;
2103 let iflag = if std::env::var("MEMRA_DSPARK_VG_AUTOFREE").as_deref() == Ok("1") {
2104 cudarc::driver::sys::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH
2105 } else {
2106 cudarc::driver::sys::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY
2107 };
2108 e.capture_graph_retained_flags(iflag, move |e| {
2109 let mut xc: Option<CudaSlice<f32>> = None;
2110 for il in lo..hi {
2111 let xr: &CudaSlice<f32> = xc.as_ref().unwrap_or(xin);
2112 let nx = if let Some(&k) = lin_pos.get(&il) {
2113 model.qwen35_tparallel_linear_layer(
2114 e,
2115 il,
2116 xr,
2117 t,
2118 cache_ref,
2119 None,
2120 Some((&mut stash_conv[k], &mut stash_ssm[k])),
2121 Some((table_all, k * 6)),
2122 )?
2123 } else if let Some(&kf) = fa_pos.get(&il) {
2124 let mut no_rows: Option<Vec<CudaSlice<i32>>> = None;
2125 model.qwen35_tparallel_fa_layer(
2126 e,
2127 il,
2128 xr,
2129 t,
2130 cache_ref,
2131 FaLayerArgs {
2132 pos_d,
2133 pos_rows: &mut no_rows,
2134 pos0,
2135 seqs_append: true,
2136 batch_fa_on: true,
2137 graph_cap: Some((fa_table, kf * 2 * t_cap, rung)),
2138 stream: None,
2139 ckpt: None,
2140 },
2141 )?
2142 } else {
2143 return Err(format!(
2144 "run_full: layer {il} is neither linear nor full-attention"
2145 )
2146 .into());
2147 };
2148 xc = Some(nx);
2149 }
2150 e.copy_into(xout, 0, xc.as_ref().unwrap(), t * n_embd)?;
2151 Ok(())
2152 })?
2153 };
2154 // Undo the net host parity motion of the 3 body runs (each run swaps iff t
2155 // is odd -> 3 runs = net one swap), then restore the device state the
2156 // warmups consumed (walk scope only — layers past hi never executed). The
2157 // launch below then behaves exactly like one run.
2158 if t % 2 == 1 {
2159 for &il in &self.lin {
2160 if il < lo || il >= hi {
2161 continue;
2162 }
2163 let rl = cache.recur[il].as_mut().unwrap();
2164 std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
2165 }
2166 }
2167 for (k, &il) in self.lin.iter().enumerate() {
2168 if il < lo || il >= hi {
2169 continue;
2170 }
2171 let rl = cache.recur[il].as_mut().unwrap();
2172 let (cw, sw) = (self.conv_words, self.ssm_words);
2173 {
2174 let sv = e.view(&self.save_conv, self.lin.len() * cw);
2175 let win = sv.slice(k * cw..(k + 1) * cw);
2176 e.copy_view_into(&mut rl.conv_state, 0, &win, cw)?;
2177 }
2178 {
2179 let sv = e.view(&self.save_ssm, self.lin.len() * sw);
2180 let win = sv.slice(k * sw..(k + 1) * sw);
2181 e.copy_view_into(&mut rl.ssm_state, 0, &win, sw)?;
2182 }
2183 }
2184 if std::env::var("MEMRA_GRAPH_CENSUS").as_deref() == Ok("1") {
2185 if let Ok(c) = crate::graph_update::node_census(&graph) {
2186 eprintln!("[dspark-vg-census] full vt={t} rung={rung} {c:?}");
2187 }
2188 }
2189 self.full.insert(
2190 key,
2191 DsparkSegGraph {
2192 graph,
2193 _keeper: keeper,
2194 },
2195 );
2196 }
2197 self.full[&key].graph.launch()?;
2198 // Host bookkeeping for the replayed body (captured host code does not re-run):
2199 // gdn parity swap per linear layer (t odd), kv len bump per fa layer — scoped
2200 // to the WALK [lo, hi): the cache can carry extra state slots past it (the MTP
2201 // head layer's kv) that the walk never touches.
2202 if t % 2 == 1 {
2203 for &il in &self.lin {
2204 if il < lo || il >= hi {
2205 continue;
2206 }
2207 let rl = cache.recur[il].as_mut().unwrap();
2208 std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
2209 }
2210 }
2211 for &il in &self.fa {
2212 if il < lo || il >= hi {
2213 continue;
2214 }
2215 cache.kv[il].as_mut().unwrap().len += t;
2216 }
2217 let (_, xout) = self.stage.get(&t).unwrap();
2218 let mut out = e.uninit(t * n_embd)?;
2219 e.copy_into(&mut out, 0, xout, t * n_embd)?;
2220 Ok(out)
2221 }
2222
2223 /// Run layers [start, end) (all linear) as one captured graph at this vt: stage the
2224 /// residual into the bucket's x_in, capture on first encounter (2 executing warmups
2225 /// bracketed by a segment state save/restore), launch, then apply the host parity
2226 /// bookkeeping the captured body would have done. Returns the fresh residual.
2227 #[allow(clippy::too_many_arguments)]
2228 fn run_segment(
2229 &mut self,
2230 model: &crate::hybrid::HybridModel,
2231 e: &Engine,
2232 start: usize,
2233 end: usize,
2234 x: &CudaSlice<f32>,
2235 t: usize,
2236 cache: &mut Cache,
2237 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2238 let n_embd = self.n_embd;
2239 debug_assert!(end - start <= self.max_run);
2240 if !self.stage.contains_key(&t) {
2241 let xin = e.uninit(t * n_embd)?;
2242 let xout = e.uninit(t * n_embd)?;
2243 self.stage.insert(t, (xin, xout));
2244 }
2245 // Stage the residual at the bucket's baked input address.
2246 {
2247 let (xin, _) = self.stage.get_mut(&t).unwrap();
2248 e.copy_into(xin, 0, x, t * n_embd)?;
2249 }
2250 let key = (start, t);
2251 if !self.graphs.contains_key(&key) {
2252 // The 2 warmups EXECUTE the segment on live state — save conv + the canonical
2253 // ssm of every segment layer first, restore after, so the graph's first real
2254 // launch starts from the exact pre-round state (bytes gated e2e).
2255 for (k, il) in (start..end).enumerate() {
2256 let rl = cache.recur[il].as_ref().unwrap();
2257 e.copy_into(
2258 &mut self.save_conv,
2259 k * self.conv_words,
2260 &rl.conv_state,
2261 self.conv_words,
2262 )?;
2263 e.copy_into(
2264 &mut self.save_ssm,
2265 k * self.ssm_words,
2266 &rl.ssm_state,
2267 self.ssm_words,
2268 )?;
2269 }
2270 let (graph, keeper) = {
2271 let table_all = &self.table_all;
2272 let lin_pos = &self.lin_pos;
2273 let stash_conv = &mut self.stash_conv;
2274 let stash_ssm = &mut self.stash_ssm;
2275 let (xin, xout) = self
2276 .stage
2277 .get_mut(&t)
2278 .map(|(a, b)| (&*a, b))
2279 .expect("stage bucket created above");
2280 let cache_ref: &mut Cache = cache;
2281 // Slice 4 (fa-execupdate lane): USE_NODE_PRIORITY instead of
2282 // AUTO_FREE_ON_LAUNCH. The slice-3 measured limiter was AUTO_FREE's
2283 // launch-time mem-pool scan — 25.6 us per cuGraphLaunch x 16 segments
2284 // = ~0.41 ms/round, most of the eager-launch savings. The captured
2285 // body's cuMemAllocAsync transients are BALANCED by in-graph frees
2286 // (every transient drops inside the capture region — the generic
2287 // capture path's census precedent, 1589/1589), so AUTO_FREE has
2288 // nothing to reclaim and the graph is legal to instantiate without
2289 // it; PRIORITY is the flag the gemma slotted door ships for exactly
2290 // this reason (both alternatives drop the scan; UPLOAD via
2291 // cuGraphInstantiateWithFlags is WithParams-only and refused).
2292 // MEMRA_DSPARK_VG_AUTOFREE=1 reverts; MEMRA_GRAPH_CENSUS=1 prints
2293 // the node census at capture (the ALLOC==FREE receipt).
2294 let iflag = if std::env::var("MEMRA_DSPARK_VG_AUTOFREE").as_deref() == Ok("1") {
2295 cudarc::driver::sys::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH
2296 } else {
2297 cudarc::driver::sys::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY
2298 };
2299 e.capture_graph_retained_flags(iflag, move |e| {
2300 let mut xc: Option<CudaSlice<f32>> = None;
2301 for il in start..end {
2302 let k = lin_pos[&il];
2303 let xr: &CudaSlice<f32> = xc.as_ref().unwrap_or(xin);
2304 let nx = model.qwen35_tparallel_linear_layer(
2305 e,
2306 il,
2307 xr,
2308 t,
2309 cache_ref,
2310 None,
2311 Some((&mut stash_conv[k], &mut stash_ssm[k])),
2312 Some((table_all, k * 6)),
2313 )?;
2314 xc = Some(nx);
2315 }
2316 e.copy_into(xout, 0, xc.as_ref().unwrap(), t * n_embd)?;
2317 Ok(())
2318 })?
2319 };
2320 // Undo the net host parity motion of the 3 body runs (each run swaps iff t
2321 // is odd -> 3 runs = net one swap), then restore the device state the
2322 // warmups consumed. The launch below then behaves exactly like one run.
2323 if t % 2 == 1 {
2324 for il in start..end {
2325 let rl = cache.recur[il].as_mut().unwrap();
2326 std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
2327 }
2328 }
2329 for (k, il) in (start..end).enumerate() {
2330 let rl = cache.recur[il].as_mut().unwrap();
2331 let (cw, sw) = (self.conv_words, self.ssm_words);
2332 {
2333 let sv = e.view(&self.save_conv, self.lin.len() * cw);
2334 let win = sv.slice(k * cw..(k + 1) * cw);
2335 e.copy_view_into(&mut rl.conv_state, 0, &win, cw)?;
2336 }
2337 {
2338 let sv = e.view(&self.save_ssm, self.lin.len() * sw);
2339 let win = sv.slice(k * sw..(k + 1) * sw);
2340 e.copy_view_into(&mut rl.ssm_state, 0, &win, sw)?;
2341 }
2342 }
2343 if std::env::var("MEMRA_GRAPH_CENSUS").as_deref() == Ok("1") {
2344 if let Ok(c) = crate::graph_update::node_census(&graph) {
2345 eprintln!("[dspark-vg-census] seg={start}..{end} vt={t} {c:?}");
2346 }
2347 }
2348 self.graphs.insert(
2349 key,
2350 DsparkSegGraph {
2351 graph,
2352 _keeper: keeper,
2353 },
2354 );
2355 }
2356 self.graphs[&key].graph.launch()?;
2357 // Host parity bookkeeping for the replayed body (the captured host swaps do not
2358 // re-run at replay).
2359 if t % 2 == 1 {
2360 for il in start..end {
2361 let rl = cache.recur[il].as_mut().unwrap();
2362 std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
2363 }
2364 }
2365 let (_, xout) = self.stage.get(&t).unwrap();
2366 let mut out = e.uninit(t * n_embd)?;
2367 e.copy_into(&mut out, 0, xout, t * n_embd)?;
2368 Ok(out)
2369 }
2370
2371 /// Slab row (conv, ssm) device pointers + lengths for the commit restore of column
2372 /// `row` (0-based) of layer `il`. None for non-linear layers.
2373 pub(crate) fn slab_row(
2374 &self,
2375 e: &Engine,
2376 il: usize,
2377 row: usize,
2378 ) -> Option<(u64, u64, usize, usize)> {
2379 use cudarc::driver::DevicePtr;
2380 let k = *self.lin_pos.get(&il)?;
2381 let s = &e.gpu.stream();
2382 let (pc, _g0) = self.stash_conv[k].device_ptr(s);
2383 let (ps, _g1) = self.stash_ssm[k].device_ptr(s);
2384 Some((
2385 pc as u64 + (row * self.conv_words * 4) as u64,
2386 ps as u64 + (row * self.ssm_words * 4) as u64,
2387 self.conv_words,
2388 self.ssm_words,
2389 ))
2390 }
2391}
2392
2393impl VerifyCkpt {
2394 fn new(n_layer: usize) -> Self {
2395 VerifyCkpt {
2396 gdn: (0..n_layer).map(|_| None).collect(),
2397 cols: (0..n_layer).map(|_| None).collect(),
2398 }
2399 }
2400}
2401
2402/// The stage-0/TX half of one PP verify. The boundary slot is the ownership token: stage 1
2403/// consumes exactly the slot selected by `tx()` / `tx_pipelined()`, never a slot inferred from
2404/// a logical round number.
2405struct VerifyBoundaryTicket {
2406 rt: &'static crate::pp::PpNRt,
2407 caller_stream: std::sync::Arc<cudarc::driver::CudaStream>,
2408 slot: usize,
2409 pos0: usize,
2410 t: usize,
2411 payload: usize,
2412 n_st: usize,
2413 pipelined: bool,
2414 pp_anatomy: bool,
2415 pp_started: std::time::Instant,
2416 reverse_ms: f64,
2417 stage0_ms: f64,
2418 tx_ms: f64,
2419 trace: Option<SpecPipeTraceCtx>,
2420}
2421
2422/// Explicit OPTIPIPE diagnostic control. Forced modes are set only by `optipipe-gate`; the
2423/// increment-2 controller can also be armed by the server's fresh-process research door.
2424#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2425pub enum OptiForkGateMode {
2426 Disabled,
2427 Hit,
2428 Miss,
2429 Alternate,
2430 Abort,
2431 Controller,
2432}
2433
2434static OPTI_FORK_GATE_MODE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
2435static OPTI_CONTROLLER_THRESHOLD: std::sync::atomic::AtomicU32 =
2436 std::sync::atomic::AtomicU32::new(0);
2437static OPTI_FORK_ATTEMPTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2438static OPTI_FORK_HITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2439static OPTI_FORK_MISSES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2440static OPTI_FORK_ABORT_DRAINS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2441static OPTI_FORK_REFUSALS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2442static OPTI_GATE_CHECKS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2443static OPTI_GATE_ADMITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2444static OPTI_GATE_REJECTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2445static OPTI_RECONCILES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2446static OPTI_WASTED_DRAFT_TOKENS: std::sync::atomic::AtomicU64 =
2447 std::sync::atomic::AtomicU64::new(0);
2448static OPTI_SHADOW_DRAFT_TOKENS: std::sync::atomic::AtomicU64 =
2449 std::sync::atomic::AtomicU64::new(0);
2450static OPTI_BREAKER_TRIPS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2451
2452impl OptiForkGateMode {
2453 fn code(self) -> u8 {
2454 match self {
2455 Self::Disabled => 0,
2456 Self::Hit => 1,
2457 Self::Miss => 2,
2458 Self::Alternate => 3,
2459 Self::Abort => 4,
2460 Self::Controller => 5,
2461 }
2462 }
2463
2464 fn configured() -> Self {
2465 match OPTI_FORK_GATE_MODE.load(std::sync::atomic::Ordering::Relaxed) {
2466 1 => Self::Hit,
2467 2 => Self::Miss,
2468 3 => Self::Alternate,
2469 4 => Self::Abort,
2470 5 => Self::Controller,
2471 _ => Self::Disabled,
2472 }
2473 }
2474
2475 fn action(self, generation: u64) -> OptiForkAction {
2476 match self {
2477 Self::Hit => OptiForkAction::Hit,
2478 Self::Miss => OptiForkAction::Miss,
2479 Self::Alternate if generation & 1 == 0 => OptiForkAction::Hit,
2480 Self::Alternate => OptiForkAction::Miss,
2481 Self::Abort => OptiForkAction::Abort,
2482 Self::Disabled | Self::Controller => {
2483 unreachable!("non-forced mode cannot choose a forced fork action")
2484 }
2485 }
2486 }
2487
2488 fn is_forced(self) -> bool {
2489 matches!(self, Self::Hit | Self::Miss | Self::Alternate | Self::Abort)
2490 }
2491}
2492
2493/// Arm or disarm the forced harness. Serving uses only `set_optipipe_controller_threshold`.
2494pub fn set_optipipe_gate_mode(mode: OptiForkGateMode) {
2495 OPTI_FORK_GATE_MODE.store(mode.code(), std::sync::atomic::Ordering::Relaxed);
2496}
2497
2498/// Arm the increment-2 diagnostic controller. The threshold applies to the uncalibrated
2499/// two-token draft-probability product. Serving can call this only through its explicit
2500/// fresh-process research door; the absent-door default remains byte-for-byte disabled.
2501pub fn set_optipipe_controller_threshold(threshold: f32) {
2502 assert!(threshold.is_finite() && (0.0..=1.0).contains(&threshold));
2503 OPTI_CONTROLLER_THRESHOLD.store(threshold.to_bits(), std::sync::atomic::Ordering::Relaxed);
2504 set_optipipe_gate_mode(OptiForkGateMode::Controller);
2505}
2506
2507#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2508pub struct OptiForkGateStats {
2509 pub attempts: u64,
2510 pub hits: u64,
2511 pub misses: u64,
2512 pub abort_drains: u64,
2513 pub refusals: u64,
2514 pub gate_checks: u64,
2515 pub gate_admits: u64,
2516 pub gate_rejects: u64,
2517 pub reconciles: u64,
2518 pub wasted_draft_tokens: u64,
2519 pub shadow_draft_tokens: u64,
2520 pub breaker_trips: u64,
2521}
2522
2523#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2524pub struct OptiForkStateIdentity {
2525 pub trunk_kv_bytes: usize,
2526 pub recurrent_bytes: usize,
2527 pub scratch_kv_bytes: usize,
2528 pub hidden_bytes: usize,
2529}
2530
2531pub fn reset_optipipe_gate_stats() {
2532 for counter in [
2533 &OPTI_FORK_ATTEMPTS,
2534 &OPTI_FORK_HITS,
2535 &OPTI_FORK_MISSES,
2536 &OPTI_FORK_ABORT_DRAINS,
2537 &OPTI_FORK_REFUSALS,
2538 &OPTI_GATE_CHECKS,
2539 &OPTI_GATE_ADMITS,
2540 &OPTI_GATE_REJECTS,
2541 &OPTI_RECONCILES,
2542 &OPTI_WASTED_DRAFT_TOKENS,
2543 &OPTI_SHADOW_DRAFT_TOKENS,
2544 &OPTI_BREAKER_TRIPS,
2545 ] {
2546 counter.store(0, std::sync::atomic::Ordering::Relaxed);
2547 }
2548}
2549
2550pub fn optipipe_gate_stats() -> OptiForkGateStats {
2551 let load = |v: &std::sync::atomic::AtomicU64| v.load(std::sync::atomic::Ordering::Relaxed);
2552 OptiForkGateStats {
2553 attempts: load(&OPTI_FORK_ATTEMPTS),
2554 hits: load(&OPTI_FORK_HITS),
2555 misses: load(&OPTI_FORK_MISSES),
2556 abort_drains: load(&OPTI_FORK_ABORT_DRAINS),
2557 refusals: load(&OPTI_FORK_REFUSALS),
2558 gate_checks: load(&OPTI_GATE_CHECKS),
2559 gate_admits: load(&OPTI_GATE_ADMITS),
2560 gate_rejects: load(&OPTI_GATE_REJECTS),
2561 reconciles: load(&OPTI_RECONCILES),
2562 wasted_draft_tokens: load(&OPTI_WASTED_DRAFT_TOKENS),
2563 shadow_draft_tokens: load(&OPTI_SHADOW_DRAFT_TOKENS),
2564 breaker_trips: load(&OPTI_BREAKER_TRIPS),
2565 }
2566}
2567
2568#[derive(Clone, Copy, Debug)]
2569struct OptiControllerPolicy {
2570 threshold: f32,
2571 consecutive_misses: u8,
2572 breaker_tripped: bool,
2573}
2574
2575impl OptiControllerPolicy {
2576 fn configured() -> Self {
2577 Self {
2578 threshold: f32::from_bits(
2579 OPTI_CONTROLLER_THRESHOLD.load(std::sync::atomic::Ordering::Relaxed),
2580 ),
2581 consecutive_misses: 0,
2582 breaker_tripped: false,
2583 }
2584 }
2585
2586 fn admit(&self, q_proxy: f32) -> bool {
2587 q_proxy.is_finite()
2588 && (0.0..=1.0).contains(&q_proxy)
2589 && (self.threshold == 0.0 || (!self.breaker_tripped && q_proxy >= self.threshold))
2590 }
2591
2592 /// Returns true exactly when this resolution newly trips the three-miss breaker.
2593 fn resolve(&mut self, hit: bool) -> bool {
2594 // q*=0 is the lane's explicit unconditional measurement arm. Its purpose is to price
2595 // every optimistic opportunity, so the safety breaker is measured separately and must
2596 // not silently turn this arm into "three attempts then serial".
2597 if self.threshold == 0.0 {
2598 self.consecutive_misses = 0;
2599 return false;
2600 }
2601 if hit {
2602 self.consecutive_misses = 0;
2603 return false;
2604 }
2605 self.consecutive_misses = self.consecutive_misses.saturating_add(1);
2606 if !self.breaker_tripped && self.consecutive_misses >= 3 {
2607 self.breaker_tripped = true;
2608 return true;
2609 }
2610 false
2611 }
2612}
2613
2614#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2615enum OptiForkAction {
2616 Hit,
2617 Miss,
2618 Abort,
2619}
2620
2621#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2622struct OptiForkGeneration {
2623 id: u64,
2624 slot: usize,
2625}
2626
2627#[derive(Default)]
2628struct OptiForkGenerationTracker {
2629 next: u64,
2630 live: [Option<u64>; 2],
2631}
2632
2633impl OptiForkGenerationTracker {
2634 fn reserve(&mut self) -> Result<OptiForkGeneration, Box<dyn std::error::Error>> {
2635 let generation = OptiForkGeneration {
2636 id: self.next,
2637 slot: (self.next & 1) as usize,
2638 };
2639 if let Some(live) = self.live[generation.slot] {
2640 return Err(format!(
2641 "optipipe snapshot slot {} still owns generation {live}; refusing to overwrite it",
2642 generation.slot,
2643 )
2644 .into());
2645 }
2646 self.next += 1;
2647 self.live[generation.slot] = Some(generation.id);
2648 Ok(generation)
2649 }
2650
2651 fn retire(&mut self, generation: OptiForkGeneration) -> Result<(), Box<dyn std::error::Error>> {
2652 match self.live[generation.slot] {
2653 Some(id) if id == generation.id => {
2654 self.live[generation.slot] = None;
2655 Ok(())
2656 }
2657 other => Err(format!(
2658 "optipipe generation teardown mismatch: ticket={} slot={} live={other:?}",
2659 generation.id, generation.slot,
2660 )
2661 .into()),
2662 }
2663 }
2664}
2665
2666struct OptiForkSeedGeneration {
2667 h_seed: CudaSlice<f32>,
2668 fill_prev: CudaSlice<f32>,
2669 scratch_len: usize,
2670}
2671
2672/// Allocate or refresh one full checkpoint through the engine that owns each PP stage. The
2673/// generic cache helper accepts one device and therefore cannot copy GDN state split across
2674/// devices. KV lengths and position stay host metadata; only recurrent buffers need stage-local
2675/// device ownership.
2676fn opti_snapshot_stage_owned(
2677 e: &Engine,
2678 cache: &Cache,
2679 rt: &'static crate::pp::PpNRt,
2680 fence: &[usize],
2681) -> Result<crate::cache::CacheSnapshot, Box<dyn std::error::Error>> {
2682 let n = cache.kv.len();
2683 let mut snapshot = crate::cache::CacheSnapshot {
2684 kv_len: vec![None; n],
2685 conv: (0..n).map(|_| None).collect(),
2686 ssm: (0..n).map(|_| None).collect(),
2687 pos: cache.pos,
2688 };
2689 opti_snapshot_stage_owned_into(e, cache, rt, fence, &mut snapshot)?;
2690 Ok(snapshot)
2691}
2692
2693fn opti_snapshot_stage_owned_into(
2694 e: &Engine,
2695 cache: &Cache,
2696 rt: &'static crate::pp::PpNRt,
2697 fence: &[usize],
2698 snapshot: &mut crate::cache::CacheSnapshot,
2699) -> Result<(), Box<dyn std::error::Error>> {
2700 if fence.len() != rt.n_stages() + 1 || snapshot.kv_len.len() != cache.kv.len() {
2701 return Err("optipipe stage-owned snapshot shape mismatch".into());
2702 }
2703 for stage in 0..rt.n_stages() {
2704 opti_snapshot_one_stage_owned_into(e, cache, rt, fence, stage, snapshot)?;
2705 }
2706 snapshot.pos = cache.pos;
2707 Ok(())
2708}
2709
2710/// Refresh one PP stage of a checkpoint. Increment 2 uses this split form so stage 0's
2711/// optimistic post-N state is captured before N+1 stage 0 is queued, while stage 1's matching
2712/// post-N state is captured only after N stage 1 is enqueued. Calling the all-stage helper at
2713/// either point would capture one side of the fork at the wrong generation.
2714fn opti_snapshot_one_stage_owned_into(
2715 e: &Engine,
2716 cache: &Cache,
2717 rt: &'static crate::pp::PpNRt,
2718 fence: &[usize],
2719 stage: usize,
2720 snapshot: &mut crate::cache::CacheSnapshot,
2721) -> Result<(), Box<dyn std::error::Error>> {
2722 if fence.len() != rt.n_stages() + 1
2723 || snapshot.kv_len.len() != cache.kv.len()
2724 || stage >= rt.n_stages()
2725 {
2726 return Err("optipipe single-stage snapshot shape mismatch".into());
2727 }
2728 let _scope = rt.enter(stage);
2729 let owner = rt.engine(stage, e);
2730 for il in fence[stage]..fence[stage + 1] {
2731 snapshot.kv_len[il] = cache.kv[il].as_ref().map(|kv| kv.len);
2732 match &cache.recur[il] {
2733 Some(recur) => {
2734 match snapshot.conv[il].as_mut() {
2735 Some(dst) => {
2736 owner.copy_into(dst, 0, &recur.conv_state, recur.conv_state.len())?
2737 }
2738 None => snapshot.conv[il] = Some(owner.clone_dtod(&recur.conv_state)?),
2739 }
2740 match snapshot.ssm[il].as_mut() {
2741 Some(dst) => {
2742 owner.copy_into(dst, 0, &recur.ssm_state, recur.ssm_state.len())?
2743 }
2744 None => snapshot.ssm[il] = Some(owner.clone_dtod(&recur.ssm_state)?),
2745 }
2746 }
2747 None if snapshot.conv[il].is_some() || snapshot.ssm[il].is_some() => {
2748 return Err(
2749 format!("optipipe stage-owned snapshot layer {il} changed shape").into(),
2750 );
2751 }
2752 None => {}
2753 }
2754 }
2755 snapshot.pos = cache.pos;
2756 Ok(())
2757}
2758
2759/// Increment-1 persistent fork state. Exactly two snapshot/seed slots alternate; a live ticket
2760/// names its generation and keeps teardown fail-closed. Only stage 0 is allowed to mutate before
2761/// resolve, so the reconcile tables and conditional restores are stage-local.
2762struct OptiForkState {
2763 mode: OptiForkGateMode,
2764 controller: Option<OptiControllerPolicy>,
2765 generations: OptiForkGenerationTracker,
2766 active_snapshot_slot: usize,
2767 alternate_snapshot: crate::cache::CacheSnapshot,
2768 seeds: [OptiForkSeedGeneration; 2],
2769 rt: &'static crate::pp::PpNRt,
2770 fence: [usize; 3],
2771 split: usize,
2772 len_ptrs: CudaSlice<u64>,
2773 saved_lens: CudaSlice<i32>,
2774 forced_acc: CudaSlice<u32>,
2775 valid: CudaSlice<u32>,
2776 stage0_stream: std::sync::Arc<cudarc::driver::CudaStream>,
2777 logical_payload_bytes: [usize; 2],
2778}
2779
2780struct OptiForkTicket {
2781 generation: OptiForkGeneration,
2782 boundary: Option<VerifyBoundaryTicket>,
2783 drain: std::sync::Arc<cudarc::driver::CudaStream>,
2784 settled: bool,
2785}
2786
2787struct OptiControllerTicket {
2788 generation: OptiForkGeneration,
2789 boundary: Option<VerifyBoundaryTicket>,
2790 ckpt: Option<VerifyCkpt>,
2791 verify_tokens: [u32; 2],
2792 draft_prob: f32,
2793 eager_seed: Option<CudaSlice<f32>>,
2794 q_proxy: f32,
2795 scratch_len: usize,
2796 issued_at: std::time::Instant,
2797 drain: std::sync::Arc<cudarc::driver::CudaStream>,
2798 settled: bool,
2799}
2800
2801struct OptiControllerPrepared {
2802 verify_tokens: [u32; 2],
2803 draft_prob: f32,
2804 eager_seed: Option<CudaSlice<f32>>,
2805 q_proxy: f32,
2806 scratch_len: usize,
2807}
2808
2809impl OptiControllerTicket {
2810 fn take_boundary(&mut self) -> VerifyBoundaryTicket {
2811 self.boundary
2812 .take()
2813 .expect("controller boundary ticket already consumed")
2814 }
2815
2816 fn take_ckpt(&mut self) -> VerifyCkpt {
2817 self.ckpt
2818 .take()
2819 .expect("controller verify checkpoint already consumed")
2820 }
2821
2822 fn take_eager_seed(&mut self) -> Option<CudaSlice<f32>> {
2823 self.eager_seed.take()
2824 }
2825
2826 fn settle(&mut self) {
2827 self.settled = true;
2828 }
2829}
2830
2831impl Drop for OptiControllerTicket {
2832 fn drop(&mut self) {
2833 if !self.settled {
2834 let _ = self.drain.synchronize();
2835 OPTI_FORK_ABORT_DRAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2836 }
2837 }
2838}
2839
2840impl OptiForkTicket {
2841 fn take_boundary(&mut self) -> VerifyBoundaryTicket {
2842 self.boundary
2843 .take()
2844 .expect("fork ticket boundary already consumed")
2845 }
2846
2847 fn settle(&mut self) {
2848 self.settled = true;
2849 }
2850}
2851
2852impl Drop for OptiForkTicket {
2853 fn drop(&mut self) {
2854 if !self.settled {
2855 let _ = self.drain.synchronize();
2856 OPTI_FORK_ABORT_DRAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2857 }
2858 }
2859}
2860
2861impl OptiForkState {
2862 #[allow(clippy::too_many_arguments)]
2863 fn new(
2864 e: &Engine,
2865 cache: &Cache,
2866 mode: OptiForkGateMode,
2867 alternate_snapshot: crate::cache::CacheSnapshot,
2868 h_seed: &CudaSlice<f32>,
2869 fill_prev: &CudaSlice<f32>,
2870 rt: &'static crate::pp::PpNRt,
2871 split: usize,
2872 n_layer: usize,
2873 ) -> Result<Self, Box<dyn std::error::Error>> {
2874 let fence = [0, split, n_layer];
2875 let mut logical_payload_bytes = [0usize; 2];
2876 for stage in 0..2 {
2877 for il in fence[stage]..fence[stage + 1] {
2878 logical_payload_bytes[stage] += alternate_snapshot.conv[il]
2879 .as_ref()
2880 .map_or(0, |v| v.len() * std::mem::size_of::<f32>());
2881 logical_payload_bytes[stage] += alternate_snapshot.ssm[il]
2882 .as_ref()
2883 .map_or(0, |v| v.len() * std::mem::size_of::<f32>());
2884 }
2885 }
2886 let seeds = [
2887 OptiForkSeedGeneration {
2888 h_seed: e.clone_dtod(h_seed)?,
2889 fill_prev: e.clone_dtod(fill_prev)?,
2890 scratch_len: 0,
2891 },
2892 OptiForkSeedGeneration {
2893 h_seed: e.clone_dtod(h_seed)?,
2894 fill_prev: e.clone_dtod(fill_prev)?,
2895 scratch_len: 0,
2896 },
2897 ];
2898 let (len_ptrs, saved_lens, forced_acc, valid, stage0_stream) = {
2899 let _stage = rt.enter(0);
2900 let e0 = rt.engine(0, e);
2901 (
2902 crate::round_stream::kv_len_ptr_table_range(e0, cache, 0..split, None)?,
2903 e0.htod_i32(&vec![0; split])?,
2904 e0.alloc_u32_zeroed(2)?,
2905 e0.alloc_u32_zeroed(1)?,
2906 e0.stream(),
2907 )
2908 };
2909 logical_payload_bytes[0] += seeds
2910 .iter()
2911 .map(|seed| (seed.h_seed.len() + seed.fill_prev.len()) * std::mem::size_of::<f32>())
2912 .sum::<usize>();
2913 logical_payload_bytes[0] += len_ptrs.len() * std::mem::size_of::<u64>()
2914 + saved_lens.len() * std::mem::size_of::<i32>()
2915 + forced_acc.len() * std::mem::size_of::<u32>()
2916 + valid.len() * std::mem::size_of::<u32>();
2917 Ok(Self {
2918 mode,
2919 controller: (mode == OptiForkGateMode::Controller)
2920 .then(OptiControllerPolicy::configured),
2921 generations: OptiForkGenerationTracker::default(),
2922 active_snapshot_slot: 0,
2923 alternate_snapshot,
2924 seeds,
2925 rt,
2926 fence,
2927 split,
2928 len_ptrs,
2929 saved_lens,
2930 forced_acc,
2931 valid,
2932 stage0_stream,
2933 logical_payload_bytes,
2934 })
2935 }
2936
2937 fn reserve(
2938 &mut self,
2939 current_snapshot: &mut crate::cache::CacheSnapshot,
2940 ) -> Result<OptiForkGeneration, Box<dyn std::error::Error>> {
2941 let generation = self.generations.reserve()?;
2942 if generation.slot != self.active_snapshot_slot {
2943 std::mem::swap(current_snapshot, &mut self.alternate_snapshot);
2944 self.active_snapshot_slot = generation.slot;
2945 }
2946 Ok(generation)
2947 }
2948
2949 fn capture_seed(
2950 &mut self,
2951 e: &Engine,
2952 generation: OptiForkGeneration,
2953 h_seed: &CudaSlice<f32>,
2954 fill_prev: &CudaSlice<f32>,
2955 scratch_len: usize,
2956 ) -> Result<(), Box<dyn std::error::Error>> {
2957 let seed = &mut self.seeds[generation.slot];
2958 e.copy_into(&mut seed.h_seed, 0, h_seed, h_seed.len())?;
2959 e.copy_into(&mut seed.fill_prev, 0, fill_prev, fill_prev.len())?;
2960 seed.scratch_len = scratch_len;
2961 Ok(())
2962 }
2963
2964 fn ticket(
2965 &self,
2966 generation: OptiForkGeneration,
2967 boundary: VerifyBoundaryTicket,
2968 ) -> OptiForkTicket {
2969 OptiForkTicket {
2970 generation,
2971 boundary: Some(boundary),
2972 drain: self.stage0_stream.clone(),
2973 settled: false,
2974 }
2975 }
2976
2977 #[allow(clippy::too_many_arguments)]
2978 fn controller_ticket(
2979 &self,
2980 generation: OptiForkGeneration,
2981 boundary: VerifyBoundaryTicket,
2982 ckpt: VerifyCkpt,
2983 verify_tokens: [u32; 2],
2984 draft_prob: f32,
2985 eager_seed: Option<CudaSlice<f32>>,
2986 q_proxy: f32,
2987 scratch_len: usize,
2988 ) -> OptiControllerTicket {
2989 OptiControllerTicket {
2990 generation,
2991 boundary: Some(boundary),
2992 ckpt: Some(ckpt),
2993 verify_tokens,
2994 draft_prob,
2995 eager_seed,
2996 q_proxy,
2997 scratch_len,
2998 issued_at: std::time::Instant::now(),
2999 drain: self.stage0_stream.clone(),
3000 settled: false,
3001 }
3002 }
3003
3004 fn reserve_successor(&mut self) -> Result<OptiForkGeneration, Box<dyn std::error::Error>> {
3005 self.generations.reserve()
3006 }
3007
3008 fn successor_snapshot_mut(&mut self) -> &mut crate::cache::CacheSnapshot {
3009 &mut self.alternate_snapshot
3010 }
3011
3012 fn promote_successor_snapshot(
3013 &mut self,
3014 current_snapshot: &mut crate::cache::CacheSnapshot,
3015 generation: OptiForkGeneration,
3016 ) {
3017 std::mem::swap(current_snapshot, &mut self.alternate_snapshot);
3018 self.active_snapshot_slot = generation.slot;
3019 }
3020
3021 fn queue_actual_reconcile(
3022 &mut self,
3023 e: &Engine,
3024 snapshot: &crate::cache::CacheSnapshot,
3025 acc: &CudaSlice<u32>,
3026 optimistic_pending: u32,
3027 base: usize,
3028 ) -> Result<(), Box<dyn std::error::Error>> {
3029 let saved: Vec<i32> = (0..self.split)
3030 .map(|il| snapshot.kv_len[il].map(|v| v as i32).unwrap_or(0))
3031 .collect();
3032 // Serving keeps the caller/accept walk on the head (stage-1) device. Record the accept
3033 // decision point there and append a wait to stage 0 after its optimistic successor/TX;
3034 // the validity/reconcile kernels must never peer-read acc before it is written. The
3035 // increment-1 harness uses primary stage 0, where stream order already provides this.
3036 if self.rt.engine(0, e).ctx().ordinal() != e.ctx().ordinal() {
3037 self.rt.fence_stages_behind(&e.stream())?;
3038 }
3039 let _stage = self.rt.enter(0);
3040 let e0 = self.rt.engine(0, e);
3041 e0.htod_i32_into(&mut self.saved_lens, &saved)?;
3042 e0.spec_fork_valid(acc, optimistic_pending, &mut self.valid)?;
3043 e0.spec_fork_reconcile_kv(
3044 &self.len_ptrs,
3045 &self.saved_lens,
3046 acc,
3047 &self.valid,
3048 base,
3049 self.split,
3050 )
3051 }
3052
3053 fn finish_actual_reconcile(
3054 &mut self,
3055 e: &Engine,
3056 cache: &mut Cache,
3057 snapshot: &crate::cache::CacheSnapshot,
3058 n_acc: usize,
3059 base: usize,
3060 hit: bool,
3061 ) -> Result<(), Box<dyn std::error::Error>> {
3062 if hit {
3063 return Ok(());
3064 }
3065 let len_delta = base + n_acc;
3066 for il in 0..self.split {
3067 if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
3068 kv.len = saved + len_delta;
3069 }
3070 }
3071 {
3072 let _stage = self.rt.enter(1);
3073 let e1 = self.rt.engine(1, e);
3074 for il in self.split..self.fence[2] {
3075 if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
3076 kv.len = saved + len_delta;
3077 e1.set_i32_one(&mut kv.len_d, kv.len as i32)?;
3078 }
3079 }
3080 }
3081 self.rt.publish_to(0, &e.stream())?;
3082 Ok(())
3083 }
3084
3085 fn cancel_controller_ticket(
3086 &mut self,
3087 e: &Engine,
3088 cache: &mut Cache,
3089 scratch: &mut MtpScratch,
3090 snapshot: &crate::cache::CacheSnapshot,
3091 ticket: &mut OptiControllerTicket,
3092 ) -> Result<(), Box<dyn std::error::Error>> {
3093 {
3094 let _stage = self.rt.enter(0);
3095 let e0 = self.rt.engine(0, e);
3096 for il in 0..self.split {
3097 if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
3098 kv.len = saved;
3099 e0.set_i32_one(&mut kv.len_d, saved as i32)?;
3100 }
3101 }
3102 }
3103 scratch.set_len(e, snapshot.pos)?;
3104 ticket.settle();
3105 self.generations.retire(ticket.generation)?;
3106 OPTI_FORK_ABORT_DRAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3107 OPTI_WASTED_DRAFT_TOKENS.fetch_add(2, std::sync::atomic::Ordering::Relaxed);
3108 eprintln!(
3109 "[opti-controller] tail-drain generation={} slot={}",
3110 ticket.generation.id, ticket.generation.slot,
3111 );
3112 Ok(())
3113 }
3114
3115 #[allow(clippy::too_many_arguments)]
3116 fn reconcile(
3117 &mut self,
3118 e: &Engine,
3119 cache: &mut Cache,
3120 scratch: &mut MtpScratch,
3121 snapshot: &crate::cache::CacheSnapshot,
3122 h_seed: &mut CudaSlice<f32>,
3123 fill_prev: &mut CudaSlice<f32>,
3124 generation: OptiForkGeneration,
3125 action: OptiForkAction,
3126 optimistic_pending: u32,
3127 ) -> Result<(), Box<dyn std::error::Error>> {
3128 debug_assert!(action != OptiForkAction::Abort);
3129 let miss_started = std::time::Instant::now();
3130 let keep = action == OptiForkAction::Hit;
3131 let saved: Vec<i32> = (0..self.split)
3132 .map(|il| snapshot.kv_len[il].map(|v| v as i32).unwrap_or(0))
3133 .collect();
3134 let seed = &self.seeds[generation.slot];
3135 {
3136 let _stage = self.rt.enter(0);
3137 let e0 = self.rt.engine(0, e);
3138 e0.htod_i32_into(&mut self.saved_lens, &saved)?;
3139 let forced = if keep {
3140 [1u32, optimistic_pending]
3141 } else {
3142 [0u32, optimistic_pending]
3143 };
3144 e0.htod_u32_into(&mut self.forced_acc, &forced)?;
3145 e0.spec_fork_valid(&self.forced_acc, optimistic_pending, &mut self.valid)?;
3146 e0.spec_fork_reconcile_kv(
3147 &self.len_ptrs,
3148 &self.saved_lens,
3149 &self.forced_acc,
3150 &self.valid,
3151 0,
3152 self.split,
3153 )?;
3154 for il in 0..self.split {
3155 if let Some(recur) = cache.recur[il].as_mut() {
3156 let conv = snapshot.conv[il]
3157 .as_ref()
3158 .ok_or("optipipe stage0 snapshot missing conv state")?;
3159 let ssm = snapshot.ssm[il]
3160 .as_ref()
3161 .ok_or("optipipe stage0 snapshot missing ssm state")?;
3162 e0.spec_fork_restore_f32(conv, &mut recur.conv_state, &self.valid)?;
3163 e0.spec_fork_restore_f32(ssm, &mut recur.ssm_state, &self.valid)?;
3164 }
3165 }
3166 e0.spec_fork_restore_f32(&seed.h_seed, h_seed, &self.valid)?;
3167 e0.spec_fork_restore_f32(&seed.fill_prev, fill_prev, &self.valid)?;
3168 }
3169
3170 if keep {
3171 OPTI_FORK_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3172 return Ok(());
3173 }
3174
3175 for il in 0..self.split {
3176 if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
3177 kv.len = saved;
3178 }
3179 }
3180 scratch.set_len(e, seed.scratch_len)?;
3181 // Targeted E_restart: publish only stage 0's reconcile to the caller, then bound the
3182 // forced diagnostic so the retained number is the actual miss cost, not enqueue time.
3183 let caller = e.stream();
3184 self.rt.publish_to(0, &caller)?;
3185 caller.synchronize()?;
3186 let miss_ms = miss_started.elapsed().as_secs_f64() * 1e3;
3187 eprintln!(
3188 "[opti-fork-reconcile] generation={} slot={} miss_ms={miss_ms:.3}",
3189 generation.id, generation.slot,
3190 );
3191 OPTI_FORK_MISSES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3192 Ok(())
3193 }
3194
3195 fn retire(&mut self, generation: OptiForkGeneration) -> Result<(), Box<dyn std::error::Error>> {
3196 self.generations.retire(generation)
3197 }
3198}
3199
3200impl HybridModel {
3201 fn opti_graph_draft_step(
3202 &self,
3203 e: &Engine,
3204 mtp: &MtpHead,
3205 dctx: &mut DraftGraphCtx,
3206 scratch: &mut MtpScratch,
3207 d_vocab: usize,
3208 ) -> Result<(u32, f32), Box<dyn std::error::Error>> {
3209 dctx.graph
3210 .as_ref()
3211 .ok_or("optipipe controller requires the greedy draft graph")?
3212 .launch()?;
3213 scratch.kv.len += 1;
3214 let idx = e.dtoh_u32_one(&dctx.g_tok)?;
3215 if (idx as usize) >= d_vocab {
3216 return Err(
3217 format!("optipipe draft argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab}").into(),
3218 );
3219 }
3220 let probability = e.dtoh(&dctx.g_p)?[0];
3221 if !probability.is_finite() || !(0.0..=1.0).contains(&probability) {
3222 return Err(format!("optipipe draft probability is invalid: {probability}").into());
3223 }
3224 let token = match &mtp.d2t {
3225 Some(map) => map[idx as usize],
3226 None => idx,
3227 };
3228 if token != idx {
3229 e.set_u32_one(&mut dctx.g_tok, token)?;
3230 }
3231 Ok((token, probability))
3232 }
3233
3234 #[allow(clippy::too_many_arguments)]
3235 fn opti_controller_draft_step(
3236 &self,
3237 e: &Engine,
3238 mtp: &MtpHead,
3239 dctx: &mut DraftGraphCtx,
3240 scratch: &mut MtpScratch,
3241 d_vocab: usize,
3242 eager_state: &mut Option<(u32, CudaSlice<f32>)>,
3243 eager_pos: usize,
3244 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3245 ) -> Result<(u32, f32), Box<dyn std::error::Error>> {
3246 if dctx.graph.is_some() {
3247 return self.opti_graph_draft_step(e, mtp, dctx, scratch, d_vocab);
3248 }
3249 let (input_token, input_seed) = eager_state
3250 .take()
3251 .ok_or("optipipe eager continuation seed is unavailable")?;
3252 let (logits, next_seed) = self.mtp_head_forward_dev(
3253 e,
3254 mtp,
3255 input_token,
3256 &input_seed,
3257 scratch,
3258 eager_pos,
3259 embd_dev,
3260 None,
3261 )?;
3262 let token_d = e.argmax_token_device(&logits, d_vocab)?;
3263 let idx = e.dtoh_u32_one(&token_d)?;
3264 if (idx as usize) >= d_vocab {
3265 return Err(format!(
3266 "optipipe eager draft argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab}"
3267 )
3268 .into());
3269 }
3270 let probability_d = e.prob_of_token_device(&logits, &token_d, d_vocab)?;
3271 let probability = e.dtoh(&probability_d)?[0];
3272 if !probability.is_finite() || !(0.0..=1.0).contains(&probability) {
3273 return Err(
3274 format!("optipipe eager draft probability is invalid: {probability}").into(),
3275 );
3276 }
3277 let token = match &mtp.d2t {
3278 Some(map) => map[idx as usize],
3279 None => idx,
3280 };
3281 *eager_state = Some((token, next_seed));
3282 Ok((token, probability))
3283 }
3284
3285 /// NextN head forward for ONE draft token (§A ops 1-13, T=1).
3286 /// Inputs: `e_tok` = the token to predict FROM (last committed / previous draft); `h_seed` =
3287 /// the trunk's pre-output_norm hidden of that token (§A op 2 input). `mtp_pos` = absolute
3288 /// position of the token being predicted from. Returns (draft_logits[n_vocab] host, h_nextn dev).
3289 /// `h_nextn` (§A op 10) becomes `h_seed` for the next autoregressive draft step.
3290 /// Device-resident: returns draft logits ON DEVICE (no [n_vocab] dtoh). The greedy draft
3291 /// loop only needs argmax — paired with `argmax_token_device` this cuts the ~600KB logits
3292 /// transfer + host argmax per draft token from the K-token draft chain.
3293 #[allow(clippy::too_many_arguments)]
3294 fn mtp_head_forward_dev(
3295 &self,
3296 e: &Engine,
3297 mtp: &MtpHead,
3298 e_tok: u32,
3299 h_seed: &CudaSlice<f32>,
3300 scratch: &mut MtpScratch,
3301 mtp_pos: usize,
3302 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3303 // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): (packed draft-vocab allowed set, words).
3304 // Applied to the head logits BEFORE they are returned, so every consumer (argmax,
3305 // gumbel draw, p-min prob) sees the grammar-legal row. None = unmasked (pre-lane).
3306 mask: Option<(&CudaSlice<u32>, usize)>,
3307 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3308 // MEMRA_SPEC_ANATOMY=1 — eager-step phase timers (diagnostic only). Phase boundaries
3309 // sync the stream, so absolute time inflates; the BREAKDOWN is the signal. Cumulative
3310 // summary on stderr every 128 steps: glue (embed..attn_norm), attn, ffn, head.
3311 use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
3312 static ANAT_NS: [AtomicU64; 5] = [
3313 AtomicU64::new(0),
3314 AtomicU64::new(0),
3315 AtomicU64::new(0),
3316 AtomicU64::new(0),
3317 AtomicU64::new(0),
3318 ];
3319 static ANAT_STEPS: AtomicU64 = AtomicU64::new(0);
3320 let anat = {
3321 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
3322 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_ANATOMY").as_deref() == Ok("1"))
3323 };
3324 if anat {
3325 e.stream().synchronize()?; // drain prior queue so phase 0 starts clean
3326 }
3327 let t_all = std::time::Instant::now();
3328 let mut t_ph = std::time::Instant::now();
3329 let mut anat_mark = |i: usize,
3330 e: &Engine,
3331 t: &mut std::time::Instant|
3332 -> Result<(), Box<dyn std::error::Error>> {
3333 if anat {
3334 e.stream().synchronize()?;
3335 ANAT_NS[i].fetch_add(t.elapsed().as_nanos() as u64, Relaxed);
3336 *t = std::time::Instant::now();
3337 }
3338 Ok(())
3339 };
3340 let cfg = &self.cfg;
3341 let n_embd = cfg.n_embd as usize;
3342 // Distilled-student geometry: the block runs at the INNER width `di` (eh_proj out /
3343 // attn / ffn); the n_embd interface (embed, norms in, carrier out, head in) is unchanged.
3344 let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
3345 let eps = cfg.rms_eps;
3346 let pos_d = e.htod_i32(&[mtp_pos as i32])?;
3347
3348 // op A: a resident table transfers one 4B token id. The exact host-row capacity path
3349 // expands this one row on CPU and transfers n_embd f32 values instead.
3350 let e_emb = match embd_dev {
3351 Some((g, qt, rb)) => e.embed_gather_device_t(g, &[e_tok], n_embd, qt, rb)?,
3352 None => e.htod(&self.embd.gather(n_embd, &[e_tok]))?,
3353 };
3354
3355 // op 1/2: e_norm = RMSNorm(e, enorm); h_norm = RMSNorm(h_seed, hnorm)
3356 let mut e_norm = e.zeros(n_embd)?;
3357 e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, 1, eps)?;
3358 let mut h_norm = e.zeros(n_embd)?;
3359 e.rms_norm(h_seed, mtp.hnorm.float_data(), &mut h_norm, n_embd, 1, eps)?;
3360
3361 // op 3: concat = [e_norm ; h_norm] -> [2*n_embd], e_norm in [0,n_embd), h_norm in [n_embd,2n_embd)
3362 let mut concat = e.zeros(2 * n_embd)?;
3363 e.copy_into(&mut concat, 0, &e_norm, n_embd)?;
3364 e.copy_into(&mut concat, n_embd, &h_norm, n_embd)?;
3365
3366 // op 4: inpSA = eh_proj @ concat (eh_proj [2*n_embd, n_embd]) -> [n_embd]
3367 let inp_sa = e.matmul(&mtp.eh_proj, &concat, 1)?;
3368
3369 // op 5: a_norm = RMSNorm(inpSA, attn_norm)
3370 let mut a_norm = e.zeros(di)?;
3371 e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, 1, eps)?;
3372 anat_mark(0, e, &mut t_ph)?;
3373
3374 // op 6: attention on the scratch KV. SAME dc launcher as the graph path (bucket_max =
3375 // scratch.cap, length from the device len_d) so eager drafts match graph drafts
3376 // bit-for-bit at any t_kv (the parity gate). Host len mirrored here (the dc append
3377 // advances only the device counter).
3378 let attn_out = match (&mtp.mixer, mtp.step35.as_ref()) {
3379 // step35 MTP block: PER-LAYER geometry + a separate head-wise gate + an SWA window,
3380 // none of which the dc launcher can express (see `mtp_step35_attn`). Host-len arm.
3381 // Advances BOTH the host len and the device counter itself (unlike the dc arm,
3382 // whose host-side mirror the caller does).
3383 (Mixer::Full(fa), Some(g)) => {
3384 self.mtp_step35_attn(e, fa, g, &a_norm, &pos_d, scratch)?
3385 }
3386 (Mixer::Full(fa), None) => {
3387 let out =
3388 self.mtp_full_attn_dc(e, fa, &a_norm, &pos_d, scratch, mtp.geom.as_ref())?;
3389 scratch.kv.len += 1;
3390 out
3391 }
3392 (Mixer::Linear(_), _) => {
3393 panic!("MTP block is full-attn in qwen35; linear MTP not supported")
3394 }
3395 (Mixer::Mla(_), _) => crate::hybrid::mla_forward_unimplemented(),
3396 };
3397 anat_mark(1, e, &mut t_ph)?;
3398
3399 // op 7: x1 = inpSA + attn_out
3400 let mut x1 = e.zeros(di)?;
3401 e.add(&inp_sa, &attn_out, &mut x1, di)?;
3402
3403 // op 8: z = RMSNorm(x1, post_attn_norm) (pre-FFN norm)
3404 let mut z = e.zeros(di)?;
3405 e.rms_norm(&x1, mtp.post_attn_norm.float_data(), &mut z, di, 1, eps)?;
3406
3407 // op 9: FFN (Dense or MoE) — same as the trunk decode FFN
3408 let ffn_out = match &mtp.ffn {
3409 crate::hybrid::Ffn::Dense {
3410 ffn_gate,
3411 ffn_up,
3412 ffn_down,
3413 } => {
3414 let n_ff = ffn_gate.out_features();
3415 let (gate, up) = if e.uses_q8_1_fast(ffn_gate) && e.uses_q8_1_fast(ffn_up) {
3416 let (zq, zd) = e.quantize_q8_1(&z, 1, di)?;
3417 (
3418 e.matmul_pre(ffn_gate, &zq, &zd, &z, 1)?,
3419 e.matmul_pre(ffn_up, &zq, &zd, &z, 1)?,
3420 )
3421 } else {
3422 (e.matmul(ffn_gate, &z, 1)?, e.matmul(ffn_up, &z, 1)?)
3423 };
3424 let mut act = e.zeros(n_ff)?;
3425 // step35: a DENSE FFN reads the per-layer SHEXP clamp (upstream's one `build_ffn`
3426 // serves the dense MLP and the shared expert off `swiglu_clamp_shexp` —
3427 // llama-graph.cpp:1751), resolved for the MTP block's OWN index. Every other arch
3428 // passes None, which is `ffn_act`'s dispatch verbatim.
3429 Self::ffn_act_lim(
3430 e,
3431 &self.cfg,
3432 &gate,
3433 &up,
3434 1.0,
3435 1.0,
3436 mtp.step35.as_ref().and_then(|s| s.clamp_shexp),
3437 &mut act,
3438 n_ff,
3439 )?;
3440 e.matmul(ffn_down, &act, 1)?
3441 }
3442 // MTP head is a distinct block — key its experts under a separate layer index (u16::MAX)
3443 // so they never alias trunk layer 0's cache keys.
3444 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, 1, u16::MAX)?,
3445 };
3446 anat_mark(2, e, &mut t_ph)?;
3447
3448 // op 10: h_nextn = x1 + ffn_out (at di)
3449 let mut h_inner = e.zeros(di)?;
3450 e.add(&x1, &ffn_out, &mut h_inner, di)?;
3451
3452 // op 10.5 (student): up-project the inner hidden back to n_embd — training semantics:
3453 // the chain carrier AND the head input are out_up(h_inner) (pre-final-norm).
3454 let h_nextn = match mtp.geom.as_ref() {
3455 Some(g) => e.matmul(&g.out_up, &h_inner, 1)?,
3456 None => h_inner,
3457 };
3458
3459 // op 11: final = RMSNorm(h_nextn, shared_head_norm OR output_norm)
3460 let final_norm = mtp.shared_head_norm.as_ref().unwrap_or(&self.output_norm);
3461 let mut final_h = e.zeros(n_embd)?;
3462 e.rms_norm(
3463 &h_nextn,
3464 final_norm.float_data(),
3465 &mut final_h,
3466 n_embd,
3467 1,
3468 eps,
3469 )?;
3470
3471 // op 12: draft_logits = (shared_head_head OR output) @ final — stays ON DEVICE.
3472 let head = mtp.shared_head_head.as_ref().unwrap_or(&self.output);
3473 let mut logits = e.matmul(head, &final_h, 1)?;
3474 // op 12b (lane/draft-mask): grammar mask over the DRAFT vocab, applied here so the
3475 // caller's argmax / gumbel draw / p-min prob all read the grammar-legal row.
3476 if let Some((mask_d, mw)) = mask {
3477 let d_vocab = head.out_features();
3478 e.mask_logits_col(&mut logits, mask_d, 0, d_vocab, mw)?;
3479 }
3480 anat_mark(3, e, &mut t_ph)?;
3481 if anat {
3482 ANAT_NS[4].fetch_add(t_all.elapsed().as_nanos() as u64, Relaxed);
3483 let n = ANAT_STEPS.fetch_add(1, Relaxed) + 1;
3484 if n % 128 == 0 {
3485 let us = |i: usize| ANAT_NS[i].load(Relaxed) / n / 1000;
3486 eprintln!(
3487 "[spec-anatomy] steps={n} avg us/step: glue={} attn={} ffn={} head={} total={}",
3488 us(0),
3489 us(1),
3490 us(2),
3491 us(3),
3492 us(4)
3493 );
3494 }
3495 }
3496 // Chain recurrence hand-over: pre-norm h_nextn (default) or post-norm final_h
3497 // (MEMRA_SPEC_HPOST — llama.cpp #24025's t_h_nextn is taken AFTER the head norm).
3498 Ok((logits, if spec_hpost() { final_h } else { h_nextn }))
3499 }
3500
3501 /// step35 MTP-block attention, T=1, on the scratch KV — the EAGER-ONLY twin of
3502 /// `mtp_full_attn_dc`. Three things force a separate arm rather than a geometry parameter on
3503 /// the dc path, and all three are properties of this arch's MTP block:
3504 ///
3505 /// 1. **The SWA window.** Block 45 is an SWA-type block (`sliding_window_pattern[45]=true`,
3506 /// window 512). Windowed decode in memra is a token-aligned VIEW OFFSET into the quantized
3507 /// cache (the gemma4 R6 / `step35_decode_attn` pattern: keys carry absolute rope and the
3508 /// mask is purely positional, so one query at `len-1` attending the last `win` rows IS the
3509 /// windowed result). `fa_decode_dc` takes the key count from a DEVICE counter and always
3510 /// starts at row 0 — it cannot express a nonzero offset, so a windowed dc arm would need a
3511 /// new kernel. That is deliberately not built here: see the CUDA-graph note below.
3512 /// 2. **Per-layer head count.** 96 q heads over 8 KV (GQA 12) at this block, vs the trunk's 64
3513 /// on its full-attn layers. The trunk cfg's `n_head` scalar is the MAX over layers, and the
3514 /// trunk ARTIFACT's per-layer arrays stop at index 44 — so the count must come from the
3515 /// resolved `Step35MtpGeom`, never from `cfg`.
3516 /// 3. **The separate head-wise gate.** `blk.45.attn_gate.weight [n_embd, 96]` produces one
3517 /// sigmoid scalar per head (broadcast over head_dim) — `attn_head_gate`, not the qwen35
3518 /// fused-into-wq `q_gate_split` form the dc arm handles.
3519 ///
3520 /// WHY EAGER-ONLY IS NOT A GAP TODAY: `mtp_head_forward_cap` refuses step35 heads
3521 /// explicitly (the SWA-window refusal below), so the graph draft never engages for step35
3522 /// models regardless of eligibility — the eager chain IS the served path. `mtp_head_forward_cap` refuses step35 explicitly rather
3523 /// than silently capturing a window-less (wrong past `win` draft rows) graph.
3524 ///
3525 /// Unlike the dc arm this advances BOTH the host `kv.len` and the device counter, so the
3526 /// caller must not mirror.
3527 fn mtp_step35_attn(
3528 &self,
3529 e: &Engine,
3530 fa: &FullAttnLayer,
3531 g: &crate::hybrid::Step35MtpGeom,
3532 h: &CudaSlice<f32>,
3533 pos_d: &CudaSlice<i32>,
3534 scratch: &mut MtpScratch,
3535 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3536 let (nh, nkv, hd) = (g.n_head, g.n_head_kv, self.cfg.head_dim_k as usize);
3537 let eps = self.cfg.rms_eps;
3538 let scale = 1.0 / (hd as f32).sqrt(); // step35.cpp:255 kq_scale
3539 let n_embd = self.cfg.n_embd as usize;
3540 let gw = fa
3541 .attn_gate
3542 .as_ref()
3543 .ok_or("step35 MTP block is missing attn_gate.weight (head-wise attention gate)")?;
3544
3545 let (q0, k0, v0, gt) = if e.uses_q8_1_fast(&fa.wq)
3546 && e.uses_q8_1_fast(&fa.wk)
3547 && e.uses_q8_1_fast(&fa.wv)
3548 && e.uses_q8_1_fast(gw)
3549 {
3550 let (hq, hdq) = e.quantize_q8_1(h, 1, n_embd)?;
3551 let (a, b, c) = match e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, &hq, &hdq)? {
3552 Some(t3) => t3,
3553 None => (
3554 e.matmul_pre(&fa.wq, &hq, &hdq, h, 1)?,
3555 e.matmul_pre(&fa.wk, &hq, &hdq, h, 1)?,
3556 e.matmul_pre(&fa.wv, &hq, &hdq, h, 1)?,
3557 ),
3558 };
3559 (a, b, c, e.matmul_pre(gw, &hq, &hdq, h, 1)?)
3560 } else {
3561 (
3562 e.matmul(&fa.wq, h, 1)?,
3563 e.matmul(&fa.wk, h, 1)?,
3564 e.matmul(&fa.wv, h, 1)?,
3565 e.matmul(gw, h, 1)?,
3566 )
3567 };
3568
3569 let mut q = e.uninit(nh * hd)?;
3570 e.rms_norm(&q0, fa.q_norm.float_data(), &mut q, hd, nh, eps)?;
3571 let mut k = e.uninit(nkv * hd)?;
3572 e.rms_norm(&k0, fa.k_norm.float_data(), &mut k, hd, nkv, eps)?;
3573 // `rope_freqs.weight` (llama3 factors) applies to the FULL-attn layers ONLY; SWA passes
3574 // null (llama-hparams / step35.cpp). Block 45 is SWA, so `ff` is None there — but read
3575 // the resolved flag, not the constant, so an all-full sibling stays correct.
3576 let ff = if g.swa {
3577 None
3578 } else {
3579 self.step35_aux.as_ref().and_then(|a| a.rope_freqs(e))
3580 };
3581 #[cfg(debug_assertions)]
3582 if let Some(ff) = ff {
3583 crate::debug_assert_tensor_stream_device(ff, &e.stream(), "mtp_step35_attn.rope_freqs");
3584 }
3585 e.rope_neox2(
3586 &mut q,
3587 &mut k,
3588 pos_d,
3589 hd,
3590 g.n_rot,
3591 nh,
3592 nkv,
3593 1,
3594 g.rope_base,
3595 1.0,
3596 ff,
3597 )?;
3598
3599 // Append at the HOST slot, then re-stamp the device counter: the eager chain has the
3600 // length on the host anyway, and the windowed view below needs it there to compute the
3601 // offset. The device counter is kept in lockstep so `mtp_kv_fill`'s `set_i32_one` and any
3602 // dc-family consumer of this scratch still agree.
3603 let kv = &mut scratch.kv;
3604 assert!(
3605 kv.len < scratch.cap,
3606 "step35 MTP scratch overflow ({} >= {})",
3607 kv.len,
3608 scratch.cap
3609 );
3610 let next_len = kv.len + 1;
3611 let (off, t_kv) = if g.swa && next_len > g.window {
3612 (next_len - g.window, g.window)
3613 } else {
3614 (0, next_len)
3615 };
3616 let write_row = e.prepare_kv_append(kv, off & !31usize, 1)?;
3617 e.append_kv_quantized(
3618 &k,
3619 &v0,
3620 &mut kv.k,
3621 &mut kv.v,
3622 write_row,
3623 kv.kv_dim_k,
3624 kv.kv_dim_v,
3625 kv.k_tok_bytes,
3626 kv.v_tok_bytes,
3627 false,
3628 )?;
3629 kv.len = next_len;
3630 e.set_i32_one(&mut kv.len_d, kv.len as i32)?;
3631 // SWA view offset (see note 1). The draft chain is short (k+2 rows), but the scratch is
3632 // PERSISTENT across rounds — `mtp_kv_fill` leaves one row per committed token behind, so
3633 // `kv.len` tracks absolute position and crosses 512 in any real generation. The window is
3634 // therefore live, not theoretical.
3635 let physical = kv.physical_rows(off, off + t_kv)?;
3636 let k_view = e.view_u8_range(
3637 &kv.k,
3638 physical.start * kv.k_tok_bytes,
3639 physical.end * kv.k_tok_bytes,
3640 );
3641 let v_view = e.view_u8_range(
3642 &kv.v,
3643 physical.start * kv.v_tok_bytes,
3644 physical.end * kv.v_tok_bytes,
3645 );
3646 let mut attn = e.uninit(nh * hd)?;
3647 e.fa_decode_kvmod(
3648 &q,
3649 &k_view,
3650 &v_view,
3651 &mut attn,
3652 hd,
3653 nh,
3654 nkv,
3655 t_kv,
3656 scale,
3657 kv.k_tok_bytes,
3658 kv.v_tok_bytes,
3659 false,
3660 )?;
3661
3662 let mut ag = e.uninit(nh * hd)?;
3663 e.attn_head_gate(&attn, >, &mut ag, None, hd, nh, 1)?;
3664 Ok(e.matmul(&fa.wo, &ag, 1)?)
3665 }
3666
3667 /// MTP-block full attention, T=1, on the scratch KV (BOTH draft paths — eager and graph):
3668 /// the scratch write slot and the attention bound come from `scratch.kv.len_d` (device i32[1])
3669 /// so the launch args are FIXED across draft steps — ONE captured graph serves the whole
3670 /// chain, and replays keep seeing KV growth through the device counter (no recapture).
3671 /// Geometry contract: n_splits is sized from `scratch.cap` (the persistent capacity); splits
3672 /// whose key range lies beyond the device t_kv exit empty and the shared combine skips them
3673 /// (fa_decode_dc bit-correct-for-any-t_kv<=bucket_max contract). The eager path uses the SAME
3674 /// launcher with the SAME bucket_max -> identical dispatch -> bit-identical draft tokens (the
3675 /// graph-vs-eager parity gate). Host len is NOT advanced here (graph contract); callers mirror.
3676 fn mtp_full_attn_dc(
3677 &self,
3678 e: &Engine,
3679 fa: &FullAttnLayer,
3680 h: &CudaSlice<f32>,
3681 pos_d: &CudaSlice<i32>,
3682 scratch: &mut MtpScratch,
3683 geom: Option<&crate::hybrid::DraftGeom>,
3684 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3685 let cfg = &self.cfg;
3686 let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
3687 let geometry = cfg.full_attention_geometry_at(mtp_il);
3688 let n_head = geom.map(|g| g.n_head).unwrap_or(geometry.n_head as usize);
3689 let n_head_kv = geom
3690 .map(|g| g.n_head_kv)
3691 .unwrap_or(geometry.n_head_kv as usize);
3692 let head_dim = geometry.head_dim_k as usize;
3693 let eps = cfg.rms_eps;
3694 let scale = geometry.attention_scale();
3695 let n_embd = geom.map(|g| g.d_inner).unwrap_or(cfg.n_embd as usize);
3696 let bucket_max = scratch.cap; // < 96 guaranteed by the graph_draft eligibility gate
3697
3698 let (qf, mut k, v) =
3699 if e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk) && e.uses_q8_1_fast(&fa.wv) {
3700 let (hq, hd) = e.quantize_q8_1(h, 1, n_embd)?;
3701 (
3702 e.matmul_pre(&fa.wq, &hq, &hd, h, 1)?,
3703 e.matmul_pre(&fa.wk, &hq, &hd, h, 1)?,
3704 e.matmul_pre(&fa.wv, &hq, &hd, h, 1)?,
3705 )
3706 } else {
3707 (
3708 e.matmul(&fa.wq, h, 1)?,
3709 e.matmul(&fa.wk, h, 1)?,
3710 e.matmul(&fa.wv, h, 1)?,
3711 )
3712 };
3713 // M3/Hy3 have no attention output gate — wq out is exactly q; skip the split.
3714 let gated = geometry.attention_gate == memra_gguf::config::AttentionGateKind::FusedQ;
3715 let (mut q, gate) = if gated {
3716 let mut q = e.zeros(n_head * head_dim)?;
3717 let mut gate = e.zeros(n_head * head_dim)?;
3718 e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, 1)?;
3719 (q, Some(gate))
3720 } else {
3721 (qf, None)
3722 };
3723
3724 let mut qn = e.zeros(n_head * head_dim)?;
3725 e.rms_norm(&q, fa.q_norm.float_data(), &mut qn, head_dim, n_head, eps)?;
3726 q = qn;
3727 let mut kn = e.zeros(n_head_kv * head_dim)?;
3728 e.rms_norm(
3729 &k,
3730 fa.k_norm.float_data(),
3731 &mut kn,
3732 head_dim,
3733 n_head_kv,
3734 eps,
3735 )?;
3736 k = kn;
3737 let rope_dims = geometry.n_rot as usize;
3738 e.rope_neox(
3739 &mut q,
3740 pos_d,
3741 head_dim,
3742 rope_dims,
3743 n_head,
3744 1,
3745 geometry.rope_base,
3746 1.0,
3747 )?;
3748 e.rope_neox(
3749 &mut k,
3750 pos_d,
3751 head_dim,
3752 rope_dims,
3753 n_head_kv,
3754 1,
3755 geometry.rope_base,
3756 1.0,
3757 )?;
3758
3759 let kv = &mut scratch.kv;
3760 // append at the DEVICE slot (kv.len_d == old len), then advance the counter in-graph.
3761 e.append_kv_quantized_dc(
3762 &k,
3763 &v,
3764 &mut kv.k,
3765 &mut kv.v,
3766 &kv.len_d,
3767 kv.kv_dim_k,
3768 kv.kv_dim_v,
3769 kv.k_tok_bytes,
3770 kv.v_tok_bytes,
3771 false,
3772 )?;
3773 e.inc_seqlen(&mut kv.len_d)?;
3774 // full-buffer views (any in-round t_kv stays in range on replay); the kernel bounds the
3775 // key range from the device counter.
3776 let k_view = e.view_u8(&kv.k, kv.k.len());
3777 let v_view = e.view_u8(&kv.v, kv.v.len());
3778 let (ktb, vtb) = (kv.k_tok_bytes, kv.v_tok_bytes);
3779 let mut attn = e.zeros(n_head * head_dim)?;
3780 e.fa_decode_dc(
3781 &q, &k_view, &v_view, &mut attn, head_dim, n_head, n_head_kv, &kv.len_d, bucket_max,
3782 scale, ktb, vtb, false,
3783 )?;
3784
3785 let attn_g = match &gate {
3786 Some(gate) => {
3787 let mut gsig = e.zeros(n_head * head_dim)?;
3788 e.sigmoid(gate, &mut gsig, n_head * head_dim)?;
3789 let mut ag = e.zeros(n_head * head_dim)?;
3790 e.mul(&attn, &gsig, &mut ag, n_head * head_dim)?;
3791 ag
3792 }
3793 None => attn,
3794 };
3795 Ok(e.matmul(&fa.wo, &attn_g, 1)?)
3796 }
3797
3798 /// PERSISTENT-DRAFT-KV fill (the reference engine's "mtp_update" analogue): compute the MTP
3799 /// block's K/V for `tokens` (committed tokens at positions pos0..pos0+T) from their EXACT
3800 /// trunk hiddens `h` ([T, n_embd] token-major, pre-output_norm) and append at slots pos0.. of
3801 /// the scratch KV. K/V-ONLY — ops A/1-5 plus the K-side of op 6 (wk/wv + k_norm + rope +
3802 /// quantized append); no wq/attention/FFN/lm_head, so per-token cost ~= eh_proj + wk/wv (a
3803 /// small fraction of one trunk layer), T-batched. Rope follows the chain convention
3804 /// rope(token@p) = p+1. Runs at round boundaries OUTSIDE the captured graph in BOTH draft
3805 /// modes -> draft parity by construction. Caller must have scratch.kv.len == pos0.
3806 #[allow(clippy::too_many_arguments)]
3807 fn mtp_kv_fill(
3808 &self,
3809 e: &Engine,
3810 mtp: &MtpHead,
3811 tokens: &[u32],
3812 h: &CudaSlice<f32>,
3813 pos0: usize,
3814 scratch: &mut MtpScratch,
3815 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3816 ) -> Result<(), Box<dyn std::error::Error>> {
3817 let cfg = &self.cfg;
3818 let n_embd = cfg.n_embd as usize;
3819 let eps = cfg.rms_eps;
3820 let t = tokens.len();
3821 assert_eq!(scratch.kv.len, pos0, "mtp_kv_fill: append slot mismatch");
3822 assert!(pos0 + t <= scratch.cap, "mtp_kv_fill: scratch overflow");
3823 let Mixer::Full(fa) = &mtp.mixer else {
3824 panic!("MTP block is full-attn in qwen35; linear MTP not supported")
3825 };
3826 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i + 1) as i32).collect();
3827 let pos_d = e.htod_i32(&pos_vec)?;
3828
3829 // ops A/1/2: embed + the two input norms, T-wide.
3830 let e_emb = match embd_dev {
3831 Some((g, qt, rb)) => e.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
3832 None => e.htod(&self.embd.gather(n_embd, tokens))?,
3833 };
3834 let mut e_norm = e.zeros(t * n_embd)?;
3835 e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, t, eps)?;
3836 let mut h_norm = e.zeros(t * n_embd)?;
3837 e.rms_norm(h, mtp.hnorm.float_data(), &mut h_norm, n_embd, t, eps)?;
3838
3839 // op 3: per-row [e_norm ; h_norm] concat, token-major [T, 2*n_embd].
3840 let mut concat = e.zeros(t * 2 * n_embd)?;
3841 for i in 0..t {
3842 e.copy_view_into(
3843 &mut concat,
3844 i * 2 * n_embd,
3845 &e_norm.slice(i * n_embd..(i + 1) * n_embd),
3846 n_embd,
3847 )?;
3848 e.copy_view_into(
3849 &mut concat,
3850 i * 2 * n_embd + n_embd,
3851 &h_norm.slice(i * n_embd..(i + 1) * n_embd),
3852 n_embd,
3853 )?;
3854 }
3855
3856 // ops 4/5: eh_proj + attn_norm, T-wide (at the student inner width when geom is set).
3857 let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
3858 let inp_sa = e.matmul(&mtp.eh_proj, &concat, t)?;
3859 let mut a_norm = e.zeros(t * di)?;
3860 e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, t, eps)?;
3861
3862 // op 6 (K/V half): wk/wv + k_norm + rope + per-row quantized append. No wq/attention —
3863 // the fill only has to leave correct K/V rows behind for later chains to attend over.
3864 let n_head_kv = mtp
3865 .geom
3866 .as_ref()
3867 .map(|g| g.n_head_kv)
3868 .or(mtp.step35.as_ref().map(|s| s.n_head_kv))
3869 .unwrap_or_else(|| {
3870 let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
3871 cfg.full_attention_geometry_at(mtp_il).n_head_kv as usize
3872 });
3873 let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
3874 let geometry = cfg.full_attention_geometry_at(mtp_il);
3875 let head_dim = geometry.head_dim_k as usize;
3876 let mut k = e.matmul(&fa.wk, &a_norm, t)?;
3877 let v = e.matmul(&fa.wv, &a_norm, t)?;
3878 let mut kn = e.zeros(t * n_head_kv * head_dim)?;
3879 e.rms_norm(
3880 &k,
3881 fa.k_norm.float_data(),
3882 &mut kn,
3883 head_dim,
3884 n_head_kv * t,
3885 eps,
3886 )?;
3887 k = kn;
3888 // step35: rotary width AND base are per-layer, and the MTP block's values come from the
3889 // resolved `Step35MtpGeom` — NOT from `cfg.rope_dim_count`/`cfg.rope_freq_base`, which
3890 // carry the arch defaults (128 / 5e6, i.e. the FULL-attn layers' base). Getting this wrong
3891 // writes K rows the attention arm then re-derives at a different theta: correct-looking
3892 // output with dead acceptance, invisible to the exactness gates.
3893 let (rope_dims, rope_base, ff) = match mtp.step35.as_ref() {
3894 Some(s) => (
3895 s.n_rot,
3896 s.rope_base,
3897 if s.swa {
3898 None
3899 } else {
3900 self.step35_aux.as_ref().and_then(|a| a.rope_freqs(e))
3901 },
3902 ),
3903 None => (geometry.n_rot as usize, geometry.rope_base, None),
3904 };
3905 #[cfg(debug_assertions)]
3906 if let Some(ff) = ff {
3907 crate::debug_assert_tensor_stream_device(ff, &e.stream(), "mtp_kv_fill.rope_freqs");
3908 }
3909 match ff {
3910 Some(f) => e.rope_neox_ff(
3911 &mut k, &pos_d, head_dim, rope_dims, n_head_kv, t, rope_base, 1.0, f,
3912 )?,
3913 None => e.rope_neox(
3914 &mut k, &pos_d, head_dim, rope_dims, n_head_kv, t, rope_base, 1.0,
3915 )?,
3916 }
3917
3918 let kv = &mut scratch.kv;
3919 // Match the trunk prime contract: a chunk may need the aligned window immediately before
3920 // its first row, so preserve that prefix when the physical tail rebases at wrap.
3921 let retain_from = kv
3922 .ring
3923 .as_ref()
3924 .map(|ring| pos0.saturating_sub(ring.window() - 1) & !31usize)
3925 .unwrap_or(0);
3926 let write_row = e.prepare_kv_append(kv, retain_from, t)?;
3927 for i in 0..t {
3928 let k_row = k.slice(i * kv.kv_dim_k..(i + 1) * kv.kv_dim_k);
3929 let v_row = v.slice(i * kv.kv_dim_v..(i + 1) * kv.kv_dim_v);
3930 e.append_kv_quantized_view(
3931 &k_row,
3932 &v_row,
3933 &mut kv.k,
3934 &mut kv.v,
3935 write_row + i,
3936 kv.kv_dim_k,
3937 kv.kv_dim_v,
3938 kv.k_tok_bytes,
3939 kv.v_tok_bytes,
3940 false,
3941 )?;
3942 }
3943 kv.len = pos0 + t;
3944 e.set_i32_one(&mut kv.len_d, kv.len as i32)?;
3945 Ok(())
3946 }
3947
3948 /// CAPTURE body for the GRAPH DRAFT (stage 2 of graph-grade spec): ONE MTP head forward with
3949 /// every varying input device-resident —
3950 /// - token id from the persistent `tok_d` (the previous replay's in-graph argmax wrote it,
3951 /// so the chain feeds itself; the host reads the same 4 bytes for the draft list),
3952 /// - h_seed from the persistent `h_seed_d` (h_nextn is copied BACK into it at the end),
3953 /// - rope pos from the persistent `pos_d` counter (inc'd in-graph),
3954 /// - scratch KV slot/bound from `scratch.kv.len_d` (see mtp_full_attn_dc).
3955 /// The p-min confidence lands in the persistent `p_d` iff `with_prob` (env is fixed per run).
3956 /// Same kernels, same dispatch as the eager mtp_head_forward_dev chain -> same draft tokens
3957 /// (exactness never depends on drafts — the verify arbitrates — but acceptance parity does).
3958 /// `with_head=false` captures the HEAD-LESS twin for the pseudo-seed replay (2026-07-03):
3959 /// the pseudo pass only needs h_nextn (op 10) + the scratch append — the lm_head read
3960 /// (~1.06ms q6_K on the 9B), argmax and prob are dead weight there. h_nextn's inputs are
3961 /// untouched, so the seed value is identical; round-start resets overwrite tok_d/p_d anyway.
3962 /// `sampled_cap` = Some((ctr_d, perturb_d, q_out_d, seed, temp)) captures the SAMPLED twin
3963 /// (step 3 of the sampled-spec arc): head logits are retained in the persistent `q_out_d`
3964 /// (host D2Ds them to the round's q slot after each replay), the DEVICE event counter is
3965 /// bumped in-graph, and the argmax reads GUMBEL-PERTURBED logits — one categorical draw per
3966 /// replay, bit-identical to the eager arm's gumbel_perturb at the same (seed, sctr, temp).
3967 /// seed/temp are capture-time constants (fixed per generate call, like p_min).
3968 #[allow(clippy::too_many_arguments)]
3969 fn mtp_head_forward_cap(
3970 &self,
3971 e: &Engine,
3972 mtp: &MtpHead,
3973 tok_d: &mut CudaSlice<u32>,
3974 pos_d: &mut CudaSlice<i32>,
3975 h_seed_d: &mut CudaSlice<f32>,
3976 p_d: &mut CudaSlice<f32>,
3977 scratch: &mut MtpScratch,
3978 with_prob: bool,
3979 with_head: bool,
3980 embd_gpu: &CudaSlice<u8>,
3981 embd_qt: i32,
3982 embd_rb: usize,
3983 d_vocab: usize,
3984 sampled_cap: Option<(
3985 &mut CudaSlice<u32>,
3986 &mut CudaSlice<f32>,
3987 &mut CudaSlice<f32>,
3988 u64,
3989 f32,
3990 )>,
3991 stream_pack: Option<(&mut CudaSlice<u32>, usize, Option<&CudaSlice<u32>>)>,
3992 // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): (packed draft-vocab allowed-set buffer,
3993 // word count). Captured as ONE mask_logits_f32 node between the head matmul and the
3994 // in-graph argmax; the buffer address is baked, its CONTENTS are re-uploaded by the
3995 // host before every replay (the decode.rs graph-mask pattern). All-ones contents = a
3996 // no-op ban, so a position the grammar cannot constrain costs one pass over the row.
3997 mask_cap: Option<(&CudaSlice<u32>, usize)>,
3998 ) -> Result<(), Box<dyn std::error::Error>> {
3999 let cfg = &self.cfg;
4000 let n_embd = cfg.n_embd as usize;
4001 // step35 REFUSAL (deliberate, named): the graph body's attention is `mtp_full_attn_dc`,
4002 // whose device-counter key bound always starts at row 0 — it cannot express this block's
4003 // SWA view offset, so a captured chain would silently attend OUTSIDE the window once the
4004 // persistent scratch passes 512 rows. Nothing is lost today: `mtp_head_forward_cap`
4005 // refuses step35 heads explicitly (SWA refusal), so the eager chain
4006 // (`mtp_head_forward_dev` -> `mtp_step35_attn`) is the served path. Returning Err (not a
4007 // panic) is what the two capture sites and the round-stream capture already handle by
4008 // degrading to eager / stream-off.
4009 if mtp.step35.is_some() {
4010 return Err(
4011 "step35 has no captured draft chain (fa_decode_dc cannot express the MTP \
4012 block's SWA view offset; same root cause as the dc decode refusal) — the \
4013 eager draft chain serves this arch"
4014 .into(),
4015 );
4016 }
4017 // student inner width (see mtp_head_forward_dev) — interface dims stay n_embd.
4018 let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
4019 let eps = cfg.rms_eps;
4020 let e_emb = e.embed_gather_device(embd_gpu, tok_d, n_embd, embd_qt, embd_rb)?;
4021 let mut e_norm = e.zeros(n_embd)?;
4022 e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, 1, eps)?;
4023 let mut h_norm = e.zeros(n_embd)?;
4024 e.rms_norm(
4025 &*h_seed_d,
4026 mtp.hnorm.float_data(),
4027 &mut h_norm,
4028 n_embd,
4029 1,
4030 eps,
4031 )?;
4032 let mut concat = e.zeros(2 * n_embd)?;
4033 e.copy_into(&mut concat, 0, &e_norm, n_embd)?;
4034 e.copy_into(&mut concat, n_embd, &h_norm, n_embd)?;
4035 let inp_sa = e.matmul(&mtp.eh_proj, &concat, 1)?;
4036 let mut a_norm = e.zeros(di)?;
4037 e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, 1, eps)?;
4038 let attn_out = match &mtp.mixer {
4039 Mixer::Full(fa) => {
4040 self.mtp_full_attn_dc(e, fa, &a_norm, pos_d, scratch, mtp.geom.as_ref())?
4041 }
4042 Mixer::Linear(_) => {
4043 panic!("MTP block is full-attn in qwen35; linear MTP not supported")
4044 }
4045 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
4046 };
4047 let mut x1 = e.zeros(di)?;
4048 e.add(&inp_sa, &attn_out, &mut x1, di)?;
4049 let mut z = e.zeros(di)?;
4050 e.rms_norm(&x1, mtp.post_attn_norm.float_data(), &mut z, di, 1, eps)?;
4051 let ffn_out = match &mtp.ffn {
4052 crate::hybrid::Ffn::Dense {
4053 ffn_gate,
4054 ffn_up,
4055 ffn_down,
4056 } => {
4057 let n_ff = ffn_gate.out_features();
4058 let (gate, up) = if e.uses_q8_1_fast(ffn_gate) && e.uses_q8_1_fast(ffn_up) {
4059 let (zq, zd) = e.quantize_q8_1(&z, 1, di)?;
4060 (
4061 e.matmul_pre(ffn_gate, &zq, &zd, &z, 1)?,
4062 e.matmul_pre(ffn_up, &zq, &zd, &z, 1)?,
4063 )
4064 } else {
4065 (e.matmul(ffn_gate, &z, 1)?, e.matmul(ffn_up, &z, 1)?)
4066 };
4067 let mut act = e.zeros(n_ff)?;
4068 Self::ffn_act(e, &self.cfg, &gate, &up, &mut act, n_ff)?;
4069 e.matmul(ffn_down, &act, 1)?
4070 }
4071 // ROUND-STREAM: the 35B NextN block carries a MoE FFN. With RESIDENT experts the
4072 // dev path is pure device launches (device top-k + rows kernels, ZERO-DtoH by
4073 // design) — capture-legal. Non-resident (SLRU-lock) stays rejected: the capture
4074 // error arm degrades the caller to eager/stream-off.
4075 crate::hybrid::Ffn::Moe(m) if m.dev_exps.is_some() => {
4076 self.moe_ffn_il(e, m, &z, 1, u16::MAX)?
4077 }
4078 crate::hybrid::Ffn::Moe(_) => {
4079 return Err("graph draft requires a Dense (or resident-MoE) MTP FFN".into());
4080 }
4081 };
4082 let mut h_inner = e.zeros(di)?;
4083 e.add(&x1, &ffn_out, &mut h_inner, di)?;
4084 // student: up-project back to n_embd (carrier + head input; see mtp_head_forward_dev).
4085 let h_nextn = match mtp.geom.as_ref() {
4086 Some(g) => e.matmul(&g.out_up, &h_inner, 1)?,
4087 None => h_inner,
4088 };
4089 // MEMRA_SPEC_HPOST needs final_h even head-less (it IS the next seed under that convention).
4090 let final_h = if with_head || spec_hpost() {
4091 let final_norm = mtp.shared_head_norm.as_ref().unwrap_or(&self.output_norm);
4092 let mut fh = e.zeros(n_embd)?;
4093 e.rms_norm(&h_nextn, final_norm.float_data(), &mut fh, n_embd, 1, eps)?;
4094 Some(fh)
4095 } else {
4096 None
4097 };
4098 if with_head {
4099 let head = mtp.shared_head_head.as_ref().unwrap_or(&self.output);
4100 let mut logits = e.matmul(head, final_h.as_ref().unwrap(), 1)?;
4101 // DRAFT-SIDE GRAMMAR MASK: ban the grammar-illegal draft ids IN the captured chain,
4102 // before the argmax — proposals become legal by construction. Contents-only
4103 // per-replay upload keeps the capture valid.
4104 if let Some((mask_d, mw)) = mask_cap {
4105 e.mask_logits_col(&mut logits, mask_d, 0, d_vocab, mw)?;
4106 }
4107 if let Some((ctr_d, perturb_d, q_out_d, seed, temp)) = sampled_cap {
4108 // SAMPLED chain: retain q (raw head logits -> persistent q_out_d; the matmul's
4109 // own buffer is pool-recycled after the capture body returns, so it can't be the
4110 // retention target), bump the device event counter, gumbel-perturb reading it,
4111 // and argmax the PERTURBED logits into tok_d — the in-graph categorical draw.
4112 e.copy_into(q_out_d, 0, &logits, d_vocab)?;
4113 e.sctr_inc(ctr_d)?;
4114 e.gumbel_perturb_ctr(&logits, perturb_d, d_vocab, seed, ctr_d, temp)?;
4115 e.argmax_token_device_into(perturb_d, tok_d, d_vocab)?;
4116 // p-min prob = the head's RAW softmax confidence in the SAMPLED pick — same
4117 // semantics as the eager sampled arm's prob_of_token_device(dl_d, tok_d).
4118 if with_prob {
4119 e.prob_of_token_device_into(&logits, tok_d, p_d, d_vocab)?;
4120 }
4121 } else {
4122 // draft token -> persistent tok_d (next replay's embed reads it; host reads the 4 bytes).
4123 e.argmax_token_device_into(&logits, tok_d, d_vocab)?;
4124 // p-min under a draft mask reads the MASKED row: confidence relative to the
4125 // grammar-LEGAL alternatives (illegal ids leave the softmax denominator), which
4126 // is the right semantics for "does the drafter know what comes next here" and
4127 // the same row the pick came from. Draft-quality only — verify arbitrates.
4128 if with_prob {
4129 e.prob_of_token_device_into(&logits, tok_d, p_d, d_vocab)?;
4130 }
4131 }
4132 }
4133 // ROUND-STREAM K-chain: pack (tok, p) into slot j, then remap tok through d2t so the
4134 // NEXT chained body's embed reads the TARGET id — zero host involvement per step.
4135 if let Some((out, slot, d2t)) = stream_pack {
4136 e.pack_tok_p(tok_d, p_d, out, slot)?;
4137 if let Some(map) = d2t {
4138 e.tok_map_u32(tok_d, map)?;
4139 }
4140 }
4141 // Next draft step's h_seed: pre-norm h_nextn (default) or post-norm final_h (HPOST).
4142 if spec_hpost() {
4143 e.copy_into(h_seed_d, 0, final_h.as_ref().unwrap(), n_embd)?;
4144 } else {
4145 e.copy_into(h_seed_d, 0, &h_nextn, n_embd)?;
4146 }
4147 // advance the draft rope position in-graph.
4148 e.inc_seqlen(pos_d)?;
4149 Ok(())
4150 }
4151
4152 /// Batched target verify forward over `tokens` at positions `pos0..pos0+T` (§D.3, T=K+1).
4153 /// Returns ALL T logit columns (host f32, [T*n_vocab]); appends T cols to every full-attn KV
4154 /// and advances every linear-attn recur state by T steps (the recur steps are SEQUENTIAL T=1).
4155 /// Advances `cache.pos` by T.
4156 pub fn decode_step_t(
4157 &self,
4158 e: &Engine,
4159 tokens: &[u32],
4160 pos0: usize,
4161 cache: &mut Cache,
4162 ) -> Result<Vec<f32>, Box<dyn std::error::Error>> {
4163 if self.is_gemma4_e4b() {
4164 return Ok(self.gemma4_e4b_decode_step_t_h(e, tokens, pos0, cache)?.0);
4165 }
4166 if self.cfg.gemma4.is_some() {
4167 return self.gemma4_decode_step_t(e, tokens, pos0, cache);
4168 }
4169 Ok(self.decode_step_t_h(e, tokens, pos0, cache)?.0)
4170 }
4171
4172 /// Like `decode_step_t` but ALSO returns the LAST column's pre-output_norm hidden (h_seed for
4173 /// the next draft round). This lets partial-accept replay run as ONE batched T=(n_acc+1) forward
4174 /// (single weight read) instead of n_acc+1 separate T=1 decode_steps (n_acc+1 weight reads).
4175 /// At batch=1 decode is bandwidth-bound, so batching the replay is THE MTP profitability lever.
4176 pub fn decode_step_t_h(
4177 &self,
4178 e: &Engine,
4179 tokens: &[u32],
4180 pos0: usize,
4181 cache: &mut Cache,
4182 ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4183 self.decode_step_t_h_emb(e, tokens, pos0, cache, None)
4184 }
4185
4186 /// Like `decode_step_t_h` with an optional RESIDENT embed table (spec hot loop): device
4187 /// gather instead of host dequant + [T, n_embd] f32 htod. Bit-identical rows.
4188 pub fn decode_step_t_h_emb(
4189 &self,
4190 e: &Engine,
4191 tokens: &[u32],
4192 pos0: usize,
4193 cache: &mut Cache,
4194 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4195 ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4196 let (logits_d, h_seed) = self.decode_step_t_h_emb_dev(e, tokens, pos0, cache, embd_dev)?;
4197 Ok((e.dtoh(&logits_d)?, h_seed))
4198 }
4199
4200 /// DEVICE-LOGITS verify forward (spec device-argmax lever): identical kernel chain to
4201 /// `decode_step_t_h_emb` but returns the [T, n_vocab] logits ON DEVICE — the accept walk
4202 /// argmaxes each column on-device and reads back ONE [T] u32 instead of dtoh'ing the full
4203 /// T x n_vocab f32 block (~1-4 MB + T host argmaxes, every round). Kernel dispatch is
4204 /// UNCHANGED (same decode-exact kernels); only the post-logits transfer moves.
4205 pub fn decode_step_t_h_emb_dev(
4206 &self,
4207 e: &Engine,
4208 tokens: &[u32],
4209 pos0: usize,
4210 cache: &mut Cache,
4211 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4212 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4213 let n_embd = self.cfg.n_embd as usize;
4214 let t = tokens.len();
4215 let (logits, x) = self.decode_step_t_core(e, tokens, pos0, cache, embd_dev, None)?;
4216 // h_seed for the next round = LAST column's pre-output_norm hidden ([n_embd]).
4217 let mut hs = vbuf(e, n_embd)?; // fully written by copy_view_into below
4218 e.copy_view_into(&mut hs, 0, &x.slice((t - 1) * n_embd..t * n_embd), n_embd)?;
4219 Ok((logits, hs))
4220 }
4221
4222 /// CORE verify forward: the `decode_step_t_h_emb_dev` kernel chain, returning the FULL
4223 /// pre-output_norm hidden stack x ([T, n_embd], any column extractable) and optionally
4224 /// filling a `VerifyCkpt` (retained per-layer state-rebuild inputs) for the REPLAY-FREE
4225 /// partial accept. `ckpt: None` => byte-for-byte the old behavior (the ckpt writes are pure
4226 /// retains/copies — they never change what any kernel computes).
4227 fn decode_step_t_core(
4228 &self,
4229 e: &Engine,
4230 tokens: &[u32],
4231 pos0: usize,
4232 cache: &mut Cache,
4233 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4234 mut ckpt: Option<&mut VerifyCkpt>,
4235 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4236 self.decode_step_t_core_stream(
4237 e,
4238 tokens,
4239 pos0,
4240 cache,
4241 embd_dev,
4242 ckpt.take(),
4243 None,
4244 None,
4245 None,
4246 None,
4247 )
4248 }
4249
4250 /// Increment-0 two-session PP seam: release the peer after this lane's stage-0 boundary TX.
4251 /// The two independent sessions keep their own cache/checkpoint state; only issue order moves.
4252 fn decode_step_t_core_pipelined(
4253 &self,
4254 e: &Engine,
4255 tokens: &[u32],
4256 pos0: usize,
4257 cache: &mut Cache,
4258 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4259 mut ckpt: Option<&mut VerifyCkpt>,
4260 pipe: &SpecPipeLane,
4261 round: usize,
4262 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4263 let fence = crate::pp::pp_cuts(self.layers.len())
4264 .ok_or("two-session speculative pipeline requires a PP stage cut")?;
4265 if crate::pp::pp2_streams_off() || !crate::pp::spec_pp_on() {
4266 return Err("two-session speculative pipeline requires the PP verify split".into());
4267 }
4268 let interval_fence = pipe.stage0_begin(round)?;
4269 let ticket = self.verify_stage0_issue(
4270 e,
4271 tokens,
4272 pos0,
4273 cache,
4274 embd_dev,
4275 ckpt.as_deref_mut(),
4276 None,
4277 &fence,
4278 Some(interval_fence),
4279 pipe.trace(round),
4280 )?;
4281 pipe.stage0_end(round);
4282 pipe.stage1_begin(round)?;
4283 let result = self.verify_stage1_finish(e, ticket, cache, ckpt, None, &fence, true)?;
4284 pipe.verify_end(round);
4285 Ok(result)
4286 }
4287
4288 /// ROUND-STREAM stage (c) 4: `stream` = (device verify tokens [t], device pos counter) —
4289 /// when Some, rope positions come from pos_iota over the counter, the embed gathers the
4290 /// device tokens, and full_attn_verify routes appends/FA through the _dc twins reading the
4291 /// SAME counter (every layer's kvl.len == cache.pos, one counter drives all three). The
4292 /// host `tokens`/`pos0` args still size buffers (t is FIXED K+1 in stream mode).
4293 /// `vtok_dev` (engine-bundle slice 2): device verify tokens for the EMBED only —
4294 /// unlike `stream` mode it changes nothing else (host pos iota, host-len KV appends).
4295 /// `tokens` then only sizes buffers (the dummy-slice pattern the round-stream arm uses).
4296 #[allow(clippy::too_many_arguments)]
4297 fn decode_step_t_core_stream(
4298 &self,
4299 e: &Engine,
4300 tokens: &[u32],
4301 pos0: usize,
4302 cache: &mut Cache,
4303 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4304 mut ckpt: Option<&mut VerifyCkpt>,
4305 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
4306 pp_pipe: Option<bool>,
4307 vtok_dev: Option<&CudaSlice<u32>>,
4308 graphs: Option<&mut DsparkVerifyGraphs>,
4309 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4310 // PP DOOR (lane/pp2-spec 2026-08-06): the verify trunk now takes its OWN stage split,
4311 // exactly as the eager and batched steps do. This is the single funnel every verify
4312 // forward reaches (decode_step_t / _h / _h_emb / _h_emb_dev / _core all land here), so
4313 // wiring it here wires the whole spec surface — the draft/accept/commit machinery above
4314 // is untouched.
4315 //
4316 // History: pp2-hardening (2026-08-06) made this funnel FAIL CLOSED, because its trunk
4317 // walk was unsplit on one stream and a sharded cross-device placement peer-read every
4318 // remote layer's weights on every spec round (measured 13.9-28x on the batched twin).
4319 // The refusal below survives to cover the residue — MEMRA_SPEC_PP=0, MEMRA_PP_STREAMS=0,
4320 // or a placement whose PpNRt fails to build — so a config that would still walk the
4321 // whole trunk on one stream refuses instead of regressing 28x.
4322 if let Some(fence) = crate::pp::pp_cuts(self.layers.len()) {
4323 if !crate::pp::pp2_streams_off() && crate::pp::spec_pp_on() {
4324 if vtok_dev.is_some() {
4325 return Err(
4326 "device-token dspark verify (slice-2 deferred readback) has no PP \
4327 stage-split arm; set MEMRA_DSPARK_DEFER_READBACK=0 or run the dspark \
4328 route on one device"
4329 .into(),
4330 );
4331 }
4332 return self.decode_step_t_core_ppn(
4333 e,
4334 tokens,
4335 pos0,
4336 cache,
4337 embd_dev,
4338 ckpt.take(),
4339 stream,
4340 &fence,
4341 pp_pipe,
4342 );
4343 }
4344 }
4345 crate::pp::refuse_unsplit_if_remote(
4346 "decode_step_t (spec verify)",
4347 "drop MEMRA_SPEC_PP=0 / MEMRA_PP_STREAMS=0 so the verify trunk takes its OWN stage \
4348 split (decode_step_t_core_ppn); or run spec on one device",
4349 )?;
4350 let cfg = &self.cfg;
4351 let n_embd = cfg.n_embd as usize;
4352 let eps = cfg.rms_eps;
4353 let t = tokens.len();
4354 let pos_d = match stream {
4355 Some((_, ctr)) => {
4356 let mut p = e.alloc_uninit::<i32>(t)?;
4357 e.pos_iota(ctr, &mut p, t)?;
4358 p
4359 }
4360 None => {
4361 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
4362 e.htod_i32(&pos_vec)?
4363 }
4364 };
4365
4366 // embed T tokens -> [T, n_embd] token-major (device gather on the spec hot loop)
4367 let x = match (stream, embd_dev) {
4368 (Some((vtok, _)), Some((g, qt, rb))) => {
4369 e.embed_gather_device_td(g, vtok, t, n_embd, qt, rb)?
4370 }
4371 (None, Some((g, qt, rb))) => match vtok_dev {
4372 // slice 2: device verify tokens, same embed_gather_u32_t kernel —
4373 // bit-identical rows to the host-token arm (same per-dtype deq).
4374 Some(vt_d) => e.embed_gather_device_td(g, vt_d, t, n_embd, qt, rb)?,
4375 None => e.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
4376 },
4377 _ => {
4378 assert!(
4379 vtok_dev.is_none(),
4380 "device-token verify requires the resident embed table (embd_dev)"
4381 );
4382 e.htod(&self.embd.gather(n_embd, tokens))?
4383 }
4384 };
4385
4386 // TRUNK WALK: layers [0, n_layers) through the SAME range-scoped subgraph the PP-N
4387 // stage split calls per stage (`verify_layers`) — one code path, so the split cannot
4388 // drift from the unsplit dispatch mirroring. lane/pp2-spec 2026-08-06.
4389 let x = self.verify_layers(
4390 e,
4391 x,
4392 0,
4393 self.layers.len(),
4394 &pos_d,
4395 pos0,
4396 t,
4397 cache,
4398 ckpt.take(),
4399 stream,
4400 graphs,
4401 )?;
4402
4403 let mut hn = vbuf(e, t * n_embd)?;
4404 let serving_head = self.cfg.step35.is_some() || self.qwen35_serving_class();
4405 let logits = if serving_head {
4406 // Step35 and the qwen35 family (MoE 2026-08-14 AM, dense-hybrid same day PM — the
4407 // Q3.8 bring-up reproduced the identical near-tie class on dense: eager-class verify
4408 // vs batched-class live serving, ULP drift amplified through the GDN recurrence)
4409 // serve one batched numeric class at every live width, including B=1. Keep the
4410 // verify head in that same class; other generic families retain the decode-exact
4411 // head that their run-spec contract pins.
4412 e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
4413 e.matmul(&self.output, &hn, t)?
4414 } else {
4415 e.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
4416 e.matmul_decode_exact(&self.output, &hn, t)?
4417 };
4418 // stream: the device pos counter owns position; host mirror reconciles at drain.
4419 if stream.is_none() {
4420 cache.pos += t;
4421 }
4422 // Hidden stack for seeds/refresh-fills: pre-norm x (default) or post-norm hn (HPOST).
4423 Ok((logits, if spec_hpost() { hn } else { x }))
4424 }
4425
4426 /// THE VERIFY TRUNK OVER PP-N (lane/pp2-spec 2026-08-06): `decode_step_t_core_stream`'s walk
4427 /// as N stage subgraphs, each on its own engine/stream (and, under `MEMRA_PP_DEVICES`, its own
4428 /// device), with a `[T, n_embd]` boundary transfer between them. T = K+1 (the verify batch),
4429 /// so this is the batched-boundary shape the pp2-batch lane's grow-only slots already handle
4430 /// (`tx(b, x, t*n_embd)`; the slot grows to the high-water T and the transport moves exactly
4431 /// the payload).
4432 ///
4433 /// Structure is `decode_step_batch_ppn`'s, which is `decode_step_h_ppn`'s. FOUR THINGS ARE
4434 /// PER-STAGE and each for a measured reason (see `decode_step_batch_ppn`'s header for the
4435 /// receipts):
4436 ///
4437 /// 1. THE ENGINE (`rt.engine(s, e)`) — `Engine` owns lazily-grown stable-pointer scratch
4438 /// (`fa_part_pool`, `fa_vf16_scratch`, `argmax_partials`) that is single-stream-safe BY
4439 /// DESIGN. Two stage streams through one Engine is the 2026-08-02 shared-scratch race
4440 /// (35% flake, nondeterministic all-logits divergence). `PpNRt::build` gives every stage
4441 /// s>0 its own Engine even on the primary device; honouring it here is what scopes the
4442 /// pools. The verify path allocates MORE of that scratch than eager decode does (FA at
4443 /// m=T, and the per-layer `GdnStash` retains), so this is load-bearing, not inherited.
4444 ///
4445 /// 2. `pos_d` — each stage uploads its OWN copy of the T rope positions on ITS stream, so the
4446 /// buffer is allocated, consumed and freed on one stream. In `stream` mode that means each
4447 /// stage runs its own `pos_iota` over the SHARED device counter (`pos_ctr`): the counter is
4448 /// read-only during the forward (the round's `inc`/`copy_add` happen outside it), so every
4449 /// stage derives the identical iota, and each stage's own output buffer is stream-local.
4450 ///
4451 /// 3. THE EMBED lives with stage 0 (`self.embd` / `embd_gpu` are host/primary-side; the
4452 /// sharded loader leaves the table with stage 0 by construction).
4453 ///
4454 /// 4. THE HEAD (`output_norm` + `output`) runs on the LAST stage — the sharded loader uploaded
4455 /// both through that stage's engine (`hybrid.rs`: `e_head = layer_engine(e, n_trunk,
4456 /// n_trunk-1)`), so reading them anywhere else is a peer read of the biggest tensor in the
4457 /// model, every round.
4458 ///
4459 /// WHAT STAYS ON THE PRIMARY, deliberately: the returned logits and hidden stack `x`. Both are
4460 /// last-stage-allocated device buffers, and every consumer (the device argmax walk, the accept
4461 /// kernels, `spec_seed_gather`, the ckpt rebuild in `commit_verified_prefix`) reads them
4462 /// through the primary context by UVA — the same read the batched serving epilogue's
4463 /// `last_logits_dev` park does. Those consumers are per-round O(T x n_vocab) and O(n_embd),
4464 /// not per-layer, so they are not the 28x class; splitting them is a separate lane.
4465 ///
4466 /// The MTP HEAD (draft side) is NOT split: it is one block, it lives wherever the loader put
4467 /// it (`load_mtp` uses the primary engine), and it is ~1-2 GB against the trunk's tens. Draft
4468 /// placement is measured, not assumed — see `research/pp2-spec-20260806`.
4469 ///
4470 /// EXACTNESS: PP-N adds ZERO deviation. Each stage runs the SAME kernels on the SAME bytes in
4471 /// the same order via the SAME `verify_layers` the unsplit body calls; the only change is
4472 /// where the residual is materialized, and the boundary is a straight f32 copy (dtod
4473 /// same-device / `cudaMemcpyPeerAsync` cross-device, no conversion). So the split MUST be
4474 /// BIT-IDENTICAL to the unsplit verify at the same T, in both placement orders. Gate:
4475 /// `decode-batch-gate --mode ppspec`. Acceptance counts are a DERIVED consequence — greedy
4476 /// accept argmaxes these logits, so bit-identical logits force identical accept walks; the
4477 /// `run-spec` K=1..8 arm checks that end-to-end rather than trusting the implication.
4478 #[allow(clippy::too_many_arguments)]
4479 fn decode_step_t_core_ppn(
4480 &self,
4481 e: &Engine,
4482 tokens: &[u32],
4483 pos0: usize,
4484 cache: &mut Cache,
4485 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4486 mut ckpt: Option<&mut VerifyCkpt>,
4487 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
4488 fence: &[usize],
4489 pp_pipe: Option<bool>,
4490 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4491 let ticket = self.verify_stage0_issue(
4492 e,
4493 tokens,
4494 pos0,
4495 cache,
4496 embd_dev,
4497 ckpt.as_deref_mut(),
4498 stream,
4499 fence,
4500 pp_pipe,
4501 None,
4502 )?;
4503 self.verify_stage1_finish(e, ticket, cache, ckpt, stream, fence, true)
4504 }
4505
4506 /// Enqueue embed, stage 0, and the first boundary TX, then return the actual boundary slot.
4507 /// The ordinary PP verify wrapper calls `verify_stage1_finish` immediately after this return.
4508 #[allow(clippy::too_many_arguments)]
4509 fn verify_stage0_issue(
4510 &self,
4511 e: &Engine,
4512 tokens: &[u32],
4513 pos0: usize,
4514 cache: &mut Cache,
4515 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4516 mut ckpt: Option<&mut VerifyCkpt>,
4517 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
4518 fence: &[usize],
4519 pp_pipe: Option<bool>,
4520 trace: Option<SpecPipeTraceCtx>,
4521 ) -> Result<VerifyBoundaryTicket, Box<dyn std::error::Error>> {
4522 assert!(
4523 !self.is_gemma4_e4b() && self.cfg.gemma4.is_none(),
4524 "decode_step_t_core_ppn covers the hybrid non-gemma4 verify trunk only \
4525 (the gemma4 arms have their own decode_step_t twins)"
4526 );
4527 if crate::pp::pp_host_bounce_active() && (stream.is_some() || embd_dev.is_some()) {
4528 return Err(
4529 "decode_step_t_core_ppn: refused with MEMRA_PP_HOST_BOUNCE=1 — the trunk \
4530 boundary itself is host-staged, but device-resident verify still peer-reads \
4531 primary-device token/position/embedding buffers from stage 0. Run plain PP \
4532 serving on this host class; spec requires local per-stage inputs first."
4533 .into(),
4534 );
4535 }
4536 let rt = crate::pp::PpNRt::get(e)?;
4537 let n_st = fence.len() - 1;
4538 assert_eq!(
4539 rt.n_stages(),
4540 n_st,
4541 "PpNRt stage count {} != fence stages {n_st}",
4542 rt.n_stages()
4543 );
4544 let n_embd = self.cfg.n_embd as usize;
4545 let t = tokens.len();
4546 let payload = t * n_embd;
4547 if pp_pipe.is_some() {
4548 assert_eq!(n_st, 2, "spec pipeline requires exactly two PP stages");
4549 }
4550 // One-shot lane diagnostic: force natural PP-2 boundaries to completion so the server
4551 // log can price stage 0, the peer hop, the RX copy, and stage 1 + head separately without
4552 // nsys. The ordinary path keeps every enqueue asynchronous. N>2 is deliberately excluded:
4553 // the report below names exactly two stages and must never imply it measured middle ones.
4554 let pp_anatomy = n_st == 2 && std::env::var("MEMRA_SPEC_PP_ANATOMY").as_deref() == Ok("1");
4555 let pp_started = std::time::Instant::now();
4556 let (mut reverse_ms, mut stage0_ms, mut tx_ms) = (0.0f64, 0.0f64, 0.0f64);
4557 // The CALLER's ambient stream, captured BEFORE any `rt.enter()` pushes a stage stream:
4558 // this body returns DEVICE-RESIDENT buffers (the device-argmax accept walk's contract),
4559 // so the exit needs the same publication the boundaries get — see `PpNRt::publish_to`.
4560 // Taken here, not at the end, because inside the last-stage scope `e.stream()` IS the
4561 // stage stream and the wait would self-order into a no-op.
4562 let caller_stream = e.stream();
4563 // #87 ROOT-CAUSE FENCE (lane/pp2spec-crash): the PREVIOUS round's stage-allocated
4564 // outputs (logits/hidden/ckpt stashes) freed stream-ordered on the STAGE streams while
4565 // the primary stream still holds queued reads of them — with event tracking elided,
4566 // nothing stops the pool from reusing those blocks for THIS round's stage allocations,
4567 // whose writes then race the queued reads (measured: 13/4096-NaN random-bits garbage in
4568 // the spec round seed; the full anatomy is on `PpNRt::fence_stages_behind`). Order every
4569 // stage stream behind the caller before enqueueing new stage work.
4570 let reverse_started = std::time::Instant::now();
4571 if pp_pipe != Some(false) {
4572 rt.fence_stages_behind(&caller_stream)?;
4573 }
4574 if pp_pipe == Some(true) {
4575 // Both session verifies must alternate boundary slots even when the ordinary
4576 // decode overlap experiment is off. Prewarm before A's stage 0 so B cannot grow
4577 // slot 1 by synchronizing the RX stream while A's stage 1 is in flight.
4578 rt.prepare_overlap_slots(0, payload)?;
4579 }
4580 if pp_anatomy {
4581 // Drain the reverse-publication dependency before timing stage 0 itself. At c=1 this
4582 // prices any primary-stream rollback/refresh tail inherited from the prior round.
4583 for s in 0..n_st {
4584 let _st = rt.enter(s);
4585 rt.engine(s, e).stream().synchronize()?;
4586 }
4587 reverse_ms = reverse_started.elapsed().as_secs_f64() * 1e3;
4588 }
4589
4590 // Per-stage rope positions: in host mode the same [T] iota each stage uploads itself; in
4591 // stream mode each stage's own `pos_iota` over the shared read-only device counter.
4592 let stage_pos = |es: &Engine| -> Result<CudaSlice<i32>, Box<dyn std::error::Error>> {
4593 match stream {
4594 Some((_, ctr)) => {
4595 let mut p = es.alloc_uninit::<i32>(t)?;
4596 es.pos_iota(ctr, &mut p, t)?;
4597 Ok(p)
4598 }
4599 None => {
4600 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
4601 es.htod_i32(&pos_vec)
4602 }
4603 }
4604 };
4605
4606 // ---- STAGE 0: embed (the table lives with stage 0) + layers [0, fence[1]) + TX ----
4607 let slot = {
4608 let _st0 = rt.enter(0);
4609 let e0 = rt.engine(0, e);
4610 enqueue_spec_pipe_trace_marker(&e0.stream(), trace.as_ref(), "S0", "start", None)?;
4611 let stage0_started = std::time::Instant::now();
4612 let pos_d = stage_pos(e0)?;
4613 let x = match (stream, embd_dev) {
4614 (Some((vtok, _)), Some((g, qt, rb))) => {
4615 e0.embed_gather_device_td(g, vtok, t, n_embd, qt, rb)?
4616 }
4617 (None, Some((g, qt, rb))) => e0.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
4618 _ => e0.htod(&self.embd.gather(n_embd, tokens))?,
4619 };
4620 let x = self.verify_layers(
4621 e0,
4622 x,
4623 fence[0],
4624 fence[1],
4625 &pos_d,
4626 pos0,
4627 t,
4628 cache,
4629 ckpt.as_deref_mut(),
4630 stream,
4631 None,
4632 )?;
4633 if pp_anatomy {
4634 e0.stream().synchronize()?;
4635 stage0_ms = stage0_started.elapsed().as_secs_f64() * 1e3;
4636 }
4637 let tx_started = std::time::Instant::now();
4638 let slot = if pp_pipe.is_some() {
4639 rt.tx_pipelined(0, &x, payload)?
4640 } else {
4641 rt.tx(0, &x, payload)?
4642 };
4643 enqueue_spec_pipe_trace_marker(&e0.stream(), trace.as_ref(), "S0", "end", Some(slot))?;
4644 if pp_anatomy {
4645 e0.stream().synchronize()?;
4646 tx_ms = tx_started.elapsed().as_secs_f64() * 1e3;
4647 }
4648 slot
4649 // x + pos_d drop here: freed stream-ordered on stage-0's stream after use.
4650 };
4651
4652 Ok(VerifyBoundaryTicket {
4653 rt,
4654 caller_stream,
4655 slot,
4656 pos0,
4657 t,
4658 payload,
4659 n_st,
4660 pipelined: pp_pipe.is_some(),
4661 pp_anatomy,
4662 pp_started,
4663 reverse_ms,
4664 stage0_ms,
4665 tx_ms,
4666 trace,
4667 })
4668 }
4669
4670 /// Consume a stage-0 boundary ticket and enqueue the remaining PP stages plus the head.
4671 /// On PP-2 this is exactly stage 1; PP-N keeps its pre-existing middle-stage walk here.
4672 #[allow(clippy::too_many_arguments)]
4673 fn verify_stage1_finish(
4674 &self,
4675 e: &Engine,
4676 ticket: VerifyBoundaryTicket,
4677 cache: &mut Cache,
4678 mut ckpt: Option<&mut VerifyCkpt>,
4679 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
4680 fence: &[usize],
4681 publish_to_caller: bool,
4682 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4683 let VerifyBoundaryTicket {
4684 rt,
4685 caller_stream,
4686 slot,
4687 pos0,
4688 t,
4689 payload,
4690 n_st,
4691 pipelined,
4692 pp_anatomy,
4693 pp_started,
4694 reverse_ms,
4695 stage0_ms,
4696 tx_ms,
4697 trace,
4698 } = ticket;
4699 let n_embd = self.cfg.n_embd as usize;
4700 let eps = self.cfg.rms_eps;
4701 let mut slot = slot;
4702 let (mut rx_ms, mut stage1_ms) = (0.0f64, 0.0f64);
4703 let stage_pos = |es: &Engine| -> Result<CudaSlice<i32>, Box<dyn std::error::Error>> {
4704 match stream {
4705 Some((_, ctr)) => {
4706 let mut p = es.alloc_uninit::<i32>(t)?;
4707 es.pos_iota(ctr, &mut p, t)?;
4708 Ok(p)
4709 }
4710 None => {
4711 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
4712 es.htod_i32(&pos_vec)
4713 }
4714 }
4715 };
4716
4717 // ---- MIDDLE STAGES: RX boundary s-1 -> range -> TX boundary s ----
4718 for s in 1..n_st - 1 {
4719 let _st = rt.enter(s);
4720 let es = rt.engine(s, e);
4721 let pos_d = stage_pos(es)?;
4722 let x = rt.rx(s - 1, slot, payload)?;
4723 let x = self.verify_layers(
4724 es,
4725 x,
4726 fence[s],
4727 fence[s + 1],
4728 &pos_d,
4729 pos0,
4730 t,
4731 cache,
4732 ckpt.as_deref_mut(),
4733 stream,
4734 None,
4735 )?;
4736 slot = if pipelined {
4737 rt.tx_pipelined(s, &x, payload)?
4738 } else {
4739 rt.tx(s, &x, payload)?
4740 };
4741 }
4742
4743 // ---- LAST STAGE: RX + final range + output_norm + lm head ----
4744 let _stl = rt.enter(n_st - 1);
4745 let el = rt.engine(n_st - 1, e);
4746 let pos_d = stage_pos(el)?;
4747 let rx_started = std::time::Instant::now();
4748 let x = rt.rx(n_st - 2, slot, payload)?;
4749 if pp_anatomy {
4750 el.stream().synchronize()?;
4751 rx_ms = rx_started.elapsed().as_secs_f64() * 1e3;
4752 }
4753 enqueue_spec_pipe_trace_marker(&el.stream(), trace.as_ref(), "S1", "start", Some(slot))?;
4754 let stage1_started = std::time::Instant::now();
4755 let x = self.verify_layers(
4756 el,
4757 x,
4758 fence[n_st - 1],
4759 fence[n_st],
4760 &pos_d,
4761 pos0,
4762 t,
4763 cache,
4764 ckpt.as_deref_mut(),
4765 stream,
4766 None,
4767 )?;
4768
4769 let mut hn = vbuf(el, payload)?;
4770 let logits = if self.cfg.step35.is_some() {
4771 // The PP Step35 serving path uses rms_norm + matmul for B=1 as well as B>1.
4772 // Verify must not switch numeric class merely because the same session speculates.
4773 el.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
4774 el.matmul(&self.output, &hn, t)?
4775 } else {
4776 el.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
4777 el.matmul_decode_exact(&self.output, &hn, t)?
4778 };
4779 enqueue_spec_pipe_trace_marker(&el.stream(), trace.as_ref(), "S1", "end", Some(slot))?;
4780 if pp_anatomy {
4781 el.stream().synchronize()?;
4782 stage1_ms = stage1_started.elapsed().as_secs_f64() * 1e3;
4783 }
4784 // EXIT PUBLICATION: both returned buffers are still being produced on the last stage's
4785 // stream. Order the caller's stream behind that work before the buffers escape this
4786 // scope (the 2026-08-06 same-device ppspec find: without it the caller's primary-stream
4787 // consumer read unwritten logits — nondeterministic, one-device-only, and it poisoned
4788 // the following arm's KV in the same process).
4789 if publish_to_caller {
4790 rt.publish_to(n_st - 1, &caller_stream)?;
4791 }
4792 if pp_anatomy {
4793 if publish_to_caller {
4794 caller_stream.synchronize()?;
4795 }
4796 eprintln!(
4797 "[spec-pp-anatomy] t={t} reverse={reverse_ms:.3}ms stage0={stage0_ms:.3}ms \
4798 tx={tx_ms:.3}ms rx={rx_ms:.3}ms stage1-head={stage1_ms:.3}ms total={:.3}ms",
4799 pp_started.elapsed().as_secs_f64() * 1e3,
4800 );
4801 }
4802 // stream: the device pos counter owns position; host mirror reconciles at drain.
4803 if stream.is_none() {
4804 cache.pos += t;
4805 }
4806 Ok((logits, if spec_hpost() { hn } else { x }))
4807 }
4808
4809 /// Step3.5/Step3.7 verify trunk in the serving batched numeric class.
4810 ///
4811 /// `step35_decode_batch_layers` is now authoritative at every live serving width, including
4812 /// B=1 (lane/cx-b1fix). The older verify walk deliberately mirrored the eager T=1 class:
4813 /// it replayed `step35_decode_attn` per row and used the eager/decode-exact FFN dispatch.
4814 /// Those classes are individually stable, but a near-tie prompt can choose different greedy
4815 /// bytes when a request moves from batched plain serving into speculative verify. Run the
4816 /// same authoritative B=1 stage subgraph for each verify row here. Rows still advance
4817 /// layer-by-layer, so every layer sees the preceding verify rows in its attention cache while
4818 /// every norm/projection/FFN uses exactly the live serving dispatch.
4819 #[allow(clippy::too_many_arguments)]
4820 fn step35_verify_batch_layers(
4821 &self,
4822 e: &Engine,
4823 mut x: CudaSlice<f32>,
4824 lo: usize,
4825 hi: usize,
4826 pos0: usize,
4827 t: usize,
4828 cache: &mut Cache,
4829 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
4830 let n_embd = self.cfg.n_embd as usize;
4831 self.cfg
4832 .step35
4833 .as_ref()
4834 .ok_or("step35 verify batch requires step35 cfg")?;
4835 let mut ph_last = std::time::Instant::now();
4836 for il in lo..hi {
4837 let mut next = e.uninit(t * n_embd)?;
4838 for r in 0..t {
4839 let mut row = e.uninit(n_embd)?;
4840 e.dtod_copy_view(&x.slice(r * n_embd..(r + 1) * n_embd), &mut row)?;
4841 // The caller owns this verify's position. During controller overlap, cache.pos
4842 // still describes generation N while this stage-0 walk belongs to N+1.
4843 let row_pos = e.htod_i32(&[(pos0 + r) as i32])?;
4844 let mut one = [&mut *cache];
4845 let out = self.step35_decode_batch_layers(
4846 e,
4847 row,
4848 &mut one,
4849 &row_pos,
4850 il,
4851 il + 1,
4852 &mut ph_last,
4853 )?;
4854 e.dtod_copy_into(&out, &mut next, r * n_embd)?;
4855 }
4856 self.dflash_tap(e, cache, il, &next, t)?;
4857 x = next;
4858 }
4859 Ok(x)
4860 }
4861
4862 /// DSpark drafter verify (lane/dspark-q38-recover): one t-row forward through the
4863 /// SERVING-CLASS verify funnel (`decode_step_t_core_stream` — the same numeric class
4864 /// MTP verify rides, GDN state advanced in place), returning per-row argmax tokens.
4865 /// Advances `cache.pos += t`; the caller owns snapshot/rollback (block acceptance is
4866 /// prefix-keep, not all-or-nothing).
4867 pub(crate) fn dspark_verify_t_am(
4868 &self,
4869 e: &Engine,
4870 tokens: &[u32],
4871 pos0: usize,
4872 cache: &mut Cache,
4873 ) -> Result<Vec<u32>, Box<dyn std::error::Error>> {
4874 let (logits, _hn) = self.decode_step_t_core_stream(
4875 e, tokens, pos0, cache, None, None, None, None, None, None,
4876 )?;
4877 let t = tokens.len();
4878 let v = self.output.out_features();
4879 let mut am_d = e.stream().alloc_zeros::<u32>(t)?;
4880 for r in 0..t {
4881 e.argmax_token_device_col(&logits, r, v, &mut am_d, r)?;
4882 }
4883 Ok(e.dtoh_u32(&am_d)?)
4884 }
4885
4886 /// DSpark verify returning the RAW verify logits [t, n_vocab] (device-resident) instead
4887 /// of per-row argmaxes — the sampled-admission arm's input (rejection-sampling accept
4888 /// gathers filtered p from these columns; lane/dspark-sampled-admission-20260820). Same
4889 /// forward as `dspark_verify_t_am`; the greedy arm keeps its argmax wrapper untouched.
4890 pub(crate) fn dspark_verify_t_logits(
4891 &self,
4892 e: &Engine,
4893 tokens: &[u32],
4894 pos0: usize,
4895 cache: &mut Cache,
4896 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
4897 let (logits, _hn) = self.decode_step_t_core_stream(
4898 e, tokens, pos0, cache, None, None, None, None, None, None,
4899 )?;
4900 Ok(logits)
4901 }
4902
4903 /// DSpark verify with the MTP column-stash armed: identical forward to
4904 /// `dspark_verify_t_am`, but fills a `VerifyCkpt` so a partial accept can restore
4905 /// column state directly (`dspark_commit_prefix`) instead of snapshot-replay.
4906 /// The ckpt type is opaque outside spec.rs (newtype) — dflash.rs threads it through.
4907 pub(crate) fn dspark_verify_t_am_ckpt(
4908 &self,
4909 e: &Engine,
4910 tokens: &[u32],
4911 pos0: usize,
4912 cache: &mut Cache,
4913 ) -> Result<(Vec<u32>, DsparkVerifyCkpt), Box<dyn std::error::Error>> {
4914 let mut ck = VerifyCkpt::new(self.layers.len());
4915 let (logits, _hn) = self.decode_step_t_core_stream(
4916 e,
4917 tokens,
4918 pos0,
4919 cache,
4920 None,
4921 Some(&mut ck),
4922 None,
4923 None,
4924 None,
4925 None,
4926 )?;
4927 let t = tokens.len();
4928 let v = self.output.out_features();
4929 let mut am_d = e.stream().alloc_zeros::<u32>(t)?;
4930 for r in 0..t {
4931 e.argmax_token_device_col(&logits, r, v, &mut am_d, r)?;
4932 }
4933 Ok((e.dtoh_u32(&am_d)?, DsparkVerifyCkpt(ck)))
4934 }
4935
4936 /// Engine-bundle slice 2: `dspark_verify_t_am_ckpt` with DEVICE tokens and NO readback.
4937 /// The verify tokens are the round's `chain_d` (cand layout: [anchor, drafts...]); the
4938 /// embed gathers its first `t` entries on-device (`embed_gather_u32_t` — bit-identical
4939 /// rows to the host arm), so the host never blocks on the draft chain before dispatching
4940 /// verify. Returns the device per-row argmax buffer; the caller merges its readback with
4941 /// the chain's into ONE sync. Forward, ckpt fill and argmax walk are `_ckpt` verbatim.
4942 pub(crate) fn dspark_verify_t_am_ckpt_dev(
4943 &self,
4944 e: &Engine,
4945 vtok: &CudaSlice<u32>,
4946 t: usize,
4947 pos0: usize,
4948 cache: &mut Cache,
4949 embd_dev: (&CudaSlice<u8>, i32, usize),
4950 graphs: Option<&mut DsparkVerifyGraphs>,
4951 ) -> Result<(CudaSlice<u32>, DsparkVerifyCkpt), Box<dyn std::error::Error>> {
4952 debug_assert!(
4953 vtok.len() >= t,
4954 "verify window exceeds the device token buffer"
4955 );
4956 // The slab flag is a per-round statement: clear it here so a verify that never
4957 // reaches the graphs door (rowwise env, a non-tparallel arm) cannot leave a
4958 // stale `true` steering the commit at slabs the round never wrote.
4959 let mut graphs = graphs;
4960 if let Some(g) = graphs.as_deref_mut() {
4961 g.round_slab = false;
4962 }
4963 let mut ck = VerifyCkpt::new(self.layers.len());
4964 // Dummy host tokens size the funnel; the embed reads `vtok` (the round-stream
4965 // arm's established pattern — spec.rs stream-mode verify does the same).
4966 let dummy = vec![0u32; t];
4967 let (logits, _hn) = self.decode_step_t_core_stream(
4968 e,
4969 &dummy,
4970 pos0,
4971 cache,
4972 Some(embd_dev),
4973 Some(&mut ck),
4974 None,
4975 None,
4976 Some(vtok),
4977 graphs,
4978 )?;
4979 let v = self.output.out_features();
4980 let mut am_d = e.stream().alloc_zeros::<u32>(t)?;
4981 for r in 0..t {
4982 e.argmax_token_device_col(&logits, r, v, &mut am_d, r)?;
4983 }
4984 Ok((am_d, DsparkVerifyCkpt(ck)))
4985 }
4986
4987 /// Ckpt-armed twin of [`Self::dspark_verify_t_logits`] (sampled-admission arm).
4988 pub(crate) fn dspark_verify_t_logits_ckpt(
4989 &self,
4990 e: &Engine,
4991 tokens: &[u32],
4992 pos0: usize,
4993 cache: &mut Cache,
4994 ) -> Result<(CudaSlice<f32>, DsparkVerifyCkpt), Box<dyn std::error::Error>> {
4995 let mut ck = VerifyCkpt::new(self.layers.len());
4996 let (logits, _hn) = self.decode_step_t_core_stream(
4997 e,
4998 tokens,
4999 pos0,
5000 cache,
5001 None,
5002 Some(&mut ck),
5003 None,
5004 None,
5005 None,
5006 None,
5007 )?;
5008 Ok((logits, DsparkVerifyCkpt(ck)))
5009 }
5010
5011 /// Restore the round to `keep` accepted columns from the verify stash: KV lens and
5012 /// pos from the pre-verify snapshot + keep, GDN conv/ssm from the stashed column
5013 /// state — no replay forward. The exact `commit_verified_prefix` the MTP path ships.
5014 pub(crate) fn dspark_commit_prefix(
5015 &self,
5016 e: &Engine,
5017 cache: &mut Cache,
5018 snap: &crate::cache::CacheSnapshot,
5019 ckpt: &DsparkVerifyCkpt,
5020 keep: usize,
5021 ) -> Result<(), Box<dyn std::error::Error>> {
5022 self.commit_verified_prefix(e, cache, snap, &ckpt.0, keep, false, None)
5023 }
5024
5025 /// Slice-3 commit twin: restore to `keep` accepted columns when the round's linear
5026 /// column stash lives in the graphs ctx's persistent slabs (`DsparkVerifyGraphs`) —
5027 /// the cols arm's exact semantics (KV lens + pos from the snapshot, GDN conv/ssm
5028 /// from the stash of column keep-1), slab-addressed and batched into two copy
5029 /// launches. `MEMRA_STATE_COPY_BATCH=0` falls back to per-layer view copies.
5030 pub(crate) fn dspark_commit_prefix_slab(
5031 &self,
5032 e: &Engine,
5033 cache: &mut Cache,
5034 snap: &crate::cache::CacheSnapshot,
5035 ctx: &DsparkVerifyGraphs,
5036 keep: usize,
5037 ) -> Result<(), Box<dyn std::error::Error>> {
5038 use cudarc::driver::DevicePtr;
5039 debug_assert!(keep >= 1, "keep==0 rounds take the legacy rollback");
5040 let mut conv_src: Vec<u64> = Vec::new();
5041 let mut ssm_src: Vec<u64> = Vec::new();
5042 let mut conv_dst: Vec<u64> = Vec::new();
5043 let mut ssm_dst: Vec<u64> = Vec::new();
5044 for il in 0..self.layers.len() {
5045 if let (Some(kvl), Some(saved)) = (cache.kv[il].as_mut(), snap.kv_len[il]) {
5046 kvl.len = saved + keep;
5047 e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
5048 }
5049 if let Some(rl) = cache.recur[il].as_ref() {
5050 let (pc, ps, _cw, _sw) = ctx
5051 .slab_row(e, il, keep - 1)
5052 .ok_or("slab commit: linear layer missing from the graphs ctx")?;
5053 conv_src.push(pc);
5054 ssm_src.push(ps);
5055 let st = &e.gpu.stream();
5056 let (dc, _g0) = rl.conv_state.device_ptr(st);
5057 let (ds, _g1) = rl.ssm_state.device_ptr(st);
5058 conv_dst.push(dc as u64);
5059 ssm_dst.push(ds as u64);
5060 }
5061 }
5062 let n = conv_src.len();
5063 if n > 0 {
5064 if state_copy_batch_on() {
5065 let mut tt = vec![0u64; 2 * n];
5066 tt[..n].copy_from_slice(&conv_src);
5067 tt[n..].copy_from_slice(&conv_dst);
5068 let ct = e.htod_u64(&tt)?;
5069 tt[..n].copy_from_slice(&ssm_src);
5070 tt[n..].copy_from_slice(&ssm_dst);
5071 let st = e.htod_u64(&tt)?;
5072 e.copy_batch_uniform_f32(&ct, n, ctx.conv_words)?;
5073 e.copy_batch_uniform_f32(&st, n, ctx.ssm_words)?;
5074 } else {
5075 let (cw, sw) = (ctx.conv_words, ctx.ssm_words);
5076 let row = keep - 1;
5077 for il in 0..self.layers.len() {
5078 let Some(rl) = cache.recur[il].as_mut() else {
5079 continue;
5080 };
5081 let k = ctx.lin_pos[&il];
5082 {
5083 let sv = e.view(&ctx.stash_conv[k], (row + 1) * cw);
5084 let win = sv.slice(row * cw..(row + 1) * cw);
5085 e.copy_view_into(&mut rl.conv_state, 0, &win, cw)?;
5086 }
5087 {
5088 let sv = e.view(&ctx.stash_ssm[k], (row + 1) * sw);
5089 let win = sv.slice(row * sw..(row + 1) * sw);
5090 e.copy_view_into(&mut rl.ssm_state, 0, &win, sw)?;
5091 }
5092 }
5093 }
5094 }
5095 cache.pos = snap.pos + keep;
5096 Ok(())
5097 }
5098
5099 /// Qwen35-family verify trunk in the live serving numeric class.
5100 ///
5101 /// Serving intentionally keeps this architecture in the generic batched program even at
5102 /// B=1. The older verify walk used its own mirrored dispatch and can flip near-tie argmaxes.
5103 ///
5104 /// Two arms, one numeric class:
5105 /// - DENSE (`Arch::Qwen35`, t<=16): `qwen35_verify_tparallel` — the weight ops (norms,
5106 /// projections, FFN) hoist to m=T through the exact-tier batched kernels whose per-row
5107 /// program IS the m=1 program (`matmul_pre == fused2 per (tensor,row); _bN mmvq per-row
5108 /// == m=1` — decode_batch.rs v2 note), while the state ops (conv ring, gdn scan, KV
5109 /// append, fa decode) stay a per-row loop running the b_n=1 serving kernels with each
5110 /// row's own t_kv-driven arm pick (the straddle law: every row executes the exact
5111 /// program its isolated serving step would). One weight read per layer per round
5112 /// instead of T — this is what makes MTP profitable in the exact class (the per-row
5113 /// walk measured verify(K+1) ~= (K+1) plain steps: 69 -> 44 tok/s served, 2026-08-15).
5114 /// - MoE / t>16 / `MEMRA_SPEC_VERIFY_ROWWISE=1`: the per-row replay of the authoritative
5115 /// serving layer body, preserving single-session autoregressive cache order (the
5116 /// correctness reference; also the rollback seam for the t-parallel arm).
5117 ///
5118 /// Bit-identity of the t-parallel arm vs the rowwise arm is gated by spec-serve-gate
5119 /// (zero differing logits at T=1..4, K arms) + the 8-prompt ON/OFF canary before ship.
5120 #[allow(clippy::too_many_arguments)]
5121 fn qwen35_verify_batch_layers(
5122 &self,
5123 e: &Engine,
5124 x: CudaSlice<f32>,
5125 lo: usize,
5126 hi: usize,
5127 pos0: usize,
5128 t: usize,
5129 cache: &mut Cache,
5130 ckpt: Option<&mut VerifyCkpt>,
5131 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
5132 graphs: Option<&mut DsparkVerifyGraphs>,
5133 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5134 // Qwen35Moe admitted 2026-08-20 (lane/draftcost-moe): the t-parallel arm already
5135 // carries the MoE FFN (`moe_ffn_il_zq8` at m=T) and the GDN per-row state loop; the
5136 // arch fence was a qualification gate, not a mechanism gap. Measured disease on the
5137 // 35B-A3B class: rowwise verify ~= 5.6 ms per drafted token (one full trunk step
5138 // each) — the same (K+1)-plain-steps wall the dense admission fixed on 2026-08-15.
5139 // Rollback seam unchanged: MEMRA_SPEC_VERIFY_ROWWISE=1.
5140 let rowwise = std::env::var("MEMRA_SPEC_VERIFY_ROWWISE").as_deref() == Ok("1")
5141 || !matches!(
5142 self.cfg.arch,
5143 memra_gguf::config::Arch::Qwen35 | memra_gguf::config::Arch::Qwen35Moe
5144 )
5145 || t > 16;
5146 if rowwise {
5147 if stream.is_some() {
5148 // rowwise replays per row with host cache.pos — irreconcilable with a
5149 // device position counter. Burst callers must keep t <= 16 and the
5150 // ROWWISE env unset; refusing beats silently mispositioned rows.
5151 return Err("qwen35 rowwise verify has no ROUND-STREAM arm \
5152 (t > 16 or MEMRA_SPEC_VERIFY_ROWWISE=1)"
5153 .into());
5154 }
5155 self.qwen35_verify_rowwise(e, x, lo, hi, pos0, t, cache, ckpt)
5156 } else {
5157 self.qwen35_verify_tparallel(e, x, lo, hi, pos0, t, cache, ckpt, stream, graphs)
5158 }
5159 }
5160
5161 /// The per-row correctness reference: replay each verify row through the authoritative
5162 /// serving layer body (`decode_batch_layers` at b_n=1). T full weight reads per layer.
5163 #[allow(clippy::too_many_arguments)]
5164 fn qwen35_verify_rowwise(
5165 &self,
5166 e: &Engine,
5167 mut x: CudaSlice<f32>,
5168 lo: usize,
5169 hi: usize,
5170 pos0: usize,
5171 t: usize,
5172 cache: &mut Cache,
5173 mut ckpt: Option<&mut VerifyCkpt>,
5174 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5175 let n_embd = self.cfg.n_embd as usize;
5176 let saved_pos = cache.pos;
5177 let mut ph_last = std::time::Instant::now();
5178 for il in lo..hi {
5179 let mut next = e.uninit(t * n_embd)?;
5180 let mut col_states: Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>> =
5181 if ckpt.is_some() && t >= 2 && matches!(self.layers[il].mixer, Mixer::Linear(_)) {
5182 Some(Vec::with_capacity(t - 1))
5183 } else {
5184 None
5185 };
5186 for r in 0..t {
5187 cache.pos = pos0 + r;
5188 let mut row = e.uninit(n_embd)?;
5189 e.dtod_copy_view(&x.slice(r * n_embd..(r + 1) * n_embd), &mut row)?;
5190 let row_pos = e.htod_i32(&[(pos0 + r) as i32])?;
5191 let mut one = [&mut *cache];
5192 let ctx = self.batch_layer_ctx(e, &one, il, il + 1)?;
5193 let out = match self.decode_batch_layers(
5194 e,
5195 row,
5196 &mut one,
5197 &ctx,
5198 &row_pos,
5199 &mut ph_last,
5200 ) {
5201 Ok(out) => out,
5202 Err(error) => {
5203 cache.pos = saved_pos;
5204 return Err(error);
5205 }
5206 };
5207 e.dtod_copy_into(&out, &mut next, r * n_embd)?;
5208 if r + 1 < t {
5209 if let Some(states) = col_states.as_mut() {
5210 let recur = cache.recur[il]
5211 .as_ref()
5212 .ok_or("Qwen35-MoE linear verify layer has no recurrent state")?;
5213 states.push((
5214 e.clone_dtod(&recur.conv_state)?,
5215 e.clone_dtod(&recur.ssm_state)?,
5216 ));
5217 }
5218 }
5219 }
5220 if let (Some(checkpoint), Some(states)) = (ckpt.as_deref_mut(), col_states) {
5221 checkpoint.cols[il] = Some(states);
5222 }
5223 x = next;
5224 }
5225 cache.pos = saved_pos;
5226 Ok(x)
5227 }
5228
5229 /// T-PARALLEL VERIFY IN THE SERVING NUMERIC CLASS (lane/tparallel-verify, 2026-08-15).
5230 ///
5231 /// The weight ops run ONCE per layer at m=T; the state ops run per row through the same
5232 /// b_n=1 serving kernels the rowwise replay uses. Per-row bit-identity rests on the two
5233 /// pins the serving batch tier already carries:
5234 /// * `matmul_pre` / `_bN` mmvq: per-row program == m=1 program (decode_batch.rs v2 note,
5235 /// kernel-check pinned) — so a [T, n_embd] projection row equals the row projected
5236 /// alone;
5237 /// * row-indexed norms/elementwise (`rms_norm`, `quantize_q8_1`, `add_rms_norm`,
5238 /// `gated_rmsnorm[_q8_1]`, `silu_mul`, `rope_neox` with per-row positions): the T-row
5239 /// launch is the per-row program (same pin the generic verify's fused norms rely on).
5240 /// The sequential dependencies keep their exact serving order: the conv ring / gdn scan
5241 /// chain state row -> row through the `_b` kernels at b_n=1 (ping-pong via a 6-entry
5242 /// alternating pointer table, host handles swapped per row so VerifyCkpt clones the
5243 /// canonical state exactly as the rowwise arm does), and each row's KV append + fa decode
5244 /// picks its arm from ITS OWN t_kv (append: format-only; fa: `fa_seqs_eligible` + its own
5245 /// `fa_split_keys` rung at b_n=1) — the straddle law per row, so every row executes the
5246 /// program its isolated B=1 serving step would.
5247 ///
5248 /// Cost: 1 weight read per layer per round + T state micro-launches, vs the rowwise arm's
5249 /// T weight reads. Gated bit-identical vs the rowwise arm by spec-serve-gate + canary.
5250 #[allow(clippy::too_many_arguments)]
5251 fn qwen35_verify_tparallel(
5252 &self,
5253 e: &Engine,
5254 mut x: CudaSlice<f32>,
5255 lo: usize,
5256 hi: usize,
5257 pos0: usize,
5258 t: usize,
5259 cache: &mut Cache,
5260 mut ckpt: Option<&mut VerifyCkpt>,
5261 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
5262 mut graphs: Option<&mut DsparkVerifyGraphs>,
5263 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5264 let seqs_append =
5265 std::env::var("MEMRA_BATCH_APPEND").as_deref() != Ok("0") && !Engine::kv_fp8_on();
5266 let batch_fa_on = std::env::var("MEMRA_BATCH_FA").as_deref() != Ok("0");
5267
5268 // Merge guard (v0.98 train, re-affirmed on the v0.100 train over slice 4c): the
5269 // ROUND-STREAM arm (lane/draftcost-moe, device position counter) and the dspark
5270 // verify graphs (engine-bundle slice 3 / trunk slice 4c) have no common caller —
5271 // stream rides the qwen35moe burst, graphs ride the dspark route. If a future
5272 // caller arms both, refuse loudly instead of silently dropping the graphs ctx
5273 // (the stream linear arm takes linear_attn_verify_t, not the graphed segment or
5274 // full-verify bodies).
5275 if stream.is_some() && graphs.is_some() {
5276 return Err(
5277 "qwen35 tparallel verify: ROUND-STREAM and dspark verify graphs \
5278 cannot arm together"
5279 .into(),
5280 );
5281 }
5282 // Engine-bundle slice 3 + slice 4c: with a graphs ctx armed, pointer tables are
5283 // refreshed once per verify (the gdn ping-pong moves handles; a fresh generation
5284 // moves the kv caches). Then:
5285 // - slice 4c: when the WHOLE round rides one seqs rung (every row batchable, one
5286 // split-ladder step, rung covers the round), the ENTIRE walk replays as ONE
5287 // full-verify graph per (vt, rung) — linear layers through the shared
5288 // `qwen35_tparallel_linear_layer` body, full-attention layers through the
5289 // shared `qwen35_tparallel_fa_layer` body in graph mode.
5290 // - fallback (straddle rounds, below the vec floor, partial walks): runs of
5291 // consecutive LINEAR layers replay the slice-3 per-(segment, vt) graphs and
5292 // the full-attention layers run eager (batched rows when eligible).
5293 if let Some(g) = graphs.as_deref_mut() {
5294 g.refresh_tables(e, cache)?;
5295 g.round_slab = false;
5296 if let Some(rung) = g.full_rung(self, cache, lo, hi, t, seqs_append && batch_fa_on) {
5297 let out = g.run_full(self, e, lo, hi, &x, t, pos0, rung, cache)?;
5298 g.round_slab = true;
5299 return Ok(out);
5300 }
5301 }
5302 // STREAM (2b, lane/draftcost-moe): positions come from the device round counter
5303 // (pos_iota / i32_copy_add) so a burst round needs no host position knowledge.
5304 let pos_d = match stream {
5305 Some((_, ctr)) => {
5306 let mut p = e.alloc_uninit::<i32>(t)?;
5307 e.pos_iota(ctr, &mut p, t)?;
5308 p
5309 }
5310 None => {
5311 let pos_host: Vec<i32> = (0..t).map(|r| (pos0 + r) as i32).collect();
5312 e.htod_i32(&pos_host)?
5313 }
5314 };
5315 // Per-row 1-element position buffers, built ONCE per verify (the append/fa wrappers
5316 // take owned pos slices; building these inside the layer x row loops cost 16xT H2Ds).
5317 // LAZY since slice 4: the batched fa/append arm never touches them — they are built
5318 // on the first per-row fallback layer only (stream-aware there; the stream FA arm
5319 // rides the dc rows kernels and never reaches the fallback).
5320 let mut pos_rows: Option<Vec<CudaSlice<i32>>> = None;
5321 let mut il = lo;
5322 while il < hi {
5323 if graphs.is_some() && matches!(self.layers[il].mixer, Mixer::Linear(_)) {
5324 let mut end = il;
5325 while end < hi && matches!(self.layers[end].mixer, Mixer::Linear(_)) {
5326 end += 1;
5327 }
5328 let g = graphs.as_deref_mut().expect("checked above");
5329 x = g.run_segment(self, e, il, end, &x, t, cache)?;
5330 g.round_slab = true;
5331 il = end;
5332 continue;
5333 }
5334 let layer = &self.layers[il];
5335 if stream.is_none() && matches!(layer.mixer, Mixer::Linear(_)) {
5336 // Eager linear layer (no graphs ctx): the shared body, legacy cols-ckpt arm.
5337 // Under ROUND-STREAM the linear layers ride the fa-body match's stream arm
5338 // below (linear_attn_verify_t — the stream COMMIT needs its GdnStash).
5339 x = self.qwen35_tparallel_linear_layer(
5340 e,
5341 il,
5342 &x,
5343 t,
5344 cache,
5345 ckpt.as_deref_mut(),
5346 None,
5347 None,
5348 )?;
5349 il += 1;
5350 continue;
5351 }
5352 // Full-attention (or stream-Linear, or MLA-refusing) layer: the extracted
5353 // shared body — eager arm (fresh per-verify pos/table, exact t_kv sizing,
5354 // in-body len bump). The slice-4c captured full-verify graphs run the SAME
5355 // body in graph mode; under ROUND-STREAM the body's dc-rows / GDN stream arms
5356 // run (lane/draftcost-moe).
5357 x = self.qwen35_tparallel_fa_layer(
5358 e,
5359 il,
5360 &x,
5361 t,
5362 cache,
5363 FaLayerArgs {
5364 pos_d: &pos_d,
5365 pos_rows: &mut pos_rows,
5366 pos0,
5367 seqs_append,
5368 batch_fa_on,
5369 graph_cap: None,
5370 stream,
5371 ckpt: ckpt.as_deref_mut(),
5372 },
5373 )?;
5374 il += 1;
5375 }
5376 Ok(x)
5377 }
5378
5379 /// SHARED dense-FFN body for the qwen35 t-parallel layers (trunk-kernels slice B) —
5380 /// ONE copy for the fa and linear layer bodies (the verify_layers extraction lesson).
5381 /// Dual arm (MEMRA_TK_FFN_DUAL, default on): gate+up in ONE dual launch from the
5382 /// pre-quantized activation with macro-scales DEFERRED into the fused SwiGLU+q8_1
5383 /// epilogue, then ffn_down from the fused (aq, ad) — the q27 verify chain verbatim.
5384 /// Every door is the bit-identical proven one: `matmul_decode_exact_dual_pre` (per
5385 /// (tensor,token,row) == the two singles), `silu_mul_scaled_q8_1` (y*s inline == the
5386 /// scale_inplace store, value-exact; fused quantize == quantize_q8_1 bytes),
5387 /// `matmul_decode_exact_pre` (dispatch mirror of the singles' q8_1-fast tail).
5388 /// Dual-refused (t outside 2..=7, non-NVFP4, layout mismatch) or seam off -> the
5389 /// original singles chain, byte-for-byte.
5390 #[allow(clippy::too_many_arguments)]
5391 fn qwen35_tparallel_dense_ffn(
5392 &self,
5393 e: &Engine,
5394 ffn_gate: &crate::model::GpuTensor,
5395 ffn_up: &crate::model::GpuTensor,
5396 ffn_down: &crate::model::GpuTensor,
5397 zn: &CudaSlice<f32>,
5398 t: usize,
5399 n_embd: usize,
5400 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5401 let n_ff = ffn_gate.out_features();
5402 let (zq, zd) = e.quantize_q8_1(zn, t, n_embd)?;
5403 if Engine::tk_ffn_dual_on() {
5404 if let Some(((g, gs), (u, us))) =
5405 e.matmul_decode_exact_dual_pre(ffn_gate, ffn_up, &zq, &zd, t)?
5406 {
5407 if e.uses_q8_1_fast(ffn_down) {
5408 let (aq, ad) = e.silu_mul_scaled_q8_1(&g, &u, gs, us, t * n_ff)?;
5409 return e.matmul_decode_exact_pre(ffn_down, &aq, &ad, t);
5410 }
5411 let mut act = e.uninit(t * n_ff)?;
5412 e.silu_mul_scaled(&g, &u, gs, us, &mut act, t * n_ff)?;
5413 let (aq, ad) = e.quantize_q8_1(&act, t, n_ff)?;
5414 return e.matmul_pre(ffn_down, &aq, &ad, &act, t);
5415 }
5416 }
5417 // v1 singles chain (seam off or dual-refused) — the pre-slice-B body verbatim.
5418 let g = e.matmul_pre(ffn_gate, &zq, &zd, zn, t)?;
5419 let u = e.matmul_pre(ffn_up, &zq, &zd, zn, t)?;
5420 let mut act = e.uninit(t * n_ff)?;
5421 e.silu_mul(&g, &u, &mut act, t * n_ff)?;
5422 let (aq, ad) = e.quantize_q8_1(&act, t, n_ff)?;
5423 e.matmul_pre(ffn_down, &aq, &ad, &act, t)
5424 }
5425
5426 /// ONE t-parallel FULL-ATTENTION layer (attn_norm + fa mixer + post_attn_norm + FFN +
5427 /// tap) — extracted from the walk exactly like `qwen35_tparallel_linear_layer` so the
5428 /// eager walk and the slice-4c captured full-verify graphs execute the SAME body (a
5429 /// second copy is how dispatch mirrors drift — the verify_layers extraction lesson).
5430 ///
5431 /// `args.graph_cap = Some((table, off, rung_end))` is the captured-graph mode:
5432 /// - kv base-pointer pairs come from the ctx-owned persistent table at `off` (a fresh
5433 /// generation's cache lands at new addresses that only the per-verify table refresh
5434 /// knows — the slice-3 baked-address lesson);
5435 /// - the seqs twins size partials/grid at `rung_end` and pin `split_keys` to the
5436 /// rung's ladder value: `n_splits_max` is pure stride, splits >= ns_eff write the
5437 /// EMPTY partial the combine never reads, and every per-row T_kv derives in-kernel
5438 /// from `pos_seq[z]` — so one captured launch replays bit-identically for every
5439 /// round whose rows all sit inside the rung;
5440 /// - the host len bump moves to the replay caller (captured host code does not
5441 /// re-run at replay).
5442 /// Graph mode REFUSES any round the batched arm cannot take: the per-row fallback
5443 /// host-branches on t_kv and must never be captured.
5444 #[allow(clippy::too_many_arguments)]
5445 fn qwen35_tparallel_fa_layer(
5446 &self,
5447 e: &Engine,
5448 il: usize,
5449 x: &CudaSlice<f32>,
5450 t: usize,
5451 cache: &mut Cache,
5452 args: FaLayerArgs<'_>,
5453 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5454 use cudarc::driver::DevicePtr;
5455 let cfg = &self.cfg;
5456 let n_embd = cfg.n_embd as usize;
5457 let eps = cfg.rms_eps;
5458 let head_dim_global = cfg.head_dim_k as usize;
5459 let layer = &self.layers[il];
5460 let FaLayerArgs {
5461 pos_d,
5462 pos_rows,
5463 pos0,
5464 seqs_append,
5465 batch_fa_on,
5466 graph_cap,
5467 stream,
5468 mut ckpt,
5469 } = args;
5470
5471 // ---- attn_norm + q8_1 quantize at m=T (row-indexed == per-row) ----
5472 let anorm = layer.attn_norm.float_data();
5473 let mut xn = e.uninit(t * n_embd)?;
5474 e.rms_norm(x, anorm, &mut xn, n_embd, t, eps)?;
5475 let (hq, hd) = e.quantize_q8_1(&xn, t, n_embd)?;
5476
5477 let mixed: CudaSlice<f32> = match &layer.mixer {
5478 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
5479 // STREAM ARM (2b, lane/draftcost-moe): under a device position counter the
5480 // per-row serving-kernel chain cannot run (host state swaps keyed on host
5481 // row index are fine, but the stream COMMIT needs the GdnStash for its _dc
5482 // rebuild — the per-row chain only produces per-column clones). GDN rides
5483 // `linear_attn_verify_t`: batched q8_1-class projections, stash-producing,
5484 // and its one-scan recurrence is pinned bit-identical to T chained T=1
5485 // steps (its header + kernel-check). Position-independent, so no counter
5486 // plumbing is needed. Guards mirror the generic call site exactly.
5487 Mixer::Linear(la) if stream.is_some() => {
5488 if !(t >= 3 || (t == 2 && spec_m2()))
5489 || !self.mixer_in_q8_1_fast(e, &layer.mixer)
5490 || !e.uses_q8_1_fast(&la.ssm_out)
5491 {
5492 return Err("qwen35 stream verify: GDN batched arm requires t>=3 \
5493 (or MEMRA_SPEC_M2 at t=2) and q8_1-fast projections"
5494 .into());
5495 }
5496 let want = ckpt.is_some();
5497 let (out, stash) =
5498 self.linear_attn_verify_t(e, la, &xn, Some((&hq, &hd)), t, cache, il, want)?;
5499 if let (Some(ck), Some(st)) = (ckpt.as_deref_mut(), stash) {
5500 ck.gdn[il] = Some(st);
5501 }
5502 out
5503 }
5504 Mixer::Linear(_) => {
5505 unreachable!("linear layers ride qwen35_tparallel_linear_layer")
5506 }
5507 Mixer::Full(fa) => {
5508 let geometry = cfg.full_attention_geometry_at(il as u32);
5509 let n_head = geometry.n_head as usize;
5510 let n_head_kv = geometry.n_head_kv as usize;
5511 let head_dim = geometry.head_dim_k as usize;
5512 let rope_dims = geometry.n_rot as usize;
5513 let rope_base = geometry.rope_base;
5514 let scale = geometry.attention_scale();
5515 // Batched projections: one weight read serves all T rows.
5516 // GROUP-3 twin (trunk-kernels slice D): q/k/v in ONE launch — the group4
5517 // kernel with n3=0, bit-identical per (tensor, token, row) to the three
5518 // singles; refused or MEMRA_TK_FA_GROUP=0 -> singles byte-for-byte.
5519 let (qf, mut k, v) = match e.matmul_decode_exact_group3_pre(
5520 [&fa.wq, &fa.wk, &fa.wv],
5521 &hq,
5522 &hd,
5523 t,
5524 )? {
5525 Some(mut g3) => {
5526 let v = g3.pop().unwrap();
5527 let k = g3.pop().unwrap();
5528 let qf = g3.pop().unwrap();
5529 (qf, k, v)
5530 }
5531 None => (
5532 e.matmul_pre(&fa.wq, &hq, &hd, &xn, t)?,
5533 e.matmul_pre(&fa.wk, &hq, &hd, &xn, t)?,
5534 e.matmul_pre(&fa.wv, &hq, &hd, &xn, t)?,
5535 ),
5536 };
5537 let gated =
5538 geometry.attention_gate == memra_gguf::config::AttentionGateKind::FusedQ;
5539 let (mut q, gate) = if gated {
5540 let mut qs = e.uninit(t * n_head * head_dim)?;
5541 let mut gs = e.uninit(t * n_head * head_dim)?;
5542 e.q_gate_split(&qf, &mut qs, &mut gs, head_dim, n_head, t)?;
5543 (qs, Some(gs))
5544 } else {
5545 (qf, None)
5546 };
5547 let mut qn = e.uninit(t * n_head * head_dim)?;
5548 e.rms_norm(
5549 &q,
5550 fa.q_norm.float_data(),
5551 &mut qn,
5552 head_dim,
5553 t * n_head,
5554 eps,
5555 )?;
5556 q = qn;
5557 let mut kn = e.uninit(t * n_head_kv * head_dim)?;
5558 e.rms_norm(
5559 &k,
5560 fa.k_norm.float_data(),
5561 &mut kn,
5562 head_dim,
5563 t * n_head_kv,
5564 eps,
5565 )?;
5566 k = kn;
5567 e.rope_neox(
5568 &mut q, pos_d, head_dim, rope_dims, n_head, t, rope_base, 1.0,
5569 )?;
5570 e.rope_neox(
5571 &mut k, pos_d, head_dim, rope_dims, n_head_kv, t, rope_base, 1.0,
5572 )?;
5573
5574 // Per-row append + attend: row r sees rows 0..r in KV (causal within the
5575 // draft), each through the b_n=1 serving kernels at its own t_kv.
5576 let q_dim = n_head * head_dim;
5577 let kv_dim = n_head_kv * head_dim;
5578 let mut attn = e.uninit(t * q_dim)?;
5579 let (kdk, kdv, ktb, vtb, len0, kv_local) = {
5580 let kvl = cache.kv[il].as_ref().unwrap();
5581 // [2T] interleaved k,v base pointers: entry pair z serves row z of
5582 // the batched twins; the per-row fallback reads pair 0 (same cache
5583 // for every row of one layer). Graph mode reads the ctx table.
5584 let local: Option<CudaSlice<u64>> = match graph_cap {
5585 Some(_) => None,
5586 None => {
5587 let s = &e.gpu.stream();
5588 let (pk, _g) = kvl.k.device_ptr(s);
5589 let (pv, _g2) = kvl.v.device_ptr(s);
5590 let mut tbl = Vec::with_capacity(2 * t);
5591 for _ in 0..t {
5592 tbl.push(pk as u64);
5593 tbl.push(pv as u64);
5594 }
5595 Some(e.htod_u64(&tbl)?)
5596 }
5597 };
5598 (
5599 kvl.kv_dim_k,
5600 kvl.kv_dim_v,
5601 kvl.k_tok_bytes,
5602 kvl.v_tok_bytes,
5603 kvl.len,
5604 local,
5605 )
5606 };
5607 let (kv_tbl, kv_off): (&CudaSlice<u64>, usize) = match graph_cap {
5608 Some((tb, off, _)) => (tb, off),
5609 None => (kv_local.as_ref().expect("built above"), 0),
5610 };
5611 // Slice 4 (fa/append rows — see dspark_fa_rows_on): the whole per-row
5612 // section batches into the z-batched serving twins when every row of
5613 // this round takes the v4-seqs arm on ONE fa_split_keys rung. Both
5614 // guards are evaluated at the round's FIRST and LAST t_kv — the
5615 // eligibility window (vec floor .. v4 max) and each split-ladder rung
5616 // are intervals in t_kv, so ends-inside means all-inside (the straddle
5617 // law). Appending all T rows before any attend is read-equivalent to
5618 // the interleaved order: row r's walk reads keys 0..len0+r only, and
5619 // rows > r land at slots it never touches; every written cache row is
5620 // the per-token appender's exact warp program (kernel-check pinned).
5621 let t_kv_first = len0 + 1;
5622 let t_kv_last = len0 + t;
5623 let rows_batched = t >= 2
5624 && seqs_append
5625 && batch_fa_on
5626 && dspark_fa_rows_on()
5627 // the z-batched twins read stacked rows at the CACHE's kv dims;
5628 // the projection stack is [T, n_head_kv*head_dim] — they must be
5629 // the same stride or row z misaligns (true for this family; the
5630 // guard keeps any asymmetric-kv model on the per-row loop).
5631 && kdk == kv_dim
5632 && kdv == kv_dim
5633 && crate::fa_seqs_eligible(t_kv_first, head_dim_global)
5634 && crate::fa_seqs_eligible(t_kv_last, head_dim_global)
5635 && crate::fa_split_keys(t_kv_first, cfg.n_head_kv as usize)
5636 == crate::fa_split_keys(t_kv_last, cfg.n_head_kv as usize);
5637 // Sizing: eager = exact round bound; graph mode = the rung end (stride +
5638 // grid only — bytes proven equal above). Capture-time invariants refuse
5639 // loudly rather than bake a divergent body.
5640 let (size_kv_max, sp) = match graph_cap {
5641 Some((_, _, rung)) => {
5642 if !rows_batched {
5643 return Err(format!(
5644 "fa graph capture: layer {il} round is not batchable \
5645 (t_kv {t_kv_first}..{t_kv_last}) — the per-row fallback \
5646 must never be captured"
5647 )
5648 .into());
5649 }
5650 let sp_r = crate::fa_split_keys(rung, cfg.n_head_kv as usize);
5651 if t_kv_last > rung
5652 || sp_r != crate::fa_split_keys(t_kv_last, cfg.n_head_kv as usize)
5653 {
5654 return Err(format!(
5655 "fa graph capture: rung {rung} does not cover round \
5656 t_kv {t_kv_first}..{t_kv_last} on one split ladder step"
5657 )
5658 .into());
5659 }
5660 (rung, sp_r)
5661 }
5662 None => (
5663 t_kv_last,
5664 crate::fa_split_keys(t_kv_last, cfg.n_head_kv as usize),
5665 ),
5666 };
5667 if let Some((_, ctr)) = stream {
5668 // STREAM ARM (2b): one batched dc append + the multi-row dc attention
5669 // — the generic stream arm's exact shape (rows kernels are pinned
5670 // byte-identical to the per-row programs by kernel-check). Host len
5671 // stays a stale lower bound; the burst drain reconciles it.
5672 let kvl = cache.kv[il].as_mut().unwrap();
5673 e.append_kv_quantized_rows_dc(
5674 &k,
5675 &v,
5676 &mut kvl.k,
5677 &mut kvl.v,
5678 ctr,
5679 t,
5680 kdk,
5681 kdv,
5682 ktb,
5683 vtb,
5684 Engine::kv_fp8_on(),
5685 )?;
5686 let upper = (kvl.len + t + 64).min(cache.max_ctx);
5687 let k_view = e.view_u8(&kvl.k, upper * ktb);
5688 let v_view = e.view_u8(&kvl.v, upper * vtb);
5689 e.fa_decode_rows_dc(
5690 &q, &k_view, &v_view, &mut attn, head_dim, n_head, n_head_kv, ctr, upper,
5691 t, scale, ktb, vtb, 0, false,
5692 )?;
5693 } else if rows_batched {
5694 e.append_kv_quantized_seqs(
5695 &k,
5696 &v,
5697 &kv_tbl.slice(kv_off..kv_off + 2 * t),
5698 pos_d,
5699 t,
5700 kdk,
5701 kdv,
5702 ktb,
5703 vtb,
5704 )?;
5705 if graph_cap.is_none() {
5706 cache.kv[il].as_mut().unwrap().len += t;
5707 }
5708 e.fa_decode_batch_seqs_v4(
5709 &q,
5710 &kv_tbl.slice(kv_off..kv_off + 2 * t),
5711 pos_d,
5712 &mut attn,
5713 head_dim,
5714 n_head,
5715 n_head_kv,
5716 t,
5717 size_kv_max,
5718 scale,
5719 sp,
5720 ktb,
5721 vtb,
5722 )?;
5723 } else {
5724 if pos_rows.is_none() {
5725 // Stream-aware for symmetry with pos_d (the stream FA arm rides
5726 // the dc rows kernels above and never reaches this fallback).
5727 *pos_rows = Some(match stream {
5728 Some((_, ctr)) => (0..t)
5729 .map(|r| {
5730 let mut b = e.alloc_uninit::<i32>(1)?;
5731 e.i32_copy_add(ctr, &mut b, r as i32)?;
5732 Ok(b)
5733 })
5734 .collect::<Result<_, Box<dyn std::error::Error>>>()?,
5735 None => (0..t)
5736 .map(|r| e.htod_i32(&[(pos0 + r) as i32]))
5737 .collect::<Result<_, _>>()?,
5738 });
5739 }
5740 let pos_rows = pos_rows.as_ref().unwrap();
5741 for r in 0..t {
5742 // Owned per-row scratch: the b_n=1 kernels take packed batch buffers
5743 // whose row 0 is this row (arithmetic-free materialization copies,
5744 // same as decode's per-seq fallback arm).
5745 let mut k_row = e.uninit(kv_dim)?;
5746 e.dtod_copy_view(&k.slice(r * kv_dim..(r + 1) * kv_dim), &mut k_row)?;
5747 let mut v_row = e.uninit(kv_dim)?;
5748 e.dtod_copy_view(&v.slice(r * kv_dim..(r + 1) * kv_dim), &mut v_row)?;
5749 let pos_row = &pos_rows[r];
5750 let kvl = cache.kv[il].as_mut().unwrap();
5751 if seqs_append {
5752 e.append_kv_quantized_seqs(
5753 &k_row,
5754 &v_row,
5755 &kv_tbl.slice(kv_off..kv_off + 2),
5756 pos_row,
5757 1,
5758 kdk,
5759 kdv,
5760 ktb,
5761 vtb,
5762 )?;
5763 kvl.len += 1;
5764 } else {
5765 e.append_kv_quantized_view(
5766 &k_row.slice(0..kv_dim),
5767 &v_row.slice(0..kv_dim),
5768 &mut kvl.k,
5769 &mut kvl.v,
5770 kvl.len,
5771 kvl.kv_dim_k,
5772 kvl.kv_dim_v,
5773 kvl.k_tok_bytes,
5774 kvl.v_tok_bytes,
5775 Engine::kv_fp8_on(),
5776 )?;
5777 kvl.len += 1;
5778 }
5779 let t_kv = kvl.len;
5780 let mut q_row = e.uninit(q_dim)?;
5781 e.dtod_copy_view(&q.slice(r * q_dim..(r + 1) * q_dim), &mut q_row)?;
5782 let mut a_row = e.uninit(q_dim)?;
5783 if batch_fa_on && crate::fa_seqs_eligible(t_kv, head_dim_global) {
5784 let sp0_r = crate::fa_split_keys(t_kv, cfg.n_head_kv as usize);
5785 e.fa_decode_batch_seqs_v4(
5786 &q_row,
5787 &kv_tbl.slice(kv_off..kv_off + 2),
5788 pos_row,
5789 &mut a_row,
5790 head_dim,
5791 n_head,
5792 n_head_kv,
5793 1,
5794 t_kv,
5795 scale,
5796 sp0_r,
5797 ktb,
5798 vtb,
5799 )?;
5800 } else {
5801 let k_view = e.view_u8(&kvl.k, t_kv * kvl.k_tok_bytes);
5802 let v_view = e.view_u8(&kvl.v, t_kv * kvl.v_tok_bytes);
5803 let mut a_view = a_row.slice_mut(0..q_dim);
5804 e.fa_decode_kvmod_view(
5805 &q_row.slice(0..q_dim),
5806 &k_view,
5807 &v_view,
5808 &mut a_view,
5809 head_dim,
5810 n_head,
5811 n_head_kv,
5812 t_kv,
5813 scale,
5814 kvl.k_tok_bytes,
5815 kvl.v_tok_bytes,
5816 Engine::kv_fp8_on(),
5817 )?;
5818 }
5819 e.dtod_copy_into(&a_row, &mut attn, r * q_dim)?;
5820 }
5821 }
5822
5823 // Output gate (element-wise) + o-proj at m=T.
5824 let attn_g = match &gate {
5825 Some(g) => {
5826 let n = t * q_dim;
5827 let mut gsig = e.uninit(n)?;
5828 e.sigmoid(g, &mut gsig, n)?;
5829 let mut ag = e.uninit(n)?;
5830 e.mul(&attn, &gsig, &mut ag, n)?;
5831 ag
5832 }
5833 None => attn,
5834 };
5835 e.matmul(&fa.wo, &attn_g, t)?
5836 }
5837 };
5838
5839 // ---- residual add + post_attn_norm + FFN at m=T (serving dispatch verbatim) ----
5840 let pnorm = layer.post_attn_norm.float_data();
5841 let mut x1 = e.uninit(t * n_embd)?;
5842 let mut zn = e.uninit(t * n_embd)?;
5843 e.add_rms_norm(x, &mixed, pnorm, &mut x1, &mut zn, n_embd, t, eps)?;
5844 let ffn_out = match &layer.ffn {
5845 crate::hybrid::Ffn::Dense {
5846 ffn_gate,
5847 ffn_up,
5848 ffn_down,
5849 } => {
5850 assert!(
5851 self.cfg.m3.is_none(),
5852 "qwen35 t-parallel verify: M3 swigluoai FFN not yet batched"
5853 );
5854 self.qwen35_tparallel_dense_ffn(e, ffn_gate, ffn_up, ffn_down, &zn, t, n_embd)?
5855 }
5856 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il_zq8(e, m, &zn, None, t, il as u16)?,
5857 };
5858 let mut x2 = e.uninit(t * n_embd)?;
5859 e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
5860 // dspark drafter tap (no-op when no sink armed): post-layer residual verify rows
5861 self.dflash_tap(e, cache, il, &x2, t)?;
5862 Ok(x2)
5863 }
5864
5865 /// ONE t-parallel LINEAR layer (attn_norm + gdn mixer + post_attn_norm + FFN + tap) —
5866 /// the exact body the old in-loop Linear arm ran, extracted so the eager walk and the
5867 /// slice-3 captured segments execute the SAME code (a second copy is how dispatch
5868 /// mirrors drift — the verify_layers extraction lesson). Two deliberate changes, both
5869 /// bit-identical by construction:
5870 /// - the gdn ping-pong host swap moves from per-row to ONE end-of-body swap (t odd):
5871 /// the device sequence is driven entirely by the 6-entry pointer table, which
5872 /// already encodes both parities; the ckpt stash reads name row r's out buffer
5873 /// directly (r even -> alt handle, odd -> canonical) — the same physical bytes the
5874 /// legacy post-swap clone read.
5875 /// - `stash` (slice-3 ctx): persistent per-layer slabs written by copy_into instead of
5876 /// per-row clone_dtod allocs — same bytes, capture-legal (no per-round host objects).
5877 /// `table_src` = (persistent pointer table, offset) when the ctx owns the tables;
5878 /// None builds the per-verify table exactly as before.
5879 #[allow(clippy::too_many_arguments)]
5880 fn qwen35_tparallel_linear_layer(
5881 &self,
5882 e: &Engine,
5883 il: usize,
5884 x: &CudaSlice<f32>,
5885 t: usize,
5886 cache: &mut Cache,
5887 mut ckpt: Option<&mut VerifyCkpt>,
5888 stash: Option<(&mut CudaSlice<f32>, &mut CudaSlice<f32>)>,
5889 table_src: Option<(&CudaSlice<u64>, usize)>,
5890 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5891 use cudarc::driver::DevicePtr;
5892 let cfg = &self.cfg;
5893 let n_embd = cfg.n_embd as usize;
5894 let eps = cfg.rms_eps;
5895 let layer = &self.layers[il];
5896 let Mixer::Linear(la) = &layer.mixer else {
5897 return Err("qwen35_tparallel_linear_layer on a non-linear layer".into());
5898 };
5899 // ---- attn_norm + q8_1 quantize at m=T (row-indexed == per-row) ----
5900 let anorm = layer.attn_norm.float_data();
5901 let mut xn = e.uninit(t * n_embd)?;
5902 e.rms_norm(x, anorm, &mut xn, n_embd, t, eps)?;
5903 let (hq, hd) = e.quantize_q8_1(&xn, t, n_embd)?;
5904
5905 let ssm = cfg.ssm.as_ref().expect("linear mixer requires ssm cfg");
5906 let d_state = ssm.state_size as usize;
5907 let num_k = ssm.group_count as usize;
5908 let num_v = ssm.time_step_rank as usize;
5909 let d_conv = ssm.conv_kernel as usize;
5910 let key_dim = d_state * num_k;
5911 let value_dim = d_state * num_v;
5912 let conv_dim = key_dim * 2 + value_dim;
5913 let gdn_scale = 1.0 / (d_state as f32).sqrt();
5914
5915 // ---- batched projections: one weight read for all T rows ----
5916 // GROUP-4 twin (trunk-kernels slice C): the whole 4-tuple in ONE launch, bit-identical
5917 // per (tensor, token, row) to the four singles; refused (layout/tier) or
5918 // MEMRA_TK_GDN_GROUP=0 -> the singles chain byte-for-byte.
5919 let (qkv_mixed, z, beta_raw, alpha) = match e.matmul_decode_exact_group4_pre(
5920 [&la.wqkv, &la.wqkv_gate, &la.ssm_beta, &la.ssm_alpha],
5921 &hq,
5922 &hd,
5923 t,
5924 )? {
5925 Some(mut g4) => {
5926 let alpha = g4.pop().unwrap();
5927 let beta_raw = g4.pop().unwrap();
5928 let z = g4.pop().unwrap();
5929 let qkv_mixed = g4.pop().unwrap();
5930 (qkv_mixed, z, beta_raw, alpha)
5931 }
5932 None => (
5933 e.matmul_pre(&la.wqkv, &hq, &hd, &xn, t)?,
5934 e.matmul_pre(&la.wqkv_gate, &hq, &hd, &xn, t)?,
5935 e.matmul_pre(&la.ssm_beta, &hq, &hd, &xn, t)?,
5936 e.matmul_pre(&la.ssm_alpha, &hq, &hd, &xn, t)?,
5937 ),
5938 };
5939 let beta_w = la.ssm_beta.out_features();
5940 let alpha_w = la.ssm_alpha.out_features();
5941 let qkv_w = la.wqkv.out_features();
5942
5943 // ---- per-row state chain through the b_n=1 serving kernels ----
5944 // 6-entry alternating pointer table expresses the ping-pong without a rebuild per
5945 // row: even rows scan s0 -> s1, odd rows s1 -> s0.
5946 let table_local: Option<CudaSlice<u64>> = match table_src {
5947 Some(_) => None,
5948 None => {
5949 let rl = cache.recur[il].as_ref().unwrap();
5950 let s = &e.gpu.stream();
5951 let (pc, _g0) = rl.conv_state.device_ptr(s);
5952 let (p0, _g1) = rl.ssm_state.device_ptr(s);
5953 let (p1, _g2) = rl.ssm_state_alt.device_ptr(s);
5954 Some(e.htod_u64(&[
5955 pc as u64, p0 as u64, p1 as u64, pc as u64, p1 as u64, p0 as u64,
5956 ])?)
5957 }
5958 };
5959 let (table, toff): (&CudaSlice<u64>, usize) = match table_src {
5960 Some((tb, off)) => (tb, off),
5961 None => (table_local.as_ref().unwrap(), 0),
5962 };
5963 let mut o_all = e.uninit(t * value_dim)?;
5964 let mut col_states: Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>> =
5965 if ckpt.is_some() && stash.is_none() && t >= 2 {
5966 Some(Vec::with_capacity(t - 1))
5967 } else {
5968 None
5969 };
5970 let mut stash = stash;
5971 // Per-row scratch reused across rows (uninit is cheap but not free at
5972 // 48 layers x T rows); row inputs/outputs pass as VIEWS into the packed
5973 // [T, ...] buffers — zero arithmetic-free copies in this loop.
5974 let mut conv_out = e.uninit(conv_dim)?;
5975 let mut q_l2 = e.uninit(value_dim)?;
5976 let mut k_l2 = e.uninit(value_dim)?;
5977 let mut v_gd = e.uninit(value_dim)?;
5978 let mut beta_b = e.uninit(num_v)?;
5979 let mut g_log = e.uninit(num_v)?;
5980 for r in 0..t {
5981 let base = toff + if r % 2 == 0 { 0 } else { 3 };
5982 let conv_view = table.slice(base..base + 1);
5983 let in_view = table.slice(base + 1..base + 2);
5984 let out_view = table.slice(base + 2..base + 3);
5985 e.ssm_conv1d_fused_decode_b_view(
5986 &qkv_mixed.slice(r * qkv_w..(r + 1) * qkv_w),
5987 &conv_view,
5988 la.ssm_conv1d.float_data(),
5989 &mut conv_out,
5990 conv_dim,
5991 d_conv,
5992 1,
5993 )?;
5994 e.gdn_prep_decode_b_view(
5995 &conv_out,
5996 &beta_raw.slice(r * beta_w..(r + 1) * beta_w),
5997 &alpha.slice(r * alpha_w..(r + 1) * alpha_w),
5998 la.ssm_dt.float_data(),
5999 la.ssm_a.float_data(),
6000 &mut q_l2,
6001 &mut k_l2,
6002 &mut v_gd,
6003 &mut beta_b,
6004 &mut g_log,
6005 d_state,
6006 num_v,
6007 num_k,
6008 key_dim,
6009 eps,
6010 conv_dim,
6011 1,
6012 )?;
6013 let mut o_row = o_all.slice_mut(r * value_dim..(r + 1) * value_dim);
6014 e.gdn_scan_s128_batched_view(
6015 &q_l2, &k_l2, &v_gd, &g_log, &beta_b, &in_view, &out_view, &mut o_row, num_v, 1,
6016 gdn_scale,
6017 )?;
6018 if r + 1 < t {
6019 // Row r's out buffer: even rows write s1 (the alt handle — no swaps ran),
6020 // odd rows write s0 — the same physical state the legacy post-swap
6021 // canonical clone read.
6022 let rl = cache.recur[il]
6023 .as_ref()
6024 .ok_or("qwen35 linear verify layer has no recurrent state")?;
6025 let ssm_src = if r % 2 == 0 {
6026 &rl.ssm_state_alt
6027 } else {
6028 &rl.ssm_state
6029 };
6030 match stash.as_mut() {
6031 Some((conv_slab, ssm_slab)) => {
6032 // BOTH stash reads go through the pointer table at run time: the
6033 // ssm handles ping-pong between rounds, and the ctx (with its
6034 // captured graphs) outlives the Cache — a fresh generation's
6035 // conv/ssm buffers land at new addresses that only the per-round
6036 // table refresh knows. A baked direct copy would read freed
6037 // memory (parity was the slice-3 smoke divergence; cache
6038 // lifetime is the cross-generation twin).
6039 e.copy_indirect_src_f32(
6040 &conv_view,
6041 conv_slab,
6042 r * conv_dim * (d_conv - 1),
6043 conv_dim * (d_conv - 1),
6044 )?;
6045 // The ssm handles PING-PONG between rounds: a captured direct
6046 // copy would bake the capture-time physical buffer and read the
6047 // wrong parity after any odd-vt round (the slice-3 smoke
6048 // divergence). Read the src address from row r's OUT table
6049 // entry at run time — the same entry the scan just wrote.
6050 e.copy_indirect_src_f32(
6051 &out_view,
6052 ssm_slab,
6053 r * d_state * d_state * num_v,
6054 d_state * d_state * num_v,
6055 )?;
6056 }
6057 None => {
6058 if let Some(states) = col_states.as_mut() {
6059 states.push((e.clone_dtod(&rl.conv_state)?, e.clone_dtod(ssm_src)?));
6060 }
6061 }
6062 }
6063 }
6064 }
6065 // ONE end-of-body parity swap (t odd) — the legacy loop swapped per row; the net
6066 // handle motion is identical and the device sequence never read the handles.
6067 if t % 2 == 1 {
6068 let rl = cache.recur[il].as_mut().unwrap();
6069 std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
6070 }
6071 if let (Some(checkpoint), Some(states)) = (ckpt.as_deref_mut(), col_states) {
6072 checkpoint.cols[il] = Some(states);
6073 }
6074
6075 // ---- batched gated norm + out-projection at m=T ----
6076 let mixed = if e.uses_q8_1_fast(&la.ssm_out) {
6077 let (gq, gd) = e.gated_rmsnorm_q8_1(
6078 &o_all,
6079 la.ssm_norm.float_data(),
6080 &z,
6081 d_state,
6082 t * num_v,
6083 eps,
6084 )?;
6085 let g0 = e.zeros(0)?;
6086 e.matmul_pre(&la.ssm_out, &gq, &gd, &g0, t)?
6087 } else {
6088 let mut gn = e.uninit(t * value_dim)?;
6089 e.gated_rmsnorm(
6090 &o_all,
6091 la.ssm_norm.float_data(),
6092 &z,
6093 &mut gn,
6094 d_state,
6095 t * num_v,
6096 eps,
6097 )?;
6098 e.matmul(&la.ssm_out, &gn, t)?
6099 };
6100
6101 // ---- residual add + post_attn_norm + FFN at m=T (serving dispatch verbatim) ----
6102 let pnorm = layer.post_attn_norm.float_data();
6103 let mut x1 = e.uninit(t * n_embd)?;
6104 let mut zn = e.uninit(t * n_embd)?;
6105 e.add_rms_norm(x, &mixed, pnorm, &mut x1, &mut zn, n_embd, t, eps)?;
6106 let ffn_out = match &layer.ffn {
6107 crate::hybrid::Ffn::Dense {
6108 ffn_gate,
6109 ffn_up,
6110 ffn_down,
6111 } => {
6112 assert!(
6113 self.cfg.m3.is_none(),
6114 "qwen35 t-parallel verify: M3 swigluoai FFN not yet batched"
6115 );
6116 self.qwen35_tparallel_dense_ffn(e, ffn_gate, ffn_up, ffn_down, &zn, t, n_embd)?
6117 }
6118 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il_zq8(e, m, &zn, None, t, il as u16)?,
6119 };
6120 let mut x2 = e.uninit(t * n_embd)?;
6121 e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
6122 // dspark drafter tap (no-op when no sink armed): post-layer residual verify rows
6123 self.dflash_tap(e, cache, il, &x2, t)?;
6124 Ok(x2)
6125 }
6126
6127 /// PP-N STAGE SUBGRAPH of the verify trunk: layers `[lo, hi)` of `decode_step_t_core_stream`'s
6128 /// walk, verbatim. Enters with a MATERIALIZED `[T, n_embd]` residual (no pending fusion pair
6129 /// carried in from outside the range) and exits with the range's final residual materialized
6130 /// (the trailing add executed) — exactly the `decode_layers_eager(lo, hi)` contract, T rows
6131 /// instead of one.
6132 ///
6133 /// EXTRACTED (lane/pp2-spec 2026-08-06) rather than duplicated: `decode_step_t_core_stream` IS
6134 /// the single funnel every verify forward reaches, and its per-layer dispatch MIRRORING (norm
6135 /// fusion per layer, the t>=3/spec_m2 batched-linear window, the fused-q8 FFN chain, the
6136 /// decode-exact projections) is what makes verify bit-identical to eager decode. A second copy
6137 /// for the split arm is how those mirrors drift apart on the next lever. The unsplit body now
6138 /// calls this with `(0, n_layers)`, so the whole-trunk path and every stage range run the SAME
6139 /// code — there is no "split version" of the verify math.
6140 ///
6141 /// Bit-identity of a cut rests on the same kernel-check-pinned identity the eager arm's cut
6142 /// does — `add_rms_norm_q8_1 == add then rms_norm_q8_1` at nrows=T — because the ONLY thing a
6143 /// fence changes is that the cross-layer fusion carry breaks at `hi-1` and is re-materialized
6144 /// as an explicit `add`. `decode-batch-gate --mode ppspec` verifies end-to-end on real weights.
6145 #[allow(clippy::too_many_arguments)]
6146 fn verify_layers(
6147 &self,
6148 e: &Engine,
6149 mut x: CudaSlice<f32>,
6150 lo: usize,
6151 hi: usize,
6152 pos_d: &CudaSlice<i32>,
6153 pos0: usize,
6154 t: usize,
6155 cache: &mut Cache,
6156 mut ckpt: Option<&mut VerifyCkpt>,
6157 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
6158 graphs: Option<&mut DsparkVerifyGraphs>,
6159 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
6160 if self.cfg.step35.is_some() {
6161 if stream.is_some() {
6162 return Err(
6163 "step35 has no ROUND-STREAM verify arm (the device-counter _dc twins \
6164 cannot express the SWA offset KV view)"
6165 .into(),
6166 );
6167 }
6168 return self.step35_verify_batch_layers(e, x, lo, hi, pos0, t, cache);
6169 }
6170 if self.qwen35_serving_class() {
6171 return self.qwen35_verify_batch_layers(
6172 e,
6173 x,
6174 lo,
6175 hi,
6176 pos0,
6177 t,
6178 cache,
6179 ckpt.take(),
6180 stream,
6181 graphs,
6182 );
6183 }
6184 let n_embd = self.cfg.n_embd as usize;
6185 let eps = self.cfg.rms_eps;
6186 // CROSS-LAYER ADD+NORM FUSION (lane/vt-fixes fix 2, mirroring decode_step_h's
6187 // launch-arc form): layer il's post-FFN residual add (x2 = x1 + ffn_out) and layer
6188 // il+1's attn_norm(+quantize) are consecutive row-wise ops — ONE add_rms_norm_q8_1
6189 // launch at nrows=t does all three (bit-identity pinned by the T-row kernel-check
6190 // arms). Carry the un-added (x1, ffn_out) pair; the fused launch materializes x2 (the
6191 // residual the next layer needs) as its `res` output. Falls back to the separate add
6192 // when the next layer is off the fused-q8 path.
6193 let mut pending: Option<(CudaSlice<f32>, CudaSlice<f32>)> = None;
6194 for il in lo..hi {
6195 let layer = &self.layers[il];
6196 // DISPATCH-MIRRORED attn-input RMSNorm (FP-order lesson #8): eager decode fuses the
6197 // 1024-thread rms_norm_q8_1 ONLY when every mixer projection is q8_1-fast; layers with
6198 // Float projections (ssm_beta/ssm_alpha on layers 1/2/4 of the 9B NVFP4 GGUF) take the
6199 // UNFUSED 256-thread rms_norm. The verify norm must mirror that PER-LAYER choice —
6200 // blockDim changes the sum-of-squares reduce order, and the ULP shift amplifies through
6201 // the GDN recurrence into argmax flips (measured: 9B text prompt, 1 ULP at layer 2 ->
6202 // 2.3e-1 logit maxdiff at the head -> K=1..8 divergence at a 0.03-margin token).
6203 let mixer_fast = self.mixer_in_q8_1_fast(e, &layer.mixer);
6204 let norm_fused = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err() && mixer_fast;
6205 // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2, 2026-08-03): when the norm is
6206 // dispatch-fused AND every consumer of `h` reads only its q8_1 form (Full mixer:
6207 // projections only; Linear mixer: the batched arm — the per-column fallback needs
6208 // f32 h), emit the attn-input norm DIRECTLY as q8_1 via `rms_norm_q8_1` at nrows=t
6209 // (row-indexed kernel — the T-row launch is the per-row m=1 program, kernel-check
6210 // pins bit-identity vs rms_norm_decode -> quantize_q8_1). Kills the standalone
6211 // quantize launch(es) + the f32 h HBM round-trip that decode never pays.
6212 // step35 (Full mixer) is the third case that needs f32 `h`: its verify arm is a
6213 // per-ROW replay of the eager decode mixer, whose `pre_q` contract is a single row —
6214 // a T-row q8_1 pair cannot be handed to it, and re-deriving per-row q8_1 from the f32
6215 // rows is exactly the dispatch being mirrored. Keep step35 on the unfused arm.
6216 let lin_q8_only = match &layer.mixer {
6217 Mixer::Linear(la) => {
6218 (t >= 3 || (t == 2 && spec_m2())) && e.uses_q8_1_fast(&la.ssm_out)
6219 }
6220 Mixer::Full(_) if self.cfg.step35.is_some() => false,
6221 _ => true,
6222 };
6223 // NOTE decode.rs's take()-first lesson: take the pending pair BEFORE branching so
6224 // a non-fused layer still performs the residual add.
6225 let taken = pending.take();
6226 let (h, h_q8) = if norm_fused && lin_q8_only {
6227 let pair = match taken {
6228 // fused add + attn_norm + q8_1: ONE launch resolves the carried residual
6229 // AND emits this layer's mixer input pre-quantized. res -> x2 (= new x).
6230 Some((x1p, f1p)) => {
6231 let mut x2 = vbuf(e, t * n_embd)?; // fully written (res output)
6232 let p = e.add_rms_norm_q8_1(
6233 &x1p,
6234 &f1p,
6235 layer.attn_norm.float_data(),
6236 &mut x2,
6237 n_embd,
6238 t,
6239 eps,
6240 )?;
6241 x = x2;
6242 p
6243 }
6244 None => e.rms_norm_q8_1(&x, layer.attn_norm.float_data(), n_embd, t, eps)?,
6245 };
6246 (e.zeros(0)?, Some(pair)) // h unused on this path (q8-only consumers)
6247 } else {
6248 if let Some((x1p, f1p)) = taken {
6249 let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
6250 e.add(&x1p, &f1p, &mut x2, t * n_embd)?;
6251 x = x2;
6252 }
6253 let mut h = vbuf(e, t * n_embd)?; // fully written by either rms_norm arm
6254 if norm_fused {
6255 e.rms_norm_decode(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
6256 } else {
6257 e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
6258 }
6259 (h, None)
6260 };
6261 let h_q8_ref = h_q8.as_ref().map(|(q, d)| (q, d));
6262
6263 let mixed = match &layer.mixer {
6264 Mixer::Full(fa) => self.full_attn_verify(
6265 e,
6266 fa,
6267 &h,
6268 h_q8_ref,
6269 pos_d,
6270 t,
6271 cache,
6272 il,
6273 stream.map(|(_, c)| c),
6274 )?,
6275 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
6276 Mixer::Linear(la) => {
6277 // BATCHED linear verify (2026-07-03, the MTP-profit lever): one T-token pass —
6278 // batched projections (weight read ONCE, hits the m=2-4 weight-resident matvec),
6279 // carried-state conv (ssm_conv1d_tm_state), GDN prep on the prefill kernels, and
6280 // ONE gdn_scan whose internal sequential t-loop is the SAME recurrence as T
6281 // chained T=1 steps (bit-identical). Falls back to the sequential per-column
6282 // chain when T < d_conv-1 (conv ring update needs T >= pad) — or when ANY
6283 // projection is off the q8_1 fast path: matmul_decode_exact would route a Float
6284 // tensor to cuBLAS at m=t (different FP accumulation than eager's per-token
6285 // GEMV), so mixed-dtype layers stay on the eager-identical per-column chain.
6286 // MEMRA_SPEC_M2 (lane/spec-m2): the t==2 batch rides the same arm — the conv
6287 // wrapper handles t<pad with a pure-copy ring rebuild; see spec_m2() header.
6288 if (t >= 3 || (t == 2 && spec_m2()))
6289 && mixer_fast
6290 && e.uses_q8_1_fast(&la.ssm_out)
6291 {
6292 let want = ckpt.is_some();
6293 let (out, stash) =
6294 self.linear_attn_verify_t(e, la, &h, h_q8_ref, t, cache, il, want)?;
6295 if let (Some(ck), Some(st)) = (ckpt.as_deref_mut(), stash) {
6296 ck.gdn[il] = Some(st);
6297 }
6298 out
6299 } else {
6300 let mut out = vbuf(e, t * n_embd)?; // every col written by copy_into
6301 let mut col_states: Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>> =
6302 if ckpt.is_some() && t >= 2 {
6303 Some(Vec::with_capacity(t - 1))
6304 } else {
6305 None
6306 };
6307 for col in 0..t {
6308 let mut h_col = vbuf(e, n_embd)?; // fully written by copy_view_into
6309 let src = h.slice(col * n_embd..(col + 1) * n_embd);
6310 e.copy_view_into(&mut h_col, 0, &src, n_embd)?;
6311 let m_col = self.linear_attn_decode(e, la, &h_col, cache, il)?;
6312 e.copy_into(&mut out, col * n_embd, &m_col, n_embd)?;
6313 // REPLAY-FREE ckpt: clone the chain's ACTUAL state after this column
6314 // (pure dtod — cannot change any computed value). Last column skipped:
6315 // rebuild targets are j <= t-1 columns.
6316 if let Some(cs) = col_states.as_mut() {
6317 if col + 1 < t {
6318 let rl = cache.recur[il].as_ref().unwrap();
6319 cs.push((
6320 e.clone_dtod(&rl.conv_state)?,
6321 e.clone_dtod(&rl.ssm_state)?,
6322 ));
6323 }
6324 }
6325 }
6326 if let (Some(ck), Some(cs)) = (ckpt.as_deref_mut(), col_states) {
6327 // ReplaySSM-assessment instrumentation (2026-07-30): the
6328 // per-column clones are the only true state snapshots left in
6329 // the verify (the batched path stashes INPUTS and replays).
6330 if std::env::var("MEMRA_SPEC_STATS").as_deref() == Ok("1") {
6331 static ONCE: std::sync::Once = std::sync::Once::new();
6332 let bytes: usize =
6333 cs.iter().map(|(c, s)| (c.len() + s.len()) * 4).sum();
6334 ONCE.call_once(|| eprintln!(
6335 "[verify-ckpt] per-column layer il={il}: {} clones, {:.2} MB/layer/round",
6336 cs.len(), bytes as f64 / 1e6));
6337 }
6338 ck.cols[il] = Some(cs);
6339 }
6340 out
6341 }
6342 }
6343 };
6344
6345 // DISPATCH-MIRRORED post-attn norm: eager residual_norm_ffn fuses add+norm+quant
6346 // (1024-thread add_rms_norm_q8_1) only for Dense FFNs whose gate+up are q8_1-fast;
6347 // otherwise (and for MoE) it runs the 256-thread fused add_rms_norm. Mirror per layer.
6348 let ffn_fuse = match &layer.ffn {
6349 crate::hybrid::Ffn::Dense {
6350 ffn_gate, ffn_up, ..
6351 } => {
6352 std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
6353 && e.uses_q8_1_fast(ffn_gate)
6354 && e.uses_q8_1_fast(ffn_up)
6355 }
6356 crate::hybrid::Ffn::Moe(_) => false,
6357 };
6358 // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): on the ffn_fuse path (Dense,
6359 // gate+up q8_1-fast, non-M3) the FFN input is emitted DIRECTLY as q8_1 by ONE
6360 // add_rms_norm_q8_1 launch at nrows=t (row-indexed kernel: the T-row launch is the
6361 // per-row m=1 program; kernel-check pins bit-identity vs the unfused
6362 // add_f32 -> rms_norm_decode -> quantize_q8_1 chain at T=2/4/5/8) — replacing the
6363 // add + rms_norm_decode launches AND the dual/singles' internal re-quantize.
6364 // M3's swigluoai must keep the f32 chain (the fused SwiGLU epilogue encodes plain
6365 // SiLU), mirroring residual_norm_ffn's m3 guard on the decode path.
6366 // step35: same guard per LAYER. A dense FFN's clamp is the SHEXP array (upstream's
6367 // one build_ffn serves dense + shared expert, llama-graph.cpp:1751), and verify MUST
6368 // mirror decode's dispatch or spec self-consistency fails.
6369 let dense_lim = self.cfg.clamp_shexp_at(il as u32);
6370 let fuse_q8 = ffn_fuse && self.cfg.m3.is_none() && dense_lim.is_none();
6371 let mut x1 = vbuf(e, t * n_embd)?; // fully written by add / add_rms_norm*
6372 let mut z = e.zeros(0)?; // replaced below on the unfused arms
6373 let z_q8 = if fuse_q8 {
6374 Some(e.add_rms_norm_q8_1(
6375 &x,
6376 &mixed,
6377 layer.post_attn_norm.float_data(),
6378 &mut x1,
6379 n_embd,
6380 t,
6381 eps,
6382 )?)
6383 } else {
6384 let mut zf = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode / add_rms_norm
6385 if ffn_fuse {
6386 e.add(&x, &mixed, &mut x1, t * n_embd)?;
6387 e.rms_norm_decode(
6388 &x1,
6389 layer.post_attn_norm.float_data(),
6390 &mut zf,
6391 n_embd,
6392 t,
6393 eps,
6394 )?;
6395 } else {
6396 e.add_rms_norm(
6397 &x,
6398 &mixed,
6399 layer.post_attn_norm.float_data(),
6400 &mut x1,
6401 &mut zf,
6402 n_embd,
6403 t,
6404 eps,
6405 )?;
6406 }
6407 z = zf;
6408 None
6409 };
6410 // DECODE-EXACT FFN projections: force MMVQ for gate/up/down at any T to match the
6411 // T=1 decode FP accumulation order. At T>=5 the generic matmul/matmul_pre falls to dp4a
6412 // (128-thread, different FP sum order). At T=2-4 the batched MMVQ is already bit-identical.
6413 let ffn_out = match &layer.ffn {
6414 crate::hybrid::Ffn::Dense {
6415 ffn_gate,
6416 ffn_up,
6417 ffn_down,
6418 } => {
6419 let n_ff = ffn_gate.out_features();
6420 if let Some((zq, zd)) = z_q8.as_ref() {
6421 // FUSED CHAIN (fix 2): pre-quantized z feeds the projections; the SwiGLU
6422 // epilogue emits act pre-quantized for ffn_down (silu_mul_scaled_q8_1,
6423 // bit-identical to silu_mul + quantize — kernel-check-pinned) with the
6424 // NVFP4 macro-scales folded (deferred-scale dual: y*s inline == the
6425 // scale_inplace store, value-exact) — the exact m=1 decode epilogue
6426 // structure at nrows=t.
6427 let pair =
6428 match e.matmul_decode_exact_dual_pre(ffn_gate, ffn_up, zq, zd, t)? {
6429 Some(((g, gs), (u, us))) => Some((g, gs, u, us)),
6430 None => None,
6431 };
6432 let (gate, gs, up, us) = match pair {
6433 Some(x4) => x4,
6434 None => (
6435 e.matmul_decode_exact_pre(ffn_gate, zq, zd, t)?,
6436 1.0, // scale already applied inside _pre
6437 e.matmul_decode_exact_pre(ffn_up, zq, zd, t)?,
6438 1.0,
6439 ),
6440 };
6441 if e.uses_q8_1_fast(ffn_down) {
6442 let (aq, ad) = e.silu_mul_scaled_q8_1(&gate, &up, gs, us, t * n_ff)?;
6443 e.matmul_decode_exact_pre(ffn_down, &aq, &ad, t)?
6444 } else {
6445 let mut act = vbuf(e, t * n_ff)?;
6446 e.silu_mul_scaled(&gate, &up, gs, us, &mut act, t * n_ff)?;
6447 e.matmul_decode_exact(ffn_down, &act, t)?
6448 }
6449 } else {
6450 // UNFUSED (pre-fix) chain — MoE-adjacent/M3/off-fast layers, unchanged.
6451 // DUAL gate+up batched twin (lane/verify-economics, 2026-08-02): one launch
6452 // for the pair at t=2..8 — bit-identical per (tensor,token,row) to the two
6453 // singles (kernel-check pins bitwise; MEMRA_SPEC_DUAL_T=0 reverts). None
6454 // (non-NVFP4 / t outside the tier / seam off) -> the two singles, unchanged.
6455 let (gate, up) =
6456 match e.matmul_decode_exact_dual(ffn_gate, ffn_up, &z, t)? {
6457 Some(pair) => pair,
6458 None => (
6459 e.matmul_decode_exact(ffn_gate, &z, t)?,
6460 e.matmul_decode_exact(ffn_up, &z, t)?,
6461 ),
6462 };
6463 let mut act = vbuf(e, t * n_ff)?; // fully written by ffn_act_lim
6464 Self::ffn_act_lim(
6465 e,
6466 &self.cfg,
6467 &gate,
6468 &up,
6469 1.0,
6470 1.0,
6471 dense_lim,
6472 &mut act,
6473 t * n_ff,
6474 )?;
6475 e.matmul_decode_exact(ffn_down, &act, t)?
6476 }
6477 }
6478 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, t, il as u16)?,
6479 };
6480 // CROSS-LAYER fusion: defer this layer's post-FFN residual add — the next layer's
6481 // fused-q8 attn norm folds it in (add_rms_norm_q8_1 == add; rms_norm; quantize,
6482 // kernel-check-pinned at nrows=T). Non-fused next layers add explicitly above.
6483 pending = Some((x1, ffn_out));
6484 }
6485 // RANGE's final add (no next norm INSIDE the range to fuse with; for the
6486 // whole-trunk call that is the last layer, whose next norm is output_norm — f32-out).
6487 if let Some((x1p, f1p)) = pending.take() {
6488 let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
6489 e.add(&x1p, &f1p, &mut x2, t * n_embd)?;
6490 x = x2;
6491 }
6492 Ok(x)
6493 }
6494 /// BATCHED linear-attn verify (T=K+1): the whole layer in ~10 launches instead of T x the
6495 /// T=1 decode chain (T x ~12 launches + T weight reads of the four projections). The GDN
6496 /// recurrence itself is inherently sequential — gdn_scan_s128 runs its internal t-loop with
6497 /// the SAME per-token math as chained T=1 calls (bit-identical state evolution); everything
6498 /// around it (projections, conv, prep, gated norm, out-proj) batches. Advances conv ring +
6499 /// ssm state exactly like T sequential decode steps.
6500 /// `want_stash`: additionally RETAIN the gdn-scan inputs (pure buffer keep-alives, zero extra
6501 /// kernels) so a partial accept can rebuild the state after any column prefix (REPLAY-FREE).
6502 #[allow(clippy::too_many_arguments)]
6503 fn linear_attn_verify_t(
6504 &self,
6505 e: &Engine,
6506 la: &LinearAttnLayer,
6507 h: &CudaSlice<f32>,
6508 h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
6509 t: usize,
6510 cache: &mut Cache,
6511 il: usize,
6512 want_stash: bool,
6513 ) -> Result<(CudaSlice<f32>, Option<GdnStash>), Box<dyn std::error::Error>> {
6514 let cfg = &self.cfg;
6515 let ssm = cfg.ssm.as_ref().unwrap();
6516 let d_state = ssm.state_size as usize;
6517 let num_k = ssm.group_count as usize;
6518 let num_v = ssm.time_step_rank as usize;
6519 let d_conv = ssm.conv_kernel as usize;
6520 let key_dim = d_state * num_k;
6521 let conv_dim = key_dim * 2 + d_state * num_v;
6522 let eps = cfg.rms_eps;
6523 let scale = 1.0 / (d_state as f32).sqrt();
6524
6525 // DECODE-EXACT projections: matmul_decode_exact forces the MMVQ (warp-per-row, 32-thread)
6526 // accumulation order for EVERY m, matching the T=1 decode path bit-for-bit. The generic
6527 // `matmul` at m>=5 falls to dp4a (128-thread, two-level reduce) which has a different FP
6528 // sum order — ULP differences propagate through gdn_scan and flip argmax on the 27B.
6529 // Q8 TRUNK-FUSION at T=1 (35B: wqkv+wqkv_gate both Q8_0): one fused2 launch, bit-identical
6530 // per (tensor,row) to the two m=1 MMVQ dispatches below — decode-exact contract holds.
6531 // VERIFY-TIER TRUNK FUSION (MEMRA_SPEC_FUSED_T, t=2-4): quantize h ONCE for every
6532 // fused-eligible same-input Q8_0 pair of this layer (35B wqkv+wqkv_gate; 9B
6533 // ssm_beta+ssm_alpha) — each fused2 batched launch then replaces two decode-exact
6534 // calls (each of which re-quantizes the same h + runs its own _b2/_b4 launch).
6535 // Bit-identical per (tensor,token,row) — see spec_fused_t().
6536 // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): `h_q8` = the attn-input norm emitted
6537 // directly as q8_1 by the caller's fused rms_norm_q8_1 (bit-identical to the unfused
6538 // chain, kernel-check-pinned). When present it REPLACES the standalone quantize below
6539 // and feeds every projection; the caller guaranteed all four input projections are
6540 // q8_1-fast. When absent, the old shared-quantize (fused-t window) stands.
6541 let h_q8_t = if h_q8.is_none()
6542 && spec_fused_t()
6543 && (2..=4).contains(&t)
6544 && ((e.uses_q8_1_fast(&la.wqkv) && e.uses_q8_1_fast(&la.wqkv_gate))
6545 || (e.uses_q8_1_fast(&la.ssm_beta) && e.uses_q8_1_fast(&la.ssm_alpha)))
6546 {
6547 Some(e.quantize_q8_1(h, t, cfg.n_embd as usize)?)
6548 } else {
6549 None
6550 };
6551 // one view: the caller's fused-norm q8 or this fn's own shared quantize.
6552 let hq8_any: Option<(&CudaSlice<i8>, &CudaSlice<f32>)> =
6553 h_q8.or(h_q8_t.as_ref().map(|(q, d)| (q, d)));
6554 let (qkv_mixed, z) = {
6555 let mut fused = None;
6556 if t == 1 && e.uses_q8_1_fast(&la.wqkv) && e.uses_q8_1_fast(&la.wqkv_gate) {
6557 let (hq, hd) = e.quantize_q8_1(h, 1, cfg.n_embd as usize)?;
6558 fused = e.matmul_q8_fused2(&la.wqkv, &la.wqkv_gate, &hq, &hd)?;
6559 } else if let Some((hq, hd)) = hq8_any {
6560 if spec_fused_t() && (2..=4).contains(&t) {
6561 fused = e.matmul_q8_fused2_t(&la.wqkv, &la.wqkv_gate, hq, hd, t)?;
6562 }
6563 }
6564 match (fused, hq8_any) {
6565 (Some(pair), _) => pair,
6566 (None, Some((hq, hd))) if h_q8.is_some() => (
6567 e.matmul_decode_exact_pre(&la.wqkv, hq, hd, t)?,
6568 e.matmul_decode_exact_pre(&la.wqkv_gate, hq, hd, t)?,
6569 ),
6570 (None, _) => (
6571 e.matmul_decode_exact(&la.wqkv, h, t)?,
6572 e.matmul_decode_exact(&la.wqkv_gate, h, t)?,
6573 ),
6574 }
6575 };
6576 // beta+alpha DUAL at T=1 (75% of p3 rounds run T=1 verify — p-min chain cuts): the dual
6577 // mr2 kernel is bit-identical per element to the m=1 MMVQ matmul_decode_exact dispatches
6578 // (same warp-per-row body, blockIdx.y picks the weight), so the decode-exact contract
6579 // holds; the run-spec battery is the arbiter. T>1 keeps the per-tensor decode-exact path.
6580 let (beta_raw, alpha) = if t == 1 {
6581 let (hq, hd) = e.quantize_q8_1(h, 1, cfg.n_embd as usize)?;
6582 match e.matmul_pre_dual_noscale(&la.ssm_beta, &la.ssm_alpha, &hq, &hd, 1)? {
6583 Some(((mut b, bs), (mut a, as_))) => {
6584 if bs != 1.0 {
6585 e.scale_inplace(&mut b, bs, la.ssm_beta.out_features())?;
6586 }
6587 if as_ != 1.0 {
6588 e.scale_inplace(&mut a, as_, la.ssm_alpha.out_features())?;
6589 }
6590 (b, a)
6591 }
6592 // Q8_0 fused2 twin (9B stores beta/alpha as Q8_0): DISPATCH-MIRRORS the eager
6593 // decode's beta_alpha closure — the fused body is qmatvec_q8_0_mmvq verbatim,
6594 // bit-identical per row (kernel-check rel=0.00e0 gate), so decode==verify holds.
6595 None => match e.matmul_q8_fused2(&la.ssm_beta, &la.ssm_alpha, &hq, &hd)? {
6596 Some((b, a)) => (b, a),
6597 None => (
6598 e.matmul_decode_exact(&la.ssm_beta, h, 1)?,
6599 e.matmul_decode_exact(&la.ssm_alpha, h, 1)?,
6600 ),
6601 },
6602 }
6603 } else {
6604 // fused-t twin (9B stores beta/alpha as Q8_0): same shared-quantize + one launch
6605 // contract as the wqkv pair above; 35B beta/alpha are Float -> None -> fallback.
6606 let mut nvfp4_fused = None;
6607 let mut q8_fused = None;
6608 if let Some((hq, hd)) = hq8_any {
6609 if t == 3 && std::env::var("MEMRA_NVFP4_AUX_DUAL").as_deref() != Ok("0") {
6610 nvfp4_fused =
6611 e.matmul_decode_exact_dual_pre(&la.ssm_beta, &la.ssm_alpha, hq, hd, t)?;
6612 if nvfp4_fused.is_some() && std::env::var("MEMRA_DEBUG").is_ok() {
6613 static ONCE: std::sync::Once = std::sync::Once::new();
6614 ONCE.call_once(|| {
6615 eprintln!("[memra] NVFP4 beta+alpha batched aux dual ENGAGED (t={t})")
6616 });
6617 }
6618 }
6619 if nvfp4_fused.is_none() && spec_fused_t() && (2..=4).contains(&t) {
6620 q8_fused = e.matmul_q8_fused2_t(&la.ssm_beta, &la.ssm_alpha, hq, hd, t)?;
6621 }
6622 }
6623 if let Some(((mut b, bs), (mut a, as_))) = nvfp4_fused {
6624 if bs != 1.0 {
6625 e.scale_inplace(&mut b, bs, t * la.ssm_beta.out_features())?;
6626 }
6627 if as_ != 1.0 {
6628 e.scale_inplace(&mut a, as_, t * la.ssm_alpha.out_features())?;
6629 }
6630 (b, a)
6631 } else if let Some(pair) = q8_fused {
6632 pair
6633 } else {
6634 match hq8_any {
6635 Some((hq, hd)) if h_q8.is_some() => (
6636 e.matmul_decode_exact_pre(&la.ssm_beta, hq, hd, t)?,
6637 e.matmul_decode_exact_pre(&la.ssm_alpha, hq, hd, t)?,
6638 ),
6639 _ => (
6640 e.matmul_decode_exact(&la.ssm_beta, h, t)?,
6641 e.matmul_decode_exact(&la.ssm_alpha, h, t)?,
6642 ),
6643 }
6644 }
6645 };
6646
6647 // conv with CARRIED state + ring roll (T >= pad rides the input-column update kernel;
6648 // T < pad — the MEMRA_SPEC_M2 t=2 arm — rolls via the pure-copy ring rebuild).
6649 let rl = cache.recur[il].as_mut().unwrap();
6650 let mut conv_out = e.uninit(conv_dim * t)?;
6651 e.ssm_conv1d_tm_state(
6652 &qkv_mixed,
6653 &mut rl.conv_state,
6654 la.ssm_conv1d.float_data(),
6655 &mut conv_out,
6656 conv_dim,
6657 t,
6658 d_conv,
6659 )?;
6660
6661 // GDN prep via the prefill kernels (repack + L2 + sigmoid + glog), T-wide.
6662 let mut q_g = e.uninit(d_state * num_v * t)?;
6663 let mut k_g = e.uninit(d_state * num_v * t)?;
6664 let mut v_g = e.uninit(d_state * num_v * t)?;
6665 e.qkv_to_gdn_repack(
6666 &conv_out, &mut q_g, &mut k_g, &mut v_g, d_state, num_v, num_k, key_dim, t,
6667 )?;
6668 let mut q_l2 = e.uninit(d_state * num_v * t)?;
6669 e.l2_norm_decode(&q_g, &mut q_l2, d_state, num_v * t, eps)?;
6670 let mut k_l2 = e.uninit(d_state * num_v * t)?;
6671 e.l2_norm_decode(&k_g, &mut k_l2, d_state, num_v * t, eps)?;
6672 let mut beta = e.uninit(t * num_v)?;
6673 e.sigmoid(&beta_raw, &mut beta, t * num_v)?;
6674 let mut g_log = e.uninit(t * num_v)?;
6675 e.gdn_glog(
6676 &alpha,
6677 la.ssm_dt.float_data(),
6678 la.ssm_a.float_data(),
6679 &mut g_log,
6680 num_v,
6681 t,
6682 )?;
6683
6684 // ONE gdn_scan over T tokens from the carried state (internal sequential loop ==
6685 // T chained T=1 steps). Ping-pong the resident buffers like eager decode.
6686 let mut o = e.uninit(d_state * num_v * t)?;
6687 {
6688 let crate::cache::RecurLayer {
6689 ssm_state,
6690 ssm_state_alt,
6691 ..
6692 } = rl;
6693 e.gdn_scan_s128(
6694 &q_l2,
6695 &k_l2,
6696 &v_g,
6697 &g_log,
6698 &beta,
6699 ssm_state,
6700 ssm_state_alt,
6701 &mut o,
6702 num_v,
6703 t,
6704 scale,
6705 )?;
6706 }
6707 std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
6708
6709 // gated RMSNorm + out projection, T-wide. FUSED-QUANTIZE ARM (lane/vt-fixes fix 2,
6710 // mirroring the T=1 decode's launch-arc form): when ssm_out rides the q8_1 fast path,
6711 // emit q8_1 straight from the gated norm at nrows=num_v*t (row-indexed kernel, the
6712 // T-wide launch is the per-row program; kernel-check pins bit-identity vs
6713 // gated_rmsnorm -> quantize_q8_1 at T=1 and T=5) and feed the decode-exact dispatch
6714 // pre-quantized — one launch replaces norm + quantize. Fallback = the f32 chain.
6715 let out = if e.uses_q8_1_fast(&la.ssm_out) {
6716 let (gq, gd) =
6717 e.gated_rmsnorm_q8_1(&o, la.ssm_norm.float_data(), &z, d_state, num_v * t, eps)?;
6718 e.matmul_decode_exact_pre(&la.ssm_out, &gq, &gd, t)?
6719 } else {
6720 let mut gn = e.uninit(d_state * num_v * t)?;
6721 e.gated_rmsnorm(
6722 &o,
6723 la.ssm_norm.float_data(),
6724 &z,
6725 &mut gn,
6726 d_state,
6727 num_v * t,
6728 eps,
6729 )?;
6730 // DECODE-EXACT out-projection: same MMVQ path as the T=1 decode (ssm_out at m>=5
6731 // would fall to dp4a with a different FP reduction order — same class of bug as
6732 // the input projs).
6733 e.matmul_decode_exact(&la.ssm_out, &gn, t)?
6734 };
6735 let stash = if want_stash {
6736 Some(GdnStash {
6737 qkv_mixed,
6738 q_l2,
6739 k_l2,
6740 v_g,
6741 g_log,
6742 beta,
6743 })
6744 } else {
6745 None
6746 };
6747 Ok((out, stash))
6748 }
6749
6750 /// REPLAY-FREE partial-accept commit (2026-07-03): make the cache state == "committed through
6751 /// the first `j` verify columns" WITHOUT the legacy rollback + duplicate trunk replay.
6752 /// - Full-attn KV: truncate len to snapshot + j. The verify's appended rows for those columns
6753 /// are bit-identical to what an eager T=1 chain writes (the decode-exact contract the
6754 /// verify-probe gates), so keeping them == replaying them.
6755 /// - Linear layers, batched path: rebuild the conv ring by PURE COPIES (ring holds raw input
6756 /// columns) and the ssm state by a prefix re-run of the SAME gdn_scan kernel (t=j) from the
6757 /// snapshot state over the stash's identical inputs — the kernel's t-loop carries state in
6758 /// registers and writes it once at the end, so iterations 0..j-1 are independent of T:
6759 /// bit-identical to the verify's own state after j tokens == the eager chain state.
6760 /// - Linear layers, per-column path: restore the cloned actual state after column j-1.
6761 /// Caller guarantees 1 <= j <= t-1 (j==0 rounds take the legacy rollback; j==t is full accept).
6762 fn commit_verified_prefix(
6763 &self,
6764 e: &Engine,
6765 cache: &mut Cache,
6766 snap: &crate::cache::CacheSnapshot,
6767 ckpt: &VerifyCkpt,
6768 j: usize,
6769 kv_lens_done: bool,
6770 dev_j: Option<(&CudaSlice<u32>, usize, usize)>,
6771 ) -> Result<(), Box<dyn std::error::Error>> {
6772 let cfg = &self.cfg;
6773 let ssm = cfg.ssm.as_ref().unwrap();
6774 let d_state = ssm.state_size as usize;
6775 let num_k = ssm.group_count as usize;
6776 let num_v = ssm.time_step_rank as usize;
6777 let d_conv = ssm.conv_kernel as usize;
6778 let conv_dim = d_state * num_k * 2 + d_state * num_v;
6779 let scale = 1.0 / (d_state as f32).sqrt();
6780 // Engine-bundle slice 1 (DSF-ROUNDCOST-20260820 §1.1): the per-column-arm restores
6781 // are 2 tiny D2D copies per linear layer (~96 dispatches/partial round on the q38
6782 // route). When every cols-arm layer shares uniform state sizes (single ssm cfg —
6783 // always true today), batch them into two `copy_batch_uniform_f32` launches. Bytes,
6784 // buffers and stream order are identical to the per-layer memcpy sequence; the
6785 // kernel-rebuild (gdn-stash) arm below is untouched. MEMRA_STATE_COPY_BATCH=0 reverts.
6786 let mut batched_cols = false;
6787 if state_copy_batch_on() && dev_j.is_none() {
6788 use cudarc::driver::DevicePtr;
6789 let s = &e.gpu.stream();
6790 let mut conv_pairs: Vec<(u64, u64)> = Vec::new();
6791 let mut ssm_pairs: Vec<(u64, u64)> = Vec::new();
6792 let (mut conv_words, mut ssm_words) = (0usize, 0usize);
6793 let mut uniform = true;
6794 for il in 0..self.layers.len() {
6795 let Some(rl) = cache.recur[il].as_ref() else {
6796 continue;
6797 };
6798 if ckpt.gdn[il].is_some() {
6799 continue; // kernel-rebuild arm restores below, per layer
6800 }
6801 let Some(cols) = &ckpt.cols[il] else {
6802 continue; // missing-ckpt error surfaces in the main loop
6803 };
6804 let (c, st) = &cols[j - 1];
6805 if conv_pairs.is_empty() {
6806 conv_words = c.len();
6807 ssm_words = st.len();
6808 } else if c.len() != conv_words || st.len() != ssm_words {
6809 uniform = false;
6810 break;
6811 }
6812 let (pc, _g0) = c.device_ptr(s);
6813 let (dc, _g1) = rl.conv_state.device_ptr(s);
6814 let (ps, _g2) = st.device_ptr(s);
6815 let (ds, _g3) = rl.ssm_state.device_ptr(s);
6816 conv_pairs.push((pc as u64, dc as u64));
6817 ssm_pairs.push((ps as u64, ds as u64));
6818 }
6819 if uniform && !conv_pairs.is_empty() {
6820 let n = conv_pairs.len();
6821 let mut t = vec![0u64; 2 * n];
6822 for (k, &(src, dst)) in conv_pairs.iter().enumerate() {
6823 t[k] = src;
6824 t[n + k] = dst;
6825 }
6826 let conv_t = e.htod_u64(&t)?;
6827 for (k, &(src, dst)) in ssm_pairs.iter().enumerate() {
6828 t[k] = src;
6829 t[n + k] = dst;
6830 }
6831 let ssm_t = e.htod_u64(&t)?;
6832 e.copy_batch_uniform_f32(&conv_t, n, conv_words)?;
6833 e.copy_batch_uniform_f32(&ssm_t, n, ssm_words)?;
6834 batched_cols = true;
6835 }
6836 }
6837 for il in 0..self.layers.len() {
6838 if let (Some(kvl), Some(saved)) = (cache.kv[il].as_mut(), snap.kv_len[il]) {
6839 kvl.len = saved + j;
6840 // devacc 3a: spec_rollback_kv already wrote len_d on-device (same value).
6841 if !kv_lens_done {
6842 e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
6843 }
6844 }
6845 if let Some(rl) = cache.recur[il].as_mut() {
6846 if let Some(st) = &ckpt.gdn[il] {
6847 let ring_old = snap.conv[il].as_ref().expect("snapshot missing conv");
6848 let state_in = snap.ssm[il].as_ref().expect("snapshot missing ssm");
6849 if let Some((acc, base, t_v)) = dev_j {
6850 // 3b: j read on-device (_dc twins, same bodies; full accept early-exits).
6851 e.ssm_conv_ring_rebuild_dc(
6852 &st.qkv_mixed,
6853 ring_old,
6854 &mut rl.conv_state,
6855 conv_dim,
6856 acc,
6857 base,
6858 t_v,
6859 d_conv,
6860 )?;
6861 let mut o = e.uninit(d_state * num_v * j.max(1))?;
6862 e.gdn_scan_s128_dc(
6863 &st.q_l2,
6864 &st.k_l2,
6865 &st.v_g,
6866 &st.g_log,
6867 &st.beta,
6868 state_in,
6869 &mut rl.ssm_state,
6870 &mut o,
6871 num_v,
6872 acc,
6873 base,
6874 t_v,
6875 scale,
6876 )?;
6877 } else {
6878 e.ssm_conv_ring_rebuild(
6879 &st.qkv_mixed,
6880 ring_old,
6881 &mut rl.conv_state,
6882 conv_dim,
6883 j,
6884 d_conv,
6885 )?;
6886 let mut o = e.uninit(d_state * num_v * j)?; // scan output, discarded
6887 e.gdn_scan_s128(
6888 &st.q_l2,
6889 &st.k_l2,
6890 &st.v_g,
6891 &st.g_log,
6892 &st.beta,
6893 state_in,
6894 &mut rl.ssm_state,
6895 &mut o,
6896 num_v,
6897 j,
6898 scale,
6899 )?;
6900 }
6901 } else if let Some(cols) = &ckpt.cols[il] {
6902 if !batched_cols {
6903 let (c, s) = &cols[j - 1];
6904 e.copy_into(&mut rl.conv_state, 0, c, c.len())?;
6905 e.copy_into(&mut rl.ssm_state, 0, s, s.len())?;
6906 }
6907 } else {
6908 return Err(
6909 "commit_verified_prefix: verify ckpt missing for linear layer".into(),
6910 );
6911 }
6912 }
6913 }
6914 cache.pos = snap.pos + j;
6915 Ok(())
6916 }
6917
6918 /// ROUND-STREAM: recur restore with device-j (the _dc twins; full accept early-exits
6919 /// in-kernel). Requires the batched-linear stash on every linear layer (stream gate).
6920 fn commit_verified_prefix_stream(
6921 &self,
6922 e: &Engine,
6923 cache: &mut Cache,
6924 snap: &crate::cache::CacheSnapshot,
6925 ckpt: &VerifyCkpt,
6926 acc: &CudaSlice<u32>,
6927 base: usize,
6928 t_v: usize,
6929 ) -> Result<(), Box<dyn std::error::Error>> {
6930 let cfg = &self.cfg;
6931 let ssm = cfg.ssm.as_ref().unwrap();
6932 let d_state = ssm.state_size as usize;
6933 let num_k = ssm.group_count as usize;
6934 let num_v = ssm.time_step_rank as usize;
6935 let d_conv = ssm.conv_kernel as usize;
6936 let conv_dim = d_state * num_k * 2 + d_state * num_v;
6937 let scale = 1.0 / (d_state as f32).sqrt();
6938 for il in 0..self.layers.len() {
6939 if let Some(rl) = cache.recur[il].as_mut() {
6940 let st = ckpt.gdn[il]
6941 .as_ref()
6942 .ok_or("stream restore: batched-linear stash missing")?;
6943 let ring_old = snap.conv[il].as_ref().expect("snapshot missing conv");
6944 let state_in = snap.ssm[il].as_ref().expect("snapshot missing ssm");
6945 e.ssm_conv_ring_rebuild_dc(
6946 &st.qkv_mixed,
6947 ring_old,
6948 &mut rl.conv_state,
6949 conv_dim,
6950 acc,
6951 base,
6952 t_v,
6953 d_conv,
6954 )?;
6955 let mut o = e.uninit(d_state * num_v * t_v)?;
6956 e.gdn_scan_s128_dc(
6957 &st.q_l2,
6958 &st.k_l2,
6959 &st.v_g,
6960 &st.g_log,
6961 &st.beta,
6962 state_in,
6963 &mut rl.ssm_state,
6964 &mut o,
6965 num_v,
6966 acc,
6967 base,
6968 t_v,
6969 scale,
6970 )?;
6971 }
6972 }
6973 Ok(())
6974 }
6975
6976 /// EAGLE3 aux-capturing verify forward over `tokens` (T) — mirrors `decode_step_t_h` exactly
6977 /// (same KV append, same causal verify, same recur advance) but ALSO clones the aux residual-
6978 /// stream hiddens (blocks in `aux_layers`) for TWO columns: the LAST column (always) and the
6979 /// optional `pred_col` (the EAGLE seed = bonus's predecessor). Returns
6980 /// (all_T_logits host, last_col_aux, pred_col_aux?). Used by the EAGLE3 orchestrator's commit.
6981 pub fn decode_step_t_aux2(
6982 &self,
6983 e: &Engine,
6984 tokens: &[u32],
6985 pos0: usize,
6986 cache: &mut Cache,
6987 aux_layers: &[usize],
6988 pred_col: Option<usize>,
6989 ) -> Result<
6990 (Vec<f32>, Vec<CudaSlice<f32>>, Option<Vec<CudaSlice<f32>>>),
6991 Box<dyn std::error::Error>,
6992 > {
6993 let cfg = &self.cfg;
6994 let n_embd = cfg.n_embd as usize;
6995 let eps = cfg.rms_eps;
6996 let t = tokens.len();
6997 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
6998 let pos_d = e.htod_i32(&pos_vec)?;
6999 let mut x = e.htod(&self.embd.gather(n_embd, tokens))?;
7000 let mut aux_last: Vec<CudaSlice<f32>> = Vec::with_capacity(aux_layers.len());
7001 let mut aux_pred: Vec<CudaSlice<f32>> = Vec::new();
7002 let want_pred = pred_col.is_some();
7003
7004 for (il, layer) in self.layers.iter().enumerate() {
7005 // DISPATCH-MIRRORED norms (FP-order lesson #8) — see decode_step_t_h_emb.
7006 let mixer_fast = self.mixer_in_q8_1_fast(e, &layer.mixer);
7007 let norm_fused = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err() && mixer_fast;
7008 let mut h = vbuf(e, t * n_embd)?; // fully written by either rms_norm arm
7009 if norm_fused {
7010 e.rms_norm_decode(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
7011 } else {
7012 e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
7013 }
7014 let mixed = match &layer.mixer {
7015 Mixer::Full(fa) => {
7016 self.full_attn_verify(e, fa, &h, None, &pos_d, t, cache, il, None)?
7017 }
7018 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
7019 Mixer::Linear(la) => {
7020 let mut out = e.zeros(t * n_embd)?;
7021 for col in 0..t {
7022 let mut h_col = e.zeros(n_embd)?;
7023 let src = h.slice(col * n_embd..(col + 1) * n_embd);
7024 e.copy_view_into(&mut h_col, 0, &src, n_embd)?;
7025 let m_col = self.linear_attn_decode(e, la, &h_col, cache, il)?;
7026 e.copy_into(&mut out, col * n_embd, &m_col, n_embd)?;
7027 }
7028 out
7029 }
7030 };
7031 let ffn_fuse = match &layer.ffn {
7032 crate::hybrid::Ffn::Dense {
7033 ffn_gate, ffn_up, ..
7034 } => {
7035 std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
7036 && e.uses_q8_1_fast(ffn_gate)
7037 && e.uses_q8_1_fast(ffn_up)
7038 }
7039 crate::hybrid::Ffn::Moe(_) => false,
7040 };
7041 let mut x1 = vbuf(e, t * n_embd)?; // fully written by add / add_rms_norm
7042 let mut z = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode / add_rms_norm
7043 if ffn_fuse {
7044 e.add(&x, &mixed, &mut x1, t * n_embd)?;
7045 e.rms_norm_decode(
7046 &x1,
7047 layer.post_attn_norm.float_data(),
7048 &mut z,
7049 n_embd,
7050 t,
7051 eps,
7052 )?;
7053 } else {
7054 e.add_rms_norm(
7055 &x,
7056 &mixed,
7057 layer.post_attn_norm.float_data(),
7058 &mut x1,
7059 &mut z,
7060 n_embd,
7061 t,
7062 eps,
7063 )?;
7064 }
7065 let ffn_out = match &layer.ffn {
7066 crate::hybrid::Ffn::Dense {
7067 ffn_gate,
7068 ffn_up,
7069 ffn_down,
7070 } => {
7071 let n_ff = ffn_gate.out_features();
7072 let gate = e.matmul_decode_exact(ffn_gate, &z, t)?;
7073 let up = e.matmul_decode_exact(ffn_up, &z, t)?;
7074 let mut act = vbuf(e, t * n_ff)?; // fully written by ffn_act_lim
7075 // dense FFN clamp = the SHEXP array (upstream build_ffn serves both).
7076 Self::ffn_act_lim(
7077 e,
7078 &self.cfg,
7079 &gate,
7080 &up,
7081 1.0,
7082 1.0,
7083 self.cfg.clamp_shexp_at(il as u32),
7084 &mut act,
7085 t * n_ff,
7086 )?;
7087 e.matmul_decode_exact(ffn_down, &act, t)?
7088 }
7089 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, t, il as u16)?,
7090 };
7091 let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
7092 e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
7093 if aux_layers.contains(&il) {
7094 let mut a = e.zeros(n_embd)?;
7095 e.copy_view_into(&mut a, 0, &x2.slice((t - 1) * n_embd..t * n_embd), n_embd)?;
7096 aux_last.push(a);
7097 if let Some(pc) = pred_col {
7098 let mut ap = e.zeros(n_embd)?;
7099 e.copy_view_into(
7100 &mut ap,
7101 0,
7102 &x2.slice(pc * n_embd..(pc + 1) * n_embd),
7103 n_embd,
7104 )?;
7105 aux_pred.push(ap);
7106 }
7107 }
7108 x = x2;
7109 }
7110 let mut hn = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode
7111 e.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
7112 let logits = e.matmul_decode_exact(&self.output, &hn, t)?;
7113 let host = e.dtoh(&logits)?;
7114 cache.pos += t;
7115 Ok((
7116 host,
7117 aux_last,
7118 if want_pred { Some(aux_pred) } else { None },
7119 ))
7120 }
7121
7122 /// step35 SPEC-VERIFY attention over T query tokens — a per-row REPLAY of the eager
7123 /// `step35_decode_attn`.
7124 ///
7125 /// WHY A REPLAY AND NOT A BATCHED TWIN. The verify's whole job is to be bit-identical to what
7126 /// the eager decode would have computed for the same tokens; that is what makes greedy spec
7127 /// decode exact (run-spec asserts token identity for K=1..8). Every other verify arm in this
7128 /// file earns that identity by carefully mirroring dispatch (`matmul_decode_exact` to force
7129 /// MMVQ at any m, per-layer `ffn_fuse` mirroring, per-row `fa_decode` key bounds). step35
7130 /// stacks FOUR more per-layer degrees of freedom on top of that — per-layer `n_head`
7131 /// (64 full / 96 SWA), per-layer rotary width (64 full / 128 SWA), per-layer rope base, and a
7132 /// SEPARATE `attn_gate` tensor whose projection shares the attn-normed input — and its SWA
7133 /// layers attend through a token-OFFSET view whose offset is a function of the ABSOLUTE
7134 /// position of each query row. A batched twin would have to reproduce all of that AND the
7135 /// per-row offset in one launch; the offset alone rules out the existing rows kernels (they
7136 /// take one `base_len`, not a per-row offset).
7137 ///
7138 /// So this arm calls the eager path itself, once per row, on the same cache. Identity is then
7139 /// true BY CONSTRUCTION rather than by mirroring: row r runs exactly the kernel sequence that
7140 /// eager decode step r runs (same projections, same q8_1 fusion decision, same append, same
7141 /// view arithmetic, same `fa_decode_kvmod`, same gate), because it IS that code. Cost: T x the
7142 /// eager decode mixer instead of one batched pass — the same trade the generic arm's `else`
7143 /// per-row loop already accepts when `fa_rows_eligible` says no. Correctness first; a batched
7144 /// step35 twin is a perf lane's job and must be gated against this arm.
7145 ///
7146 /// The `h_q8` pre-quantized pair from the caller's fused norm is NOT forwarded: it is a
7147 /// T-row buffer and `step35_decode_attn`'s `pre_q` contract is one row. Instead each row's
7148 /// f32 `h` slice is handed over and the callee re-derives its own q8_1 exactly as eager decode
7149 /// does (`quantize_q8_1(h, 1, n_embd)`) — which is the dispatch being mirrored. Callers that
7150 /// took the fused arm therefore MUST still pass a live `h`; `step35_verify` asserts that.
7151 #[allow(clippy::too_many_arguments)]
7152 fn step35_verify(
7153 &self,
7154 e: &Engine,
7155 fa: &FullAttnLayer,
7156 h: &CudaSlice<f32>,
7157 h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
7158 t: usize,
7159 cache: &mut Cache,
7160 il: usize,
7161 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
7162 let n_embd = self.cfg.n_embd as usize;
7163 // The fused (h-less) attn-norm arm hands `h` as a zero-length placeholder. This arm needs
7164 // the f32 rows, so the caller must not take that lever for step35 — enforced at the call
7165 // site by the `Mixer::Full(_) if self.cfg.step35.is_some() => false` arm of
7166 // `lin_q8_only` in `decode_step_t_core_stream`, and asserted here so a future caller
7167 // cannot regress it into silently reading an empty buffer.
7168 assert_eq!(
7169 h.len(),
7170 t * n_embd,
7171 "step35_verify needs the f32 attn-normed rows ([t*n_embd]); the caller took the \
7172 fused q8-only norm arm (h_q8={}) — step35 must stay on the unfused arm",
7173 h_q8.is_some()
7174 );
7175 // ROW WIDTH IS n_embd, NOT n_head*head_dim: `step35_decode_attn` returns the mixer output
7176 // AFTER `wo`, so a row is [n_embd] — the same contract the generic arm's
7177 // `matmul_decode_exact(&fa.wo, &attn_g, t)` return has. Sizing this buffer from the
7178 // per-layer head geometry (8192 on full-attn, 12288 on SWA) instead overran the row on the
7179 // FIRST copy and panicked inside `copy_into`'s `CudaView::slice` unwrap
7180 // (raw/mtp-bt-20260806T212127Z.log frames 12-13).
7181 let mut out = vbuf(e, t * n_embd)?; // each row fully written by the copy below
7182 for r in 0..t {
7183 // Absolute position of this query row. `cache.pos` is the committed length at round
7184 // start and every row before r has already been appended by this loop, so the r-th
7185 // verify token sits at cache.pos + r — the same position eager decode would give it.
7186 let pos_d = e.htod_i32(&[(cache.pos + r) as i32])?;
7187 let mut h_row = vbuf(e, n_embd)?; // fully written by copy_view_into
7188 e.copy_view_into(
7189 &mut h_row,
7190 0,
7191 &h.slice(r * n_embd..(r + 1) * n_embd),
7192 n_embd,
7193 )?;
7194 // THE eager decode mixer: appends this row's K/V at kvl.len, advances it, then
7195 // attends over the (SWA-offset) view. Post-`wo`, same contract as this fn returns.
7196 let o = self.step35_decode_attn(e, fa, il, &h_row, None, &pos_d, cache)?;
7197 debug_assert_eq!(
7198 o.len(),
7199 n_embd,
7200 "step35_decode_attn returns post-wo [n_embd]"
7201 );
7202 e.copy_into(&mut out, r * n_embd, &o, n_embd)?;
7203 }
7204 Ok(out)
7205 }
7206
7207 /// Full-attention mixer over T query tokens with a GROWING resident KV (verify path, §D.3).
7208 /// Appends the T new K/V columns to cache.kv[il] then attends causally over [0..len) via
7209 /// fa_prefill. Token-major [T, kv_dim] projection layout == cache row layout (single copy).
7210 #[allow(clippy::too_many_arguments)]
7211 fn full_attn_verify(
7212 &self,
7213 e: &Engine,
7214 fa: &FullAttnLayer,
7215 h: &CudaSlice<f32>,
7216 h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
7217 pos_d: &CudaSlice<i32>,
7218 t: usize,
7219 cache: &mut Cache,
7220 il: usize,
7221 stream_ctr: Option<&CudaSlice<i32>>,
7222 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
7223 // step35: the generic geometry below is wrong for this arch (per-layer n_head, partial
7224 // per-layer rope, the SWA offset view, and a SEPARATE head-wise gate tensor), so it takes
7225 // its own arm. A verify that silently computes different attention than decode defeats the
7226 // whole self-consistency gate, so the arm is a per-row REPLAY of `step35_decode_attn`
7227 // rather than a batched twin — see `step35_verify` for why that is the exactness-correct
7228 // shape and not laziness.
7229 if self.cfg.step35.is_some() {
7230 if stream_ctr.is_some() {
7231 return Err(
7232 "step35 has no ROUND-STREAM verify arm (the device-counter _dc twins \
7233 cannot express the SWA offset KV view; same root cause as the dc \
7234 decode refusal) — run spec without the stream arm"
7235 .into(),
7236 );
7237 }
7238 return self.step35_verify(e, fa, h, h_q8, t, cache, il);
7239 }
7240 let cfg = &self.cfg;
7241 let geometry = cfg.full_attention_geometry_at(il as u32);
7242 let n_head = geometry.n_head as usize;
7243 let n_head_kv = geometry.n_head_kv as usize;
7244 let head_dim = geometry.head_dim_k as usize;
7245 let eps = cfg.rms_eps;
7246 let scale = geometry.attention_scale();
7247 let n_embd = cfg.n_embd as usize;
7248
7249 // DECODE-EXACT Q/K/V projections: matmul_decode_exact forces the MMVQ (warp-per-row) path
7250 // for every m, matching the T=1 decode's FP accumulation order. matmul_pre at m>=5 would
7251 // fall to dp4a (128-thread, two-level reduce) with a different FP sum order.
7252 // Q8 TRUNK-FUSION at T=1: DISPATCH-MIRRORS the eager decode's fused3 (bit-identical body).
7253 // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): `h_q8` = the attn-input norm's q8_1
7254 // form emitted by the fused rms_norm_q8_1 (bit-identical to rms_norm_decode ->
7255 // quantize_q8_1, kernel-check-pinned). When present (caller checked mixer q8_1-fast),
7256 // every projection consumes it — `h` may be a zero-len placeholder and must not be read.
7257 let (qf, mut k, v) = {
7258 let mut fused = None;
7259 let qkv_fast =
7260 e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk) && e.uses_q8_1_fast(&fa.wv);
7261 if t == 1 && qkv_fast {
7262 let (hq_o, hd_o);
7263 let (hq, hd): (&CudaSlice<i8>, &CudaSlice<f32>) = match h_q8 {
7264 Some(p) => p,
7265 None => {
7266 (hq_o, hd_o) = e.quantize_q8_1(h, 1, n_embd)?;
7267 (&hq_o, &hd_o)
7268 }
7269 };
7270 fused = e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, hq, hd)?;
7271 } else if spec_fused_t() && (2..=4).contains(&t) && qkv_fast {
7272 // VERIFY-TIER TRUNK FUSION (MEMRA_SPEC_FUSED_T): one shared quantize + one
7273 // fused3 batched launch replaces three decode-exact calls (3 re-quantizes of
7274 // the same h + 3 _b2/_b4 launches). Bit-identical per (tensor,token,row).
7275 let (hq_o, hd_o);
7276 let (hq, hd): (&CudaSlice<i8>, &CudaSlice<f32>) = match h_q8 {
7277 Some(p) => p,
7278 None => {
7279 (hq_o, hd_o) = e.quantize_q8_1(h, t, n_embd)?;
7280 (&hq_o, &hd_o)
7281 }
7282 };
7283 fused = e.matmul_q8_fused3_t(&fa.wq, &fa.wk, &fa.wv, hq, hd, t)?;
7284 }
7285 match (fused, h_q8) {
7286 (Some(triple), _) => triple,
7287 // shared pre-quantized activation (q8_1-fast guaranteed by the caller): the
7288 // decode-exact dispatch consumes (hq, hd) instead of re-quantizing 3x.
7289 (None, Some((hq, hd))) if qkv_fast => (
7290 e.matmul_decode_exact_pre(&fa.wq, hq, hd, t)?,
7291 e.matmul_decode_exact_pre(&fa.wk, hq, hd, t)?,
7292 e.matmul_decode_exact_pre(&fa.wv, hq, hd, t)?,
7293 ),
7294 (None, _) => (
7295 e.matmul_decode_exact(&fa.wq, h, t)?,
7296 e.matmul_decode_exact(&fa.wk, h, t)?,
7297 e.matmul_decode_exact(&fa.wv, h, t)?,
7298 ),
7299 }
7300 };
7301 // M3/Hy3 have no attention output gate — wq out is exactly q; skip the split.
7302 let gated = geometry.attention_gate == memra_gguf::config::AttentionGateKind::FusedQ;
7303 let (mut q, gate) = if gated {
7304 let mut q = vbuf(e, t * n_head * head_dim)?; // fully written by q_gate_split
7305 let mut gate = vbuf(e, t * n_head * head_dim)?; // fully written by q_gate_split
7306 e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, t)?;
7307 (q, Some(gate))
7308 } else {
7309 (qf, None)
7310 };
7311
7312 let mut qn = vbuf(e, t * n_head * head_dim)?; // fully written by rms_norm
7313 e.rms_norm(
7314 &q,
7315 fa.q_norm.float_data(),
7316 &mut qn,
7317 head_dim,
7318 n_head * t,
7319 eps,
7320 )?;
7321 q = qn;
7322 let mut kn = vbuf(e, t * n_head_kv * head_dim)?; // fully written by rms_norm
7323 e.rms_norm(
7324 &k,
7325 fa.k_norm.float_data(),
7326 &mut kn,
7327 head_dim,
7328 n_head_kv * t,
7329 eps,
7330 )?;
7331 k = kn;
7332 let rope_dims = geometry.n_rot as usize;
7333 e.rope_neox(
7334 &mut q,
7335 pos_d,
7336 head_dim,
7337 rope_dims,
7338 n_head,
7339 t,
7340 geometry.rope_base,
7341 1.0,
7342 )?;
7343 e.rope_neox(
7344 &mut k,
7345 pos_d,
7346 head_dim,
7347 rope_dims,
7348 n_head_kv,
7349 t,
7350 geometry.rope_base,
7351 1.0,
7352 )?;
7353
7354 // append T new K/V columns to the resident QUANTIZED cache. k/v are token-major [T, kv_dim]
7355 // f32; append-quantize each of the T token rows into the byte cache (q8_0 K / q5_1 V).
7356 let kvl = cache.kv[il].as_mut().unwrap();
7357 let (kv_dim_k, kv_dim_v, ktb, vtb) =
7358 (kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes, kvl.v_tok_bytes);
7359 if let Some(ctr) = stream_ctr {
7360 // stream: ONE batched append at the device counter (rows kernel = the per-view warp
7361 // math on a (block, token) grid, documented byte-identical); host len is a stale
7362 // LOWER BOUND under pre-issue (drain reconciles it).
7363 e.append_kv_quantized_rows_dc(
7364 &k,
7365 &v,
7366 &mut kvl.k,
7367 &mut kvl.v,
7368 ctr,
7369 t,
7370 kv_dim_k,
7371 kv_dim_v,
7372 ktb,
7373 vtb,
7374 crate::Engine::kv_fp8_on(),
7375 )?;
7376 } else {
7377 for i in 0..t {
7378 let k_row = k.slice(i * kv_dim_k..(i + 1) * kv_dim_k);
7379 let v_row = v.slice(i * kv_dim_v..(i + 1) * kv_dim_v);
7380 e.append_kv_quantized_view(
7381 &k_row,
7382 &v_row,
7383 &mut kvl.k,
7384 &mut kvl.v,
7385 kvl.len + i,
7386 kv_dim_k,
7387 kv_dim_v,
7388 ktb,
7389 vtb,
7390 crate::Engine::kv_fp8_on(),
7391 )?;
7392 }
7393 kvl.len += t;
7394 }
7395
7396 // BIT-IDENTICAL VERIFY ATTENTION (spec-exactness fix): the FP accumulation order must be
7397 // byte-for-byte identical to the eager decode path. fa_prefill uses a different tile size
7398 // (BLOCK_Q=64, BK=32) and online-softmax structure than fa_decode's split-K + combine,
7399 // which changes FP summation order and can flip argmax at tight logit margins. Query row r
7400 // attends to keys [0..base_len+r+1) — each successive row sees one more key (the causal
7401 // property). This matches eager: decode appends k at len, then fa_decode sees t_kv = len+1
7402 // keys. The verify appends all T tokens first but bounds the key range per row.
7403 //
7404 // MULTI-ROW FUSED PATH (the long-ctx spec fix, 2026-07-03): when every row takes the vec
7405 // kernel (base_len+1 >= FA_VEC_MIN_TKV), ONE fa_decode_rows launch executes the exact
7406 // per-row program for all T rows (grid.z = row, per-row n_splits from the same
7407 // fa_split_keys formula) — replacing T x (2 launches + 2 dtod copies + 5 partial allocs)
7408 // and multiplying resident CTAs by T on a latency-bound kernel. Bit-identical per row by
7409 // construction; kernel-check pins rows-vs-loop byte identity, run-spec is the end gate.
7410 // Short ctx (any row below the vec crossover) and MEMRA_NO_FA_VEC/MEMRA_FA_ROWS_OFF keep the
7411 // per-row loop (whose fa_decode picks scalar/vec per row exactly like eager decode).
7412 let mut attn = vbuf(e, t * n_head * head_dim)?; // fully written by every FA arm below
7413 let base_len = kvl.len - t; // KV len BEFORE this round's T tokens were appended
7414 // T=1 INCLUDED (2026-07-05): p-min cuts the draft to 1 in ~75% of rounds on hard
7415 // (agentic) content — the old t>1 gate sent those rounds to the per-row loop (262us/row
7416 // + q-row copy + per-row allocs vs 93us/row through the fused kernel at grid.z=1, same
7417 // program). nsys accounting: 1088 of 1456 verify FA launches were T=1 escapees.
7418 // LEAN T=1 ARM (MEMRA_SPEC_LEAN, close35): at t==1, q IS one row and fa_decode on it is
7419 // the EXACT eager decode dispatch (vec_q_v2 + combine_f32; the rows pair measured +50us
7420 // at m=1). Byte-identical: kernel-check pins rows-vs-loop identity, and the per-row loop
7421 // at t=1 is fa_decode on the same q with zero-offset copies. Gates arbitrate.
7422 if let Some(ctr) = stream_ctr {
7423 // STREAM ARM: causal base from the device counter; host kvl.len is a stale lower
7424 // bound used only for the split-sizing upper bound (+64 slack covers M pre-issued
7425 // rounds at K<=8). Views span the bound; per-row limits derive in-kernel.
7426 let upper = kvl.len + t + 64;
7427 let k_view = e.view_u8(&kvl.k, (upper.min(cache.max_ctx)) * ktb);
7428 let v_view = e.view_u8(&kvl.v, (upper.min(cache.max_ctx)) * vtb);
7429 e.fa_decode_rows_dc(
7430 &q,
7431 &k_view,
7432 &v_view,
7433 &mut attn,
7434 head_dim,
7435 n_head,
7436 n_head_kv,
7437 ctr,
7438 upper.min(cache.max_ctx),
7439 t,
7440 scale,
7441 ktb,
7442 vtb,
7443 0,
7444 false,
7445 )?;
7446 } else if spec_lean() && t == 1 {
7447 let t_kv = base_len + 1;
7448 let k_view = e.view_u8(&kvl.k, t_kv * ktb);
7449 let v_view = e.view_u8(&kvl.v, t_kv * vtb);
7450 e.fa_decode_kvmod(
7451 &q,
7452 &k_view,
7453 &v_view,
7454 &mut attn,
7455 head_dim,
7456 n_head,
7457 n_head_kv,
7458 t_kv,
7459 scale,
7460 ktb,
7461 vtb,
7462 crate::Engine::kv_fp8_on(),
7463 )?;
7464 } else if e.fa_rows_eligible(base_len, head_dim) {
7465 let k_view = e.view_u8(&kvl.k, (base_len + t) * ktb);
7466 let v_view = e.view_u8(&kvl.v, (base_len + t) * vtb);
7467 e.fa_decode_rows(
7468 &q,
7469 &k_view,
7470 &v_view,
7471 &mut attn,
7472 head_dim,
7473 n_head,
7474 n_head_kv,
7475 base_len,
7476 t,
7477 scale,
7478 ktb,
7479 vtb,
7480 None,
7481 false,
7482 crate::Engine::kv_fp8_on(),
7483 None,
7484 )?;
7485 } else {
7486 for r in 0..t {
7487 let t_kv_r = base_len + r + 1; // this row sees keys [0..t_kv_r)
7488 let k_view_r = e.view_u8(&kvl.k, t_kv_r * ktb);
7489 let v_view_r = e.view_u8(&kvl.v, t_kv_r * vtb);
7490 // copy q row into an owned buffer (fa_decode takes &CudaSlice, not CudaView)
7491 let mut q_row = vbuf(e, n_head * head_dim)?; // fully written by copy_view_into
7492 let q_src = q.slice(r * n_head * head_dim..(r + 1) * n_head * head_dim);
7493 e.copy_view_into(&mut q_row, 0, &q_src, n_head * head_dim)?;
7494 let mut attn_row = vbuf(e, n_head * head_dim)?; // fully written by fa_decode
7495 e.fa_decode_kvmod(
7496 &q_row,
7497 &k_view_r,
7498 &v_view_r,
7499 &mut attn_row,
7500 head_dim,
7501 n_head,
7502 n_head_kv,
7503 t_kv_r,
7504 scale,
7505 ktb,
7506 vtb,
7507 crate::Engine::kv_fp8_on(),
7508 )?;
7509 e.copy_into(
7510 &mut attn,
7511 r * n_head * head_dim,
7512 &attn_row,
7513 n_head * head_dim,
7514 )?;
7515 }
7516 }
7517
7518 let attn_g = match &gate {
7519 Some(gate) => {
7520 let mut gsig = vbuf(e, t * n_head * head_dim)?; // fully written by sigmoid
7521 e.sigmoid(gate, &mut gsig, t * n_head * head_dim)?;
7522 let mut ag = vbuf(e, t * n_head * head_dim)?; // fully written by mul
7523 e.mul(&attn, &gsig, &mut ag, t * n_head * head_dim)?;
7524 ag
7525 }
7526 None => attn,
7527 };
7528 // DECODE-EXACT wo projection: at m>=5 (K=4+ with pending) the generic matmul would use dp4a
7529 // (128-thread, different FP sum order than MMVQ). Force MMVQ for bit-identity with decode.
7530 Ok(e.matmul_decode_exact(&fa.wo, &attn_g, t)?)
7531 }
7532
7533 /// Context-linear bytes for a plain serving session's trunk cache.
7534 pub fn plain_session_kv_bytes_per_token(&self) -> usize {
7535 crate::cache::cache_bytes_per_token(&self.cfg)
7536 }
7537
7538 /// `(logical bytes/token, ring-capped bytes/token, ring row cap)` for exact admission.
7539 pub fn plain_session_kv_shape(&self) -> (usize, usize, usize) {
7540 (
7541 self.plain_session_kv_bytes_per_token(),
7542 crate::cache::cache_ring_bytes_per_token(&self.cfg),
7543 crate::cache::cache_ring_row_cap(&self.cfg),
7544 )
7545 }
7546
7547 /// Context-linear bytes for a speculative serving session: trunk cache plus persistent MTP
7548 /// scratch. With no MTP head this equals the plain coefficient.
7549 pub fn spec_session_kv_bytes_per_token(&self) -> usize {
7550 let scratch = self
7551 .mtp
7552 .as_ref()
7553 .map(|mtp| {
7554 let (_, _, k, v) = mtp_scratch_layout(&self.cfg, mtp.geom.as_ref());
7555 k + v
7556 })
7557 .unwrap_or(0);
7558 self.plain_session_kv_bytes_per_token()
7559 .saturating_add(scratch)
7560 }
7561
7562 /// Spec twin of [`HybridModel::plain_session_kv_shape`]; Step35's persistent MTP scratch is
7563 /// capped by the same SWA ring rows as the trunk.
7564 pub fn spec_session_kv_shape(&self) -> (usize, usize, usize) {
7565 let total = self.spec_session_kv_bytes_per_token();
7566 let (_, mut ring, rows) = self.plain_session_kv_shape();
7567 if rows > 0 {
7568 ring = ring.saturating_add(
7569 self.mtp
7570 .as_ref()
7571 .map(|mtp| {
7572 let (_, _, k, v) = mtp_scratch_layout(&self.cfg, mtp.geom.as_ref());
7573 k + v
7574 })
7575 .unwrap_or(0),
7576 );
7577 }
7578 (total, ring, rows)
7579 }
7580
7581 /// Greedy MTP speculative decode (§B). Token-identical to `generate(prompt, max_new)` but uses
7582 /// the NextN head to draft K tokens then verifies them in one batched target forward.
7583 /// Returns (generated tokens, total_drafted, total_accepted) so the caller can report
7584 /// acceptance rate. `k` = draft length per round.
7585 ///
7586 /// GRAPH DRAFT (stage 2 of graph-grade spec): when the model is all-Dense and the MTP head is
7587 /// Dense (no MoE host readbacks), the fixed-shape T=1 MTP forward is CUDA-graph-captured ONCE
7588 /// and replayed per draft step — the ~40 eager launches per drafted token collapse into one
7589 /// graph dispatch; only the 4-byte token id (and 4-byte p-min confidence) round-trip per step.
7590 /// Event tracking is disabled for the whole call (generate_graph pattern) so every buffer the
7591 /// captured graph references is event-free; the spec loop is strictly single-stream.
7592 /// MEMRA_SPEC_NOGRAPH=1 forces the eager draft chain.
7593 /// SAMPLED mode (MEMRA_SPEC_TEMP>0) has its OWN capture (gumbel-perturbed in-graph argmax,
7594 /// device Philox event counter, persistent q retention) — graph-vs-eager sampled streams are
7595 /// bit-identical for the same (seed, prompt, K, temp); see the sampled-graph setup in
7596 /// generate_spec_inner2.
7597 /// Multi-turn session: trunk cache + MTP draft scratch persist across generate calls, so
7598 /// turn N+1 primes ONLY its new suffix (the 124k-conversation daily pattern — re-priming a
7599 /// 32k history costs ~54s; a suffix prime costs seconds). APPEND-ONLY by construction: the
7600 /// hybrid linear-attn states are in-place (no position index), so a session can extend but
7601 /// never rewind — `committed` is the exact token list whose state the caches hold (includes
7602 /// any overshoot tokens past max_new; the caller renders from `committed`, not its own echo).
7603 pub fn new_session(
7604 &self,
7605 e: &Engine,
7606 max_ctx: usize,
7607 ) -> Result<SpecSession, Box<dyn std::error::Error>> {
7608 Ok(SpecSession {
7609 // STAGE-OWNED KV (lane/pp2-spec 2026-08-06): `pp::new_cache`, not `Cache::new`. This
7610 // is the SERVING spec-session path, and with the ppN door open across two cards a
7611 // primary-homed cache makes every remote stage peer-read its OWN KV on every verify
7612 // round — the wrong-card class already fixed on the two batched serving paths
7613 // (worker.rs 2483 / 2837). With the door shut `new_cache` IS `Cache::new` (same
7614 // branch, same allocations), so single-device behavior is byte-unchanged.
7615 cache: crate::pp::new_cache(e, &self.cfg, max_ctx)?,
7616 scratch: MtpScratch::new(
7617 e,
7618 &self.cfg,
7619 max_ctx,
7620 self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
7621 )?,
7622 committed: Vec::new(),
7623 last_h: None,
7624 next_pred: None,
7625 sctr: 0,
7626 uctr: 0,
7627 draft_ctx: None,
7628 pending_tok: None,
7629 turn_ckpt: None,
7630 telem: SpecTelemetryCounters::default(),
7631 capture_at: None,
7632 boundary_captures: Vec::new(),
7633 ckpt_at: None,
7634 })
7635 }
7636
7637 /// SPEC-ON-CACHE-HIT restore (lane/spec-on-cache-hit, 2026-08-18 — PORT-PLAN item 3,
7638 /// research/cache-spec-design-20260814, scoped to WHOLE-ENTRY restores only): build a
7639 /// SpecSession around a trunk cache the worker already restored from a prefix-cache
7640 /// entry, re-installing the entry's published draft plane as the MTP scratch rows
7641 /// `[0..prefix.len())` and the entry's boundary hidden as `last_h`, then feeding the
7642 /// prompt SUFFIX here — through EXACTLY the plain path's program selection — so the
7643 /// worker always receives a fully-warm continuation session (committed = whole
7644 /// prompt, `next_pred` + `last_h` set; caller sets `next_pred` from the entry's
7645 /// boundary logits on the empty-suffix shape).
7646 ///
7647 /// PROGRAM LAW (the splitiso two-programs class, learned AGAIN in this lane's own
7648 /// gate): the identity target for a converted hit is the PLAIN hit serving the same
7649 /// request, and plain feeds a carried suffix via eager `decode_step` below
7650 /// PRIME_MIN_T and via `prime_cache` at/above it (prefill_tick's arms). The generate
7651 /// path's tokenwise arm routes qwen35-class through the BATCHED T=1 program
7652 /// (`spec_target_step_h`) instead — ULP-different suffix rows, and the gate measured
7653 /// the near-tie flip at generated token ~8 (research/spec-cache-20260818, qwen r3).
7654 /// So the suffix is fed HERE, mirroring prefill_tick arm-for-arm, not handed to the
7655 /// burst prime.
7656 ///
7657 /// SEED RULE (both sampling regimes; lane/sampled-hit-spec 2026-08-19, sampled draw
7658 /// added by lane/sampled-spec-quality 2026-08-19). The boundary token is produced by
7659 /// EXACTLY the rule the cold burst entry applies to its own first token from the same
7660 /// logits row: `argmax` when greedy, and a `sample_boundary_token` draw at Philox
7661 /// counter 0 when sampled. Both shapes are covered — the entry's boundary logits on a
7662 /// full-cover (empty-suffix) hit, this feed's own boundary logits on a suffix hit.
7663 /// That is what keeps a restored session seed-identical to a cold one PER SEED: the
7664 /// cold session draws from the identical row at counter 0 and then runs its rounds from
7665 /// counter 1, so the restored session admits with `sctr = 1` after its own draw.
7666 /// The WORKER owns the one refusal this constructor cannot see — a constrained request.
7667 /// (The penalized-sampled refusal was LIFTED once the burst's penalty window learned to
7668 /// span the session: `committed` here is the WHOLE prompt, so the restored session's
7669 /// window is the cold session's window. It comes back if `MEMRA_SPEC_PEN_SESSION=0`.)
7670 ///
7671 /// NOT the rolled-back partial-restore hazard: the caller restores at exactly the
7672 /// entry's captured endpoint (`e.pos`) through the shipping whole-entry path;
7673 /// mid-entry (`at < e.pos`) trunk restores stay behind MEMRA_PREFIX_PARTIAL_RESTORE
7674 /// and are never routed here.
7675 ///
7676 /// Failure contract: `Err((Some(cache), why))` before any trunk mutation — the
7677 /// worker rebuilds the plain carrier and the hit serves plain, byte-unchanged.
7678 /// `Err((None, why))` after the suffix feed began — the carrier is part-fed and
7679 /// UNUSABLE; the worker serves the request cold-plain (correct, slower) and the
7680 /// entry stays published for the next request.
7681 #[allow(clippy::too_many_arguments)]
7682 pub fn spec_session_from_restored(
7683 &self,
7684 e: &Engine,
7685 mut cache: Cache,
7686 prefix: Vec<u32>,
7687 suffix: &[u32],
7688 draft_k: &CudaSlice<u8>,
7689 draft_v: &CudaSlice<u8>,
7690 draft_k_tok_bytes: usize,
7691 draft_v_tok_bytes: usize,
7692 draft_len: usize,
7693 last_h: &[f32],
7694 // The ENTRY's boundary logits row (the full-cover shape's seed source). May be empty
7695 // when a suffix follows — the feed's own logits are the boundary then.
7696 boundary_logits: &[f32],
7697 // The request's sampler, or None for greedy. Owned here so the seed rule lives in
7698 // ONE place instead of being half-applied by the worker.
7699 sampling: Option<SpecSampling>,
7700 require_anchor: bool,
7701 max_ctx: usize,
7702 // STABLE-BOUNDARY REPUBLICATION (lane/frspec-multiturn-cache, 2026-08-21): ABSOLUTE
7703 // prompt position to split the suffix feed at and capture the extended-entry
7704 // publication + this session's `turn_ckpt` — the worker's stable pre-generation
7705 // boundary (`plain_checkpoint_boundary`). None = legacy prompt-end republication.
7706 // WHY: the prompt-end capture below includes the template's live generation header
7707 // (`<|im_start|>assistant\n<think>\n`), which the next turn's re-render replaces, so
7708 // for a hybrid (whole-entry restores only) every extended entry's last ~2 tokens
7709 // diverged from every future prompt and the hit boundary FROZE at the first
7710 // lcp-split entry forever (measured: cached 6811 of 38228 by turn 8, B4).
7711 republish_at: Option<usize>,
7712 ) -> Result<SpecSession, (Option<Cache>, String)> {
7713 let pos = prefix.len();
7714 let fail = |cache: Cache, msg: String| -> Result<SpecSession, (Option<Cache>, String)> {
7715 Err((Some(cache), msg))
7716 };
7717 if self.mtp.is_none() {
7718 return fail(cache, "no MTP head attached (nothing to draft with)".into());
7719 }
7720 if pos == 0 {
7721 return fail(cache, "empty committed prefix".into());
7722 }
7723 if cache.pos != pos {
7724 let msg = format!(
7725 "restored cache pos {} != restored prefix len {pos}",
7726 cache.pos
7727 );
7728 return fail(cache, msg);
7729 }
7730 if draft_len != pos {
7731 return fail(
7732 cache,
7733 format!("draft plane len {draft_len} != restored prefix len {pos}"),
7734 );
7735 }
7736 if pos + suffix.len() >= max_ctx {
7737 return fail(
7738 cache,
7739 format!(
7740 "prompt {} + suffix would not leave generation room in ctx {max_ctx}",
7741 pos + suffix.len(),
7742 ),
7743 );
7744 }
7745 let mut scratch = match MtpScratch::new(
7746 e,
7747 &self.cfg,
7748 max_ctx,
7749 self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
7750 ) {
7751 Ok(s) => s,
7752 Err(err) => return fail(cache, format!("draft scratch alloc failed: {err}")),
7753 };
7754 if scratch.kv.ring.is_some() {
7755 return fail(
7756 cache,
7757 "ring-backed draft scratch (Step35 SWA) cannot take a flat prefix restore".into(),
7758 );
7759 }
7760 if scratch.kv.k_tok_bytes != draft_k_tok_bytes
7761 || scratch.kv.v_tok_bytes != draft_v_tok_bytes
7762 {
7763 return fail(
7764 cache,
7765 format!(
7766 "draft plane layout {draft_k_tok_bytes}/{draft_v_tok_bytes} != scratch \
7767 {}/{} bytes/token (stale entry across a format change)",
7768 scratch.kv.k_tok_bytes, scratch.kv.v_tok_bytes,
7769 ),
7770 );
7771 }
7772 if pos > scratch.cap {
7773 return fail(
7774 cache,
7775 format!(
7776 "draft plane rows {pos} exceed scratch capacity {}",
7777 scratch.cap
7778 ),
7779 );
7780 }
7781 let kb = pos * draft_k_tok_bytes;
7782 let vb = pos * draft_v_tok_bytes;
7783 if draft_k.len() < kb || draft_v.len() < vb {
7784 return fail(
7785 cache,
7786 format!(
7787 "truncated draft plane: K {} < {kb} or V {} < {vb} bytes",
7788 draft_k.len(),
7789 draft_v.len(),
7790 ),
7791 );
7792 }
7793 if kb > 0 {
7794 if let Err(err) = e.copy_u8_into(&mut scratch.kv.k, 0, draft_k, kb) {
7795 return fail(cache, format!("draft K restore copy failed: {err}"));
7796 }
7797 }
7798 if vb > 0 {
7799 if let Err(err) = e.copy_u8_into(&mut scratch.kv.v, 0, draft_v, vb) {
7800 return fail(cache, format!("draft V restore copy failed: {err}"));
7801 }
7802 }
7803 if let Err(err) = scratch.set_len(e, pos) {
7804 return fail(cache, format!("draft scratch len set failed: {err}"));
7805 }
7806 let mut last_h_dev = if last_h.len() == self.cfg.n_embd as usize {
7807 // anchor upload failure is acceptance-only when a suffix feed follows (fill
7808 // row-0 falls back to zeros) but FATAL for an empty-suffix continuation (the
7809 // burst entry asserts committed + last_h + next_pred) — the caller says which.
7810 e.htod(last_h).ok()
7811 } else {
7812 None
7813 };
7814 if require_anchor && last_h_dev.is_none() {
7815 return fail(
7816 cache,
7817 "empty-suffix continuation requires the entry's boundary hidden anchor".into(),
7818 );
7819 }
7820 let mut committed = prefix;
7821 // Set on BOTH shapes below (suffix-fed and full-cover) — never left None, which is
7822 // what the empty-suffix continuation assert in the burst entry requires.
7823 let next_pred;
7824 // Philox: (0,0) at admit exactly like a fresh session; a sampled boundary draw below
7825 // consumes counter 0 and leaves 1, which is the state a cold session reaches after
7826 // drawing its own first token from the same row.
7827 let mut sctr = 0u32;
7828 let sampled = sampling.is_some_and(|s| s.temp > 0.0) && spec_sampled_boundary_on();
7829 // Penalty window for the boundary draw: the last `penalty_last_n` tokens of the WHOLE
7830 // prompt, which is what the cold session's own burst sees (Item 2's window). Built
7831 // after the suffix joins `committed` below.
7832 let mut boundary_captures: Vec<SpecBoundaryCapture> = Vec::new();
7833 let mut restored_turn_ckpt: Option<SpecCheckpoint> = None;
7834 if !suffix.is_empty() {
7835 // ---- SUFFIX FEED, mirroring prefill_tick's program selection exactly ----
7836 // From here on the trunk cache mutates: failures return Err((None, _)) and
7837 // the worker serves the request cold-plain instead of reusing the carrier.
7838 let dirty =
7839 |msg: String| -> Result<SpecSession, (Option<Cache>, String)> { Err((None, msg)) };
7840 let n_embd = self.cfg.n_embd as usize;
7841 let t = suffix.len();
7842 let mut h_rows = match e.uninit(t * n_embd) {
7843 Ok(b) => b,
7844 Err(err) => return fail(cache, format!("suffix hidden buffer alloc: {err}")),
7845 };
7846 // STABLE-BOUNDARY split (see `republish_at`): feed stops at the boundary so the
7847 // in-place GDN conv/ssm state can be snapshotted there — the only moment it
7848 // exists (the cold prime-split law). suffix-relative; None = one-segment legacy.
7849 let b_rel = republish_at
7850 .and_then(|abs| abs.checked_sub(pos))
7851 .filter(|&r| r > 0 && r < t);
7852 let mut feed_logits = Vec::new();
7853 let tokenwise_env = std::env::var("MEMRA_PRIME_TOKENWISE").is_ok()
7854 || e.frozen_cpu_experts_prefer_tokenwise_prime();
7855 let mut fed = 0usize;
7856 for seg_end in [b_rel, Some(t)].into_iter().flatten() {
7857 if seg_end <= fed {
7858 continue;
7859 }
7860 let seg = &suffix[fed..seg_end];
7861 let batched = seg.len() >= crate::hybrid_forward::PRIME_MIN_T && !tokenwise_env;
7862 if batched {
7863 // prefill_tick's prime arm: request-level prime_cache call; tokens still
7864 // queued after this segment ride `queued_after` so Step35 arm selection
7865 // stays keyed to the request's end (tick-seg law).
7866 match self.prime_cache(e, seg, &mut cache, t - seg_end) {
7867 Ok((l, _h_seed, hiddens)) => {
7868 if let Err(err) =
7869 e.copy_into(&mut h_rows, fed * n_embd, &hiddens, seg.len() * n_embd)
7870 {
7871 return dirty(format!("suffix hidden copy: {err}"));
7872 }
7873 feed_logits = l;
7874 }
7875 Err(err) => return dirty(format!("suffix prime failed: {err}")),
7876 }
7877 } else {
7878 // prefill_tick's tokenwise arm: eager decode_step, one token at a time.
7879 for (i, &tok) in seg.iter().enumerate() {
7880 match self.decode_step_h(e, tok, &mut cache) {
7881 Ok((l, h)) => {
7882 if let Err(err) =
7883 e.copy_into(&mut h_rows, (fed + i) * n_embd, &h, n_embd)
7884 {
7885 return dirty(format!("suffix hidden copy: {err}"));
7886 }
7887 feed_logits = l;
7888 }
7889 Err(err) => return dirty(format!("suffix decode_step failed: {err}")),
7890 }
7891 }
7892 }
7893 fed = seg_end;
7894 if Some(seg_end) == b_rel {
7895 // The stable pre-generation boundary: capture the extended-entry
7896 // publication AND this session's own turn checkpoint here instead of at
7897 // prompt-end (both would otherwise carry the volatile live-header tail
7898 // the next re-render replaces). Failure silent, turn_ckpt convention.
7899 debug_assert_eq!(
7900 cache.pos,
7901 pos + seg_end,
7902 "stable-boundary capture off the feed split"
7903 );
7904 if spec_restore_republish_on() {
7905 if let Ok(snap) = cache.snapshot(e) {
7906 boundary_captures.push(SpecBoundaryCapture {
7907 snap,
7908 pos: pos + seg_end,
7909 logits: feed_logits.clone(),
7910 last_h: capture_boundary_hidden(e, &h_rows, seg_end, n_embd),
7911 });
7912 }
7913 }
7914 let anchor: Result<CudaSlice<f32>, Box<dyn std::error::Error>> =
7915 e.uninit(n_embd).and_then(|mut a| {
7916 e.copy_view_into(
7917 &mut a,
7918 0,
7919 &h_rows.slice((seg_end - 1) * n_embd..seg_end * n_embd),
7920 n_embd,
7921 )?;
7922 Ok(a)
7923 });
7924 if let (Ok(snap), Ok(last_h)) = (cache.snapshot(e), anchor) {
7925 restored_turn_ckpt = Some(SpecCheckpoint {
7926 snap,
7927 pos: pos + seg_end,
7928 last_h,
7929 });
7930 }
7931 }
7932 }
7933 // Draft-scratch fill for the suffix rows, predecessor-paired: row `pos` reads
7934 // the entry's boundary anchor (zeros fallback — acceptance-only), row `pos+i`
7935 // reads h_rows[i-1]. Chunked like the generate path's fill (transients scale
7936 // with T). Fill failures are acceptance-only — truncate to the restored rows
7937 // and continue; the burst's own set_len keeps the invariant.
7938 let mtp = self.mtp.as_ref().expect("mtp checked above");
7939 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
7940 let embd_gpu = if spec_host_embd() {
7941 None
7942 } else {
7943 Some(
7944 self.embd_gpu
7945 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
7946 )
7947 };
7948 let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
7949 let fill_chunk = 4096usize;
7950 let mut filled = true;
7951 let mut start = 0usize;
7952 'fill: while start < t {
7953 let end = (start + fill_chunk).min(t);
7954 let tc = end - start;
7955 let Ok(mut phs) = e.zeros(tc * n_embd) else {
7956 filled = false;
7957 break 'fill;
7958 };
7959 let (src_lo, dst_off, n_copy) = if start == 0 {
7960 (0, n_embd, (tc - 1) * n_embd)
7961 } else {
7962 ((start - 1) * n_embd, 0, tc * n_embd)
7963 };
7964 if start == 0 {
7965 if let Some(lh) = last_h_dev.as_ref() {
7966 if e.copy_into(&mut phs, 0, lh, n_embd).is_err() {
7967 filled = false;
7968 break 'fill;
7969 }
7970 }
7971 }
7972 if n_copy > 0
7973 && e.copy_view_into(
7974 &mut phs,
7975 dst_off,
7976 &h_rows.slice(src_lo..src_lo + n_copy),
7977 n_copy,
7978 )
7979 .is_err()
7980 {
7981 filled = false;
7982 break 'fill;
7983 }
7984 if self
7985 .mtp_kv_fill(
7986 e,
7987 mtp,
7988 &suffix[start..end],
7989 &phs,
7990 pos + start,
7991 &mut scratch,
7992 embd_dev,
7993 )
7994 .is_err()
7995 {
7996 filled = false;
7997 break 'fill;
7998 }
7999 start = end;
8000 }
8001 if !filled {
8002 // acceptance-only: drafts over missing suffix rows are cheap and wrong,
8003 // so keep only the restored rows resident and let verify arbitrate.
8004 if let Err(err) = scratch.set_len(e, pos) {
8005 return dirty(format!("scratch truncation after failed fill: {err}"));
8006 }
8007 }
8008 // EXTENDED-ENTRY PUBLICATION (lane/sampled-spec-quality, Item 3 — the fix for
8009 // "a restored spec session never publishes an extended entry", SAMPLED-HIT.md
8010 // finding (d)). Pre-lane, publication was armed only for COLD sessions
8011 // (`spec_resumed == 0` in the worker) and both engine capture sites require a
8012 // non-continuation burst — but a converted hit's first burst IS a continuation,
8013 // so a growing conversation learned exactly ONE boundary and turn 3 could never
8014 // hit a longer prefix than turn 2 did.
8015 //
8016 // WHERE, and why it is safe here: `cache.pos == prefix + suffix` at this exact
8017 // line — the trunk is primed over the whole prompt, nothing is generated, and the
8018 // draft plane rows [0..prompt) are filled just above. That is a complete
8019 // whole-entry boundary (`pos == fed_len`), the same shape the cold seed capture
8020 // publishes; the worker's existing publication sweep picks it up because it is
8021 // keyed on non-empty `boundary_captures` and is sampler- and resume-independent.
8022 // NOT the partial-restore hazard: the boundary is this session's own prompt END,
8023 // never mid-entry, so `entry_pos != fed_len` still refuses on the way back in.
8024 // Failure is SILENT by design (the turn_ckpt / boundary-capture convention):
8025 // publication is an optimization, never a correctness dependency.
8026 //
8027 // SUPERSEDED WHEN `republish_at` FIRED (lane/frspec-multiturn-cache): a prompt-end
8028 // entry's tail is the live generation header the next re-render replaces, so on a
8029 // hybrid (whole-entry restores) it can never serve the conversation's next turn —
8030 // the stable-boundary capture above IS this publication, minus the poisoned tail.
8031 if spec_restore_republish_on() && boundary_captures.is_empty() {
8032 debug_assert_eq!(
8033 cache.pos,
8034 pos + t,
8035 "extended-entry capture must sit at the restored session's prompt end",
8036 );
8037 if let Ok(snap) = cache.snapshot(e) {
8038 boundary_captures.push(SpecBoundaryCapture {
8039 snap,
8040 pos: pos + t,
8041 logits: feed_logits.clone(),
8042 last_h: capture_boundary_hidden(e, &h_rows, t, n_embd),
8043 });
8044 }
8045 }
8046 // continuation seed: the feed's boundary logits ARE the plain path's boundary
8047 // logits (same program), so greedy's argmax here is plain's first emitted token,
8048 // and the sampled draw is the cold sampled session's own first token.
8049 next_pred = Some(if sampled {
8050 let sp = sampling.expect("sampled implies a sampler");
8051 // `committed` is still the restored prefix here; the suffix joins it below —
8052 // so this is the last-N window over the WHOLE prompt, exactly the cold
8053 // session's own window at its first token.
8054 let hist = pen_window_seed(&committed, suffix, sp.penalty_last_n);
8055 match sample_boundary_token(
8056 e,
8057 &feed_logits,
8058 &sp,
8059 &hist,
8060 &mut sctr,
8061 "restore-suffix-feed",
8062 ) {
8063 Ok(t) => t,
8064 // the trunk is already fed: hand nothing back, the worker serves the
8065 // request cold-plain. Never fall back to an argmax — that would put a
8066 // greedy token in a sampled stream to save a slow path.
8067 Err(err) => {
8068 return dirty(format!("boundary token draw failed: {err}"));
8069 }
8070 }
8071 } else {
8072 argmax(&feed_logits) as u32
8073 });
8074 let mut lh = match e.uninit(n_embd) {
8075 Ok(b) => b,
8076 Err(err) => return dirty(format!("boundary hidden alloc: {err}")),
8077 };
8078 if let Err(err) = e.copy_view_into(
8079 &mut lh,
8080 0,
8081 &h_rows.slice((t - 1) * n_embd..t * n_embd),
8082 n_embd,
8083 ) {
8084 return dirty(format!("boundary hidden copy: {err}"));
8085 }
8086 last_h_dev = Some(lh);
8087 committed.extend_from_slice(suffix);
8088 } else {
8089 // FULL-COVER shape (empty suffix — the identical-repeat / agent-loop shape): the
8090 // ENTRY's boundary logits are the boundary row, and this is the token the cold
8091 // session emits from that same row. Owned here rather than in the worker so the
8092 // sampled draw cannot be half-applied on one shape (the worker used to argmax it).
8093 if boundary_logits.is_empty() {
8094 return fail(
8095 cache,
8096 "full-cover restore without the entry's boundary logits".into(),
8097 );
8098 }
8099 next_pred = Some(if sampled {
8100 let sp = sampling.expect("sampled implies a sampler");
8101 let hist = pen_window_seed(&committed, &[], sp.penalty_last_n);
8102 match sample_boundary_token(
8103 e,
8104 boundary_logits,
8105 &sp,
8106 &hist,
8107 &mut sctr,
8108 "restore-full-cover",
8109 ) {
8110 Ok(t) => t,
8111 // nothing has been mutated on this shape — hand the carrier back and let
8112 // the hit serve PLAIN (the banked pre-lane path).
8113 Err(err) => {
8114 return fail(cache, format!("boundary token draw failed: {err}"));
8115 }
8116 }
8117 } else {
8118 argmax(boundary_logits) as u32
8119 });
8120 }
8121 Ok(SpecSession {
8122 cache,
8123 scratch,
8124 committed,
8125 last_h: last_h_dev,
8126 next_pred,
8127 sctr,
8128 uctr: 0,
8129 draft_ctx: None,
8130 pending_tok: None,
8131 // Stable-boundary capture from the split feed above (None on the legacy shape):
8132 // a restored session previously parked WITHOUT a checkpoint, so the next turn's
8133 // affinity probe declined ("no turn checkpoint retained") and the conversation
8134 // fell back to the frozen prefix entry forever.
8135 turn_ckpt: restored_turn_ckpt,
8136 telem: SpecTelemetryCounters::default(),
8137 capture_at: None,
8138 boundary_captures,
8139 ckpt_at: None,
8140 })
8141 }
8142
8143 /// Forced-gate exact state comparison. This intentionally reads the real live prefixes from
8144 /// their owning PP devices: matching emitted ids alone would miss a stale `len_d`, recurrent
8145 /// snapshot, or draft-KV row that only corrupts the following round.
8146 pub fn optipipe_compare_session_state(
8147 &self,
8148 e: &Engine,
8149 reference: &SpecSession,
8150 candidate: &SpecSession,
8151 ) -> Result<OptiForkStateIdentity, Box<dyn std::error::Error>> {
8152 fn fail(what: &str) -> Box<dyn std::error::Error> {
8153 format!("optipipe state mismatch: {what}").into()
8154 }
8155 fn same_f32(a: &[f32], b: &[f32]) -> bool {
8156 a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.to_bits() == y.to_bits())
8157 }
8158 fn compare_layers(
8159 es: &Engine,
8160 range: std::ops::Range<usize>,
8161 reference: &SpecSession,
8162 candidate: &SpecSession,
8163 report: &mut OptiForkStateIdentity,
8164 ) -> Result<(), Box<dyn std::error::Error>> {
8165 for il in range {
8166 match (&reference.cache.kv[il], &candidate.cache.kv[il]) {
8167 (Some(a), Some(b)) => {
8168 if a.len != b.len {
8169 return Err(fail(&format!(
8170 "layer {il} host KV len {} != {}",
8171 a.len, b.len
8172 )));
8173 }
8174 let ad = es.dtoh_i32(&a.len_d)?;
8175 let bd = es.dtoh_i32(&b.len_d)?;
8176 if ad != bd || ad.first().copied() != Some(a.len as i32) {
8177 return Err(fail(&format!(
8178 "layer {il} device KV len {ad:?} != {bd:?} (host={})",
8179 a.len,
8180 )));
8181 }
8182 let kb = a.len * a.k_tok_bytes;
8183 let vb = a.len * a.v_tok_bytes;
8184 if kb > 0 {
8185 let ak = es.dtoh_u8_view(&a.k.slice(0..kb))?;
8186 let bk = es.dtoh_u8_view(&b.k.slice(0..kb))?;
8187 if ak != bk {
8188 let at = ak.iter().zip(&bk).position(|(x, y)| x != y).unwrap();
8189 return Err(fail(&format!(
8190 "layer {il} K bytes at byte {at} row {} offset {}: {} != {}",
8191 at / a.k_tok_bytes,
8192 at % a.k_tok_bytes,
8193 ak[at],
8194 bk[at],
8195 )));
8196 }
8197 }
8198 if vb > 0 {
8199 let av = es.dtoh_u8_view(&a.v.slice(0..vb))?;
8200 let bv = es.dtoh_u8_view(&b.v.slice(0..vb))?;
8201 if av != bv {
8202 let at = av.iter().zip(&bv).position(|(x, y)| x != y).unwrap();
8203 return Err(fail(&format!(
8204 "layer {il} V bytes at byte {at} row {} offset {}: {} != {}",
8205 at / a.v_tok_bytes,
8206 at % a.v_tok_bytes,
8207 av[at],
8208 bv[at],
8209 )));
8210 }
8211 }
8212 report.trunk_kv_bytes += kb + vb;
8213 }
8214 (None, None) => {}
8215 _ => return Err(fail(&format!("layer {il} KV presence"))),
8216 }
8217 match (&reference.cache.recur[il], &candidate.cache.recur[il]) {
8218 (Some(a), Some(b)) => {
8219 let ac = es.dtoh(&a.conv_state)?;
8220 let bc = es.dtoh(&b.conv_state)?;
8221 if !same_f32(&ac, &bc) {
8222 return Err(fail(&format!("layer {il} conv state")));
8223 }
8224 let as_ = es.dtoh(&a.ssm_state)?;
8225 let bs = es.dtoh(&b.ssm_state)?;
8226 if !same_f32(&as_, &bs) {
8227 return Err(fail(&format!("layer {il} SSM state")));
8228 }
8229 report.recurrent_bytes += (ac.len() + as_.len()) * 4;
8230 }
8231 (None, None) => {}
8232 _ => return Err(fail(&format!("layer {il} recurrent presence"))),
8233 }
8234 }
8235 Ok(())
8236 }
8237
8238 if reference.committed != candidate.committed {
8239 return Err(fail("committed token ids"));
8240 }
8241 if reference.cache.pos != candidate.cache.pos
8242 || reference.cache.max_ctx != candidate.cache.max_ctx
8243 {
8244 return Err(fail("cache pos/capacity"));
8245 }
8246 if reference.pending_tok != candidate.pending_tok
8247 || reference.next_pred != candidate.next_pred
8248 || reference.sctr != candidate.sctr
8249 || reference.uctr != candidate.uctr
8250 {
8251 return Err(fail("pending/prediction/counter tail"));
8252 }
8253
8254 let mut report = OptiForkStateIdentity::default();
8255 if let Some(fence) = crate::pp::pp_cuts(self.layers.len()) {
8256 let rt = crate::pp::PpNRt::get(e)?;
8257 for stage in 0..rt.n_stages() {
8258 let _scope = rt.enter(stage);
8259 compare_layers(
8260 rt.engine(stage, e),
8261 fence[stage]..fence[stage + 1],
8262 reference,
8263 candidate,
8264 &mut report,
8265 )?;
8266 }
8267 } else {
8268 compare_layers(e, 0..self.layers.len(), reference, candidate, &mut report)?;
8269 }
8270
8271 let (a, b) = (&reference.scratch.kv, &candidate.scratch.kv);
8272 if a.len != b.len || e.dtoh_i32(&a.len_d)? != e.dtoh_i32(&b.len_d)? {
8273 return Err(fail("draft scratch length"));
8274 }
8275 let kb = a.len * a.k_tok_bytes;
8276 let vb = a.len * a.v_tok_bytes;
8277 if kb > 0 && e.dtoh_u8_view(&a.k.slice(0..kb))? != e.dtoh_u8_view(&b.k.slice(0..kb))? {
8278 return Err(fail("draft scratch K bytes"));
8279 }
8280 if vb > 0 && e.dtoh_u8_view(&a.v.slice(0..vb))? != e.dtoh_u8_view(&b.v.slice(0..vb))? {
8281 return Err(fail("draft scratch V bytes"));
8282 }
8283 report.scratch_kv_bytes = kb + vb;
8284
8285 match (&reference.last_h, &candidate.last_h) {
8286 (Some(a), Some(b)) => {
8287 let ah = e.dtoh(a)?;
8288 let bh = e.dtoh(b)?;
8289 if !same_f32(&ah, &bh) {
8290 return Err(fail("last hidden/seed bytes"));
8291 }
8292 report.hidden_bytes = ah.len() * 4;
8293 }
8294 (None, None) => {}
8295 _ => return Err(fail("last hidden/seed presence")),
8296 }
8297 Ok(report)
8298 }
8299
8300 /// SESSION-AFFINITY REWIND (lane/session-affinity, 2026-08-05): roll `sess` back to its
8301 /// retained prompt-end checkpoint, so a request whose prompt matches
8302 /// `committed[..rewind_pos()]` exactly can resume there and prime only its own delta.
8303 ///
8304 /// EXACTNESS. After this returns, the session is byte-for-byte the state it was in AT that
8305 /// boundary: full-attn KV truncated to it (append-only, position-addressed), GDN conv/ssm
8306 /// restored from the device copy taken there, draft scratch length reset, `committed`
8307 /// truncated, `last_h` = the boundary's predecessor anchor. That is precisely the state a
8308 /// fresh prime of `committed[..pos]` would have produced, so the following suffix prime and
8309 /// every burst after it are identical to a cold run of the same token stream — the
8310 /// committed-tokens-authoritative contract.
8311 ///
8312 /// `next_pred` and `pending_tok` are CLEARED: both describe generation past the boundary,
8313 /// which the rewind discards. The caller therefore must supply a non-empty suffix (a
8314 /// rewound session cannot serve an empty-suffix continuation burst — there is nothing to
8315 /// continue). The persistent draft graph survives: it bakes only session-stable pointers
8316 /// (the scratch KV, the resident embedding), none of which the rewind moves.
8317 ///
8318 /// The checkpoint is CONSUMED (`turn_ckpt` taken): its snapshot buffers are freed here, and
8319 /// this turn's own prime installs a fresh one at the new prompt end. Returns the position
8320 /// rewound to, or `None` when the session holds no checkpoint (caller: full re-prime).
8321 pub fn spec_rewind_to_checkpoint(
8322 &self,
8323 e: &Engine,
8324 sess: &mut SpecSession,
8325 ) -> Result<Option<usize>, Box<dyn std::error::Error>> {
8326 if sess.turn_ckpt.as_ref().is_some_and(|ckpt| {
8327 !sess.cache.can_rollback(&ckpt.snap, 0) || !sess.scratch.can_rewind_to(ckpt.pos)
8328 }) {
8329 return Err(
8330 "SWA ring rewind checkpoint has been lapped; full re-prime required".into(),
8331 );
8332 }
8333 let Some(ckpt) = sess.turn_ckpt.take() else {
8334 return Ok(None);
8335 };
8336 assert!(
8337 ckpt.pos <= sess.committed.len(),
8338 "checkpoint past committed ({} > {})",
8339 ckpt.pos,
8340 sess.committed.len()
8341 );
8342 // Restore through each layer's owning engine. A single primary-engine rollback is not
8343 // sufficient when the serving cache is stage-owned under cross-device PP.
8344 crate::pp::restore_cache_checkpoint(e, &self.cfg, None, &mut sess.cache, &ckpt.snap)?;
8345 debug_assert_eq!(
8346 sess.cache.pos, ckpt.pos,
8347 "rollback landed off the checkpoint"
8348 );
8349 sess.scratch.set_len(e, ckpt.pos)?;
8350 sess.committed.truncate(ckpt.pos);
8351 sess.last_h = Some(ckpt.last_h);
8352 sess.next_pred = None;
8353 sess.pending_tok = None;
8354 Ok(Some(ckpt.pos))
8355 }
8356
8357 /// Grow a parked speculative session to `target_cap` and rewind it to its retained turn
8358 /// checkpoint without re-priming the checkpoint prefix.
8359 ///
8360 /// The trunk cache is restored exactly like a plain grown cache: append-only full-attention
8361 /// KV rows come from the parked cache, while recurrent state comes from the checkpoint's
8362 /// owned snapshot. The MTP scratch is also context-linear and its rows below the checkpoint
8363 /// remain authoritative, so they are copied into a fresh larger scratch before its length is
8364 /// truncated. Pointer-baking draft graphs are dropped and recaptured on the next burst.
8365 ///
8366 /// All fallible work completes before `sess` is mutated. A failed allocation or copy leaves
8367 /// the parked session intact, allowing the caller one reclaim-and-retry attempt.
8368 pub fn spec_grow_and_rewind_to_checkpoint(
8369 &self,
8370 e: &Engine,
8371 sess: &mut SpecSession,
8372 target_cap: usize,
8373 ) -> Result<Option<usize>, Box<dyn std::error::Error>> {
8374 if target_cap <= sess.cache.max_ctx {
8375 return self.spec_rewind_to_checkpoint(e, sess);
8376 }
8377 let Some(ckpt) = sess.turn_ckpt.as_ref() else {
8378 return Ok(None);
8379 };
8380 if ckpt.pos == 0 || ckpt.pos > sess.committed.len() {
8381 return Err(format!(
8382 "checkpoint pos {} outside committed length {}",
8383 ckpt.pos,
8384 sess.committed.len(),
8385 )
8386 .into());
8387 }
8388 if ckpt.pos > target_cap {
8389 return Err(format!(
8390 "checkpoint pos {} exceeds grown capacity {target_cap}",
8391 ckpt.pos,
8392 )
8393 .into());
8394 }
8395
8396 let mut grown_cache = crate::pp::new_cache(e, &self.cfg, target_cap)?;
8397 let mut grown_scratch = MtpScratch::new(
8398 e,
8399 &self.cfg,
8400 target_cap,
8401 self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
8402 )?;
8403 crate::pp::restore_cache_checkpoint(
8404 e,
8405 &self.cfg,
8406 Some(&sess.cache),
8407 &mut grown_cache,
8408 &ckpt.snap,
8409 )?;
8410
8411 let src = &sess.scratch.kv;
8412 let dst = &mut grown_scratch.kv;
8413 if ckpt.pos > src.len
8414 || src.kv_dim_k != dst.kv_dim_k
8415 || src.kv_dim_v != dst.kv_dim_v
8416 || src.k_tok_bytes != dst.k_tok_bytes
8417 || src.v_tok_bytes != dst.v_tok_bytes
8418 {
8419 return Err(format!(
8420 "checkpoint draft layout mismatch (pos {}, source len {})",
8421 ckpt.pos, src.len,
8422 )
8423 .into());
8424 }
8425 let kb = ckpt.pos * src.k_tok_bytes;
8426 let vb = ckpt.pos * src.v_tok_bytes;
8427 if kb > 0 {
8428 e.copy_u8_into(&mut dst.k, 0, &src.k, kb)?;
8429 }
8430 if vb > 0 {
8431 e.copy_u8_into(&mut dst.v, 0, &src.v, vb)?;
8432 }
8433 grown_scratch.set_len(e, ckpt.pos)?;
8434 // The old scratch is dropped immediately after publication below. Bound its D2D reads
8435 // first; growth happens once per rewritten turn, outside the decode hot loop.
8436 e.stream().synchronize()?;
8437
8438 let ckpt = sess
8439 .turn_ckpt
8440 .take()
8441 .expect("checkpoint remained present through transactional grow");
8442 let pos = ckpt.pos;
8443 sess.cache = grown_cache;
8444 sess.scratch = grown_scratch;
8445 sess.committed.truncate(pos);
8446 sess.last_h = Some(ckpt.last_h);
8447 sess.next_pred = None;
8448 sess.pending_tok = None;
8449 sess.draft_ctx = None;
8450 debug_assert_eq!(sess.cache.pos, pos, "grown rewind landed off checkpoint");
8451 debug_assert_eq!(
8452 sess.scratch.kv.len, pos,
8453 "grown draft rewind landed off checkpoint"
8454 );
8455 Ok(Some(pos))
8456 }
8457
8458 /// Commit a carried pending bonus (see SpecSession::pending_tok): one T=1 trunk pass
8459 /// (its logits' argmax becomes next_pred) + the draft-KV fill at the carried anchor —
8460 /// byte-identical to the pre-carry session tail. Required before a non-empty-suffix
8461 /// prime, a sampled turn, or parking a session for pool reuse. No-op without a pending.
8462 /// `sampling` is the sampler of the request that will CONSUME the resulting `next_pred`
8463 /// (lane/sampled-spec-quality): this is a boundary site like any other, so a sampled
8464 /// consumer must get a DRAWN token, not an argmax. Pass `None` from the park/demote
8465 /// callers — a pending only ever exists on the GREEDY tail, and the consumer of a
8466 /// park-time flush is a future request whose sampler is not knowable here (residual
8467 /// named at the pool-resume probe in worker.rs and in SAMPLED-QUALITY.md).
8468 pub fn spec_flush_pending(
8469 &self,
8470 e: &Engine,
8471 sess: &mut SpecSession,
8472 sampling: Option<SpecSampling>,
8473 ) -> Result<(), Box<dyn std::error::Error>> {
8474 let Some(b) = sess.pending_tok.take() else {
8475 return Ok(());
8476 };
8477 let mtp = self
8478 .mtp
8479 .as_ref()
8480 .expect("pending carry requires an MTP head");
8481 let n_embd = self.cfg.n_embd as usize;
8482 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
8483 let embd_gpu = if spec_host_embd() {
8484 None
8485 } else {
8486 Some(
8487 self.embd_gpu
8488 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
8489 )
8490 };
8491 let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
8492 let pos_b = sess.cache.pos;
8493 sess.scratch.set_len(e, pos_b)?;
8494 let (lg_b, hb) = self.spec_target_step_h(e, b, &mut sess.cache)?;
8495 sess.next_pred = Some(match sampling {
8496 Some(sp) if sp.temp > 0.0 && spec_sampled_boundary_on() => {
8497 // window includes `b` itself: it is committed by this pass, and the pre-lane
8498 // code never counted a boundary token in the penalty history at all.
8499 let hist = pen_window_seed(&sess.committed, &[b], sp.penalty_last_n);
8500 sample_boundary_token(e, &lg_b, &sp, &hist, &mut sess.sctr, "flush-pending")?
8501 }
8502 _ => argmax(&lg_b) as u32,
8503 });
8504 let anchor = sess
8505 .last_h
8506 .as_ref()
8507 .expect("pending carry requires last_h (the predecessor-row anchor)");
8508 self.mtp_kv_fill(e, mtp, &[b], anchor, pos_b, &mut sess.scratch, embd_dev)?;
8509 sess.last_h = Some(hb);
8510 sess.committed.push(b);
8511 Ok(())
8512 }
8513
8514 /// Solo target feed used only at speculative round boundaries. Step35 serving made its
8515 /// staged batched B=1 graph authoritative, so a speculative session must enter and leave
8516 /// rounds through that same graph. Other model families keep their eager T=1 contract.
8517 fn spec_target_step_h(
8518 &self,
8519 e: &Engine,
8520 token: u32,
8521 cache: &mut Cache,
8522 ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
8523 if self.cfg.step35.is_none() && !self.qwen35_serving_class() {
8524 return self.decode_step_h(e, token, cache);
8525 }
8526 let pos0 = cache.pos;
8527 let (logits, hidden) = self.decode_step_t_core(e, &[token], pos0, cache, None, None)?;
8528 Ok((e.dtoh(&logits)?, hidden))
8529 }
8530
8531 /// The archs whose LIVE B=1 serving runs the generic BATCHED numeric class (decode_step_batch
8532 /// walk + batched head), so their spec verify must run the SAME class. MoE learned this
8533 /// 2026-08-14 AM (4b777ccc5); the dense hybrid reproduced the identical near-tie flip class
8534 /// the same day on Qwen3.8-27B — eager-class verify logits drift from batched-class serving
8535 /// logits ("1 ULP at layer 2 → 2.3e-1 logit maxdiff at the head"), and the GDN recurrence
8536 /// carries the drift until a near-tie flips deep in generation. One predicate so the five
8537 /// dispatch sites cannot drift apart again.
8538 /// Draft-graph head admissibility (lane/draftcost-moe, 2026-08-20): the capture body
8539 /// (`mtp_head_forward_cap`) supports Dense heads AND resident-MoE heads
8540 /// (`Ffn::Moe(m) if m.dev_exps.is_some()`); non-resident MoE still refuses inside the
8541 /// capture and the caller falls back to the eager chain by design. Trunk FFN class is
8542 /// irrelevant — the graph body is the HEAD forward only. One predicate for all three
8543 /// eligibility sites so they cannot drift (the qwen35_serving_class lesson).
8544 fn mtp_graph_capturable(&self) -> bool {
8545 self.mtp
8546 .as_ref()
8547 .map(|m| match &m.ffn {
8548 crate::hybrid::Ffn::Dense { .. } => true,
8549 crate::hybrid::Ffn::Moe(mo) => mo.dev_exps.is_some(),
8550 })
8551 .unwrap_or(false)
8552 }
8553
8554 fn qwen35_serving_class(&self) -> bool {
8555 matches!(
8556 self.cfg.arch,
8557 memra_gguf::config::Arch::Qwen35 | memra_gguf::config::Arch::Qwen35Moe
8558 )
8559 }
8560
8561 /// Reduced-matrix admission for increment 1. This deliberately does not change the PP-2
8562 /// serving policy: the worker calls it only after `MEMRA_SPEC_PIPE=1` and an explicit spec
8563 /// session already exist.
8564 pub fn spec_pipe_available(&self, e: &Engine) -> bool {
8565 if std::env::var("MEMRA_SPEC_PIPE").as_deref() != Ok("1")
8566 || !spec_devacc()
8567 || spec_replay_env_enabled()
8568 || spec_stream()
8569 || std::env::var("MEMRA_SPEC_ADAPT").as_deref() == Ok("1")
8570 || std::env::var("MEMRA_SPEC_PMIN0").as_deref() == Ok("1")
8571 || std::env::var("MEMRA_SPEC_PP_ANATOMY").as_deref() == Ok("1")
8572 || std::env::var("MEMRA_SPEC_PMIN")
8573 .ok()
8574 .and_then(|v| v.parse::<f32>().ok())
8575 .unwrap_or(0.0)
8576 > 0.0
8577 || self.is_gemma4_e4b()
8578 || self.cfg.gemma4.is_some()
8579 || self.mtp.is_none()
8580 {
8581 return false;
8582 }
8583 let Some(cuts) = crate::pp::pp_cuts(self.layers.len()) else {
8584 return false;
8585 };
8586 if cuts.len() != 3 || crate::pp::pp2_streams_off() || !crate::pp::spec_pp_on() {
8587 return false;
8588 }
8589 crate::pp::PpNRt::get(e)
8590 .map(|rt| rt.n_stages() == 2 && rt.cross_device())
8591 .unwrap_or(false)
8592 }
8593
8594 /// Two warm greedy continuation bursts over one PP-2 interval coordinator. The two existing
8595 /// `generate_spec_inner2` call stacks own all per-session round locals; only phase issue order
8596 /// changes. No callback is accepted in increment 1 — the worker publishes each completed burst.
8597 #[allow(clippy::too_many_arguments)]
8598 pub fn generate_spec_session_pair(
8599 &self,
8600 e: &Engine,
8601 sess_a: &mut SpecSession,
8602 max_new_a: usize,
8603 k_a: usize,
8604 sess_b: &mut SpecSession,
8605 max_new_b: usize,
8606 k_b: usize,
8607 ) -> Result<((Vec<u32>, usize, usize), (Vec<u32>, usize, usize)), Box<dyn std::error::Error>>
8608 {
8609 if !self.spec_pipe_available(e) {
8610 return Err("two-session speculative pipeline is outside its reduced matrix".into());
8611 }
8612 if max_new_a == 0 || max_new_b == 0 || k_a == 0 || k_b == 0 {
8613 return Err(
8614 "two-session speculative pipeline requires non-empty positive-K bursts".into(),
8615 );
8616 }
8617 for sess in [&*sess_a, &*sess_b] {
8618 if sess.committed.is_empty()
8619 || sess.last_h.is_none()
8620 || (sess.next_pred.is_none() && sess.pending_tok.is_none())
8621 {
8622 return Err("two-session speculative pipeline requires warm continuations".into());
8623 }
8624 }
8625
8626 let graph_ok = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
8627 && !spec_host_embd()
8628 && self.mtp_graph_capturable()
8629 && !crate::model::full_prec_enabled();
8630 let graph_a = graph_ok && k_a + 2 < 96;
8631 let graph_b = graph_ok && k_b + 2 < 96;
8632 let was_tracking = e.ctx().is_event_tracking();
8633 if (graph_a || graph_b) && was_tracking {
8634 unsafe {
8635 e.ctx().disable_event_tracking();
8636 }
8637 }
8638
8639 static LOGGED: std::sync::Once = std::sync::Once::new();
8640 LOGGED.call_once(|| {
8641 eprintln!("[spec-pipe] two-session PP-2 continuation pipeline engaged");
8642 });
8643 let sync = std::sync::Arc::new(SpecPipeSync::new());
8644 let lane_a = SpecPipeLane {
8645 sync: sync.clone(),
8646 lane: 0,
8647 };
8648 let lane_b = SpecPipeLane { sync, lane: 1 };
8649 let mut sess_b_ptr = SpecPipeSessionPtr(sess_b as *mut SpecSession);
8650 let (result_a, result_b) = std::thread::scope(|scope| {
8651 let b = scope.spawn(move || {
8652 let mut finish = SpecPipeFinish::new(&lane_b);
8653 let sess_b = unsafe { sess_b_ptr.get_mut() };
8654 let result = e
8655 .ctx()
8656 .bind_to_thread()
8657 .map_err(|err| err.to_string())
8658 .and_then(|_| {
8659 self.generate_spec_inner2(
8660 e,
8661 &[],
8662 max_new_b,
8663 k_b,
8664 graph_b,
8665 Some(sess_b),
8666 None,
8667 None,
8668 None,
8669 None,
8670 Some(&lane_b),
8671 )
8672 .map_err(|err| err.to_string())
8673 });
8674 finish.close(result.is_err());
8675 result
8676 });
8677 let mut finish = SpecPipeFinish::new(&lane_a);
8678 let result_a = self.generate_spec_inner2(
8679 e,
8680 &[],
8681 max_new_a,
8682 k_a,
8683 graph_a,
8684 Some(sess_a),
8685 None,
8686 None,
8687 None,
8688 None,
8689 Some(&lane_a),
8690 );
8691 finish.close(result_a.is_err());
8692 let result_b = b
8693 .join()
8694 .map_err(|_| "paired speculative session B panicked".to_string())
8695 .and_then(|r| r);
8696 (result_a, result_b)
8697 });
8698
8699 if (graph_a || graph_b) && was_tracking {
8700 unsafe {
8701 e.ctx().enable_event_tracking();
8702 }
8703 }
8704 let result_a = result_a?;
8705 let result_b = result_b.map_err(|err| -> Box<dyn std::error::Error> { err.into() })?;
8706 Ok((result_a, result_b))
8707 }
8708
8709 /// One spec-decode turn on a live session. `suffix` = the NEW tokens only (turn N+1's user
8710 /// message rendered through the chat template continuation). Returns (new tokens emitted,
8711 /// drafted, accepted); session.committed grows by suffix + emitted.
8712 pub fn generate_spec_session(
8713 &self,
8714 e: &Engine,
8715 sess: &mut SpecSession,
8716 suffix: &[u32],
8717 max_new: usize,
8718 k: usize,
8719 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
8720 self.generate_spec_session_sampled(e, sess, suffix, max_new, k, None, None)
8721 }
8722
8723 /// Serve-path sampled spec: routes the burst through the rejection-sampling verify with
8724 /// per-SESSION Philox continuity (sess.sctr/uctr). None = env-driven (CLI) or greedy.
8725 /// Filters (top-k/p/min-p) apply SYMMETRICALLY to draft q and verify p — distribution-exact
8726 /// for the filtered target (feat/filtered-spec).
8727 ///
8728 /// `on_commit` (sse-cadence, 2026-08-05): called with each newly-emitted slice of the
8729 /// output — once right after the prime's first token, then once per round commit — so a
8730 /// streaming caller can flush text at round cadence instead of once per burst. The slices
8731 /// are disjoint, in order, and concatenate to exactly the returned token vec. Emission-
8732 /// timing only: token bytes, session state, and exactness are untouched.
8733 ///
8734 /// The returned bool is a CONTINUE-VERDICT (admission yield, 2026-08-06): `false` ends
8735 /// the burst at the current round boundary, exactly as if `max_new` had been reached —
8736 /// the caller's scheduler regains control without waiting the burst out. Burst size is
8737 /// content-neutral (spec-levers battery), so an early exit moves WHEN the burst returns,
8738 /// never what tokens say. The slice may be EMPTY (a poll-only boundary — round-stream
8739 /// drains and the defensive tail flush can land with nothing new committed).
8740 #[allow(clippy::too_many_arguments)]
8741 pub fn generate_spec_session_sampled(
8742 &self,
8743 e: &Engine,
8744 sess: &mut SpecSession,
8745 suffix: &[u32],
8746 max_new: usize,
8747 k: usize,
8748 sampling: Option<SpecSampling>,
8749 on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
8750 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
8751 self.generate_spec_session_sampled_prime_split(
8752 e, sess, suffix, max_new, k, sampling, None, on_commit,
8753 )
8754 }
8755
8756 /// Serve-only cold-prime segmentation twin. `prime_split` is the same stable boundary the
8757 /// plain worker would honor before entering its sub-floor tokenwise tail; warm continuations
8758 /// pass `None` and stay on the existing zero-prime path.
8759 #[allow(clippy::too_many_arguments)]
8760 pub fn generate_spec_session_sampled_prime_split(
8761 &self,
8762 e: &Engine,
8763 sess: &mut SpecSession,
8764 suffix: &[u32],
8765 max_new: usize,
8766 k: usize,
8767 sampling: Option<SpecSampling>,
8768 prime_split: Option<usize>,
8769 on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
8770 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
8771 self.generate_spec_session_constrained_prime_split(
8772 e,
8773 sess,
8774 suffix,
8775 max_new,
8776 k,
8777 sampling,
8778 None,
8779 prime_split,
8780 on_commit,
8781 )
8782 }
8783
8784 /// `generate_spec_session_sampled` + GRAMMAR (constrained decoding, 2026-08-03): the
8785 /// hook truncates acceptance at the first grammar-illegal token AFTER the exactness
8786 /// verify (grammar is an extra rejection rule, ordering like the batched-verify twins)
8787 /// and replaces an illegal bonus with the MASKED argmax of the target's own verify
8788 /// column — token-identical to constrained plain greedy decode. GREEDY only (the
8789 /// worker routes sampled constrained to plain decode). Acceptance under tight grammars
8790 /// may drop (drafter is unconstrained); that is measured, not hidden.
8791 #[allow(clippy::too_many_arguments)]
8792 pub fn generate_spec_session_constrained(
8793 &self,
8794 e: &Engine,
8795 sess: &mut SpecSession,
8796 suffix: &[u32],
8797 max_new: usize,
8798 k: usize,
8799 sampling: Option<SpecSampling>,
8800 constraint: Option<&mut dyn SpecConstraint>,
8801 on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
8802 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
8803 self.generate_spec_session_constrained_prime_split(
8804 e, sess, suffix, max_new, k, sampling, constraint, None, on_commit,
8805 )
8806 }
8807
8808 #[allow(clippy::too_many_arguments)]
8809 pub fn generate_spec_session_constrained_prime_split(
8810 &self,
8811 e: &Engine,
8812 sess: &mut SpecSession,
8813 suffix: &[u32],
8814 max_new: usize,
8815 k: usize,
8816 sampling: Option<SpecSampling>,
8817 constraint: Option<&mut dyn SpecConstraint>,
8818 prime_split: Option<usize>,
8819 on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
8820 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
8821 if constraint.is_some() && sampling.is_some_and(|s| s.temp > 0.0) {
8822 return Err(
8823 "constrained spec decode is greedy-only (worker routes sampled \
8824 constrained to plain decode)"
8825 .into(),
8826 );
8827 }
8828 // PENDING-CARRY entry flush: a carried bonus precedes any new suffix in the sequence,
8829 // so it must commit BEFORE the suffix primes; the sampled path doesn't carry (its
8830 // round-0 accept needs the commit pass's logits). Empty-suffix greedy bursts — the
8831 // serve continuation case — consume the carry in-loop with zero solo passes.
8832 if sess.pending_tok.is_some()
8833 && (!suffix.is_empty() || sampling.map_or(false, |s| s.temp > 0.0))
8834 {
8835 self.spec_flush_pending(e, sess, sampling)?;
8836 }
8837
8838 // FULL_PREC forces the EAGER draft: the graph capture would enclose cuBLASLt f32 GEMV
8839 // (the FloatBf16 else-branches) and a bf16_to_f32 dequant alloc — neither is stream-capture
8840 // safe. Eager rides matmul/matmul_decode_exact, which dequant FloatBf16 on use. (§item 2.)
8841 let graph_draft = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
8842 && !spec_host_embd()
8843 && self.mtp_graph_capturable()
8844 && k + 2 < 96
8845 && !crate::model::full_prec_enabled();
8846 let was_tracking = e.ctx().is_event_tracking();
8847 if graph_draft && was_tracking {
8848 unsafe {
8849 e.ctx().disable_event_tracking();
8850 }
8851 }
8852 let r = self.generate_spec_inner2(
8853 e,
8854 suffix,
8855 max_new,
8856 k,
8857 graph_draft,
8858 Some(sess),
8859 sampling,
8860 constraint,
8861 on_commit,
8862 prime_split,
8863 None,
8864 );
8865 if graph_draft && was_tracking {
8866 unsafe {
8867 e.ctx().enable_event_tracking();
8868 }
8869 }
8870 let (out, d, a) = r?;
8871 Ok((out, d, a))
8872 }
8873
8874 pub fn generate_spec(
8875 &self,
8876 e: &Engine,
8877 prompt: &[u32],
8878 max_new: usize,
8879 k: usize,
8880 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
8881 // FULL_PREC forces eager (see generate_spec_session note): CUDA graph capture cannot
8882 // enclose cuBLASLt f32 GEMV or the bf16_to_f32 dequant alloc the FloatBf16 path needs.
8883 let graph_draft = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
8884 && !spec_host_embd()
8885 && self.mtp_graph_capturable()
8886 && k + 2 < 96
8887 && !crate::model::full_prec_enabled();
8888 if !graph_draft {
8889 return self.generate_spec_inner2(
8890 e, prompt, max_new, k, false, None, None, None, None, None, None,
8891 );
8892 }
8893 let was_tracking = e.ctx().is_event_tracking();
8894 if was_tracking {
8895 unsafe {
8896 e.ctx().disable_event_tracking();
8897 }
8898 }
8899 let r = self.generate_spec_inner2(
8900 e, prompt, max_new, k, true, None, None, None, None, None, None,
8901 );
8902 if was_tracking {
8903 unsafe {
8904 e.ctx().enable_event_tracking();
8905 }
8906 }
8907 r
8908 }
8909
8910 fn generate_spec_inner2(
8911 &self,
8912 e: &Engine,
8913 prompt: &[u32],
8914 max_new: usize,
8915 k: usize,
8916 graph_draft: bool,
8917 mut sess: Option<&mut SpecSession>,
8918 sampling: Option<SpecSampling>,
8919 mut constraint: Option<&mut dyn SpecConstraint>,
8920 mut on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
8921 prime_split: Option<usize>,
8922 pipe: Option<&SpecPipeLane>,
8923 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
8924 assert!(k >= 1, "k must be >= 1");
8925 if let Some(p) = pipe {
8926 p.setup_begin()?;
8927 }
8928 // sse-cadence flush cursor: everything in out[..flushed] has been handed to on_commit.
8929 let mut flushed = 0usize;
8930 // admission yield (2026-08-06): on_commit's continue-verdict; false = end the burst
8931 // at the next round boundary (same exit as max_new reached — the session tail runs).
8932 // Initialized by the unconditional post-prime flush below.
8933 let mut keep_going;
8934 let mtp = self
8935 .mtp
8936 .as_ref()
8937 .expect("generate_spec requires an MTP head (nextn_predict_layers>0)");
8938 let n_vocab = self.output.out_features();
8939 // FR-Spec: the draft head may be TRIMMED (fewer rows than n_vocab); the draft argmax runs
8940 // over the draft vocab and the winning index maps through d2t to a TARGET token id.
8941 // Everything downstream (verify/accept/commit) sees target ids only — exactness unchanged.
8942 let d_vocab = mtp
8943 .shared_head_head
8944 .as_ref()
8945 .unwrap_or(&self.output)
8946 .out_features();
8947 let n_embd = self.cfg.n_embd as usize;
8948 // SESSION MODE: reuse the live cache/scratch, prime only the suffix. `base` = tokens
8949 // already committed (their state is in the caches); 0 = fresh single-shot call.
8950 let session_mode = sess.is_some();
8951 let max_ctx = match sess.as_ref() {
8952 Some(s) => s.cache.max_ctx,
8953 None => prompt.len() + max_new + k + 8,
8954 };
8955 let mut own_cache;
8956 let mut own_scratch;
8957 // PREFIX-CACHE capture request threaded out of the session (lane/spec-prefix-cache):
8958 // (requested split, destination list). Single-shot per burst; fresh calls have none.
8959 let mut sess_capture: Option<(Option<usize>, &mut Vec<SpecBoundaryCapture>)> = None;
8960 // STABLE-BOUNDARY turn-checkpoint request (lane/frspec-multiturn-cache): ABSOLUTE
8961 // committed-length position; consumed one-shot like `capture_at`. None = legacy
8962 // prompt-end capture below.
8963 let mut ckpt_req: Option<usize> = None;
8964 let (
8965 cache,
8966 scratch,
8967 mut sess_tail,
8968 mut sess_draft_slot,
8969 mut sess_pending_slot,
8970 sess_ckpt_slot,
8971 sess_telem,
8972 ): (
8973 &mut Cache,
8974 &mut MtpScratch,
8975 Option<(
8976 &mut Vec<u32>,
8977 &mut Option<CudaSlice<f32>>,
8978 &mut Option<u32>,
8979 &mut u32,
8980 &mut u32,
8981 )>,
8982 Option<&mut Option<DraftGraphCtx>>,
8983 Option<&mut Option<u32>>,
8984 Option<&mut Option<SpecCheckpoint>>,
8985 Option<&SpecTelemetryCounters>,
8986 ) = match sess.take() {
8987 Some(sr) => {
8988 let SpecSession {
8989 cache,
8990 scratch,
8991 committed,
8992 last_h,
8993 next_pred,
8994 sctr: s_sctr,
8995 uctr: s_uctr,
8996 draft_ctx,
8997 pending_tok,
8998 turn_ckpt,
8999 telem,
9000 capture_at,
9001 boundary_captures,
9002 ckpt_at,
9003 } = sr;
9004 sess_capture = Some((capture_at.take(), boundary_captures));
9005 ckpt_req = ckpt_at.take();
9006 (
9007 cache,
9008 scratch,
9009 Some((committed, last_h, next_pred, s_sctr, s_uctr)),
9010 Some(draft_ctx),
9011 Some(pending_tok),
9012 Some(turn_ckpt),
9013 Some(telem),
9014 )
9015 }
9016 None => {
9017 // STAGE-OWNED KV (lane/pp2-spec 2026-08-06) — see `new_session`. Door shut =
9018 // `Cache::new` verbatim.
9019 own_cache = crate::pp::new_cache(e, &self.cfg, max_ctx)?;
9020 // Persistent scratch = max_ctx rows (~2KB/token quantized).
9021 own_scratch = MtpScratch::new(
9022 e,
9023 &self.cfg,
9024 max_ctx,
9025 self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
9026 )?;
9027 (
9028 &mut own_cache,
9029 &mut own_scratch,
9030 None,
9031 None,
9032 None,
9033 None,
9034 None,
9035 )
9036 }
9037 };
9038 let base = cache.pos;
9039 // PENDING-CARRY consume (2026-08-01): a carried bonus reaches here only on the
9040 // empty-suffix GREEDY continuation path (generate_spec_session_sampled flushed every
9041 // other case). It enters the round loop as round-0's pending — verify col 0 — exactly
9042 // like a mid-burst full-accept boundary: no init feed, no tail commit pass.
9043 let carried_pending: Option<u32> = sess_pending_slot.as_mut().and_then(|s| s.take());
9044 // PERSISTENT DRAFT KV (the only mode since 2026-07-08 — the legacy round-local scratch,
9045 // MEMRA_SPEC_KVLOCAL, measured -35 acceptance pts on the 27B p3 sweep and was removed;
9046 // acceptance-only — exactness is verify's job either way).
9047 // HIDDEN-PAIRING CONVENTION (DEFAULT = predecessor-row, 2026-07-04 — the 27B acceptance
9048 // unlock, +16pts): the MTP head is TRAINED on rows pairing token x_p with the trunk
9049 // hidden of its PREDECESSOR h_{p-1} (the reference engine's mtp_update shifts the target
9050 // hiddens right by one; its draft step 0 feeds (id_last, TRUE hidden of the row id_last
9051 // was sampled from)). memra's historical convention paired SAME-ROW (x_p, h_p) in the fill
9052 // and seeded chain step 0 through an extra MTP pass on a duplicated token (the
9053 // pseudo-seed) — measured 27B p2 K=3 acceptance 0.569 vs 0.731, p3 0.445 vs 0.63+, and
9054 // the chain steps j>=1 were already predecessor-shaped, so ONLY the fill + step-0 seed
9055 // move. The fill shifts by one and the chain seeds from the predecessor's true hidden
9056 // DIRECTLY (vh_seed / vx[j-1]) — the pseudo pass disappears (one MTP-block pass saved
9057 // per round on top of the acceptance win). Draft-quality-only: exactness stays the
9058 // verify's job either way. (The legacy same-row pairing seam, MEMRA_SPEC_HSAME, and its
9059 // pseudo-seed passes were removed 2026-07-08 — predecessor pairing won by +16 acc pts;
9060 // the legacy round-local scratch, MEMRA_SPEC_KVLOCAL, went with it.)
9061 // REPLAY-FREE PARTIAL ACCEPT (default, 2026-07-03): partial rounds keep the verify's own
9062 // bit-identical committed-prefix state (KV truncate + recur rebuild from the VerifyCkpt)
9063 // and leave the bonus PENDING — no duplicate trunk pass (profiled ~0.54 extra full weight
9064 // reads/round at long ctx). MEMRA_SPEC_REPLAY=1 restores the legacy rollback+replay (A/B
9065 // + fallback seam).
9066 // Qwen35-MoE replay pin LIFTED (lane/draftcost-moe, 2026-08-20). The pin's stated
9067 // bar — the retained verify-state commit proven equivalent to sequential serving —
9068 // was waiting on this arch running the serving batched verify class, which the
9069 // t-parallel admission (this lane, increment 1) provided: the VerifyCkpt the
9070 // replay-free commit consumes is now produced by the SAME serving-class verify that
9071 // qualified dense qwen35 on 2026-08-15 (where the per-round duplicate replay
9072 // measured 69 -> 30 tok/s). Qualification receipts (run-spec K=1..8 both arms,
9073 // 8-prompt replay-vs-replay-free canary, long-prompt cell):
9074 // research/draftcost-moe-20260820/RECEIPTS.md. MEMRA_SPEC_REPLAY=1 stays the
9075 // rollback + A/B seam.
9076 let spec_replay = spec_replay_env_enabled();
9077 if constraint.is_some() && spec_replay {
9078 return Err(
9079 "constrained spec decode does not support MEMRA_SPEC_REPLAY=1 \
9080 (legacy replay commits an unmasked bonus)"
9081 .into(),
9082 );
9083 }
9084 // TRUE-HIDDEN REFRESH (default in persistent-draft-KV mode): every round overwrites the
9085 // committed positions' scratch entries from the verify's exact hiddens (mtp_kv_fill batch)
9086 // instead of keeping chain-approximate entries. MEMRA_SPEC_NOREFRESH=1 = legacy (A/B seam).
9087 let refresh = std::env::var("MEMRA_SPEC_NOREFRESH").is_err();
9088
9089 // prime: BATCHED cache prime (prime_cache — the measured #1 e2e gap: tokenwise primed at
9090 // ~102/38 tok/s vs the engine's ~2000-5900 tok/s batched prefill). prime_cache returns the
9091 // full pre-output_norm hidden stack [T, n_embd], which IS prompt_h (the persistent-draft-KV
9092 // mtp_kv_fill input) — no per-token collection needed. Prompts below PRIME_MIN_T, and
9093 // MEMRA_PRIME_TOKENWISE=1, and frozen Hy3 CPU/GPU expert splits take the tokenwise
9094 // decode_step_h loop. The latter avoids transient GPU staging of the spilled expert bank.
9095 // EMPTY-SUFFIX CONTINUATION (serve bursts): a session turn with NO new tokens resumes
9096 // generation exactly where the last turn stopped — no prime at all. The stashed
9097 // `next_pred` plays prime_logits' role: it is the token produced from the logits after
9098 // committed.last() by the same rule this entry applies to a cold prime's last row —
9099 // an argmax when greedy, a `sample_boundary_token` draw when sampled (the burst tail,
9100 // or `spec_session_from_restored` for a converted prefix-cache hit, did the drawing
9101 // where the sampler and the session's Philox counters were live). `last_h` seeds the
9102 // predecessor pairing below. Fresh calls and non-empty suffixes take the normal path.
9103 let continuation = prompt.is_empty();
9104 if continuation {
9105 assert!(session_mode, "empty prompt requires a session");
9106 assert!(
9107 sess_tail
9108 .as_ref()
9109 .map_or(false, |(c, lh, np, _, _)| !c.is_empty()
9110 && lh.is_some()
9111 && (np.is_some() || carried_pending.is_some())),
9112 "empty-suffix continuation needs a primed session (committed + last_h + next_pred|pending)"
9113 );
9114 }
9115 let mut prime_logits;
9116 let mut prompt_h: Option<CudaSlice<f32>> = None;
9117 let t_prime = std::time::Instant::now();
9118 let batched_prime = !continuation
9119 && prompt.len() >= crate::hybrid_forward::PRIME_MIN_T
9120 && std::env::var("MEMRA_PRIME_TOKENWISE").is_err()
9121 && !e.frozen_cpu_experts_prefer_tokenwise_prime();
9122 let prime_split = prime_split.filter(|&split| split > 0 && split < prompt.len());
9123 if prime_split.is_some() && continuation {
9124 return Err("spec prime split requires a non-empty prime".into());
9125 }
9126 // STABLE-BOUNDARY TURN CHECKPOINT stop (lane/frspec-multiturn-cache, 2026-08-21):
9127 // the worker's `ckpt_at` request, ABSOLUTE -> prompt-relative. On WARM bursts
9128 // (base != 0, an affinity-rewound or pool-resumed session priming its own delta)
9129 // this is the only stop; on COLD bursts it usually coincides with `prime_split`
9130 // (both are the plain tier's stable pre-generation boundary). A boundary the prime
9131 // cannot honor (outside this prime's range) silently drops the capture — the
9132 // turn_ckpt convention: the next turn re-primes in full, never a wrong resume.
9133 let ckpt_rel = if continuation {
9134 None
9135 } else {
9136 ckpt_req
9137 .and_then(|abs| abs.checked_sub(base))
9138 .filter(|&r| r > 0 && r < prompt.len())
9139 };
9140 // Prime stops, ordered: each is a boundary the prime halts at so the in-place GDN
9141 // conv/ssm state can be snapshotted there (the only moment it exists). One stop =
9142 // the legacy single-split program, byte-for-byte.
9143 let mut stops: Vec<usize> = Vec::new();
9144 for b in [prime_split, ckpt_rel].into_iter().flatten() {
9145 if !stops.contains(&b) {
9146 stops.push(b);
9147 }
9148 }
9149 stops.sort_unstable();
9150 // Captured at the ckpt stop, installed into the session slot post-prime (replacing
9151 // the legacy prompt-end capture). Some(None) = capture attempted and failed -> the
9152 // slot is cleared (a stale checkpoint would rewind to the WRONG boundary).
9153 let mut ckpt_early: Option<Option<SpecCheckpoint>> = None;
9154 if continuation {
9155 prime_logits = Vec::new();
9156 } else if !stops.is_empty() {
9157 if let Some(&first) = stops.first() {
9158 if prime_split == Some(first) && first < crate::hybrid_forward::PRIME_MIN_T {
9159 return Err(format!(
9160 "spec prime split {first} is below PRIME_MIN_T {}",
9161 crate::hybrid_forward::PRIME_MIN_T,
9162 )
9163 .into());
9164 }
9165 }
9166 // Mirror the plain worker's boundary stops exactly. Each segment is a
9167 // request-level prime (`queued_after` keeps Step35 arm selection independent of
9168 // the stops — tick-seg law); a segment below PRIME_MIN_T (and the final tail
9169 // under MEMRA_PRIME_TOKENWISE) takes the same eager tokenwise continuation as
9170 // prefill_tick. Retain every hidden row so the draft scratch fill remains one
9171 // coherent prompt.
9172 let mut h_all = e.uninit(prompt.len() * n_embd)?;
9173 prime_logits = Vec::new();
9174 let mut prev = 0usize;
9175 for seg_end in stops.iter().copied().chain(std::iter::once(prompt.len())) {
9176 if seg_end <= prev {
9177 continue;
9178 }
9179 let seg = &prompt[prev..seg_end];
9180 let is_final = seg_end == prompt.len();
9181 let batched_seg = seg.len() >= crate::hybrid_forward::PRIME_MIN_T
9182 && (!is_final
9183 || (std::env::var("MEMRA_PRIME_TOKENWISE").is_err()
9184 && !e.frozen_cpu_experts_prefer_tokenwise_prime()));
9185 if batched_seg {
9186 let (l, _, h_seg) =
9187 self.prime_cache(e, seg, &mut *cache, prompt.len() - seg_end)?;
9188 e.copy_into(&mut h_all, prev * n_embd, &h_seg, seg.len() * n_embd)?;
9189 prime_logits = l;
9190 } else {
9191 for (i, &tok) in seg.iter().enumerate() {
9192 let (l, h) = self.decode_step_h(e, tok, &mut *cache)?;
9193 e.copy_into(&mut h_all, (prev + i) * n_embd, &h, n_embd)?;
9194 prime_logits = l;
9195 }
9196 }
9197 prev = seg_end;
9198 if is_final {
9199 break;
9200 }
9201 debug_assert_eq!(cache.pos, base + seg_end, "prime stop landed off boundary");
9202 // PREFIX-CACHE BOUNDARY CAPTURE (lane/spec-prefix-cache): the GDN conv/ssm
9203 // states are about to be advanced in place by the next segment, so this is
9204 // the ONLY moment the boundary's recurrent state exists. Capture iff the
9205 // worker requested exactly this stop (cold sessions only — `capture_at` is
9206 // never armed warm). A failed snapshot is silent (turn_ckpt convention) —
9207 // publication is an optimization, never a correctness dependency.
9208 if base == 0 {
9209 if let Some((requested, slot)) = sess_capture.as_mut() {
9210 // Publish at the requested miss-LCP stop (the shared-prefix class)
9211 // AND at the stable-boundary stop (the next-turn re-render class,
9212 // lane/frspec-multiturn-cache) — the same boundary set the plain
9213 // prefill tick learns. Without the second entry, the turn after a
9214 // cold re-park could only hit the OLDER lcp entry (the measured
9215 // one-turn transient: t3 restored 607 of 24122 while the plain arm
9216 // rewound to 15222). Dedupe is the worker sweep's has_key.
9217 if *requested == Some(seg_end) || ckpt_rel == Some(seg_end) {
9218 if let Ok(snap) = cache.snapshot(e) {
9219 slot.push(SpecBoundaryCapture {
9220 snap,
9221 pos: seg_end,
9222 logits: prime_logits.clone(),
9223 // rows [0..seg_end) of h_all are primed — the following
9224 // segments append, never overwrite.
9225 last_h: capture_boundary_hidden(e, &h_all, seg_end, n_embd),
9226 });
9227 }
9228 }
9229 }
9230 }
9231 // SESSION-AFFINITY TURN CHECKPOINT at the STABLE boundary (see `ckpt_at`):
9232 // same snapshot mechanics, installed post-prime in place of the prompt-end
9233 // capture the re-render class always diverged below.
9234 if ckpt_rel == Some(seg_end) {
9235 let anchor: Result<CudaSlice<f32>, Box<dyn std::error::Error>> =
9236 e.uninit(n_embd).and_then(|mut a| {
9237 e.copy_view_into(
9238 &mut a,
9239 0,
9240 &h_all.slice((seg_end - 1) * n_embd..seg_end * n_embd),
9241 n_embd,
9242 )?;
9243 Ok(a)
9244 });
9245 ckpt_early = Some(match (cache.snapshot(e), anchor) {
9246 (Ok(snap), Ok(last_h)) => Some(SpecCheckpoint {
9247 snap,
9248 pos: base + seg_end,
9249 last_h,
9250 }),
9251 _ => None,
9252 });
9253 }
9254 }
9255 if std::env::var("MEMRA_SPEC_STATS").as_deref() == Ok("1") {
9256 eprintln!(
9257 "[spec-prime] stops={stops:?} tail={}",
9258 prompt.len() - stops.last().copied().unwrap_or(0)
9259 );
9260 }
9261 prompt_h = Some(h_all);
9262 } else if batched_prime {
9263 let (l, _h_seed, hiddens) = self.prime_cache(e, prompt, &mut *cache, 0)?;
9264 prime_logits = l;
9265 prompt_h = Some(hiddens);
9266 } else {
9267 prime_logits = Vec::new();
9268 prompt_h = Some(e.uninit(prompt.len() * n_embd)?);
9269 for (i, &tok) in prompt.iter().enumerate() {
9270 let (l, h) = self.spec_target_step_h(e, tok, &mut *cache)?;
9271 if let Some(ph) = prompt_h.as_mut() {
9272 e.copy_into(ph, i * n_embd, &h, n_embd)?;
9273 }
9274 prime_logits = l;
9275 }
9276 }
9277 e.stream().synchronize()?;
9278 // PREFIX-CACHE SEED CAPTURE (lane/spec-prefix-cache): boundary == prompt end (the seed
9279 // case — no shared-prefix split, publish the whole prompt). The prime just finished, so
9280 // cache.pos == base + prompt.len() and the recurrent state IS the boundary state;
9281 // prime_logits are the boundary logits. Cold sessions only (base == 0) — same law as
9282 // prime_split. The mid-prompt capture above already consumed the request if it matched.
9283 if !continuation && base == 0 {
9284 if let Some((requested, slot)) = sess_capture.as_mut() {
9285 if *requested == Some(prompt.len()) && slot.is_empty() {
9286 debug_assert_eq!(cache.pos, prompt.len(), "seed capture off prompt end");
9287 if let Ok(snap) = cache.snapshot(e) {
9288 slot.push(SpecBoundaryCapture {
9289 snap,
9290 pos: prompt.len(),
9291 logits: prime_logits.clone(),
9292 last_h: prompt_h
9293 .as_ref()
9294 .map(|ph| capture_boundary_hidden(e, ph, prompt.len(), n_embd))
9295 .unwrap_or_default(),
9296 });
9297 }
9298 }
9299 }
9300 }
9301 // Harness timing contract (see crate::PRIME_NANOS): gen-only throughput without the
9302 // prime-subtraction hack.
9303 crate::PRIME_NANOS.store(
9304 t_prime.elapsed().as_nanos() as u64,
9305 std::sync::atomic::Ordering::Relaxed,
9306 );
9307
9308 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
9309 // Resident table is fastest when it fits. Large spill deployments can preserve that HBM
9310 // for expert-cache slots and gather only the exact rows needed by MTP/verify from host.
9311 let host_embd = spec_host_embd();
9312 let embd_gpu = if host_embd {
9313 None
9314 } else {
9315 Some(
9316 self.embd_gpu
9317 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
9318 )
9319 };
9320 let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
9321 if host_embd {
9322 eprintln!(
9323 "[spec] host-row embedding: {} bytes kept off HBM",
9324 self.embd.raw.len()
9325 );
9326 }
9327 let mut out: Vec<u32> = Vec::with_capacity(max_new);
9328 let mut total_drafted = 0usize;
9329 let mut total_accepted = 0usize;
9330
9331 // --- SAMPLER FIRST (lane/sampled-spec-quality, 2026-08-19) ---
9332 // The sampler config, the session's Philox counters and the penalty window are parsed
9333 // HERE, above the boundary-token selection, because the boundary token must be drawn
9334 // from the sampler the request asked for. Pre-lane this block sat ~50 lines BELOW the
9335 // selection, which is the whole mechanical reason the boundary token was an argmax:
9336 // the sampler state was not in scope yet. Nothing here depends on the round loop, so
9337 // moving it up is a pure reordering for greedy (`sampled == false` ⇒ every branch
9338 // below takes the argmax path it always took).
9339 // --- SAMPLED SPEC (MEMRA_SPEC_TEMP>0, research/sampled-spec-impl-map.md): rejection-
9340 // sampling verify (Leviathan/Chen) — accept draft x at u < p(x)/q(x), resample from
9341 // norm(max(0,p-q)) on reject, bonus sampled from p on full accept. Counter-based Philox
9342 // everywhere (seed, event) -> reproducible. temp==0/unset = the greedy path, untouched.
9343 let sp = sampling.unwrap_or_else(|| SpecSampling {
9344 temp: std::env::var("MEMRA_SPEC_TEMP")
9345 .ok()
9346 .and_then(|v| v.parse().ok())
9347 .unwrap_or(0.0),
9348 seed: std::env::var("MEMRA_SEED")
9349 .ok()
9350 .and_then(|v| v.parse().ok())
9351 .unwrap_or(42),
9352 top_k: std::env::var("MEMRA_TOP_K")
9353 .ok()
9354 .and_then(|v| v.parse().ok())
9355 .unwrap_or(0),
9356 top_p: std::env::var("MEMRA_TOP_P")
9357 .ok()
9358 .and_then(|v| v.parse().ok())
9359 .unwrap_or(1.0),
9360 min_p: std::env::var("MEMRA_MIN_P")
9361 .ok()
9362 .and_then(|v| v.parse().ok())
9363 .unwrap_or(0.0),
9364 penalty_last_n: std::env::var("MEMRA_PENALTY_LAST_N")
9365 .ok()
9366 .and_then(|v| v.parse().ok())
9367 .unwrap_or(0),
9368 penalty_repeat: std::env::var("MEMRA_PENALTY_REPEAT")
9369 .ok()
9370 .and_then(|v| v.parse().ok())
9371 .unwrap_or(1.0),
9372 penalty_freq: std::env::var("MEMRA_PENALTY_FREQ")
9373 .ok()
9374 .and_then(|v| v.parse().ok())
9375 .unwrap_or(0.0),
9376 penalty_present: std::env::var("MEMRA_PENALTY_PRESENT")
9377 .ok()
9378 .and_then(|v| v.parse().ok())
9379 .unwrap_or(0.0),
9380 });
9381 let (sp_temp, sp_seed) = (sp.temp, sp.seed);
9382 let sampled = sp_temp > 0.0;
9383 // Counters resume from the session (burst continuity: randomness must never repeat
9384 // across generate_spec_session calls); one-shot callers start at (0,0). Read through
9385 // sess_tail — `sess` was take()n into it above, so sess.as_ref() here is always None.
9386 let mut sctr: u32 = sess_tail.as_ref().map(|(_, _, _, s, _)| **s).unwrap_or(0);
9387 let mut uctr: u32 = sess_tail.as_ref().map(|(_, _, _, _, u)| **u).unwrap_or(0);
9388 // Penalties (v2.1): applied to COPIES of q rows and p columns symmetrically (exactness
9389 // for the penalized+filtered target). History = generated tokens, host-tracked window.
9390 let pen_on = sampled
9391 && sp.penalty_last_n > 0
9392 && (sp.penalty_repeat != 1.0 || sp.penalty_freq != 0.0 || sp.penalty_present != 0.0);
9393 // SESSION-SPANNING PENALTY WINDOW (Item 2). Pre-lane this was
9394 // `prompt.iter().rev().take(64).rev()` — the BURST's suffix slice — so a continuation
9395 // burst (the majority of a stream's tokens, and ALL of a converted cache hit's) started
9396 // with an EMPTY penalty history and the client's repetition/frequency/presence penalties
9397 // silently reset at every burst boundary. The window now spans `committed ++ prompt`,
9398 // which is what the API contract says and what the plain sampler's own `history` does.
9399 // Byte-identical to the pre-lane seed for a cold turn-1 burst at the default window.
9400 let mut pen_hist: Vec<u32> = if pen_on {
9401 let sess_hist: &[u32] = if spec_pen_session_on() {
9402 sess_tail
9403 .as_ref()
9404 .map(|(c, ..)| c.as_slice())
9405 .unwrap_or(&[])
9406 } else {
9407 &[] // MEMRA_SPEC_PEN_SESSION=0: pre-lane burst-local window
9408 };
9409 pen_window_seed(sess_hist, prompt, sp.penalty_last_n)
9410 } else {
9411 Vec::new()
9412 };
9413 // First generated token = the BOUNDARY token: greedy takes the argmax of the prompt's
9414 // last logits (== greedy's first token, byte-contract); SAMPLED draws it from the
9415 // request's own filtered/penalized target through the session's Philox stream
9416 // (`sample_boundary_token`, lane/sampled-spec-quality Item 1 — pre-lane this was an
9417 // argmax in both regimes, so ~1 token per burst of a sampled stream was greedy).
9418 // Emit it, then FEED it to establish the loop invariant below.
9419 // PENDING-CARRY: the carried bonus was already emitted by the LAST burst — it becomes
9420 // last_token WITHOUT re-emission, and round 0 consumes it as pending (no init feed).
9421 // CONSTRAINED entry rules: the first emitted token is the MASKED argmax of the
9422 // prompt's last logits (plain constrained-greedy identity); a continuation without
9423 // a carried pending would emit an UNMASKED stashed next_pred — refused loudly (the
9424 // worker never resumes constrained sessions from the pool, so this cannot fire).
9425 if let Some(c) = constraint.as_deref_mut() {
9426 if continuation && carried_pending.is_none() {
9427 return Err("constrained spec continuation requires a carried pending \
9428 (pool resume is unconstrained-only)"
9429 .into());
9430 }
9431 if !continuation {
9432 c.mask_logits(&mut prime_logits)
9433 .map_err(|e2| format!("constraint: {e2}"))?;
9434 }
9435 }
9436 let mut last_token = if let Some(b) = carried_pending {
9437 b
9438 } else if continuation {
9439 // A continuation's boundary token was DRAWN by the burst that stashed it (the
9440 // session tail below), or by `spec_session_from_restored` for a converted
9441 // prefix-cache hit — in both cases from the correct logits row with this same
9442 // session's Philox stream, which is why it can be consumed here as-is.
9443 sess_tail.as_ref().unwrap().2.unwrap()
9444 } else if sampled && constraint.is_none() && spec_sampled_boundary_on() {
9445 sample_boundary_token(e, &prime_logits, &sp, &pen_hist, &mut sctr, "cold-prime")?
9446 } else {
9447 // greedy (byte contract), the rollback door, or constrained (masked-argmax
9448 // identity — the worker routes sampled+constrained to the plain path, and this
9449 // function refuses the combination outright above).
9450 argmax(&prime_logits) as u32
9451 };
9452 if pen_on {
9453 // The boundary token is a GENERATED token: the plain sampler `accept()`s every
9454 // emitted token into its penalty history, and pre-lane the burst's first token
9455 // was invisible to penalties forever (never pushed, and never in `committed`
9456 // until this burst's tail). Covers the carry/continuation seeds too — neither is
9457 // in `committed` yet.
9458 pen_hist.push(last_token);
9459 }
9460 if carried_pending.is_none() {
9461 out.push(last_token);
9462 // grammar advances with every emitted token (carried pendings were consumed
9463 // by the burst that emitted them).
9464 if let Some(c) = constraint.as_deref_mut() {
9465 c.consume(last_token)
9466 .map_err(|e2| format!("constraint: {e2}"))?;
9467 }
9468 }
9469 if continuation {
9470 // draft-KV invariant: entries [0..base) are the session's exact fills; truncate any
9471 // overhang so the chain's first append lands at slot base (== committed.len()).
9472 scratch.set_len(e, base)?;
9473 }
9474 // sse-cadence: hand the caller every not-yet-flushed token (disjoint in-order slices
9475 // concatenating to the full `out`). Called after the prime's first token and after each
9476 // round commit — emission timing only, token bytes untouched. The slice may be EMPTY
9477 // (poll-only boundary: zero-round folds commit nothing new); returns the caller's
9478 // continue-verdict (admission yield, 2026-08-06) — false ends the burst at this round.
9479 fn flush_commit(
9480 cb: &mut Option<&mut dyn FnMut(&[u32]) -> bool>,
9481 out: &[u32],
9482 flushed: &mut usize,
9483 ) -> bool {
9484 if let Some(f) = cb.as_mut() {
9485 let keep = f(&out[*flushed..]);
9486 *flushed = out.len();
9487 keep
9488 } else {
9489 true
9490 }
9491 }
9492 keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
9493 // INVARIANT at loop top: `last_token` is the most-recently-committed/emitted token, its
9494 // KV+recur state IS in `cache` (cache.pos = position right AFTER last_token), `last_pred`
9495 // is the greedy ARGMAX of the logits that predict the token FOLLOWING last_token, and
9496 // `h_seed` = last_token's pre-output_norm hidden. Establish it by feeding last_token once
9497 // (mirrors plain greedy). DEVICE-ARGMAX lever: the accept walk only ever consumes the
9498 // argmax of those logits — never the full vector — so a host u32 replaces the Vec<f32>.
9499 // Trimmed heads: q lives on the trimmed vocab; accept gathers use the TRIMMED index and
9500 // the residual scatters q into target-id space (q=-inf off-trim — the head cannot propose
9501 // those, so their residual mass is p(x), correct by construction).
9502 let d2t_dev: Option<CudaSlice<u32>> = if sampled || crate::spec::spec_stream() {
9503 match &mtp.d2t {
9504 Some(map) => Some(e.htod_u32_v(map)?),
9505 None => None,
9506 }
9507 } else {
9508 None
9509 };
9510 let mut q_full_buf: Option<CudaSlice<f32>> = None;
9511 // host Philox4x32-10 accept-test uniforms: module fn `host_u01` (shared with the
9512 // dspark sampled-admission walk); byte-identical to the closure it replaces.
9513 let mut draft_logits: Vec<CudaSlice<f32>> = Vec::new(); // retained head logits (q), per slot
9514 let mut draft_stats: Vec<(f32, f32, f32)> = Vec::new(); // (row_max, th_e, z_e) per slot
9515 let mut perturb_buf: Option<CudaSlice<f32>> = None; // gumbel scratch (max(n_vocab,d_vocab))
9516 let mut sample_tok = e.alloc_u32_zeroed(1)?; // residual/bonus sample out
9517 let mut col_buf: Option<CudaSlice<f32>> = None; // materialized verify column
9518 let mut pen_hist_d: Option<CudaSlice<u32>> = None;
9519 let mut pcol_buf: Option<CudaSlice<f32>> = None; // penalized p-column scratch
9520 // MEMRA_SPEC_SETUP_TRACE=1 (diagnostics): per-call wall decomposition of the burst
9521 // SETUP + TAIL segments (the round loop's internals are MEMRA_SPEC_PHASE's job) —
9522 // built to pin the serve per-burst fixed cost (research/spec-serving-20260801).
9523 let setup_trace = std::env::var("MEMRA_SPEC_SETUP_TRACE").as_deref() == Ok("1");
9524 let t_ent = std::time::Instant::now();
9525
9526 // SESSION-AFFINITY TURN CHECKPOINT (lane/session-affinity, 2026-08-05): capture the
9527 // PROMPT-END boundary state so a LATER turn can rewind here and re-prime only its own
9528 // delta instead of the whole conversation. See `SpecCheckpoint` for why this boundary is
9529 // the one that matters (a history-rewriting client mutates what the session GENERATED,
9530 // so the next turn's prompt agrees with this one up to exactly here).
9531 //
9532 // WHERE — AND WHY THIS EXACT LINE. Right after the trunk prime, BEFORE the init feed
9533 // (`decode_step_h(last_token)`) and before round 0: the last instant at which the caches
9534 // hold exactly `base + prompt.len()` rows and nothing generated.
9535 //
9536 // This was WRONG in the first cut of this lane: the capture sat after the draft-KV fill,
9537 // which is also after the init feed, so `cache.pos` was `base + prompt.len() + 1` — the
9538 // boundary included the FIRST GENERATED TOKEN. That token is the first thing inside the
9539 // `<think>` block the client strips, so every later turn's diff diverged exactly one
9540 // token below the checkpoint and affinity declined 100% of the time. Measured on the
9541 // owner regime: "history diverged at 12233 of checkpoint 12234". The off-by-one made the
9542 // whole mechanism inert while looking, from the outside, like a working
9543 // correctness-declines-safely path — hence the decline log carries the offsets.
9544 //
9545 // The full-attn planes are `len`-truncatable so the snapshot copies only the GDN conv/ssm
9546 // state (the reason a spec session could not rewind before). The draft scratch needs no
9547 // copy: rows below the boundary are rewritten by the next turn's own fill.
9548 //
9549 // WHEN: non-empty prime only. An empty-suffix continuation burst adds no prompt boundary
9550 // (its "prompt end" IS the previous checkpoint's, already held), so it keeps the existing
9551 // checkpoint rather than replacing it with a strictly worse one.
9552 //
9553 // FAILURE IS SILENT BY DESIGN: on a VRAM-tight rig the snapshot alloc can fail. That
9554 // costs the NEXT turn its rewind (it re-primes fully, today's behavior) and must never
9555 // fail the burst that is already running — so the error is swallowed, loud only under
9556 // MEMRA_DEBUG_SPEC.
9557 //
9558 // STABLE-BOUNDARY OVERRIDE (lane/frspec-multiturn-cache, 2026-08-21): the prompt-end
9559 // posture above was DISPROVED for the think-posture template class — the prompt's own
9560 // tail is the live generation header (`<|im_start|>assistant\n<think>\n`) that the
9561 // next turn's re-render replaces, so the diff diverged a couple tokens BELOW the
9562 // checkpoint and affinity declined 100% of multi-turn agent traffic (the same class
9563 // the plain tier fixed on 2026-08-09 via `plain_checkpoint_boundary`; the port to the
9564 // spec tier is this lane). When the worker armed `ckpt_at`, the capture happened at
9565 // that stop inside the prime above (`ckpt_early`) and is installed here instead;
9566 // capture-attempted-but-failed clears the slot exactly like the legacy arm.
9567 if let Some(slot) = sess_ckpt_slot {
9568 if let Some(early) = ckpt_early {
9569 if early.is_none() && std::env::var("MEMRA_DEBUG_SPEC").is_ok() {
9570 eprintln!(
9571 "[spec] stable-boundary turn checkpoint skipped; \
9572 next turn re-primes in full"
9573 );
9574 }
9575 *slot = early;
9576 } else if !continuation {
9577 let pos = cache.pos;
9578 debug_assert_eq!(
9579 pos,
9580 base + prompt.len(),
9581 "turn checkpoint must sit at the prompt end, before the init feed"
9582 );
9583 let anchor: Result<CudaSlice<f32>, Box<dyn std::error::Error>> =
9584 if let Some(ph) = &prompt_h {
9585 // hidden of the LAST primed row = the predecessor anchor at this
9586 // boundary (exactly what a fresh prime of committed[..pos] leaves in
9587 // last_h, and what the next prime's fill reads for its first row).
9588 let np = prompt.len();
9589 e.uninit(n_embd).and_then(|mut a| {
9590 e.copy_view_into(
9591 &mut a,
9592 0,
9593 &ph.slice((np - 1) * n_embd..np * n_embd),
9594 n_embd,
9595 )?;
9596 Ok(a)
9597 })
9598 } else {
9599 Err("no prompt hiddens".into())
9600 };
9601 match (cache.snapshot(e), anchor) {
9602 (Ok(snap), Ok(last_h)) => {
9603 *slot = Some(SpecCheckpoint { snap, pos, last_h });
9604 }
9605 (s, a) => {
9606 *slot = None; // a stale checkpoint would rewind to the WRONG boundary
9607 if std::env::var("MEMRA_DEBUG_SPEC").is_ok() {
9608 let err = s
9609 .err()
9610 .map(|e| e.to_string())
9611 .or_else(|| a.err().map(|e| e.to_string()))
9612 .unwrap_or_default();
9613 eprintln!(
9614 "[spec] turn checkpoint skipped ({err}); \
9615 next turn re-primes in full"
9616 );
9617 }
9618 }
9619 }
9620 }
9621 }
9622 // INIT FEED — skipped on a pending carry: last_token (the carried bonus) is NOT in the
9623 // caches and must NOT be fed solo; round 0's batched verify commits it as col 0. Its
9624 // seed/anchor hidden is the carried last_h (copied below); last_pred is dead in the
9625 // pending path (t_pred reads verify col 0 — the accept walk overwrites it).
9626 let mut last_pred = 0u32;
9627 let mut last_col_logits: Option<CudaSlice<f32>> = None;
9628 // CONSTRAINED: the init feed's logits back the (n_acc==0, base==0) masked-argmax
9629 // recompute in the grammar-truncation walk — retained host-side, round 0 only.
9630 let mut init_logits_host: Option<Vec<f32>> = None;
9631 let h_seed0: CudaSlice<f32> = if carried_pending.is_none() {
9632 let (init_logits, h) = self.spec_target_step_h(e, last_token, &mut *cache)?;
9633 last_pred = argmax(&init_logits) as u32;
9634 if constraint.is_some() {
9635 init_logits_host = Some(init_logits.clone());
9636 }
9637 // sampled mode: p-distribution after last_token, for the j==0/base==0 accept test.
9638 if sampled {
9639 last_col_logits = Some(e.htod(&init_logits)?);
9640 }
9641 h
9642 } else {
9643 // predecessor-row anchor: hidden of the last COMMITTED row (the carry contract).
9644 let lh = sess_tail
9645 .as_ref()
9646 .unwrap()
9647 .1
9648 .as_ref()
9649 .expect("pending carry requires last_h");
9650 e.clone_dtod(lh)?
9651 };
9652 let t_init = t_ent.elapsed();
9653 let mut last_col_stats: Option<(f32, f32, f32)> = None;
9654 // PERSISTENT h_seed buffer (allocated BEFORE any graph capture so no captured scratch can
9655 // alias it): every path that updates the round seed copies INTO it — no per-round allocs,
9656 // stable pointer for the graph-draft round-start copy.
9657 let mut h_seed_buf = e.clone_dtod(&h_seed0)?;
9658 // Predecessor-pairing trackers: `fill_prev` = trunk hidden AT the last COMMITTED row (the
9659 // predecessor of the next verify's col 0 — the reference's carried pending-h analogue;
9660 // also the predecessor-row hidden for the round-0 legacy-replay seed). At round 0 that
9661 // row is last_token's own (h_seed0). The chain step-0 seed under the pairing default =
9662 // hidden of the row BEFORE last_token = the prompt's last row at round 0 (h_seed_buf
9663 // overwritten below).
9664 let mut fill_prev = e.clone_dtod(&h_seed0)?;
9665 {
9666 if let Some(ph) = &prompt_h {
9667 let np = prompt.len();
9668 e.copy_view_into(
9669 &mut h_seed_buf,
9670 0,
9671 &ph.slice((np - 1) * n_embd..np * n_embd),
9672 n_embd,
9673 )?;
9674 } else if continuation {
9675 if let Some((_, lh, _, _, _)) = sess_tail.as_ref() {
9676 if let Some(lh) = lh.as_ref() {
9677 e.copy_into(&mut h_seed_buf, 0, lh, n_embd)?;
9678 }
9679 }
9680 }
9681 }
9682 // Persistent device prediction slots for the accept walk (max k+1 verify columns).
9683 let mut preds_d = e.alloc_u32_zeroed(k + 2)?;
9684
9685 let debug_spec = std::env::var("MEMRA_DEBUG_SPEC").is_ok();
9686 let fork_mode = OptiForkGateMode::configured();
9687 // MEMRA_SPEC_STATS=1: per-slot accept histogram + draft-length histogram, printed once at
9688 // the end. Metric normalization vs the reference engine: BOTH engines count
9689 // accepted/drafted where the chain stopped at p-min and the sub-threshold token is
9690 // discarded uncounted — per-slot decay + chain-length mix are the extra dimensions.
9691 let spec_stats = std::env::var("MEMRA_SPEC_STATS").is_ok();
9692 let mut st_drafted = vec![0usize; k];
9693 let mut st_accepted = vec![0usize; k];
9694 let mut st_len_hist = vec![0usize; k + 1];
9695 let mut st_full = 0usize;
9696 // P-MIN CONFIDENCE GATE (MEMRA_SPEC_PMIN, the serve script's --spec-draft-p-min mechanism):
9697 // stop the draft chain early when the head's softmax confidence in its own pick drops
9698 // below p_min. Hoisted above the loop: the graph capture bakes the prob kernels iff on.
9699 static PMIN: std::sync::OnceLock<f32> = std::sync::OnceLock::new();
9700 let p_min = *PMIN.get_or_init(|| {
9701 std::env::var("MEMRA_SPEC_PMIN")
9702 .ok()
9703 .and_then(|v| v.parse().ok())
9704 .unwrap_or(0.0)
9705 });
9706 // ZERO-DRAFT ROUNDS (MEMRA_SPEC_PMIN0=1, vendored from llama.cpp's draft gating): let the
9707 // p-min gate apply at j==0 too, so a low-confidence round drafts NOTHING and the verify
9708 // batch is just the pending bonus (m=1 = a plain decode step). llama's 35B win rides
9709 // exactly this — draft acceptance 76% at mean len 2.5 because unpredictable stretches
9710 // never pay draft+verify overhead. Only legal when a pending bonus exists (an empty
9711 // verify batch is not); the j==0 exemption stays for pending-less rounds.
9712 let pmin0 = std::env::var("MEMRA_SPEC_PMIN0")
9713 .map(|v| v == "1")
9714 .unwrap_or(false);
9715
9716 // --- GRAPH DRAFT setup: persistent I/O buffers + ONE capture (2 warmups inside). The
9717 // warmups mutate scratch len_d / pos / tok / seed — all reset at every round start, so the
9718 // only restore needed is the scratch counter. Capture failure (e.g. a non-capturable
9719 // cuBLAS path in an exotic head) falls back to the eager draft chain.
9720 // PER-SESSION PERSISTENCE (2026-08-01): session calls reuse the DraftGraphCtx parked on
9721 // the SpecSession — the capture (2 warmup head forwards + instantiate) ran ONCE at the
9722 // session's first burst, not per burst (measured ~16ms/burst fixed cost on H100 q27,
9723 // research/spec-serving-20260801). Reuse is pointer-exact: the graph bakes the session's
9724 // own scratch KV (never realloc'd), the model's resident embedding, the OnceLock p_min,
9725 // and the g_* buffers carried in the ctx — replay dispatch is identical to a fresh
9726 // capture, so draft tokens are bit-identical (drafts never decide exactness anyway; the
9727 // verify arbitrates). Single-shot calls (sess=None) build a fresh ctx and drop it.
9728 let mut dctx: DraftGraphCtx = match sess_draft_slot.as_mut().and_then(|s| s.take()) {
9729 Some(c) => c,
9730 None => DraftGraphCtx::new(e, n_embd, if sampled { d_vocab } else { 1 })?,
9731 };
9732 // A session that ran greedy bursts first sized g_q/g_perturb at 1; a sampled resume
9733 // needs d_vocab. Realloc is legal exactly while graph_s is None (nothing baked them).
9734 if sampled && dctx.g_q.len() < d_vocab {
9735 dctx.g_q = e.zeros(d_vocab)?;
9736 dctx.g_perturb = e.zeros(d_vocab)?;
9737 }
9738 // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask, 2026-08-04): the drafter samples the
9739 // grammar's legal set, so proposals are legal BY CONSTRUCTION and the verify-side
9740 // truncation (the correctness backstop) stops cutting every tight-schema round.
9741 // The mask is one node inside the captured draft chain — presence is a CAPTURE-TIME
9742 // shape, so a parked graph of the other shape is dropped and recaptured.
9743 let dmask_on = constraint
9744 .as_deref()
9745 .is_some_and(|c| c.draft_mask_enabled());
9746 let dmask_words = if dmask_on { d_vocab.div_ceil(32) } else { 0 };
9747 if dmask_on && dctx.g_dmask.len() < dmask_words {
9748 dctx.g_dmask = e.alloc_u32_zeroed(dmask_words)?;
9749 dctx.graph = None; // the old capture baked the old (or no) mask pointer
9750 dctx.failed.clear_greedy();
9751 dctx.keeper.clear();
9752 }
9753 if dctx.graph.is_some() && dctx.graph_masked != dmask_on {
9754 dctx.graph = None;
9755 dctx.failed.clear_greedy();
9756 dctx.keeper.clear();
9757 }
9758 if graph_draft && !sampled && dctx.graph.is_none() && !dctx.failed.greedy_failed() {
9759 let DraftGraphCtx {
9760 g_tok,
9761 g_pos,
9762 g_seed,
9763 g_p,
9764 g_dmask,
9765 ..
9766 } = &mut dctx;
9767 // capture-time contents: ALL-ONES (ban nothing). A replay only ever runs after the
9768 // host uploads the position's real words, so the warmups stay grammar-free.
9769 if dmask_on {
9770 e.htod_u32_into(g_dmask, &vec![u32::MAX; dmask_words])?;
9771 }
9772 let g_dmask_ro: &CudaSlice<u32> = &*g_dmask;
9773 // CAPTURE-RETAIN (#68 fix): the warmup transients' pool addresses are baked into the
9774 // captured graph; the keeper pins them for the graph's lifetime. capture_graph (non-
9775 // retained) freed them at exit — safe for one-shot generate_spec (nothing else touches
9776 // the pool between replays) but WRONG for sessions: burst-boundary prime/fill/commit
9777 // passes (and, in serve, other sessions) recycle those addresses and the replay then
9778 // clobbers live buffers — the ST serve-spec corruption (research/serve-st-20260803).
9779 let cap_res = e.capture_graph_retained(|e| {
9780 self.mtp_head_forward_cap(
9781 e,
9782 mtp,
9783 g_tok,
9784 g_pos,
9785 g_seed,
9786 g_p,
9787 &mut *scratch,
9788 p_min > 0.0 || fork_mode == OptiForkGateMode::Controller,
9789 true,
9790 embd_gpu.expect("graph draft requires resident embedding"),
9791 embd_qt,
9792 embd_rb,
9793 d_vocab,
9794 None,
9795 None,
9796 if dmask_on {
9797 Some((g_dmask_ro, dmask_words))
9798 } else {
9799 None
9800 },
9801 )
9802 });
9803 match cap_res {
9804 Ok((g, keep)) => {
9805 scratch.set_len(e, base)?;
9806 dctx.graph = Some(g);
9807 dctx.graph_masked = dmask_on;
9808 dctx.keeper = keep;
9809 }
9810 Err(err) => {
9811 scratch.set_len(e, base)?;
9812 // LOUD flip (audit Q2): a dropped draft graph is a coverage loss, never
9813 // silent. Once per flip — mark returns None on an already-failed ctx.
9814 if let Some(line) = dctx.failed.mark_greedy(&err.to_string()) {
9815 eprintln!("{line}");
9816 }
9817 }
9818 }
9819 }
9820 // --- SAMPLED GRAPH DRAFT setup (step 3 of the sampled-spec arc): a SECOND capture, own
9821 // graph object, built only when sampled && graph-eligible — the greedy capture above is
9822 // untouched (and skipped when sampled: its graph would never be launched). Same head
9823 // forward, but the in-graph argmax reads GUMBEL-PERTURBED logits; the Philox event
9824 // counter lives in the persistent device g_ctr (bumped in-graph, host-seeded from sctr
9825 // once per round); the raw head logits land in the persistent g_q for the host's
9826 // per-replay async D2D into the round's q slot (q_slots, K x d_vocab, allocated once).
9827 // seed/temp are capture-time constants — baked into graph_s, so a pool-resumed request
9828 // with a different (seed, temp, k) drops the parked sampled graph and recaptures.
9829 // COST OF THE FRESH-SEED SERVE DEFAULT (dogfood F4, 2026-08-04): omitting `seed` on a
9830 // serve request now draws fresh per-request entropy (it used to default to a pinned 0),
9831 // so a seed-omitting request that RESUMES a parked spec session finds an s_key baked
9832 // with the PREVIOUS request's seed and pays one recapture. Bounded, and it does not
9833 // reopen the ~16ms/burst regression the persistent ctx exists to fix: a session's seed
9834 // is fixed for its whole lifetime (worker.rs reads s.sampler.seed() per burst), so
9835 // this compare misses at most ONCE per resumed request — the first burst recaptures
9836 // and every later burst in that request replays. A client that wants the parked graph
9837 // AND reproducibility supplies an explicit `seed`, honored exactly, which keeps s_key
9838 // stable across its whole conversation.
9839 // COMPOSITION RULE (fspec x gsd merge): the in-graph chain samples from the RAW
9840 // softmax — it can hold neither per-row filter stats nor the varying penalty history.
9841 // The sampled graph therefore engages only in the PURE-TEMP regime; filters/penalties
9842 // force the eager draft (which computes stats/penalties per row).
9843 // KEY THE WHOLE REGIME, not just the baked constants (lane/graph-s-key-exactness-
9844 // 20260819). `s_key` used to be `(seed, temp, k)`; the filters and penalties were left
9845 // out, so a filtered request resuming a session that parked a PURE-TEMP graph kept it —
9846 // and the launch site never re-asked `pure_temp`. See [`SampledGraphKey`] for what that
9847 // costs (an unconditional accept of out-of-head draft tokens, i.e. an exactness bug on
9848 // the request shape the vendor-default flip makes the majority).
9849 let s_key = SampledGraphKey::new(sp_seed, sp_temp, k, sp.top_k, sp.top_p, sp.min_p, pen_on);
9850 let pure_temp = s_key.pure_temp();
9851 if sampled && dctx.s_key.is_some_and(|old| old != s_key) {
9852 dctx.graph_s = None;
9853 dctx.failed.clear_sampled();
9854 dctx.s_key = None;
9855 dctx.q_slots.clear();
9856 dctx.keeper_s.clear();
9857 }
9858 if graph_draft
9859 && sampled
9860 && pure_temp
9861 && dctx.graph_s.is_none()
9862 && !dctx.failed.sampled_failed()
9863 {
9864 let DraftGraphCtx {
9865 g_tok,
9866 g_pos,
9867 g_seed,
9868 g_p,
9869 g_ctr,
9870 g_perturb,
9871 g_q,
9872 ..
9873 } = &mut dctx;
9874 // CAPTURE-RETAIN (#68 fix): same keeper contract as the greedy capture above.
9875 let cap_res = e.capture_graph_retained(|e| {
9876 self.mtp_head_forward_cap(
9877 e,
9878 mtp,
9879 g_tok,
9880 g_pos,
9881 g_seed,
9882 g_p,
9883 &mut *scratch,
9884 p_min > 0.0,
9885 true,
9886 embd_gpu.expect("graph draft requires resident embedding"),
9887 embd_qt,
9888 embd_rb,
9889 d_vocab,
9890 Some((g_ctr, g_perturb, g_q, sp_seed, sp_temp)),
9891 None,
9892 None, // constrained spec is greedy-only — sampled never carries a hook
9893 )
9894 });
9895 match cap_res {
9896 Ok((g, keep)) => {
9897 scratch.set_len(e, base)?;
9898 for _ in 0..k {
9899 dctx.q_slots.push(e.zeros(d_vocab)?);
9900 }
9901 dctx.graph_s = Some(g);
9902 dctx.s_key = Some(s_key);
9903 dctx.keeper_s = keep;
9904 }
9905 Err(err) => {
9906 scratch.set_len(e, base)?;
9907 // LOUD flip (audit Q2): same contract as the greedy capture above.
9908 if let Some(line) = dctx.failed.mark_sampled(&err.to_string()) {
9909 eprintln!("{line}");
9910 }
9911 }
9912 }
9913 }
9914 // ---- EXACTNESS GUARD, the enforceable half (lane/graph-s-key-exactness-20260819) ----
9915 // With the filters and penalties in `s_key`, a graph that SURVIVED the drop above was
9916 // captured under this request's exact regime, and capture requires `pure_temp` — so a
9917 // parked graph implies `pure_temp`. That implication is the whole exactness argument for
9918 // the graph arm, so it is asserted here rather than assumed: a future change that widens
9919 // the capture condition, narrows the key, or copies a `DraftGraphCtx` across regimes
9920 // fails LOUDLY at this line instead of silently drafting from the raw softmax while the
9921 // verify applies filter stats. Release builds refuse the graph (drop it, draft eager)
9922 // rather than launching it; the launch site re-tests `pure_temp` independently.
9923 if sampled && !pure_temp && dctx.graph_s.is_some() {
9924 debug_assert!(
9925 false,
9926 "sampled draft graph parked under {:?} survived into a FILTERED request \
9927 (top_k={} top_p={} min_p={} pen_on={}): the in-graph chain draws from the RAW \
9928 softmax, so the verify's filtered q would test a distribution the draft was \
9929 never sampled from",
9930 dctx.s_key, sp.top_k, sp.top_p, sp.min_p, pen_on,
9931 );
9932 eprintln!(
9933 "[spec] BUG: dropping a parked sampled draft graph that outlived its capture \
9934 regime (s_key={:?}, request top_k={} top_p={} min_p={} pen_on={}); drafting \
9935 EAGER — the key must carry every field that shapes q",
9936 dctx.s_key, sp.top_k, sp.top_p, sp.min_p, pen_on,
9937 );
9938 dctx.graph_s = None;
9939 dctx.s_key = None;
9940 dctx.q_slots.clear();
9941 dctx.keeper_s.clear();
9942 }
9943 // SKEY PROBE (MEMRA_SKEY_PROBE=1): the burst-entry facts the reachability question turns
9944 // on — is this request sampled, is it in the pure-temp regime the sampled graph is only
9945 // legal in, and is a graph PARKED from an earlier request of the same session? The launch
9946 // arms below print which chain actually ran, so the probe never restates the condition.
9947 if skey_probe() {
9948 eprintln!(
9949 "[skey] burst sampled={} pure_temp={} temp={} top_k={} top_p={} min_p={} \
9950 pen_on={} k={} graph_draft={} graph_s_parked={} s_key_parked={:?}",
9951 sampled as u8,
9952 pure_temp as u8,
9953 sp_temp,
9954 sp.top_k,
9955 sp.top_p,
9956 sp.min_p,
9957 pen_on as u8,
9958 k,
9959 graph_draft as u8,
9960 dctx.graph_s.is_some() as u8,
9961 dctx.s_key,
9962 );
9963 }
9964 let t_cap = t_ent.elapsed();
9965 // PERSISTENT DRAFT KV: fill the MTP block's K/V for every prompt position from the exact
9966 // trunk hiddens collected during prime — ONE batched K/V-only pass (overwrites any
9967 // capture-warmup garbage; capture left len at 0). last_token (the init feed) needs no
9968 // fill: the first chain step processes it and appends its entry at slot prompt.len().
9969 if let Some(ph) = &prompt_h {
9970 // SESSION: rows [0..base) are the previous turns' exact fills (refresh overwrote them
9971 // with true verify hiddens) — truncate any draft overhang, fill ONLY the suffix at
9972 // global positions [base..base+tp). Fresh call: base==0, identical to before.
9973 scratch.set_len(e, base)?;
9974 // CHUNKED FILL (long-ctx OOM fix, 2026-07-05): mtp_kv_fill's transients scale with its
9975 // T (concat = T*2*n_embd*4B — 1.5GB at 40k) and its concat loop is 2*T launches. The
9976 // fill is a pure sequential append, so chunking is exact: each chunk appends its rows
9977 // at pos0=base+start with the identical per-row math. Same knob as the trunk prime.
9978 let tp = prompt.len();
9979 let fill_chunk: usize = if crate::cache::swa_ring_on() {
9980 crate::hybrid_forward::prime_chunk_tokens(tp, self.layers.len())
9981 } else {
9982 // Preserve the flag-OFF schedule byte-for-byte, including the legacy zero value
9983 // meaning one monolithic fill.
9984 std::env::var("MEMRA_PRIME_CHUNK")
9985 .ok()
9986 .and_then(|v| v.parse().ok())
9987 .unwrap_or(4096)
9988 };
9989 let fill_chunk = if fill_chunk == 0 { tp } else { fill_chunk };
9990 let mut start = 0usize;
9991 while start < tp {
9992 let end = (start + fill_chunk).min(tp);
9993 let tc = end - start;
9994 {
9995 // PREDECESSOR pairing: row i gets h[i-1]; global row 0 a zeros row (the
9996 // reference engine's initial pending-h is zeroed too); a session turn's row 0
9997 // gets the PREVIOUS turn's last committed hidden (sess.last_h). Per chunk:
9998 // rows start..end read h[start-1..end-1] — one dtod into a chunk buffer.
9999 let mut phs = e.zeros(tc * n_embd)?;
10000 let (src_lo, dst_off) = if start == 0 {
10001 (0, n_embd)
10002 } else {
10003 ((start - 1) * n_embd, 0)
10004 };
10005 let n_copy = if start == 0 {
10006 (tc - 1) * n_embd
10007 } else {
10008 tc * n_embd
10009 };
10010 if start == 0 {
10011 if let Some((_, lh, _, _, _)) = sess_tail.as_ref() {
10012 if let Some(lh) = lh.as_ref() {
10013 e.copy_into(&mut phs, 0, lh, n_embd)?;
10014 }
10015 }
10016 }
10017 if n_copy > 0 {
10018 e.copy_view_into(
10019 &mut phs,
10020 dst_off,
10021 &ph.slice(src_lo..src_lo + n_copy),
10022 n_copy,
10023 )?;
10024 }
10025 self.mtp_kv_fill(
10026 e,
10027 mtp,
10028 &prompt[start..end],
10029 &phs,
10030 base + start,
10031 &mut *scratch,
10032 embd_dev,
10033 )?;
10034 }
10035 start = end;
10036 }
10037 }
10038 // MEMRA_PROFILE_SPEC=2: profiler capture starts HERE — after the prime, so an
10039 // `nsys -c cudaProfilerApi` capture contains ONLY the round loop (draft/verify/commit).
10040 // (=1 brackets the whole call in run_spec.rs, prime included.)
10041 if std::env::var("MEMRA_PROFILE_SPEC").as_deref() == Ok("2") {
10042 unsafe extern "C" {
10043 fn cudaProfilerStart() -> i32;
10044 }
10045 unsafe {
10046 cudaProfilerStart();
10047 }
10048 }
10049 // ROUND-STREAM stage (c) 4 (MEMRA_SPEC_STREAM=1, experimental): pre-issued M-round
10050 // bursts with ZERO per-round host readbacks — the accept/seed/rollback/ring kernels
10051 // consume each other's device outputs; the host drains the ring every M rounds. v1
10052 // constraints: greedy, !spec_replay, single-shot, batched-linear layers, no refresh
10053 // fills (acceptance effect A/B-arbitrated), enters from round 1 (pending guaranteed).
10054 // NOTE: not gated on the caller's graph_draft (its trunk_dense conjunct turns the 35B
10055 // MoE off) — the stream capture encloses ONLY the dense MTP head; the head-dense /
10056 // full-prec / k gates are re-derived here and a failed capture degrades to stream-off.
10057 let stream_on = crate::spec::spec_stream()
10058 && !sampled
10059 && !spec_replay
10060 && constraint.is_none()
10061 && !session_mode
10062 && embd_gpu.is_some()
10063 && !crate::model::full_prec_enabled()
10064 && k + 2 < 96;
10065 let mut stream_graph: Option<cudarc::driver::CudaGraph> = None;
10066 let mut g_tokp2k = e.alloc_u32_zeroed(2 * k.max(1))?;
10067 if stream_on {
10068 let cap = e.capture_graph(|e| {
10069 for j in 0..k.max(1) {
10070 self.mtp_head_forward_cap(
10071 e,
10072 mtp,
10073 &mut dctx.g_tok,
10074 &mut dctx.g_pos,
10075 &mut dctx.g_seed,
10076 &mut dctx.g_p,
10077 &mut *scratch,
10078 true,
10079 true,
10080 embd_gpu.expect("round stream requires resident embedding"),
10081 embd_qt,
10082 embd_rb,
10083 d_vocab,
10084 None,
10085 Some((&mut g_tokp2k, j, d2t_dev.as_ref())),
10086 None, // round-stream requires constraint.is_none() (see stream_on)
10087 )?;
10088 }
10089 Ok(())
10090 });
10091 match cap {
10092 Ok(g) => {
10093 scratch.set_len(e, 0)?;
10094 stream_graph = Some(g);
10095 }
10096 Err(err) => {
10097 scratch.set_len(e, 0)?;
10098 if debug_spec {
10099 eprintln!("[spec] stream-graph capture failed ({err}); stream off");
10100 }
10101 }
10102 }
10103 }
10104 let stream_active = stream_on && stream_graph.is_some();
10105 if debug_spec {
10106 eprintln!(
10107 "[spec] stream_on={stream_on} env={} samp={sampled} dg={} captured={} active={stream_active} session={session_mode} replay={spec_replay}",
10108 crate::spec::spec_stream(),
10109 dctx.graph.is_some(),
10110 stream_graph.is_some()
10111 );
10112 }
10113 let t_v_s = k + 1;
10114 // ROUND-STREAM buffers + ptr tables now live in the model-generic round_stream
10115 // module (extracted 2026-07-12; the gemma burst reuses them).
10116 let sb = crate::round_stream::StreamBufs::new(e, k, crate::spec::spec_stream_m())?;
10117 let crate::round_stream::StreamBufs {
10118 mut vtok_d,
10119 mut brk_d,
10120 mut pend_d,
10121 last_pred_d,
10122 mut pos_ctr,
10123 mut pos_start_d,
10124 mut ring_d,
10125 acc_d: mut stream_acc,
10126 m_rounds,
10127 k: _,
10128 } = sb;
10129 let stream_ptrs: Option<CudaSlice<u64>> = if stream_active {
10130 Some(crate::round_stream::kv_len_ptr_table(
10131 e,
10132 cache,
10133 Some(&pos_ctr),
10134 )?)
10135 } else {
10136 None
10137 };
10138
10139 let t_fill = t_ent.elapsed();
10140 let mut round = 0usize;
10141 // ADAPTIVE DRAFT LENGTH (MEMRA_SPEC_ADAPT=1, opt-in — the gemma_spec accepted-run law,
10142 // ported 2026-08-01): next round's draft depth = last round's accepted run + 1, clamped
10143 // to [floor(pos), k_cap] — a miss shrinks the next draft to the miss point + 1,
10144 // full-accept streaks re-deepen one step per round. NOT the 2026-07-07 acceptance-EMA
10145 // (that arm measured an HONEST LOSS to static per-class optima — 115.0/85.8/73.4 vs
10146 // 121.6/92.7/75.6, EMA lag — and was removed 2026-07-08; rig5090.jsonl has the record).
10147 // The gemma law has no lag class: it reacts within one round, and was worth +7-20% on
10148 // the gemma cells at unchanged exactness (2026-07-10 flip; floor sweep 2026-07-25;
10149 // position key 2026-07-26). Signal = n_acc from the round's EXISTING accept readback —
10150 // zero new syncs; the draft graph is a SINGLE-STEP capture replayed per drafted token,
10151 // so a per-round depth needs no re-capture (unlike gemma's whole-chain graphs). qwen's
10152 // in-round p-min cut already shortens chains mid-round, so gemma's one-round-late p-min
10153 // fold into kc is unnecessary here — the accepted-run law sees the cut via n_acc.
10154 // Exactness is the verify's job at ANY depth (same contract as p-min variable rounds).
10155 // DEFAULT OFF on the qwen path until its cells gate a flip (gemma's is default-on).
10156 // MEASURED 2026-08-01 (H100 GPU-3, interleaved x3, NGEN=256, same-invocation plain
10157 // denominators; research/qwen-adaptive-k-20260801/): REFUTED on the tuned qwen configs.
10158 // q27 K=3+HPOST+PMIN=0.3: short +0.8% (noise; law ~idles, len_hist identical), board
10159 // -1.9%, agentic -0.5%; board PMIN=0 -2.1% (not p-min shadowing — the law itself);
10160 // floor=1 -2.8% (gemma's floor-collapse, reproduced). q35 K=2 board: -6.4% (52/136
10161 // rounds shrink to depth 1; no depth to reclaim at K=2). The gemma direction DOES
10162 // appear at untuned depth-K — q27 K=6 floor=4 +1.5% over fixed K=6 — but stays -3.7%
10163 // below fixed K=3: same verdict class as the retired EMA arm (honest loss to static
10164 // per-class optima). Acceptance-rate rises under the law while tokens/round falls —
10165 // it buys accept-% by adding rounds, and a round's fixed draft+verify cost wins.
10166 // K=1..8 self-consistency PASS both models with the law ON (exactness held).
10167 let adapt = std::env::var("MEMRA_SPEC_ADAPT").as_deref() == Ok("1");
10168 // floor: per-model default keyed on n_embd (gemma's tiering — models with an expensive
10169 // verify keep deep drafts after a miss); MEMRA_SPEC_ADAPT_FLOOR pins it everywhere.
10170 let adapt_floor_env: Option<usize> = std::env::var("MEMRA_SPEC_ADAPT_FLOOR")
10171 .ok()
10172 .and_then(|v| v.parse().ok());
10173 let adapt_floor_default: usize = if self.cfg.n_embd as usize >= 3500 {
10174 4
10175 } else if self.cfg.n_embd as usize >= 2500 {
10176 2
10177 } else {
10178 1
10179 };
10180 let adapt_floor: usize = adapt_floor_env.unwrap_or(adapt_floor_default);
10181 // position key: past floor_ctx a HIGH floor (>=4) relaxes to 1 — forced-deep drafts
10182 // turn net-negative at depth (gemma 31B d1736 evidence); MEMRA_SPEC_FLOOR_CTX moves
10183 // the boundary, an explicit MEMRA_SPEC_ADAPT_FLOOR pins the floor everywhere.
10184 let floor_ctx: usize = std::env::var("MEMRA_SPEC_FLOOR_CTX")
10185 .ok()
10186 .and_then(|v| v.parse().ok())
10187 .unwrap_or(1024);
10188 let floor_at = |pos: usize| -> usize {
10189 if adapt_floor_env.is_some() || pos < floor_ctx {
10190 adapt_floor
10191 } else if adapt_floor >= 4 {
10192 1
10193 } else {
10194 adapt_floor
10195 }
10196 };
10197 // cap: MEMRA_SPEC_CAPMAX (gemma semantics, default 7). Binds only under adapt — the
10198 // fixed-K default path is untouched by this whole block.
10199 let cap_max: usize = std::env::var("MEMRA_SPEC_CAPMAX")
10200 .ok()
10201 .and_then(|v| v.parse().ok())
10202 .unwrap_or(7);
10203 let k_cap = k.min(cap_max).max(1);
10204 let mut kc = k_cap;
10205 let mut opti_fork: Option<OptiForkState> = None;
10206 let mut fork_snapshot: Option<crate::cache::CacheSnapshot> = None;
10207 if fork_mode != OptiForkGateMode::Disabled {
10208 let fence = crate::pp::pp_cuts(self.layers.len());
10209 let refusal = if !session_mode {
10210 Some("not-session")
10211 } else if k != 1 || adapt {
10212 Some("requires-fixed-k1")
10213 } else if sampled || constraint.is_some() || spec_replay {
10214 Some("sampled-constrained-or-replay")
10215 } else if pipe.is_some() {
10216 Some("two-session-pipeline")
10217 } else if !spec_devacc() {
10218 Some("requires-device-accept")
10219 } else if stream_active || crate::spec::spec_stream() {
10220 Some("round-stream")
10221 } else if crate::cache::swa_ring_on() || cache.has_swa_ring() {
10222 Some("swa-ring")
10223 } else if crate::pp::pp_host_bounce_active() {
10224 Some("host-bounce")
10225 } else if fork_mode == OptiForkGateMode::Controller
10226 && cache.recur.iter().any(Option::is_some)
10227 {
10228 Some("controller-requires-zero-recurrent-state")
10229 } else if fence.as_ref().is_none_or(|f| f.len() != 3) {
10230 Some("requires-pp2")
10231 } else {
10232 None
10233 };
10234 if let Some(reason) = refusal {
10235 OPTI_FORK_REFUSALS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10236 eprintln!("[opti-fork] refused reason={reason}");
10237 } else {
10238 let fence = fence.expect("validated PP-2 fence");
10239 let rt = crate::pp::PpNRt::get(e)?;
10240 let primary_stage0 = rt.engine(0, e).ctx().ordinal() == e.ctx().ordinal();
10241 let primary_stage1 = rt.engine(1, e).ctx().ordinal() == e.ctx().ordinal();
10242 let primary_supported =
10243 primary_stage0 || (fork_mode == OptiForkGateMode::Controller && primary_stage1);
10244 if !rt.cross_device() || !primary_supported {
10245 OPTI_FORK_REFUSALS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10246 eprintln!("[opti-fork] refused reason=requires-supported-primary-cross-device");
10247 } else {
10248 // Both recurrent snapshots and both seed generations are allocated before
10249 // the first fork, each through its owning PP stage. Allocation failure
10250 // therefore happens before any optimistic state mutation can occur.
10251 let current_snapshot = opti_snapshot_stage_owned(e, cache, rt, &fence)?;
10252 let alternate_snapshot = opti_snapshot_stage_owned(e, cache, rt, &fence)?;
10253 let fork = OptiForkState::new(
10254 e,
10255 cache,
10256 fork_mode,
10257 alternate_snapshot,
10258 &h_seed_buf,
10259 &fill_prev,
10260 rt,
10261 fence[1],
10262 self.layers.len(),
10263 )?;
10264 eprintln!(
10265 "[opti-fork] armed mode={fork_mode:?} snapshots=2 seeds=2 split={} \
10266 payload_dev0={} payload_dev1={} q_threshold={:.3}",
10267 fence[1],
10268 fork.logical_payload_bytes[0],
10269 fork.logical_payload_bytes[1],
10270 fork.controller.map_or(0.0, |policy| policy.threshold),
10271 );
10272 fork_snapshot = Some(current_snapshot);
10273 opti_fork = Some(fork);
10274 }
10275 }
10276 }
10277 // Persistent snapshot buffers are allocated once and refreshed in place. The fork arm
10278 // uses stage-owned snapshots; refused/disabled arms retain the existing generic helper.
10279 let mut snap = match fork_snapshot {
10280 Some(snapshot) => snapshot,
10281 None => cache.snapshot(e)?,
10282 };
10283 let mut carried_opti: Option<OptiControllerTicket> = None;
10284 // ROUND-STREAM stage (b) 3a: device table of per-layer kvl.len_d pointers (stable — the
10285 // cache never reallocates len_d; see cache.rs "stable pointer" note). 0 = no KV layer.
10286 let kv_len_ptrs: Option<CudaSlice<u64>> = if spec_devacc() && !spec_replay {
10287 Some(crate::round_stream::kv_len_ptr_table(e, cache, None)?)
10288 } else {
10289 None
10290 };
10291 // BONUS FOLD (2026-07-04): after a FULL accept the bonus token is NOT committed with a
10292 // separate T=1 trunk pass (a full weight read per round). It stays PENDING and rides as
10293 // column 0 of the NEXT round's verify batch. Under predecessor pairing the next chain
10294 // seeds from the bonus's predecessor's TRUE verify hidden (free — no extra
10295 // pass of any kind). Verify still
10296 // checks every emitted token against the target -> exactness holds by construction; only
10297 // DRAFT QUALITY can shift, which the acceptance numbers arbitrate.
10298 // bonus emitted but not yet committed to cache. A carried pending (see SpecSession::
10299 // pending_tok) enters round 0 directly — the burst boundary becomes a plain round edge.
10300 let mut pending: Option<u32> = carried_pending;
10301 // MEMRA_SPEC_PHASE=1: per-round wall decomposition (draft / verify / accept+commit) —
10302 // no tracing, no extra syncs (each phase is naturally sync-bounded: draft readbacks,
10303 // the verify accept readback). Printed once at loop end via spec-stats.
10304 let anatomy_on = std::env::var("MEMRA_SPEC_PP_ANATOMY").as_deref() == Ok("1");
10305 let phase_on = anatomy_on || std::env::var("MEMRA_SPEC_PHASE").as_deref() == Ok("1");
10306 // DRAFT-MASK receipt (lane/draft-mask): speculative-clone wall + rounds, printed with
10307 // spec-stats. The clone is the one cost the design adds per round — measured, not assumed.
10308 let (mut dm_clone_ns, mut dm_rounds) = (0u128, 0usize);
10309 // grammar-truncation counters: how many rounds the verify-side cut fired and how many
10310 // already-verified tokens it threw away. THIS is the quantity draft masking targets.
10311 let (mut dm_cuts, mut dm_cut_tokens) = (0usize, 0usize);
10312 let (mut ph_draft, mut ph_verify, mut ph_rest) = (0f64, 0f64, 0f64);
10313 let mut ph_wait = 0f64;
10314 let mut ph_commit = 0f64;
10315 let mut ph_t = std::time::Instant::now();
10316 let mut ph_mark = |acc: &mut f64, on: bool| {
10317 if on {
10318 let now = std::time::Instant::now();
10319 *acc += (now - ph_t).as_secs_f64();
10320 ph_t = now;
10321 }
10322 };
10323 if let Some(p) = pipe {
10324 p.setup_end();
10325 }
10326 while keep_going && out.len() < max_new {
10327 // ROUND-STREAM BURST: from round 1 (pending guaranteed by every non-replay arm),
10328 // issue M rounds with zero readbacks, then drain the ring + reconcile mirrors.
10329 if let (true, Some(sg), Some(ptrs)) = (
10330 stream_active && round >= 1 && pending.is_some(),
10331 &stream_graph,
10332 &stream_ptrs,
10333 ) {
10334 if debug_spec {
10335 static ONCE: std::sync::Once = std::sync::Once::new();
10336 ONCE.call_once(|| {
10337 eprintln!("[memra] ROUND-STREAM burst engaged (M={m_rounds} k={k})")
10338 });
10339 }
10340 e.set_i32_one(&mut pos_ctr, cache.pos as i32)?;
10341 e.set_u32_one(&mut pend_d, pending.unwrap())?;
10342 e.set_u32_one(&mut ring_d, 0)?; // ring count = 0 (writes element 0)
10343 for _mi in 0..m_rounds {
10344 e.i32_copy_add(&pos_ctr, &mut pos_start_d, 0)?;
10345 cache.snapshot_into(e, &mut snap)?; // device D2Ds, stream-ordered
10346 e.i32_copy_add(&pos_ctr, &mut scratch.kv.len_d, 0)?; // draft-KV rollback
10347 e.i32_copy_add(&pos_ctr, &mut dctx.g_pos, 1)?; // rope pos = pos + base
10348 e.u32_copy(&pend_d, &mut dctx.g_tok)?;
10349 e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
10350 sg.launch()?;
10351 e.spec_assemble_verify(
10352 &g_tokp2k,
10353 &pend_d,
10354 d2t_dev.as_ref(),
10355 &mut vtok_d,
10356 &mut brk_d,
10357 p_min,
10358 k,
10359 pmin0,
10360 )?;
10361 let mut ck = VerifyCkpt::new(self.layers.len());
10362 let dummy = vec![0u32; t_v_s];
10363 let (tl_d, vx) = self.decode_step_t_core_stream(
10364 e,
10365 &dummy,
10366 0,
10367 &mut *cache,
10368 embd_dev,
10369 Some(&mut ck),
10370 Some((&vtok_d, &pos_ctr)),
10371 None,
10372 None,
10373 None,
10374 )?;
10375 for j in 0..t_v_s {
10376 e.argmax_token_device_col(&tl_d, j, n_vocab, &mut preds_d, j)?;
10377 }
10378 e.spec_accept_greedy_dc(
10379 &preds_d,
10380 &vtok_d,
10381 &last_pred_d,
10382 &brk_d,
10383 &mut stream_acc,
10384 )?;
10385 e.spec_seed_gather(&vx, &fill_prev, &stream_acc, &mut h_seed_buf, 1, n_embd)?;
10386 e.copy_into(&mut fill_prev, 0, &h_seed_buf, n_embd)?;
10387 self.commit_verified_prefix_stream(
10388 e,
10389 &mut *cache,
10390 &snap,
10391 &ck,
10392 &stream_acc,
10393 1,
10394 t_v_s,
10395 )?;
10396 e.spec_rollback_stream(
10397 ptrs,
10398 &pos_start_d,
10399 &stream_acc,
10400 1,
10401 self.layers.len() + 1,
10402 )?;
10403 e.spec_ring_commit(&vtok_d, &stream_acc, &brk_d, &mut ring_d, &mut pend_d)?;
10404 }
10405 e.stream().synchronize()?;
10406 let ring_h = e.dtoh_u32(&ring_d)?;
10407 let cnt = ring_h[0] as usize;
10408 for i in 0..cnt {
10409 if out.len() < max_new {
10410 out.push(ring_h[1 + i]);
10411 }
10412 }
10413 let pos_h = e.dtoh_i32(&pos_ctr)?[0] as usize;
10414 for il in 0..self.layers.len() {
10415 if let Some(kvl) = cache.kv[il].as_mut() {
10416 kvl.len = pos_h;
10417 }
10418 }
10419 cache.pos = pos_h;
10420 scratch.kv.len = pos_h;
10421 pending = Some(ring_h[cnt]); // last drained token = the live bonus
10422 last_token = ring_h[cnt];
10423 total_drafted += k * m_rounds; // upper bound (p-min breaks uncounted)
10424 total_accepted += cnt.saturating_sub(m_rounds);
10425 if let Some(t) = sess_telem {
10426 // totals only — the burst's per-round accept counts stayed on device
10427 // (that is the point of the round-stream arm). pos_* untouched.
10428 t.record_totals(m_rounds, k * m_rounds, cnt.saturating_sub(m_rounds));
10429 }
10430 round += m_rounds;
10431 // sse-cadence: the drained ring is committed — flush it at burst-drain cadence.
10432 keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
10433 continue;
10434 }
10435 let pipe_draft = match pipe {
10436 Some(p) => Some(p.draft_begin(round)?),
10437 None => None,
10438 };
10439 let pos = cache.pos; // #tokens committed (EXCLUDES a pending bonus)
10440 let mut current_opti = carried_opti.take();
10441 let mut fork_generation = if current_opti.is_none() && pending.is_some() {
10442 match opti_fork.as_mut() {
10443 Some(fork) if fork.mode.is_forced() => Some(fork.reserve(&mut snap)?),
10444 None => None,
10445 Some(_) => None,
10446 }
10447 } else {
10448 None
10449 };
10450 if current_opti.is_none() {
10451 if let Some(fork) = opti_fork.as_ref() {
10452 opti_snapshot_stage_owned_into(e, cache, fork.rt, &fork.fence, &mut snap)?;
10453 } else {
10454 cache.snapshot_into(e, &mut snap)?;
10455 }
10456 } else if snap.pos != pos {
10457 return Err(format!(
10458 "optipipe carried snapshot pos {} != current pos {pos}",
10459 snap.pos
10460 )
10461 .into());
10462 } // §C: snapshot BEFORE draft+verify (already retained for a carried successor)
10463 ph_mark(&mut ph_rest, phase_on);
10464
10465 // --- 1. DRAFT k tokens with the NextN head (autoregressive, T=1 each) ---
10466 // p-min semantics (both paths): stop the chain early when the head's confidence in
10467 // its own pick drops below p_min — the just-drafted token is DISCARDED, but its
10468 // scratch append stands (identical to the eager chain's ordering). j==0 always drafts.
10469 let base0 = if pending.is_some() { 1usize } else { 0usize };
10470 // fixed draft length by default; MEMRA_SPEC_ADAPT=1 drafts at last round's
10471 // accepted run + 1 (the gemma law — see the setup block above the loop).
10472 let k_this = if adapt { kc } else { k };
10473 let mut draft: Vec<u32> = Vec::with_capacity(k);
10474 let mut draft_idx: Vec<u32> = Vec::with_capacity(k); // trimmed-vocab ids (== draft when untrimmed)
10475 let mut controller_draft_prob: Option<f32> = None;
10476 let mut controller_eager_state: Option<(u32, CudaSlice<f32>)> = None;
10477 if let Some(ticket) = current_opti.as_mut() {
10478 let carried_pending = pending.ok_or("optipipe carried successor lost pending")?;
10479 if ticket.verify_tokens[0] != carried_pending {
10480 return Err(format!(
10481 "optipipe carried pending mismatch: ticket={} live={carried_pending}",
10482 ticket.verify_tokens[0],
10483 )
10484 .into());
10485 }
10486 draft.push(ticket.verify_tokens[1]);
10487 controller_draft_prob = Some(ticket.draft_prob);
10488 controller_eager_state = ticket
10489 .take_eager_seed()
10490 .map(|seed| (ticket.verify_tokens[1], seed));
10491 } else {
10492 // Round-start draft-KV sync (BOTH paths). Persistent: truncate/align to the committed
10493 // history — slots 0..P hold entries for the tokens before last_token@P (P = pos +
10494 // base0 - 1); this single set_len IS the draft-side rollback (drops last round's
10495 // rejected drafts and p-min extras via the len mechanism).
10496 scratch.set_len(e, pos + base0 - 1)?;
10497 if pen_on {
10498 // PEN_WINDOW_MAX also bounds the per-round upload and the O(n_hist^2)
10499 // device dedup: `penalty_last_n` is usize::MAX for any serve request with
10500 // a penalty, so without the cap this grew with the whole session.
10501 let win = sp.penalty_last_n.min(PEN_WINDOW_MAX);
10502 let w0 = pen_hist.len().saturating_sub(win);
10503 pen_hist_d = Some(e.htod_u32_v(&pen_hist[w0..])?);
10504 }
10505 if sampled {
10506 draft_logits.clear();
10507 draft_stats.clear();
10508 }
10509 // DRAFT-SIDE GRAMMAR MASK: clone the committed grammar state ONCE per round; each
10510 // position's mask is computed on that clone and advanced by the PROPOSED token. The
10511 // real state moves only on emission (verify's job), so the emitted stream is
10512 // unchanged — the mask only removes tokens the verify would have truncated anyway.
10513 let mut dmask_live = dmask_on;
10514 if dmask_live {
10515 let t_c = std::time::Instant::now();
10516 constraint
10517 .as_deref_mut()
10518 .unwrap()
10519 .draft_begin()
10520 .map_err(|e2| format!("constraint: {e2}"))?;
10521 dm_clone_ns += t_c.elapsed().as_nanos();
10522 dm_rounds += 1;
10523 }
10524 if let (false, Some(gr)) = (sampled || pen_on, &dctx.graph) {
10525 // GRAPH DRAFT: one dispatch per drafted token. The chain feeds itself on-device
10526 // (in-graph argmax -> tok_d -> next replay's embed; h_nextn -> h_seed_d; pos_d
10527 // inc'd in-graph); the host only reads 4B token (+4B p) and decides the break.
10528 e.set_i32_one(&mut dctx.g_pos, (pos + base0) as i32)?;
10529 e.set_u32_one(&mut dctx.g_tok, last_token)?;
10530 e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
10531 for j in 0..k_this {
10532 // per-position mask upload (contents only — the graph's baked pointer is
10533 // dctx.g_dmask). All-ones once masking goes dead mid-chain, so the captured
10534 // mask node degrades to a no-op ban instead of needing a second graph.
10535 if dmask_live
10536 && !upload_draft_mask(
10537 e,
10538 constraint.as_deref_mut().unwrap(),
10539 &mut dctx.g_dmask,
10540 mtp.d2t.as_ref(),
10541 d_vocab,
10542 dmask_words,
10543 )?
10544 {
10545 // no draft-vocab row is grammar-legal here (a trimmed FR-Spec head can
10546 // genuinely miss the legal set): neutralize the captured mask node and
10547 // finish the chain UNMASKED — exactly pre-lane behaviour, never worse.
10548 e.htod_u32_into(&mut dctx.g_dmask, &vec![u32::MAX; dmask_words])?;
10549 dmask_live = false;
10550 }
10551 gr.launch()?;
10552 scratch.kv.len += 1; // host mirror (len_d advanced in-graph)
10553 let idx = e.dtoh_u32_one(&dctx.g_tok)?;
10554 // #87 SENTINEL TRAP: an all-NaN head-logits row leaves the device argmax's
10555 // init sentinel (0x7FFFFFFF) in g_tok — feeding it onward dereferences
10556 // embed_row(sentinel) = table + ~4.6TB (never mapped) inside the NEXT graph
10557 // replay's embed node, and the MMU fault kills the CUDA context for the
10558 // whole process (research/pp2spec-crash-20260807: 3 coredumps, byte-exact
10559 // VA arithmetic). Refuse loudly instead; the diagnostics name the first-NaN
10560 // buffer (g_seed = the verify-side handoff vs head-side compute).
10561 if (idx as usize) >= d_vocab {
10562 // g_seed is SELF-FED (the replay writes h_nextn back into it), so it
10563 // reads as the head's OUTPUT at j; h_seed_buf is the round's INPUT
10564 // seed, untouched since the round-start copy — the pair discriminates
10565 // "seed arrived poisoned" from "head forward produced NaN".
10566 let seed_h = e.dtoh(&dctx.g_seed)?;
10567 let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
10568 let in_h = e.dtoh(&h_seed_buf)?;
10569 let in_nan = in_h.iter().filter(|v| v.is_nan()).count();
10570 return Err(format!(
10571 "draft(graph) argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab} at \
10572 round {round} j={j} pos={pos}: head-out NaN {seed_nan}/{n_embd}, \
10573 round-input-seed NaN {in_nan}/{n_embd} — refusing to dereference \
10574 the embed row (#87 trap)"
10575 )
10576 .into());
10577 }
10578 // trimmed draft vocab -> target token id (identity when no d2t map)
10579 let d = match &mtp.d2t {
10580 Some(map) => map[idx as usize],
10581 None => idx,
10582 };
10583 let draft_p = if p_min > 0.0
10584 || opti_fork
10585 .as_ref()
10586 .is_some_and(|fork| fork.controller.is_some())
10587 {
10588 Some(e.dtoh(&dctx.g_p)?[0])
10589 } else {
10590 None
10591 };
10592 if j == 0 {
10593 controller_draft_prob = draft_p;
10594 }
10595 if let Some(p) = draft_p.filter(|_| p_min > 0.0) {
10596 if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
10597 break;
10598 }
10599 }
10600 draft.push(d);
10601 // with a trimmed head the NEXT embed must read the TARGET id, not the draft
10602 // index the argmax wrote — patch the persistent token buffer (4B htod).
10603 if d != idx {
10604 e.set_u32_one(&mut dctx.g_tok, d)?;
10605 }
10606 // advance the SPECULATIVE state with the proposal; a dead chain drops to
10607 // unmasked drafting for the remaining positions (verify still arbitrates).
10608 // speculative advance; a chain the grammar can no longer follow (EOS
10609 // proposed) ends here. The captured mask node always runs, so a dead chain
10610 // leaves the buffer NEUTRAL (all-ones = ban nothing) before it exits.
10611 if dmask_live
10612 && !constraint
10613 .as_deref_mut()
10614 .unwrap()
10615 .draft_advance(d)
10616 .map_err(|e2| format!("constraint: {e2}"))?
10617 {
10618 e.htod_u32_into(&mut dctx.g_dmask, &vec![u32::MAX; dmask_words])?;
10619 break;
10620 }
10621 }
10622 // PURE-TEMP RE-TEST (lane/graph-s-key-exactness-20260819): the sampled graph is
10623 // legal ONLY in the regime it was captured in. The condition used to read
10624 // `(sampled, &dctx.graph_s)` and trusted `s_key` to have dropped anything else —
10625 // which it could not, because the key omitted the filters. Both halves are now
10626 // enforced: the key drops a stale graph, and this site refuses to launch one.
10627 } else if let (true, Some(gr)) = (sampled && pure_temp, &dctx.graph_s) {
10628 if skey_probe() {
10629 eprintln!(
10630 "[skey] chain=graph_s round={round} pure_temp={} top_k={} \
10631 top_p={} min_p={} s_key_parked={:?}",
10632 pure_temp as u8, sp.top_k, sp.top_p, sp.min_p, dctx.s_key,
10633 );
10634 }
10635 // SAMPLED GRAPH DRAFT: one replay per drafted token — head forward + gumbel +
10636 // argmax in ONE dispatch; the host reads 4B token (+4B p), D2Ds q into slot j,
10637 // and decides the break. Event-counter continuity: g_ctr is host-seeded to
10638 // sctr-1 ONCE per round (outside the graph); the in-graph bump runs BEFORE the
10639 // perturb, so replay j consumes counter sctr+j — exactly the eager arm's Philox
10640 // stream. Host sctr advances in lockstep (computed, no readback needed).
10641 e.set_i32_one(&mut dctx.g_pos, (pos + base0) as i32)?;
10642 e.set_u32_one(&mut dctx.g_tok, last_token)?;
10643 e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
10644 e.set_u32_one(&mut dctx.g_ctr, sctr.wrapping_sub(1))?;
10645 for j in 0..k_this {
10646 gr.launch()?;
10647 scratch.kv.len += 1; // host mirror (len_d advanced in-graph)
10648 sctr += 1; // mirrors the in-graph g_ctr bump (eager parity:
10649 // counts the p-min-discarded token too)
10650 // q retention: ONE async D2D of the persistent head-logits buffer into this
10651 // round's slot j (stream-ordered after the replay, before the next one).
10652 e.copy_into(&mut dctx.q_slots[j], 0, &dctx.g_q, d_vocab)?;
10653 let idx = e.dtoh_u32_one(&dctx.g_tok)?;
10654 // #87 SENTINEL TRAP (see the greedy graph arm above).
10655 if (idx as usize) >= d_vocab {
10656 let seed_h = e.dtoh(&dctx.g_seed)?;
10657 let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
10658 return Err(format!(
10659 "draft(graph-sampled) argmax sentinel 0x{idx:08x} >= d_vocab \
10660 {d_vocab} at round {round} j={j} pos={pos}: round-seed NaN \
10661 {seed_nan}/{n_embd} — refusing to dereference the embed row \
10662 (#87 trap)"
10663 )
10664 .into());
10665 }
10666 let d = match &mtp.d2t {
10667 Some(map) => map[idx as usize],
10668 None => idx,
10669 };
10670 draft_idx.push(idx);
10671 if p_min > 0.0 {
10672 let p = e.dtoh(&dctx.g_p)?[0];
10673 if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
10674 break;
10675 }
10676 }
10677 draft.push(d);
10678 // trimmed head: the NEXT embed must read the TARGET id (see the greedy arm).
10679 if d != idx {
10680 e.set_u32_one(&mut dctx.g_tok, d)?;
10681 }
10682 }
10683 // uniform accept path: fill draft_stats per used slot (pure-temp regime — the
10684 // stats degenerate to th=0 / full-Z; one filter_stats launch per slot, tiny).
10685 for j in 0..draft.len().max(draft_idx.len()) {
10686 let rows0 = e.htod_i32(&[0])?;
10687 let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
10688 e.filter_stats(
10689 &dctx.q_slots[j],
10690 d_vocab,
10691 &rows0,
10692 &mut th_d,
10693 &mut z_d,
10694 &mut mx_d,
10695 d_vocab,
10696 1,
10697 sp_temp,
10698 sp.top_k,
10699 sp.top_p,
10700 sp.min_p,
10701 )?;
10702 draft_stats.push((e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0]));
10703 }
10704 } else {
10705 if skey_probe() && sampled {
10706 eprintln!(
10707 "[skey] chain=eager round={round} pure_temp={} top_k={} \
10708 top_p={} min_p={} s_key_parked={:?}",
10709 pure_temp as u8, sp.top_k, sp.top_p, sp.min_p, dctx.s_key,
10710 );
10711 }
10712 // EAGER DRAFT (fallback: MoE head/trunk, huge k, MEMRA_SPEC_NOGRAPH, capture fail).
10713 let mut e_tok = last_token;
10714 let mut d_seed = e.clone_dtod(&h_seed_buf)?;
10715 for j in 0..k_this {
10716 // GPU-ARGMAX DRAFT (2026-07-03): device logits + device argmax + 4-byte token
10717 // read instead of the ~600KB full-vocab dtoh + host argmax per draft token.
10718 let mtp_pos = pos + base0 + j;
10719 // draft-side grammar mask (eager twin of the graph arm's in-graph node).
10720 // A position with no legal draft-vocab row drops to unmasked drafting for
10721 // the rest of the chain (pre-lane behaviour; verify still arbitrates).
10722 if dmask_live {
10723 dmask_live = upload_draft_mask(
10724 e,
10725 constraint.as_deref_mut().unwrap(),
10726 &mut dctx.g_dmask,
10727 mtp.d2t.as_ref(),
10728 d_vocab,
10729 dmask_words,
10730 )?;
10731 }
10732 let (dl_d, h_nextn) = self.mtp_head_forward_dev(
10733 e,
10734 mtp,
10735 e_tok,
10736 &d_seed,
10737 &mut *scratch,
10738 mtp_pos,
10739 embd_dev,
10740 if dmask_live {
10741 Some((&dctx.g_dmask, dmask_words))
10742 } else {
10743 None
10744 },
10745 )?;
10746 let tok_d = if sampled {
10747 // FILTERED Gumbel-max: stats -> masked perturb -> argmax = one draw from
10748 // the filtered softmax (filters off => th=0, exact v1 semantics).
10749 if perturb_buf.is_none() {
10750 perturb_buf = Some(e.zeros(d_vocab.max(n_vocab))?);
10751 }
10752 let mut q_row = e.clone_dtod(&dl_d)?; // retained q (penalized when on)
10753 if pen_on {
10754 let h = pen_hist_d.as_ref().unwrap();
10755 let nh = h.len();
10756 e.penalize_logits(
10757 &mut q_row,
10758 h,
10759 nh,
10760 sp.penalty_repeat,
10761 sp.penalty_freq,
10762 sp.penalty_present,
10763 d_vocab,
10764 )?;
10765 }
10766 let rows0 = e.htod_i32(&[0])?;
10767 let (mut th_d, mut z_d, mut mx_d) =
10768 (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
10769 e.filter_stats(
10770 &q_row, d_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, d_vocab,
10771 1, sp_temp, sp.top_k, sp.top_p, sp.min_p,
10772 )?;
10773 let (th, z, mx) =
10774 (e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0], e.dtoh(&mx_d)?[0]);
10775 let pb = perturb_buf.as_mut().unwrap();
10776 e.gumbel_perturb_filtered(
10777 &q_row, pb, d_vocab, sp_seed, sctr, sp_temp, mx, th,
10778 )?;
10779 sctr += 1;
10780 draft_logits.push(q_row);
10781 draft_stats.push((mx, th, z));
10782 e.argmax_token_device(pb, d_vocab)?
10783 } else {
10784 e.argmax_token_device(&dl_d, d_vocab)?
10785 };
10786 let idx = e.dtoh_u32_one(&tok_d)?;
10787 // #87 SENTINEL TRAP (eager twin — see the graph arm). Extra diagnostics
10788 // here because the eager chain's operands are all readable: dl_d (the head
10789 // logits row) and d_seed (this step's h_seed) name the first-NaN buffer.
10790 if (idx as usize) >= d_vocab {
10791 let dl_h = e.dtoh(&dl_d)?;
10792 let dl_nan = dl_h.iter().filter(|v| v.is_nan()).count();
10793 let seed_h = e.dtoh(&d_seed)?;
10794 let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
10795 return Err(format!(
10796 "draft(eager) argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab} at \
10797 round {round} j={j} pos={pos}: head-logits NaN {dl_nan}/{d_vocab}, \
10798 step-seed NaN {seed_nan}/{n_embd} — refusing to dereference the \
10799 embed row (#87 trap)"
10800 )
10801 .into());
10802 }
10803 let d = match &mtp.d2t {
10804 Some(map) => map[idx as usize],
10805 None => idx,
10806 };
10807 if sampled {
10808 draft_idx.push(idx);
10809 }
10810 let draft_p = if p_min > 0.0
10811 || opti_fork
10812 .as_ref()
10813 .is_some_and(|fork| fork.controller.is_some())
10814 {
10815 let p_d = e.prob_of_token_device(&dl_d, &tok_d, d_vocab)?;
10816 Some(e.dtoh(&p_d)?[0])
10817 } else {
10818 None
10819 };
10820 if j == 0 {
10821 controller_draft_prob = draft_p;
10822 }
10823 if let Some(p) = draft_p.filter(|_| p_min > 0.0) {
10824 if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
10825 break;
10826 }
10827 }
10828 draft.push(d);
10829 e_tok = d;
10830 d_seed = h_nextn;
10831 // speculative advance; a chain the grammar can no longer follow (EOS
10832 // proposed) ends here — the prefix already proposed still rides verify.
10833 if dmask_live
10834 && !constraint
10835 .as_deref_mut()
10836 .unwrap()
10837 .draft_advance(d)
10838 .map_err(|e2| format!("constraint: {e2}"))?
10839 {
10840 break;
10841 }
10842 }
10843 if opti_fork
10844 .as_ref()
10845 .is_some_and(|fork| fork.controller.is_some())
10846 {
10847 controller_eager_state = Some((e_tok, d_seed));
10848 }
10849 }
10850 }
10851 let k_round = draft.len();
10852 if let Some(p) = pipe {
10853 p.draft_end(round);
10854 }
10855 drop(pipe_draft);
10856
10857 ph_mark(&mut ph_draft, phase_on);
10858 // --- 2. VERIFY: one batched target forward. With a pending bonus, it rides as col 0
10859 // (committing its KV/recur inside the SAME weight read); drafts follow. ---
10860 let verify_tokens: Vec<u32> = match pending {
10861 Some(b) => {
10862 let mut v = Vec::with_capacity(k_round + 1);
10863 v.push(b);
10864 v.extend_from_slice(&draft);
10865 v
10866 }
10867 None => draft.clone(),
10868 };
10869 let base = if pending.is_some() { 1 } else { 0 };
10870 // ckpt (REPLAY-FREE partial accept): retain per-layer state-rebuild inputs alongside
10871 // the verify. Pure buffer keep-alives + dtod clones — kernel work is unchanged.
10872 let mut ckpt = if let Some(ticket) = current_opti.as_mut() {
10873 Some(ticket.take_ckpt())
10874 } else if spec_replay {
10875 None
10876 } else {
10877 Some(VerifyCkpt::new(self.layers.len()))
10878 };
10879 let controller_can_probe = base == 1
10880 && k_round == 1
10881 && out.len().saturating_add(2) < max_new
10882 && controller_draft_prob.is_some()
10883 && opti_fork
10884 .as_ref()
10885 .and_then(|fork| fork.controller.as_ref())
10886 .is_some_and(|policy| !policy.breaker_tripped);
10887 let mut successor_attempt: Option<OptiControllerTicket> = None;
10888 let mut rejected_probe: Option<(f32, u32)> = None;
10889 let mut controller_prepared: Option<OptiControllerPrepared> = None;
10890 if controller_can_probe {
10891 // Prepare d2/q and, on admission, d3 before either current verify half is
10892 // issued. N stage 0 can then be followed immediately by N+1 stage 0; once N's
10893 // boundary fires, those dev0 launches overlap N stage 1 on dev1. Preparing on
10894 // the primary stream after N stage 1 would serialize the supposed pipeline.
10895 let eager_pos = scratch.kv.len + 1;
10896 let (optimistic_pending, pending_probability) = self.opti_controller_draft_step(
10897 e,
10898 mtp,
10899 &mut dctx,
10900 &mut *scratch,
10901 d_vocab,
10902 &mut controller_eager_state,
10903 eager_pos,
10904 embd_dev,
10905 )?;
10906 let first_probability = controller_draft_prob
10907 .ok_or("optipipe controller probe lost first-token probability")?;
10908 let q_proxy = first_probability * pending_probability;
10909 OPTI_GATE_CHECKS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10910 OPTI_SHADOW_DRAFT_TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10911 let admitted = opti_fork
10912 .as_ref()
10913 .and_then(|fork| fork.controller.as_ref())
10914 .ok_or("optipipe controller policy disappeared")?
10915 .admit(q_proxy);
10916 if admitted {
10917 OPTI_GATE_ADMITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10918 let eager_pos = scratch.kv.len + 1;
10919 let (optimistic_draft, optimistic_draft_probability) = self
10920 .opti_controller_draft_step(
10921 e,
10922 mtp,
10923 &mut dctx,
10924 &mut *scratch,
10925 d_vocab,
10926 &mut controller_eager_state,
10927 eager_pos,
10928 embd_dev,
10929 )?;
10930 OPTI_SHADOW_DRAFT_TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10931 let eager_seed = controller_eager_state.take().map(|(token, seed)| {
10932 debug_assert_eq!(token, optimistic_draft);
10933 seed
10934 });
10935 controller_prepared = Some(OptiControllerPrepared {
10936 verify_tokens: [optimistic_pending, optimistic_draft],
10937 draft_prob: optimistic_draft_probability,
10938 eager_seed,
10939 q_proxy,
10940 scratch_len: scratch.kv.len,
10941 });
10942 } else {
10943 OPTI_GATE_REJECTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10944 OPTI_WASTED_DRAFT_TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10945 rejected_probe = Some((q_proxy, optimistic_pending));
10946 eprintln!(
10947 "[opti-controller] reject q={q_proxy:.6} threshold={:.3}",
10948 opti_fork
10949 .as_ref()
10950 .and_then(|fork| fork.controller.as_ref())
10951 .expect("controller policy")
10952 .threshold,
10953 );
10954 }
10955 }
10956 let fork_attempt = match fork_generation.take() {
10957 Some(generation) if base == 1 && k_round == 1 => Some(generation),
10958 Some(generation) => {
10959 opti_fork
10960 .as_mut()
10961 .expect("fork generation without fork state")
10962 .retire(generation)?;
10963 None
10964 }
10965 None => None,
10966 };
10967 let (tlogits_d, vx) = if let Some(p) = pipe {
10968 self.decode_step_t_core_pipelined(
10969 e,
10970 &verify_tokens,
10971 pos,
10972 &mut *cache,
10973 embd_dev,
10974 ckpt.as_mut(),
10975 p,
10976 round,
10977 )?
10978 } else if controller_can_probe {
10979 let fence = opti_fork
10980 .as_ref()
10981 .ok_or("optipipe controller probe lost fork state")?
10982 .fence;
10983 let boundary = match current_opti.as_mut() {
10984 Some(ticket) => ticket.take_boundary(),
10985 None => self.verify_stage0_issue(
10986 e,
10987 &verify_tokens,
10988 pos,
10989 &mut *cache,
10990 embd_dev,
10991 ckpt.as_mut(),
10992 None,
10993 &fence,
10994 Some(true),
10995 None,
10996 )?,
10997 };
10998 if let Some(prepared) = controller_prepared.take() {
10999 let generation = {
11000 let fork = opti_fork
11001 .as_mut()
11002 .ok_or("optipipe controller admission lost fork state")?;
11003 let generation = fork.reserve_successor()?;
11004 let rt = fork.rt;
11005 let snapshot_fence = fork.fence;
11006 opti_snapshot_one_stage_owned_into(
11007 e,
11008 cache,
11009 rt,
11010 &snapshot_fence,
11011 0,
11012 fork.successor_snapshot_mut(),
11013 )?;
11014 generation
11015 };
11016 let mut successor_ckpt = VerifyCkpt::new(self.layers.len());
11017 let successor_boundary = self.verify_stage0_issue(
11018 e,
11019 &prepared.verify_tokens,
11020 pos + verify_tokens.len(),
11021 &mut *cache,
11022 embd_dev,
11023 Some(&mut successor_ckpt),
11024 None,
11025 &fence,
11026 Some(false),
11027 None,
11028 )?;
11029 OPTI_FORK_ATTEMPTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
11030 let fork = opti_fork
11031 .as_ref()
11032 .ok_or("optipipe controller ticket lost fork state")?;
11033 successor_attempt = Some(fork.controller_ticket(
11034 generation,
11035 successor_boundary,
11036 successor_ckpt,
11037 prepared.verify_tokens,
11038 prepared.draft_prob,
11039 prepared.eager_seed,
11040 prepared.q_proxy,
11041 prepared.scratch_len,
11042 ));
11043 eprintln!(
11044 "[opti-controller] issue generation={} q={:.6} threshold={:.3} \
11045 verify={:?}",
11046 generation.id,
11047 prepared.q_proxy,
11048 fork.controller.expect("controller policy").threshold,
11049 prepared.verify_tokens,
11050 );
11051 }
11052 let result = self.verify_stage1_finish(
11053 e,
11054 boundary,
11055 &mut *cache,
11056 ckpt.as_mut(),
11057 None,
11058 &fence,
11059 successor_attempt.is_none(),
11060 )?;
11061 if let Some(ticket) = current_opti.as_mut() {
11062 ticket.settle();
11063 }
11064 if successor_attempt.is_some() {
11065 let fork = opti_fork
11066 .as_mut()
11067 .ok_or("optipipe successor snapshot lost fork state")?;
11068 let rt = fork.rt;
11069 let snapshot_fence = fork.fence;
11070 opti_snapshot_one_stage_owned_into(
11071 e,
11072 cache,
11073 rt,
11074 &snapshot_fence,
11075 1,
11076 fork.successor_snapshot_mut(),
11077 )?;
11078 // Publish N only after both independent successor-state queues are complete.
11079 fork.rt.publish_to(1, &e.stream())?;
11080 }
11081 result
11082 } else if let Some(ticket) = current_opti.as_mut() {
11083 let fork = opti_fork
11084 .as_mut()
11085 .ok_or("optipipe carried controller ticket lost fork state")?;
11086 let boundary = ticket.take_boundary();
11087 let result = self.verify_stage1_finish(
11088 e,
11089 boundary,
11090 &mut *cache,
11091 ckpt.as_mut(),
11092 None,
11093 &fork.fence,
11094 true,
11095 )?;
11096 ticket.settle();
11097 result
11098 } else if let Some(generation) = fork_attempt {
11099 let fork = opti_fork
11100 .as_mut()
11101 .expect("fork generation without fork state");
11102 fork.capture_seed(e, generation, &h_seed_buf, &fill_prev, scratch.kv.len)?;
11103 let action = fork.mode.action(generation.id);
11104 let boundary = self.verify_stage0_issue(
11105 e,
11106 &verify_tokens,
11107 pos,
11108 &mut *cache,
11109 embd_dev,
11110 ckpt.as_mut(),
11111 None,
11112 &fork.fence,
11113 Some(true),
11114 None,
11115 )?;
11116 OPTI_FORK_ATTEMPTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
11117 let mut ticket = fork.ticket(generation, boundary);
11118 if action == OptiForkAction::Abort {
11119 return Err(format!(
11120 "optipipe forced abort with generation {} stage0 in flight",
11121 generation.id,
11122 )
11123 .into());
11124 }
11125 fork.reconcile(
11126 e,
11127 &mut *cache,
11128 &mut *scratch,
11129 &snap,
11130 &mut h_seed_buf,
11131 &mut fill_prev,
11132 generation,
11133 action,
11134 verify_tokens[0],
11135 )?;
11136 let result = if action == OptiForkAction::Hit {
11137 let boundary = ticket.take_boundary();
11138 self.verify_stage1_finish(
11139 e,
11140 boundary,
11141 &mut *cache,
11142 ckpt.as_mut(),
11143 None,
11144 &fork.fence,
11145 true,
11146 )?
11147 } else {
11148 // The optimistic boundary slot has no reader. Re-run the unchanged serial
11149 // verify only after E_restart published the restored stage-0 state.
11150 self.decode_step_t_core(
11151 e,
11152 &verify_tokens,
11153 pos,
11154 &mut *cache,
11155 embd_dev,
11156 ckpt.as_mut(),
11157 )?
11158 };
11159 ticket.settle();
11160 debug_assert_eq!(ticket.generation, generation);
11161 fork.retire(generation)?;
11162 result
11163 } else {
11164 self.decode_step_t_core(
11165 e,
11166 &verify_tokens,
11167 pos,
11168 &mut *cache,
11169 embd_dev,
11170 ckpt.as_mut(),
11171 )?
11172 };
11173 let pipe_accept = match pipe {
11174 Some(p) => Some(p.accept_begin(round)?),
11175 None => None,
11176 };
11177
11178 ph_mark(&mut ph_verify, phase_on);
11179 // --- 3. GREEDY ACCEPT (walk prefix, stop at first mismatch) ---
11180 // DEVICE-ARGMAX ACCEPT: argmax every verify column ON DEVICE (same 2-pass kernels +
11181 // smallest-index tie-break as host argmax, argmax_gate-validated) and read back ONE
11182 // [T] u32 — replaces the T x n_vocab f32 dtoh + T host argmaxes per round.
11183 // t_pred[j] = target's greedy prediction for the slot after draft[j-1] (j>=1) or after
11184 // last_token (j==0). With a pending bonus, col 0 IS the prediction after last_token
11185 // (== the bonus), so every index shifts by `base` and last_pred is unused.
11186 let t_v = verify_tokens.len();
11187 let mut preds: Vec<u32> = Vec::new();
11188 if !sampled {
11189 for j in 0..t_v {
11190 e.argmax_token_device_col(&tlogits_d, j, n_vocab, &mut preds_d, j)?;
11191 }
11192 preds = e.dtoh_u32(&preds_d)?; // <- the verify-GPU wait lands here
11193 // #87 SENTINEL TRAP, verify side: a sentinel pred becomes the round's bonus =
11194 // next round's last_token = the next chain's embed lookup. Catch it at the
11195 // source with the column named — an all-NaN VERIFY column implicates the
11196 // stage-split trunk (decode_step_t_core_ppn), not the draft head.
11197 if let Some(bad) = preds[..t_v].iter().position(|&p| (p as usize) >= n_vocab) {
11198 let col = &tlogits_d.slice(bad * n_vocab..(bad + 1) * n_vocab);
11199 let mut probe = e.zeros(n_vocab)?;
11200 e.copy_view_into(&mut probe, 0, col, n_vocab)?;
11201 let col_h = e.dtoh(&probe)?;
11202 let col_nan = col_h.iter().filter(|v| v.is_nan()).count();
11203 return Err(format!(
11204 "verify argmax sentinel 0x{:08x} >= n_vocab {n_vocab} at round {round} \
11205 col {bad}/{t_v} pos={pos}: verify-logits col NaN {col_nan}/{n_vocab} \
11206 — the stage-split verify produced a poisoned column (#87 trap)",
11207 preds[bad]
11208 )
11209 .into());
11210 }
11211 }
11212 ph_mark(&mut ph_wait, phase_on);
11213 let t_pred = |j: usize| -> u32 {
11214 if j == 0 && base == 0 {
11215 last_pred
11216 } else {
11217 // GREEDY-ONLY: `preds` is filled under `if !sampled` above. The debug print
11218 // used to call this from the sampled arm and panicked the worker; it now goes
11219 // through `debug_t_pred0`. Keep the strict index here — in the greedy walk an
11220 // out-of-range pred is a real bug, not something to paper over.
11221 debug_assert!(
11222 !sampled,
11223 "t_pred is greedy-only: `preds` is empty in the sampled arm"
11224 );
11225 preds[base + j - 1]
11226 }
11227 };
11228 let mut devacc_seeded = false;
11229 let mut devacc_acc: Option<CudaSlice<u32>> = None;
11230 let (n_acc, bonus) = if !sampled {
11231 // ROUND-STREAM stage (a) (MEMRA_SPEC_DEVACC=1 opt-in): the walk runs ON DEVICE
11232 // (spec_accept_greedy, verbatim rule) and the host reads back 8B (n_acc, bonus)
11233 // instead of the [T] preds. Same sync count — machinery for stages (b)/(c),
11234 // gated on token identity vs the host walk (the arms below are bit-equal rules).
11235 if crate::spec::spec_devacc() && k_round > 0 && !spec_replay && constraint.is_none()
11236 {
11237 let draft_d = e.htod_u32_v(&draft)?;
11238 let mut acc_out = e.alloc_u32_zeroed(2)?;
11239 e.spec_accept_greedy(
11240 &preds_d,
11241 &draft_d,
11242 last_pred,
11243 base,
11244 k_round,
11245 &mut acc_out,
11246 )?;
11247 devacc_acc = Some(acc_out.clone());
11248 // stage (b): next-round seed gathered ON DEVICE from acc_out before the host
11249 // ever reads n_acc (j=base+n_acc -> vx col j-1; j==0 -> fill_prev). The three
11250 // non-replay commit arms skip their host-offset seed copies (guarded below);
11251 // the legacy spec_replay arm keeps its own rx-based seeding (excluded here).
11252 // NOTE: fill_prev is NOT updated here — the commit arms' TRUE-HIDDEN
11253 // REFRESH reads the OLD fill_prev (predecessor of this round's verify batch);
11254 // the update lands after the arms (devacc_seeded guard below).
11255 e.spec_seed_gather(&vx, &fill_prev, &acc_out, &mut h_seed_buf, base, n_embd)?;
11256 // 3a: KV lens roll back on device (len = saved + base + n_acc, all arms'
11257 // unified rule; full accept rewrites the verify-left value). Host mirrors
11258 // update after the readback; commit_verified_prefix skips its len_d writes.
11259 if let Some(successor) = successor_attempt.as_ref() {
11260 opti_fork
11261 .as_mut()
11262 .ok_or("optipipe successor reconcile lost fork state")?
11263 .queue_actual_reconcile(
11264 e,
11265 &snap,
11266 &acc_out,
11267 successor.verify_tokens[0],
11268 base,
11269 )?;
11270 } else if let Some(ptrs) = &kv_len_ptrs {
11271 let saved: Vec<i32> = (0..self.layers.len())
11272 .map(|il| snap.kv_len[il].map(|v| v as i32).unwrap_or(0))
11273 .collect();
11274 let saved_d = e.htod_i32(&saved)?;
11275 e.spec_rollback_kv(ptrs, &saved_d, &acc_out, base, self.layers.len())?;
11276 }
11277 devacc_seeded = true;
11278 let ab = e.dtoh_u32(&acc_out)?;
11279 (ab[0] as usize, ab[1])
11280 } else {
11281 let mut n_acc = 0usize;
11282 for j in 0..k_round {
11283 if t_pred(j) == draft[j] {
11284 n_acc += 1;
11285 } else {
11286 break;
11287 }
11288 }
11289 // bonus = target's own token at the first non-accepted slot. n_acc in 0..=k; t_pred
11290 // is defined for j in 0..=k (j==0 -> last_logits, j>=1 -> col j-1, last col = k-1).
11291 (n_acc, t_pred(n_acc))
11292 }
11293 } else {
11294 // --- SAMPLED ACCEPT (rejection sampling): u_j < p_j(x_j)/q_j(x_j) walk ---
11295 if col_buf.is_none() {
11296 col_buf = Some(e.zeros(n_vocab)?);
11297 }
11298 // FILTERED p_j: per-verify-col stats (one batched filter_stats call), then the
11299 // filtered gather. j==0&&base==0 reads last_col (its own stats row appended).
11300 let mut pj = vec![0f32; k_round.max(1)];
11301 let mut col_stats: Vec<(f32, f32, f32)> = Vec::new(); // (max, th, z) per verify col used
11302 if k_round > 0 {
11303 let mut ids: Vec<u32> = Vec::new();
11304 let mut rows: Vec<i32> = Vec::new();
11305 for j in 0..k_round {
11306 if j > 0 || base == 1 {
11307 ids.push(draft[j]);
11308 rows.push((base + j) as i32 - 1);
11309 }
11310 }
11311 if !ids.is_empty() {
11312 let nr = rows.len();
11313 // penalties: materialize the used columns into one contiguous penalized
11314 // buffer (rows remapped 0..nr) so stats+gathers see the penalized p.
11315 // penalties: materialize used columns contiguously, penalize all rows in
11316 // one launch, and point stats+gathers at the penalized buffer (rows 0..nr).
11317 let p_rows: Vec<i32> = if pen_on {
11318 (0..nr as i32).collect()
11319 } else {
11320 rows.clone()
11321 };
11322 if pen_on {
11323 if pcol_buf.as_ref().map(|b| b.len()).unwrap_or(0) < nr * n_vocab {
11324 pcol_buf = Some(e.zeros(nr * n_vocab)?);
11325 }
11326 let pc = pcol_buf.as_mut().unwrap();
11327 for (i2, &r) in rows.iter().enumerate() {
11328 let c = r as usize;
11329 e.copy_view_into(
11330 pc,
11331 i2 * n_vocab,
11332 &tlogits_d.slice(c * n_vocab..(c + 1) * n_vocab),
11333 n_vocab,
11334 )?;
11335 }
11336 let h = pen_hist_d.as_ref().unwrap();
11337 let nh = h.len();
11338 e.penalize_logits_rows(
11339 pc,
11340 h,
11341 nh,
11342 sp.penalty_repeat,
11343 sp.penalty_freq,
11344 sp.penalty_present,
11345 n_vocab,
11346 nr,
11347 )?;
11348 }
11349 let p_src: &CudaSlice<f32> = if pen_on {
11350 pcol_buf.as_ref().unwrap()
11351 } else {
11352 &tlogits_d
11353 };
11354 let rowsd = e.htod_i32(&p_rows)?;
11355 let (mut th_d, mut z_d, mut mx_d) =
11356 (e.zeros(nr)?, e.zeros(nr)?, e.zeros(nr)?);
11357 e.filter_stats(
11358 p_src, n_vocab, &rowsd, &mut th_d, &mut z_d, &mut mx_d, n_vocab, nr,
11359 sp_temp, sp.top_k, sp.top_p, sp.min_p,
11360 )?;
11361 let idsd = e.htod_u32_v(&ids)?;
11362 let mut outd = e.zeros(nr)?;
11363 e.softmax_gather_filtered(
11364 p_src, n_vocab, &idsd, &rowsd, &th_d, &z_d, &mut outd, n_vocab, nr,
11365 sp_temp,
11366 )?;
11367 let outv = e.dtoh(&outd)?;
11368 let (thv, zv, mxv) = (e.dtoh(&th_d)?, e.dtoh(&z_d)?, e.dtoh(&mx_d)?);
11369 let mut oi = 0usize;
11370 for j in 0..k_round {
11371 if j > 0 || base == 1 {
11372 pj[j] = outv[oi];
11373 oi += 1;
11374 }
11375 }
11376 col_stats = (0..nr).map(|i| (mxv[i], thv[i], zv[i])).collect();
11377 }
11378 if base == 0 {
11379 let lc: &CudaSlice<f32> = if pen_on {
11380 if col_buf.is_none() {
11381 col_buf = Some(e.zeros(n_vocab)?);
11382 }
11383 let cb = col_buf.as_mut().unwrap();
11384 e.copy_into(
11385 cb,
11386 0,
11387 last_col_logits
11388 .as_ref()
11389 .expect("sampled: last_col_logits unset"),
11390 n_vocab,
11391 )?;
11392 let h = pen_hist_d.as_ref().unwrap();
11393 let nh = h.len();
11394 e.penalize_logits(
11395 cb,
11396 h,
11397 nh,
11398 sp.penalty_repeat,
11399 sp.penalty_freq,
11400 sp.penalty_present,
11401 n_vocab,
11402 )?;
11403 col_buf.as_ref().unwrap()
11404 } else {
11405 last_col_logits
11406 .as_ref()
11407 .expect("sampled: last_col_logits unset")
11408 };
11409 let rows0 = e.htod_i32(&[0])?;
11410 let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
11411 e.filter_stats(
11412 lc, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1,
11413 sp_temp, sp.top_k, sp.top_p, sp.min_p,
11414 )?;
11415 let idsd = e.htod_u32_v(&[draft[0]])?;
11416 let mut outd = e.zeros(1)?;
11417 e.softmax_gather_filtered(
11418 lc, n_vocab, &idsd, &rows0, &th_d, &z_d, &mut outd, n_vocab, 1, sp_temp,
11419 )?;
11420 pj[0] = e.dtoh(&outd)?[0];
11421 last_col_stats =
11422 Some((e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0]));
11423 }
11424 }
11425 // q source: the graph arm retained the head logits in the persistent q_slots;
11426 // the eager arm in per-round draft_logits clones. Same raw-logit values either way.
11427 // FILTERED q_j: stats from draft_stats (eager pushes in-chain; the graph arm
11428 // computes them post-replay — graph engages only filter/penalty-free, so the
11429 // stats degenerate to th=0/full-Z there, keeping ONE accept path).
11430 let q_bufs: &[CudaSlice<f32>] = if dctx.graph_s.is_some() {
11431 &dctx.q_slots
11432 } else {
11433 &draft_logits
11434 };
11435 let mut n_acc = 0usize;
11436 for j in 0..k_round {
11437 let (qmx, qth, qz) = draft_stats[j];
11438 let idsd = e.htod_u32_v(&[draft_idx[j]])?;
11439 let rowsd = e.htod_i32(&[0])?;
11440 let thd = e.htod(&[qth])?;
11441 let zd = e.htod(&[qz])?;
11442 let _ = qmx;
11443 let mut outd = e.zeros(1)?;
11444 e.softmax_gather_filtered(
11445 &q_bufs[j], d_vocab, &idsd, &rowsd, &thd, &zd, &mut outd, d_vocab, 1,
11446 sp_temp,
11447 )?;
11448 let qj = e.dtoh(&outd)?[0];
11449 let u = host_u01(sp_seed, uctr);
11450 uctr += 1;
11451 let accept = (u as f64) * (qj as f64) < pj[j] as f64;
11452 // SKEY PROBE: q == 0 for the token the draft actually proposed is the
11453 // exactness signature (see `skey_probe`). Impossible when the draft was
11454 // drawn from the same filtered distribution the verify reconstructs here;
11455 // `u * 0 < p` makes it an UNCONDITIONAL accept whenever p > 0.
11456 if skey_probe() && qj == 0.0 {
11457 eprintln!(
11458 "[skey] EXACTNESS q=0 round={round} j={j} draft_tok={} \
11459 draft_idx={} p={:e} u={u} accepted={} th_z={:?}",
11460 draft[j], draft_idx[j], pj[j], accept as u8, draft_stats[j],
11461 );
11462 }
11463 if accept {
11464 n_acc += 1;
11465 } else {
11466 break;
11467 }
11468 }
11469 let bonus = if n_acc == k_round {
11470 // FULL ACCEPT: bonus ~ FILTERED softmax at the last verify column.
11471 let col = base + k_round - 1;
11472 let cb = col_buf.as_mut().unwrap();
11473 e.copy_view_into(
11474 cb,
11475 0,
11476 &tlogits_d.slice(col * n_vocab..(col + 1) * n_vocab),
11477 n_vocab,
11478 )?;
11479 if pen_on {
11480 let h = pen_hist_d.as_ref().unwrap();
11481 let nh = h.len();
11482 e.penalize_logits(
11483 cb,
11484 h,
11485 nh,
11486 sp.penalty_repeat,
11487 sp.penalty_freq,
11488 sp.penalty_present,
11489 n_vocab,
11490 )?;
11491 }
11492 if perturb_buf.is_none() {
11493 perturb_buf = Some(e.zeros(d_vocab.max(n_vocab))?);
11494 }
11495 // STATS MUST COME FROM THIS COLUMN (bug fix 2026-08-05, lane/sampler-
11496 // truncation-fix; receipts research/sampfix-20260805/). The old code reused
11497 // `col_stats.last()` here, which is ALWAYS the wrong row: the gathered set
11498 // covers verify columns 0..=(base+k_round-2) (rows pushed as base+j-1), while
11499 // the full-accept bonus samples column base+k_round-1 — exactly ONE PAST the
11500 // last gathered column, in both base arms. `th` is a threshold in e-units of
11501 // its OWN row's max, so feeding a neighbour's (row_max, th) into
11502 // gumbel_perturb_filtered mis-scales every e0 = exp((x-row_max)/T). When the
11503 // donor column's peak is higher by more than T*ln(1/th), EVERY id fails
11504 // `e0 >= th`, the whole perturbed row becomes -3.4e38, and the 2-pass argmax
11505 // falls through to its smallest-index tie-break => token id 0 ("!") spliced
11506 // mid-word. Fragility is ordered by how large th is: min_p pins th = min_p
11507 // (0.05 => trigger at delta > 2.4 at T=0.8, fires constantly), top_p's
11508 // mass-boundary th is smaller, top_k's k-th-largest th smaller still — which
11509 // is why the head-to-head matrix saw min_p and top_p corrupt while top_k-only
11510 // stayed clean. The pure-temp default regime is immune (th == 0 masks nothing,
11511 // and row_max is unused once nothing is masked), so this fix is a byte-level
11512 // no-op for the untruncated serve default. One extra one-block filter_stats
11513 // per full-accept round is the whole cost.
11514 let (mx, th) = {
11515 let rows0 = e.htod_i32(&[0])?;
11516 let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
11517 let cb0 = col_buf.as_ref().unwrap();
11518 e.filter_stats(
11519 cb0, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1,
11520 sp_temp, sp.top_k, sp.top_p, sp.min_p,
11521 )?;
11522 (e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0])
11523 };
11524 let pb = perturb_buf.as_mut().unwrap();
11525 let cb2 = col_buf.as_ref().unwrap();
11526 e.gumbel_perturb_filtered(cb2, pb, n_vocab, sp_seed, sctr, sp_temp, mx, th)?;
11527 sctr += 1;
11528 let td = e.argmax_token_device(pb, n_vocab)?;
11529 e.dtoh_u32_one(&td)?
11530 } else {
11531 // REJECT at n_acc: bonus ~ norm(max(0, softmax_T(p) - softmax_T(q))).
11532 let cb = col_buf.as_mut().unwrap();
11533 if n_acc > 0 || base == 1 {
11534 let col = base + n_acc - 1;
11535 e.copy_view_into(
11536 cb,
11537 0,
11538 &tlogits_d.slice(col * n_vocab..(col + 1) * n_vocab),
11539 n_vocab,
11540 )?;
11541 } else {
11542 let lc = last_col_logits.as_ref().unwrap();
11543 e.copy_into(cb, 0, lc, n_vocab)?;
11544 }
11545 if pen_on {
11546 let h = pen_hist_d.as_ref().unwrap();
11547 let nh = h.len();
11548 e.penalize_logits(
11549 cb,
11550 h,
11551 nh,
11552 sp.penalty_repeat,
11553 sp.penalty_freq,
11554 sp.penalty_present,
11555 n_vocab,
11556 )?;
11557 }
11558 let cb2 = col_buf.as_ref().unwrap();
11559 let sc = sctr;
11560 sctr += 1;
11561 // p-stats for the reject column: from col_stats when the col was gathered,
11562 // else (j==0&&base==0) from last_col_stats.
11563 let p_stats = if n_acc > 0 || base == 1 {
11564 // col index within the gathered set == number of gathered cols before n_acc
11565 let gi = if base == 1 { n_acc } else { n_acc - 1 };
11566 col_stats.get(gi).copied().unwrap_or_else(|| {
11567 (0.0, 0.0, 1.0) // unreachable: gathered cols always cover the reject slot
11568 })
11569 } else {
11570 last_col_stats.expect("sampled: last_col_stats unset at reject")
11571 };
11572 let q_stats = draft_stats[n_acc];
11573 if let Some(map) = &d2t_dev {
11574 if q_full_buf.is_none() {
11575 q_full_buf = Some(e.zeros(n_vocab)?);
11576 }
11577 let qf = q_full_buf.as_mut().unwrap();
11578 e.scatter_trim_logits(&q_bufs[n_acc], map, qf, d_vocab, n_vocab)?;
11579 let qf2 = q_full_buf.as_ref().unwrap();
11580 e.residual_sample_filtered(
11581 cb2,
11582 Some(qf2),
11583 n_vocab,
11584 sp_temp,
11585 sp_seed,
11586 sc,
11587 p_stats,
11588 q_stats,
11589 &mut sample_tok,
11590 )?;
11591 } else {
11592 e.residual_sample_filtered(
11593 cb2,
11594 Some(&q_bufs[n_acc]),
11595 n_vocab,
11596 sp_temp,
11597 sp_seed,
11598 sc,
11599 p_stats,
11600 q_stats,
11601 &mut sample_tok,
11602 )?;
11603 }
11604 e.dtoh_u32(&sample_tok)?[0]
11605 };
11606 (n_acc, bonus)
11607 };
11608 // --- 3b. GRAMMAR TRUNCATION (constrained spec, 2026-08-03): the grammar is
11609 // an extra rejection rule AFTER the exactness verify (the batched-verify-twins
11610 // ordering). Walk the accepted drafts through the grammar in commit order; the
11611 // first illegal token truncates acceptance at its slot, and that slot's emission
11612 // is recomputed as the MASKED argmax of the target's own verify column — token-
11613 // identical to constrained plain greedy decode (an unmasked argmax that is
11614 // grammar-legal IS the masked argmax: masking only removes competitors). The
11615 // column D2H (~1MB) is paid only when a cut fires — the tight-grammar cost,
11616 // measured in acceptance numbers, never hidden.
11617 let (n_acc, bonus) = match constraint.as_deref_mut() {
11618 None => (n_acc, bonus),
11619 Some(c) => {
11620 fn ce(e2: String) -> Box<dyn std::error::Error> {
11621 format!("constraint: {e2}").into()
11622 }
11623 let mut na = n_acc;
11624 let mut cut = false;
11625 for (j, &d) in draft.iter().enumerate().take(n_acc) {
11626 if c.is_allowed(d).map_err(ce)? {
11627 c.consume(d).map_err(ce)?;
11628 } else {
11629 na = j;
11630 cut = true;
11631 dm_cut_tokens += n_acc - j;
11632 break;
11633 }
11634 }
11635 if cut {
11636 dm_cuts += 1;
11637 }
11638 let mut bo = bonus;
11639 if cut || !c.is_allowed(bo).map_err(ce)? {
11640 let mut row = if na == 0 && base == 0 {
11641 init_logits_host
11642 .clone()
11643 .ok_or("constraint: init logits missing (round-0 cut)")?
11644 } else {
11645 e.dtoh_view(
11646 &tlogits_d.slice((base + na - 1) * n_vocab..(base + na) * n_vocab),
11647 )?
11648 };
11649 c.mask_logits(&mut row).map_err(ce)?;
11650 bo = argmax(&row) as u32;
11651 }
11652 c.consume(bo).map_err(ce)?;
11653 (na, bo)
11654 }
11655 };
11656 let mut successor_valid = false;
11657 if let Some((q_proxy, expected_d2)) = rejected_probe {
11658 let v_n = n_acc == 1 && bonus == expected_d2;
11659 eprintln!(
11660 "[opti-controller] shadow q={q_proxy:.6} admitted=false v_n={v_n} \
11661 expected_d2={expected_d2} n_acc={n_acc} bonus={bonus}",
11662 );
11663 }
11664 if let Some(successor) = successor_attempt.as_ref() {
11665 successor_valid = n_acc == 1 && bonus == successor.verify_tokens[0];
11666 let generation = successor.generation;
11667 let q_proxy = successor.q_proxy;
11668 let expected_pending = successor.verify_tokens[0];
11669 let resolution_ms = successor.issued_at.elapsed().as_secs_f64() * 1e3;
11670 let fork = opti_fork
11671 .as_mut()
11672 .ok_or("optipipe successor resolution lost fork state")?;
11673 fork.finish_actual_reconcile(e, &mut *cache, &snap, n_acc, base, successor_valid)?;
11674 if successor_valid {
11675 OPTI_FORK_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
11676 } else {
11677 OPTI_FORK_MISSES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
11678 OPTI_RECONCILES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
11679 OPTI_WASTED_DRAFT_TOKENS.fetch_add(2, std::sync::atomic::Ordering::Relaxed);
11680 }
11681 let breaker_tripped = fork
11682 .controller
11683 .as_mut()
11684 .expect("controller policy")
11685 .resolve(successor_valid);
11686 if breaker_tripped {
11687 OPTI_BREAKER_TRIPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
11688 }
11689 eprintln!(
11690 "[opti-controller] resolve generation={} hit={} q={q_proxy:.6} \
11691 expected_pending={expected_pending} n_acc={n_acc} bonus={bonus} \
11692 resolution_ms={resolution_ms:.3} reconcile={} breaker={}",
11693 generation.id, successor_valid, !successor_valid, breaker_tripped,
11694 );
11695 if !successor_valid {
11696 let mut successor = successor_attempt
11697 .take()
11698 .expect("controller successor disappeared on miss");
11699 successor.settle();
11700 fork.retire(generation)?;
11701 }
11702 }
11703 total_drafted += k_round;
11704 total_accepted += n_acc;
11705 if let Some(t) = sess_telem {
11706 // Greedy, rejection-sampling, and grammar truncation all converge here after
11707 // the accept decision is already on host. Fixed-size relaxed atomics only.
11708 t.record_round(k_round, n_acc);
11709 }
11710 if spec_stats {
11711 st_len_hist[k_round] += 1;
11712 for j in 0..k_round {
11713 st_drafted[j] += 1;
11714 }
11715 for j in 0..n_acc {
11716 st_accepted[j] += 1;
11717 }
11718 if n_acc == k_round {
11719 st_full += 1;
11720 }
11721 }
11722
11723 if debug_spec {
11724 eprintln!(
11725 "[R{round}] pos={pos} out_len={} last_tok={last_token} draft={draft:?} n_acc={n_acc} bonus={bonus} t_pred0={}",
11726 out.len(),
11727 // NOT `t_pred(0)`: `preds` is filled only under `if !sampled` above, so on a
11728 // sampled request round >= 1 (base == 1) indexed an EMPTY vector and PANICKED
11729 // the GPU worker thread — a debug flag that killed the exact regime you would
11730 // set it to investigate. See `debug_t_pred0`.
11731 debug_t_pred0(sampled, base, last_pred, &preds)
11732 );
11733 }
11734
11735 // --- 4. COMMIT: draft[0..n_acc] then bonus (n_acc + 1 tokens) ---
11736 let commit_started = std::time::Instant::now();
11737 // SESSION MODE: every accepted column is already in the CACHE — `out` must carry all
11738 // of them (overshoot past max_new included) or `committed` under-counts the cache rows
11739 // and the next turn's continuation seeds one token off (gate-caught 2026-07-05). The
11740 // single-shot path keeps the cap (its caller truncates + drops the cache anyway).
11741 for j in 0..n_acc {
11742 if !session_mode && out.len() >= max_new {
11743 break;
11744 }
11745 out.push(draft[j]);
11746 }
11747 if pen_on {
11748 pen_hist.extend_from_slice(&draft[0..n_acc]);
11749 pen_hist.push(bonus);
11750 }
11751 let bonus_emitted = session_mode || out.len() < max_new;
11752 if bonus_emitted {
11753 out.push(bonus);
11754 }
11755 last_token = bonus;
11756
11757 // --- 5. ROLLBACK + advance (§C) ---
11758 if n_acc == k_round && !spec_replay {
11759 // FULL ACCEPT, BONUS FOLD: all verify columns (pending? + drafts) are committed in
11760 // cache; the NEW bonus stays PENDING for the next round's verify batch — NO extra
11761 // T=1 trunk pass. The next draft chain seeds from the MTP block's h_nextn at the
11762 // bonus position: one MTP-block pass (~1/33 trunk cost) replaces the trunk read.
11763 // last_pred is dead in the pending path (t_pred reads verify col 0).
11764 //
11765 // PERSISTENT DRAFT KV, full-accept fill: the chain covered last_token +
11766 // draft[0..k_round-2] as INPUTS (slots P..P'-2); draft[k_round-1] (slot P'-1) was
11767 // only ever an output, so its entry is MISSING. Fill it from vh_seed — its EXACT
11768 // trunk hidden (the last verify column). set_len first: a p-min break may have
11769 // left one extra chain append at that slot. Partial accepts need NO fill (the
11770 // chain already covered every accepted position; round-start set_len truncates).
11771 let mut vh_seed = e.zeros(n_embd)?;
11772 e.copy_view_into(
11773 &mut vh_seed,
11774 0,
11775 &vx.slice((t_v - 1) * n_embd..t_v * n_embd),
11776 n_embd,
11777 )?;
11778 if refresh {
11779 // TRUE-HIDDEN REFRESH (2026-07-03, the HANDOVER-listed acceptance lever):
11780 // overwrite ALL committed positions' scratch entries with K/V from their EXACT
11781 // verify hiddens — the reference engine's mtp_update fills from true hiddens;
11782 // the full stack (vx) is already resident from the verify. Replaces both the
11783 // chain-approximate entries AND the old last-token-only fill. Acceptance-only
11784 // (draft attention quality); exactness stays the verify's job.
11785 scratch.set_len(e, pos)?;
11786 // PREDECESSOR pairing: row i gets vx[i-1]; row 0 the carried fill_prev
11787 // (hidden of the last committed row before this verify batch).
11788 let mut vxs = e.zeros(t_v * n_embd)?;
11789 e.copy_into(&mut vxs, 0, &fill_prev, n_embd)?;
11790 if t_v > 1 {
11791 e.copy_view_into(
11792 &mut vxs,
11793 n_embd,
11794 &vx.slice(0..(t_v - 1) * n_embd),
11795 (t_v - 1) * n_embd,
11796 )?;
11797 }
11798 self.mtp_kv_fill(e, mtp, &verify_tokens, &vxs, pos, &mut *scratch, embd_dev)?;
11799 } else {
11800 scratch.set_len(e, pos + base + k_round - 1)?;
11801 // predecessor of the last draft = verify col t_v-2 (or fill_prev at t_v==1)
11802 let mut hp = e.zeros(n_embd)?;
11803 if t_v >= 2 {
11804 e.copy_view_into(
11805 &mut hp,
11806 0,
11807 &vx.slice((t_v - 2) * n_embd..(t_v - 1) * n_embd),
11808 n_embd,
11809 )?;
11810 } else {
11811 e.copy_into(&mut hp, 0, &fill_prev, n_embd)?;
11812 }
11813 self.mtp_kv_fill(
11814 e,
11815 mtp,
11816 &[draft[k_round - 1]],
11817 &hp,
11818 pos + base + k_round - 1,
11819 &mut *scratch,
11820 embd_dev,
11821 )?;
11822 }
11823 // REFERENCE SEEDING: no pseudo pass — the next chain's step 0 IS the
11824 // reference's (id_last, h_prev) draft row; it appends the bonus's scratch
11825 // entry itself. Seed = TRUE hidden of the bonus's predecessor (last verify
11826 // col). Saves one MTP-block pass per round on top of the pairing fix.
11827 if !devacc_seeded {
11828 e.copy_into(&mut h_seed_buf, 0, &vh_seed, n_embd)?;
11829 e.copy_into(&mut fill_prev, 0, &vh_seed, n_embd)?;
11830 }
11831 pending = Some(bonus);
11832 if debug_spec {
11833 eprintln!(" -> FULL ACCEPT (bonus pending, prev-h seed)");
11834 }
11835 } else if !spec_replay && base + n_acc >= 1 {
11836 // PARTIAL ACCEPT, REPLAY-FREE (2026-07-03 — the profiled #1 long-ctx spec cost):
11837 // the verify's first j = base+n_acc columns ARE the committed sequence, computed
11838 // bit-identically to eager (decode-exact contract) — so KEEP them: KV truncates to
11839 // pos+j, recurrent state rebuilds from the VerifyCkpt (same-kernel gdn prefix
11840 // re-run / pure state-clone restore), and the bonus stays PENDING exactly like the
11841 // full-accept path — the legacy duplicate trunk replay is gone. The next chain
11842 // seeds from the MTP pseudo-hidden of the bonus, whose seed = the TRUE verify
11843 // hidden of its predecessor (col j-1) — same one-hop pseudo structure as full
11844 // accept (never compounds: the next verify recomputes true hiddens for all
11845 // committed columns).
11846 let j = base + n_acc;
11847 self.commit_verified_prefix(
11848 e,
11849 &mut *cache,
11850 &snap,
11851 ckpt.as_ref().unwrap(),
11852 j,
11853 devacc_seeded,
11854 if devacc_seeded {
11855 devacc_acc.as_ref().map(|a| (a, base, t_v))
11856 } else {
11857 None
11858 },
11859 )?;
11860 let mut seed = e.zeros(n_embd)?;
11861 e.copy_view_into(
11862 &mut seed,
11863 0,
11864 &vx.slice((j - 1) * n_embd..j * n_embd),
11865 n_embd,
11866 )?;
11867 // Draft scratch: TRUE-HIDDEN REFRESH of the committed prefix (see the full-accept
11868 // branch); without it the chain entries stand and only the tail truncates. Either
11869 // way len ends at pos+j so the pseudo append lands at the bonus's slot pos+j
11870 // (persistent mode), rope pos+j+1 (chain convention).
11871 if refresh {
11872 scratch.set_len(e, pos)?;
11873 let mut vxs = e.zeros(j * n_embd)?;
11874 e.copy_into(&mut vxs, 0, &fill_prev, n_embd)?;
11875 if j > 1 {
11876 e.copy_view_into(
11877 &mut vxs,
11878 n_embd,
11879 &vx.slice(0..(j - 1) * n_embd),
11880 (j - 1) * n_embd,
11881 )?;
11882 }
11883 self.mtp_kv_fill(
11884 e,
11885 mtp,
11886 &verify_tokens[0..j],
11887 &vxs,
11888 pos,
11889 &mut *scratch,
11890 embd_dev,
11891 )?;
11892 } else {
11893 scratch.set_len(e, pos + j)?;
11894 }
11895 // REFERENCE SEEDING (see the full-accept branch): seed = TRUE hidden of the
11896 // bonus's predecessor (verify col j-1); no pseudo pass.
11897 if !devacc_seeded {
11898 e.copy_into(&mut h_seed_buf, 0, &seed, n_embd)?;
11899 e.copy_into(&mut fill_prev, 0, &seed, n_embd)?;
11900 }
11901 pending = Some(bonus);
11902 if debug_spec {
11903 eprintln!(" -> PARTIAL(replay-free j={j}, bonus pending, prev-h seed)");
11904 }
11905 } else if !spec_replay {
11906 // ZERO ROUND FOLD (2026-07-10, verify-cost target #3): base+n_acc == 0 — a
11907 // pending-less round where nothing was accepted (PMIN0 zero-draft chains after a
11908 // replay/commit, or plain 0-accept rounds at round 0). The old path replayed
11909 // [bonus] through a FULL m=1 trunk+head forward (the 489us full-vocab head pass
11910 // measured at ~0.75/round on PMIN0 configs). Instead: restore the pre-round
11911 // snapshot and let the bonus ride the NEXT round's verify as col 0 — the existing
11912 // base=1 pending machinery, bit-identical by the decode-exact verify contract.
11913 // Seed: the bonus's predecessor is the last COMMITTED token, whose hidden
11914 // fill_prev already carries (same seeding as the 1-token-replay case it replaces).
11915 cache.rollback(e, &snap, 0)?;
11916 scratch.set_len(e, pos)?;
11917 e.copy_into(&mut h_seed_buf, 0, &fill_prev, n_embd)?;
11918 pending = Some(bonus);
11919 if debug_spec {
11920 eprintln!(" -> ZERO-ROUND FOLD (bonus pending, fill_prev seed)");
11921 }
11922 } else {
11923 // PARTIAL ACCEPT, LEGACY REPLAY (seam MEMRA_SPEC_REPLAY=1 — or j==0: nothing of
11924 // this round survives, only possible before the first pending exists, ~round 0):
11925 // restore EVERYTHING to the pre-round snapshot (KV truncate to pos + recur
11926 // restore), then replay the committed prefix pending? ++ draft[0..n_acc] ++
11927 // [bonus] as ONE batched T forward — single weight read, bit-identical to greedy
11928 // (the verify-all-columns path is the same math). Commits the bonus with a TRUE
11929 // trunk hidden.
11930 cache.rollback(e, &snap, 0)?; // accept_len=0: KV len = pos, recur = snapshot
11931 let mut replay: Vec<u32> = Vec::with_capacity(base + n_acc + 1);
11932 if let Some(b) = pending.take() {
11933 replay.push(b);
11934 }
11935 replay.extend_from_slice(&draft[0..n_acc]);
11936 replay.push(bonus);
11937 // Full-stack forward (decode_step_t_core = decode_step_t_h_emb_dev's body):
11938 // Predecessor pairing seeds from the PREDECESSOR row (col len-2) — the same-row path takes the
11939 // last col exactly as before (byte-identical to the old _h_emb_dev call).
11940 let (rl_d, rx) = if self.qwen35_serving_class() {
11941 let mut logits = Vec::with_capacity(replay.len() * n_vocab);
11942 let mut hidden = e.uninit(replay.len() * n_embd)?;
11943 for (row, &token) in replay.iter().enumerate() {
11944 let (row_logits, row_hidden) =
11945 self.spec_target_step_h(e, token, &mut *cache)?;
11946 logits.extend_from_slice(&row_logits);
11947 e.dtod_copy_into(&row_hidden, &mut hidden, row * n_embd)?;
11948 }
11949 (e.htod(&logits)?, hidden)
11950 } else {
11951 self.decode_step_t_core(e, &replay, pos, &mut *cache, embd_dev, None)?
11952 };
11953 // last_pred = argmax of the LAST column's logits (predicts the token after `bonus`)
11954 // — device argmax + one 4-byte read instead of the full-vocab column dtoh.
11955 e.argmax_token_device_col(&rl_d, replay.len() - 1, n_vocab, &mut preds_d, 0)?;
11956 last_pred = e.dtoh_u32(&preds_d)?[0];
11957 if sampled {
11958 let lr0 = replay.len();
11959 let lc = last_col_logits
11960 .as_mut()
11961 .expect("sampled: last_col_logits unset");
11962 e.copy_view_into(
11963 lc,
11964 0,
11965 &rl_d.slice((lr0 - 1) * n_vocab..lr0 * n_vocab),
11966 n_vocab,
11967 )?;
11968 }
11969 let lr = replay.len();
11970 if lr >= 2 {
11971 e.copy_view_into(
11972 &mut h_seed_buf,
11973 0,
11974 &rx.slice((lr - 2) * n_embd..(lr - 1) * n_embd),
11975 n_embd,
11976 )?;
11977 } else {
11978 // 1-token replay (round-0 miss): the bonus's predecessor is the OLD
11979 // last_token, whose own-row hidden fill_prev still holds.
11980 e.copy_into(&mut h_seed_buf, 0, &fill_prev, n_embd)?;
11981 }
11982 // the bonus is COMMITTED here — it becomes the last committed row.
11983 let mut rh_last = e.zeros(n_embd)?;
11984 e.copy_view_into(
11985 &mut rh_last,
11986 0,
11987 &rx.slice((lr - 1) * n_embd..lr * n_embd),
11988 n_embd,
11989 )?;
11990 e.copy_into(&mut fill_prev, 0, &rh_last, n_embd)?;
11991 if debug_spec {
11992 eprintln!(" -> PARTIAL(replay={replay:?}), next_pred={last_pred}");
11993 }
11994 }
11995 if devacc_seeded {
11996 // stage (b) epilogue: fill_prev takes the gathered seed AFTER the refresh fills
11997 // consumed the old value (both slots carry the same value in every non-replay arm).
11998 e.copy_into(&mut fill_prev, 0, &h_seed_buf, n_embd)?;
11999 }
12000 if successor_valid {
12001 let optimistic_scratch_len = successor_attempt
12002 .as_ref()
12003 .expect("valid controller successor disappeared")
12004 .scratch_len;
12005 // The normal current-round commit refreshed/truncated the logical scratch tail.
12006 // Its optimistic successor row was already written physically, so restoring only
12007 // the retained logical length makes that row live for the carried round.
12008 scratch.set_len(e, optimistic_scratch_len)?;
12009 }
12010 if let Some(current) = current_opti.take() {
12011 opti_fork
12012 .as_mut()
12013 .ok_or("optipipe current retirement lost fork state")?
12014 .retire(current.generation)?;
12015 }
12016 if successor_valid {
12017 let successor = successor_attempt
12018 .take()
12019 .expect("valid controller successor disappeared before promotion");
12020 let generation = successor.generation;
12021 opti_fork
12022 .as_mut()
12023 .ok_or("optipipe successor promotion lost fork state")?
12024 .promote_successor_snapshot(&mut snap, generation);
12025 carried_opti = Some(successor);
12026 }
12027 if anatomy_on {
12028 // Commit/rollback is normally asynchronous on the primary/head stream. Bound it
12029 // only for this diagnostic so it does not disappear into the following draft's
12030 // first token readback.
12031 e.stream().synchronize()?;
12032 ph_commit += commit_started.elapsed().as_secs_f64();
12033 }
12034 // adaptive-K update (host math, zero syncs): next round drafts accepted-run + 1,
12035 // clamped to [floor(pos), k_cap]. cache.pos is post-rollback here (the round's
12036 // final position — the floor's position key reads the committed depth). Burst
12037 // rounds (`continue` above) draft the captured fixed depth and skip this, exactly
12038 // like gemma's burst arm.
12039 if adapt {
12040 let fl_now = floor_at(cache.pos);
12041 kc = (n_acc + 1).clamp(fl_now.min(k_cap), k_cap);
12042 }
12043 ph_mark(&mut ph_rest, phase_on);
12044 if let Some(p) = pipe {
12045 p.accept_end(round);
12046 }
12047 drop(pipe_accept);
12048 round += 1;
12049 // sse-cadence: this round's accepted drafts + bonus are committed (out is
12050 // append-only past step 4) — flush at round cadence.
12051 keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
12052 }
12053 if let Some(mut ticket) = carried_opti.take() {
12054 opti_fork
12055 .as_mut()
12056 .ok_or("optipipe tail drain lost fork state")?
12057 .cancel_controller_ticket(e, &mut *cache, &mut *scratch, &snap, &mut ticket)?;
12058 }
12059 // sse-cadence: nothing below appends to `out`; flush any remainder (defensive).
12060 // (verdict ignored — the burst is over either way; the session tail runs unchanged.)
12061 let _ = flush_commit(&mut on_commit, &out, &mut flushed);
12062
12063 if spec_stats {
12064 let per_slot: Vec<String> = (0..k)
12065 .map(|j| {
12066 if st_drafted[j] > 0 {
12067 format!(
12068 "{}/{}={:.3}",
12069 st_accepted[j],
12070 st_drafted[j],
12071 st_accepted[j] as f64 / st_drafted[j] as f64
12072 )
12073 } else {
12074 "0/0".into()
12075 }
12076 })
12077 .collect();
12078 let acc = if total_drafted > 0 {
12079 total_accepted as f64 / total_drafted as f64
12080 } else {
12081 0.0
12082 };
12083 eprintln!(
12084 "[spec-stats] rounds={round} full_accept={st_full} len_hist={st_len_hist:?} \
12085 per_slot=[{}] total={total_accepted}/{total_drafted}={acc:.3} \
12086 tok_per_round={:.3}",
12087 per_slot.join(" "),
12088 (total_accepted + round) as f64 / round.max(1) as f64
12089 );
12090 }
12091 if constraint.is_some() {
12092 eprintln!(
12093 "[draft-mask] mask_rounds={dm_rounds} clone_total={:.3}ms \
12094 clone_per_round={:.4}ms gram_cuts={dm_cuts}/{round} cut_tokens={dm_cut_tokens}",
12095 dm_clone_ns as f64 / 1e6,
12096 dm_clone_ns as f64 / 1e6 / dm_rounds.max(1) as f64
12097 );
12098 }
12099 if phase_on {
12100 let tot = ph_draft + ph_verify + ph_wait + ph_rest;
12101 eprintln!(
12102 "[spec-phase] draft={:.1}ms ({:.1}%) verify-issue={:.1}ms ({:.1}%) verify-wait={:.1}ms ({:.1}%) commit-host={:.1}ms ({:.1}%) rounds={round}",
12103 ph_draft * 1e3,
12104 ph_draft / tot * 100.0,
12105 ph_verify * 1e3,
12106 ph_verify / tot * 100.0,
12107 ph_wait * 1e3,
12108 ph_wait / tot * 100.0,
12109 ph_rest * 1e3,
12110 ph_rest / tot * 100.0
12111 );
12112 }
12113 if anatomy_on {
12114 let rounds_f = round.max(1) as f64;
12115 let other = (ph_rest - ph_commit).max(0.0);
12116 eprintln!(
12117 "[spec-anatomy] per-round draft={:.3}ms pp-verify={:.3}ms \
12118 verify-accept={:.3}ms commit-rollback={:.3}ms other={:.3}ms rounds={round}",
12119 ph_draft * 1e3 / rounds_f,
12120 ph_verify * 1e3 / rounds_f,
12121 ph_wait * 1e3 / rounds_f,
12122 ph_commit * 1e3 / rounds_f,
12123 other * 1e3 / rounds_f,
12124 );
12125 }
12126 let _pipe_tail = pipe.map(|p| p.primary());
12127 // SESSION TAIL: leave the session in the exact invariant the next turn's suffix prime
12128 // expects — every row in `committed` has trunk KV/recur state AND an exact draft-KV row.
12129 // Park the draft-graph ctx back on the session (the serve-burst fixed-cost fix): the next
12130 // burst replays instead of recapturing. Error paths (`?` above) drop it — recaptured then.
12131 if let Some(slot) = sess_draft_slot.take() {
12132 *slot = Some(dctx);
12133 }
12134 let t_rounds = t_ent.elapsed();
12135 if let Some((committed, last_h, next_pred_slot, sctr_slot, uctr_slot)) = sess_tail.take() {
12136 // NEXT BURST'S BOUNDARY TOKEN (lane/sampled-spec-quality, Item 1). Greedy stashes
12137 // the argmax `last_pred` exactly as before (byte contract). SAMPLED draws the token
12138 // HERE, where the sampler, the session Philox counters and the penalty window are
12139 // all live and the boundary logits row still exists — that is the "make the state
12140 // available" half of the fix; the consuming burst then just emits it. `sctr` is
12141 // written to the session BELOW the draws so the advance is never lost.
12142 *next_pred_slot = Some(last_pred);
12143 let sample_boundary = sampled && constraint.is_none() && spec_sampled_boundary_on();
12144 let mut stashed_pending = false;
12145 if let Some(b) = pending.take() {
12146 if !sampled {
12147 // PENDING-CARRY (2026-08-01): stash the bonus on the session instead of
12148 // committing it with a solo T=1 pass — the next empty-suffix greedy burst
12149 // consumes it as round-0 verify col 0 (a plain round edge; the old tail
12150 // commit + next burst's init feed were 11.6+11.5ms solo trunk passes per
12151 // burst on H100 q27, [spec-setup] trace). b stays in `out` (emitted) but
12152 // OUT of `committed` (cache rows == committed); the consuming call
12153 // prepends it once its verify commits the row. next_pred is unknowable
12154 // without the commit pass — None; callers gate on pending_tok too.
12155 debug_assert_eq!(out.last(), Some(&b), "pending must be the last emitted");
12156 if let Some(slot) = sess_pending_slot.take() {
12157 *slot = Some(b);
12158 }
12159 *next_pred_slot = None;
12160 // fill_prev = hidden of the last COMMITTED row (b's predecessor) — the
12161 // exact chain-seed/fill anchor the consuming burst (or a flush) needs.
12162 *last_h = Some(e.clone_dtod(&fill_prev)?);
12163 stashed_pending = true;
12164 } else {
12165 // SAMPLED tail (unchanged): commit the bonus (one T=1 pass) + draft fill —
12166 // the sampled round-0 accept needs this pass's logits (last_col_logits).
12167 let pos_b = cache.pos;
12168 scratch.set_len(e, pos_b)?;
12169 let (lg_b, hb) = self.spec_target_step_h(e, b, &mut *cache)?;
12170 // after a FULL-accept exit `last_pred` is STALE (it predicted the bonus
12171 // itself — the prediction AFTER the bonus never materialized; it would have
12172 // been the next round's verify col 0). The commit's logits ARE that
12173 // prediction — so they are also the row the next burst's boundary token
12174 // comes off, and (lane/sampled-spec-quality) it is DRAWN from them here.
12175 *next_pred_slot = Some(if sample_boundary {
12176 sample_boundary_token(
12177 e,
12178 &lg_b,
12179 &sp,
12180 &pen_hist,
12181 &mut sctr,
12182 "burst-tail-commit",
12183 )?
12184 } else {
12185 argmax(&lg_b) as u32
12186 });
12187 self.mtp_kv_fill(e, mtp, &[b], &fill_prev, pos_b, &mut *scratch, embd_dev)?;
12188 *last_h = Some(hb);
12189 }
12190 } else {
12191 // fill_prev tracks the hidden of the last COMMITTED row throughout the loop.
12192 *last_h = Some(e.clone_dtod(&fill_prev)?);
12193 if sample_boundary {
12194 // No pending to commit, so the boundary row is the one `last_pred` was
12195 // argmaxed from and the sampled path keeps it on device: the init feed's
12196 // logits when the burst ran zero rounds, else the legacy-replay path's
12197 // last verify column (both predict the token AFTER the last committed
12198 // row). It is retained precisely because round 0's accept test needs it,
12199 // so the draw costs no extra D2H of the [n_vocab] row.
12200 match last_col_logits.as_ref() {
12201 Some(lc) => {
12202 *next_pred_slot = Some(sample_boundary_token_dev(
12203 e,
12204 lc,
12205 n_vocab,
12206 &sp,
12207 &pen_hist,
12208 &mut sctr,
12209 "burst-tail-nopending",
12210 )?);
12211 }
12212 // NAME THE FALLBACK (house standard): unreachable today — a sampled
12213 // burst always feeds or replays, so the row exists — but if it ever
12214 // is, the stream takes a greedy token and SAYS so rather than
12215 // silently regressing to the pre-lane behaviour.
12216 None => eprintln!(
12217 "[spec-boundary] sampled tail kept the ARGMAX boundary token \
12218 (reason: no retained boundary logits row)"
12219 ),
12220 }
12221 }
12222 }
12223 *sctr_slot = sctr;
12224 *uctr_slot = uctr;
12225 committed.extend_from_slice(prompt);
12226 if let Some(cb) = carried_pending {
12227 // the consumed carry's cache row landed in round 0's verify (every pending
12228 // round commits col 0) — it joins `committed` here, in sequence order.
12229 committed.push(cb);
12230 }
12231 if stashed_pending {
12232 // ZERO-EMIT BURST (2026-08-06 c=8 serve panic, pre-existing since b4aea184):
12233 // `out.len() - 1` underflowed on an EMPTY `out` — "range end index
12234 // 18446744073709551615 out of range for slice of length 0", killing the
12235 // memra-gpu-worker and failing 31 of 32 concurrent requests with "worker closed
12236 // stream". Reachable because `pending` starts as `carried_pending` (a bonus
12237 // stashed by the PREVIOUS burst) while `out` starts empty, and the carry is
12238 // deliberately NOT pushed to `out` (line ~3239: the burst that emitted it already
12239 // did). So a burst that stashes a pending without emitting anything of its own —
12240 // the round loop exits before a push, e.g. the ring drain's `out.len() < max_new`
12241 // guard skipping every token under a tight budget — arrives here with
12242 // out.len() == 0 and stashed_pending == true.
12243 //
12244 // The invariant is unchanged: `committed` gets every emitted token EXCEPT the
12245 // stashed bonus. With nothing emitted, that is nothing — and the carry pushed
12246 // just above is already accounted. Saturating, not a min/assert: an empty `out`
12247 // here is a legitimate burst shape, not a corrupt state.
12248 let emitted = out.len().saturating_sub(1);
12249 committed.extend_from_slice(&out[..emitted]);
12250 } else {
12251 committed.extend_from_slice(&out); // FULL out incl. overshoot — all committed
12252 }
12253 debug_assert_eq!(
12254 cache.pos,
12255 committed.len(),
12256 "session invariant: cache rows == committed tokens"
12257 );
12258 if setup_trace {
12259 e.stream().synchronize()?; // bound the async tail fill in the trace
12260 let t_tail = t_ent.elapsed();
12261 eprintln!(
12262 "[spec-setup] init={:.2}ms cap={:.2}ms fill={:.2}ms rounds={:.2}ms tail={:.2}ms total={:.2}ms out={} cont={}",
12263 t_init.as_secs_f64() * 1e3,
12264 (t_cap - t_init).as_secs_f64() * 1e3,
12265 (t_fill - t_cap).as_secs_f64() * 1e3,
12266 (t_rounds - t_fill).as_secs_f64() * 1e3,
12267 (t_tail - t_rounds).as_secs_f64() * 1e3,
12268 t_tail.as_secs_f64() * 1e3,
12269 out.len(),
12270 continuation
12271 );
12272 }
12273 return Ok((out, total_drafted, total_accepted));
12274 }
12275 out.truncate(max_new);
12276 Ok((out, total_drafted, total_accepted))
12277 }
12278
12279 /// Anchor-bounded DSpark target extraction. The trunk sees the exact generated token tape;
12280 /// only requested hidden rows and target-logit rows cross PCIe. An anchor token at p pairs
12281 /// with the pre-output-norm h[p-1] carrier, exactly as the existing replay/NextN path does.
12282 pub fn extract_dspark_anchors(
12283 &self,
12284 e: &Engine,
12285 tokens: &[u32],
12286 anchor_positions: &[usize],
12287 gamma: usize,
12288 top_k: usize,
12289 chunk: usize,
12290 temperature: f32,
12291 ) -> Result<Vec<DsparkAnchorRecord>, Box<dyn std::error::Error>> {
12292 if tokens.len() < gamma + 2 || gamma == 0 || chunk < 2 {
12293 return Err("DSpark extraction token tape/gamma/chunk is invalid".into());
12294 }
12295 if anchor_positions.windows(2).any(|pair| pair[0] >= pair[1]) {
12296 return Err("DSpark anchor positions must be sorted and unique".into());
12297 }
12298 for &position in anchor_positions {
12299 if position == 0 || position + gamma >= tokens.len() {
12300 return Err(format!(
12301 "DSpark anchor {position} has no predecessor or cannot cover gamma={gamma} in {} tokens",
12302 tokens.len()
12303 )
12304 .into());
12305 }
12306 }
12307
12308 let n_vocab = self.output.out_features();
12309 let n_embd = self.cfg.n_embd as usize;
12310 let mut cache = crate::pp::new_cache(e, &self.cfg, tokens.len() + gamma + 8)?;
12311 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
12312 let embd_gpu = if spec_host_embd() {
12313 None
12314 } else {
12315 Some(
12316 self.embd_gpu
12317 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
12318 )
12319 };
12320 let embd_dev = embd_gpu.map(|gpu| (gpu, embd_qt, embd_rb));
12321
12322 struct PendingRecord {
12323 position: usize,
12324 hidden: Option<Vec<f32>>,
12325 tokens: Vec<u32>,
12326 target_top_ids: Vec<Option<Vec<u32>>>,
12327 target_top_logits: Vec<Option<Vec<f32>>>,
12328 target_top_probs: Vec<Option<Vec<f32>>>,
12329 target_tail_probs: Vec<Option<f32>>,
12330 }
12331
12332 let mut pending: Vec<PendingRecord> = anchor_positions
12333 .iter()
12334 .map(|&position| PendingRecord {
12335 position,
12336 hidden: None,
12337 tokens: tokens[position..=position + gamma].to_vec(),
12338 target_top_ids: vec![None; gamma],
12339 target_top_logits: vec![None; gamma],
12340 target_top_probs: vec![None; gamma],
12341 target_tail_probs: vec![None; gamma],
12342 })
12343 .collect();
12344
12345 let mut start = 0usize;
12346 while start < tokens.len() {
12347 let end = (start + chunk).min(tokens.len());
12348 let chunk_tokens = &tokens[start..end];
12349 let (target_logits, hidden_rows) =
12350 self.decode_step_t_core(e, chunk_tokens, start, &mut cache, embd_dev, None)?;
12351 for record in &mut pending {
12352 let hidden_position = record.position - 1;
12353 if hidden_position >= start && hidden_position < end {
12354 let local = hidden_position - start;
12355 record.hidden = Some(
12356 e.dtoh_view(&hidden_rows.slice(local * n_embd..(local + 1) * n_embd))?,
12357 );
12358 }
12359 for slot in 0..gamma {
12360 let target_row = record.position + slot;
12361 if target_row < start || target_row >= end {
12362 continue;
12363 }
12364 let local = target_row - start;
12365 let logits =
12366 e.dtoh_view(&target_logits.slice(local * n_vocab..(local + 1) * n_vocab))?;
12367 let (ids, top_logits, probs, tail) =
12368 dspark_sparse_softmax_topk(&logits, top_k, temperature)?;
12369 record.target_top_ids[slot] = Some(ids);
12370 record.target_top_logits[slot] = Some(top_logits);
12371 record.target_top_probs[slot] = Some(probs);
12372 record.target_tail_probs[slot] = Some(tail);
12373 }
12374 }
12375 start = end;
12376 }
12377
12378 pending
12379 .into_iter()
12380 .map(|record| {
12381 let hidden = record
12382 .hidden
12383 .ok_or_else(|| format!("missing DSpark hidden at {}", record.position))?;
12384 let target_top_ids =
12385 flatten_dspark_rows(record.target_top_ids, record.position, "target ids")?;
12386 let target_top_logits = flatten_dspark_rows(
12387 record.target_top_logits,
12388 record.position,
12389 "target logits",
12390 )?;
12391 let target_top_probs =
12392 flatten_dspark_rows(record.target_top_probs, record.position, "target probs")?;
12393 let target_tail_probs = record
12394 .target_tail_probs
12395 .into_iter()
12396 .enumerate()
12397 .map(|(slot, value)| {
12398 value.ok_or_else(|| {
12399 format!("missing DSpark tail at {} slot {slot}", record.position)
12400 })
12401 })
12402 .collect::<Result<Vec<_>, _>>()?;
12403 Ok(DsparkAnchorRecord {
12404 position: record.position,
12405 hidden,
12406 tokens: record.tokens,
12407 target_top_ids,
12408 target_top_logits,
12409 target_top_probs,
12410 target_tail_probs,
12411 })
12412 })
12413 .collect()
12414 }
12415
12416 /// TEACHER-FORCED REPLAY ACCEPTANCE (hqmtp MTP-heal protocol): walk a FIXED token
12417 /// sequence and, at sampled positions, compare the MTP head's K-token draft chain against
12418 /// the trunk's own teacher-forced greedy predictions. Nothing is generated — the context is
12419 /// the corpus text itself, so (a) degenerate self-generated loops cannot inflate acceptance
12420 /// and (b) two arms (bf16 ceiling vs NVFP4) score on IDENTICAL contexts, isolating the
12421 /// quant-induced head/hidden-state mismatch from text drift.
12422 ///
12423 /// Per eval position p (context = tokens[0..=p], predecessor pairing as in spec decode):
12424 /// draft_j = chain token j from (tokens[p], h_{p-1}), then its own drafts — the exact
12425 /// eager spec-decode chain (same mtp_head_forward_dev, same rope positions).
12426 /// target_j = teacher-forced greedy pick for position p+1+j (argmax of the trunk logits
12427 /// at forced context tokens[0..p+j]). For j==0 this equals live spec
12428 /// acceptance; for j>=1 live verify would condition on the drafts, here it
12429 /// conditions on the corpus — deterministic and arm-comparable by design.
12430 ///
12431 /// Returns (rows, bg): one (p, drafts[k], targets[k]) row per eval position (ascending p),
12432 /// plus the full teacher-forced greedy track bg (bg[i] = greedy pick for position i, i>=1)
12433 /// so harnesses can cross-check runs (e.g. different chunk sizes must give identical bg).
12434 ///
12435 /// `hdump`: when Some, every position's pre-output_norm trunk hidden (the exact rows the
12436 /// draft-KV fill pairs from) streams to the file as little-endian f32 [t_total, n_embd] —
12437 /// the head-distillation extraction (hqmtp): the ENGINE is the source of truth for trunk
12438 /// hiddens (HF torch reproductions of the hybrid trunk measured only ~0.5 greedy
12439 /// agreement vs this path — not usable as a training-data source).
12440 pub fn replay_acceptance(
12441 &self,
12442 e: &Engine,
12443 tokens: &[u32],
12444 k: usize,
12445 stride: usize,
12446 chunk: usize,
12447 mut hdump: Option<&mut std::fs::File>,
12448 ) -> Result<(Vec<(usize, Vec<u32>, Vec<u32>)>, Vec<u32>), Box<dyn std::error::Error>> {
12449 assert!(k >= 1 && stride >= 1 && chunk >= 2);
12450 let mtp = self
12451 .mtp
12452 .as_ref()
12453 .expect("replay_acceptance requires an MTP head");
12454 let n_vocab = self.output.out_features();
12455 let d_vocab = mtp
12456 .shared_head_head
12457 .as_ref()
12458 .unwrap_or(&self.output)
12459 .out_features();
12460 let n_embd = self.cfg.n_embd as usize;
12461 let t_total = tokens.len();
12462 assert!(t_total >= 8, "corpus too short ({t_total} tokens)");
12463 // STAGE-OWNED KV (lane/pp2-spec 2026-08-06) — see `new_session`. Door shut = `Cache::new`.
12464 let mut cache = crate::pp::new_cache(e, &self.cfg, t_total + k + 8)?;
12465 let mut scratch = MtpScratch::new(
12466 e,
12467 &self.cfg,
12468 t_total + k + 8,
12469 self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
12470 )?;
12471 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
12472 let embd_gpu = if spec_host_embd() {
12473 None
12474 } else {
12475 Some(
12476 self.embd_gpu
12477 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
12478 )
12479 };
12480 let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
12481
12482 // bg[i] = the trunk's greedy pick for position i under the forced context (i >= 1).
12483 let mut bg: Vec<u32> = vec![0; t_total + 1];
12484 let mut rows: Vec<(usize, Vec<u32>, Vec<u32>)> = Vec::new();
12485 let mut prev_last_h = e.zeros(n_embd)?; // predecessor hidden entering the chunk
12486 let mut seed_buf = e.zeros(n_embd)?;
12487 let mut preds_d = e.alloc_u32_zeroed(chunk)?;
12488 let nll_on = std::env::var("MEMRA_REPLAY_NLL").as_deref() == Ok("1");
12489 let (mut nll_sum, mut nll_cnt) = (0f64, 0u64);
12490 let mut s = 0usize;
12491 while s < t_total {
12492 let cend = (s + chunk).min(t_total);
12493 let tc = cend - s;
12494 let ch = &tokens[s..cend];
12495 // 1. forced trunk pass — verify path (decode-exact contract): all-column logits +
12496 // the chunk's true hiddens.
12497 let (tl_d, vx) = self.decode_step_t_core(e, ch, s, &mut cache, embd_dev, None)?;
12498 for j in 0..tc {
12499 e.argmax_token_device_col(&tl_d, j, n_vocab, &mut preds_d, j)?;
12500 }
12501 let preds = e.dtoh_u32(&preds_d)?;
12502 for j in 0..tc {
12503 bg[s + j + 1] = preds[j];
12504 }
12505 // MEMRA_REPLAY_NLL=1: teacher-forced NLL/perplexity over the same forced pass — the
12506 // checkpoint-quality metric (position j's logits score the GOLD next token).
12507 if nll_on {
12508 let jmax = if cend < t_total { tc } else { tc - 1 }; // last pos has no gold next
12509 if jmax > 0 {
12510 let ids: Vec<u32> = (0..jmax).map(|j| tokens[s + j + 1]).collect();
12511 let rows: Vec<i32> = (0..jmax as i32).collect();
12512 let idsd = e.htod_u32_v(&ids)?;
12513 let rowsd = e.htod_i32(&rows)?;
12514 let mut outd = e.zeros(jmax)?;
12515 e.softmax_gather(&tl_d, n_vocab, &idsd, &rowsd, &mut outd, n_vocab, jmax, 1.0)?;
12516 for pr in e.dtoh(&outd)? {
12517 nll_sum += -((pr.max(1e-30)) as f64).ln();
12518 nll_cnt += 1;
12519 }
12520 }
12521 }
12522 if let Some(f) = hdump.as_deref_mut() {
12523 use std::io::Write;
12524 let host: Vec<f32> = e.dtoh(&vx)?;
12525 // bf16 round-to-nearest-even — f32 doubled the disk bill at bulk
12526 // extraction scale (20M tokens x 4096 = 320GB f32 vs 160GB bf16).
12527 let mut bytes = Vec::with_capacity(tc * n_embd * 2);
12528 for v in &host[..tc * n_embd] {
12529 let b = v.to_bits();
12530 let r = b.wrapping_add(0x7FFF + ((b >> 16) & 1));
12531 bytes.extend_from_slice(&((r >> 16) as u16).to_le_bytes());
12532 }
12533 f.write_all(&bytes)?;
12534 }
12535 // CHAINLESS extraction (stride > corpus, the bulk-hdump mode): no chunk ever
12536 // drafts, so the draft-KV fills are pure waste — skip them (2 MTP-block passes
12537 // per token saved; the forced trunk pass + hdump is all the mode needs).
12538 let chainless = stride > t_total;
12539 if chainless {
12540 e.copy_view_into(
12541 &mut prev_last_h,
12542 0,
12543 &vx.slice((tc - 1) * n_embd..tc * n_embd),
12544 n_embd,
12545 )?;
12546 s = cend;
12547 continue;
12548 }
12549 // 2. TRUE predecessor-paired draft-KV fill for the chunk (row i carries h_{i-1};
12550 // row s reads the previous chunk's last true hidden, zeros at corpus start).
12551 let mut vxs = e.zeros(tc * n_embd)?;
12552 e.copy_into(&mut vxs, 0, &prev_last_h, n_embd)?;
12553 if tc > 1 {
12554 e.copy_view_into(
12555 &mut vxs,
12556 n_embd,
12557 &vx.slice(0..(tc - 1) * n_embd),
12558 (tc - 1) * n_embd,
12559 )?;
12560 }
12561 scratch.set_len(e, s)?;
12562 self.mtp_kv_fill(e, mtp, ch, &vxs, s, &mut scratch, embd_dev)?;
12563 // 3. draft chains at sampled positions, DESCENDING: a chain reads only slots
12564 // [0..p) (true fills) and appends at >= p; the next (smaller-p) chain's set_len
12565 // truncates those approximate appends before they can ever be read.
12566 let ps: Vec<usize> = (s..cend)
12567 .filter(|p| *p >= 1 && *p % stride == 0 && *p + k <= t_total)
12568 .collect();
12569 for &p in ps.iter().rev() {
12570 scratch.set_len(e, p)?;
12571 if p == s {
12572 e.copy_into(&mut seed_buf, 0, &prev_last_h, n_embd)?;
12573 } else {
12574 e.copy_view_into(
12575 &mut seed_buf,
12576 0,
12577 &vx.slice((p - 1 - s) * n_embd..(p - s) * n_embd),
12578 n_embd,
12579 )?;
12580 }
12581 let mut e_tok = tokens[p];
12582 let mut d_seed = e.clone_dtod(&seed_buf)?;
12583 let mut drafts: Vec<u32> = Vec::with_capacity(k);
12584 for j in 0..k {
12585 let (dl_d, h_nextn) = self.mtp_head_forward_dev(
12586 e,
12587 mtp,
12588 e_tok,
12589 &d_seed,
12590 &mut scratch,
12591 p + 1 + j,
12592 embd_dev,
12593 None, // acceptance-oracle walk: no grammar
12594 )?;
12595 let tok_d = e.argmax_token_device(&dl_d, d_vocab)?;
12596 let idx = e.dtoh_u32_one(&tok_d)?;
12597 let d = match &mtp.d2t {
12598 Some(map) => map[idx as usize],
12599 None => idx,
12600 };
12601 drafts.push(d);
12602 e_tok = d;
12603 d_seed = h_nextn;
12604 }
12605 // targets may live in a LATER chunk's bg — resolved after the walk.
12606 rows.push((p, drafts, Vec::new()));
12607 }
12608 // 4. restore TRUE entries for the whole chunk (the next chunk's chains and fills
12609 // expect scratch.len == cend with exact rows).
12610 scratch.set_len(e, s)?;
12611 self.mtp_kv_fill(e, mtp, ch, &vxs, s, &mut scratch, embd_dev)?;
12612 e.copy_view_into(
12613 &mut prev_last_h,
12614 0,
12615 &vx.slice((tc - 1) * n_embd..tc * n_embd),
12616 n_embd,
12617 )?;
12618 s = cend;
12619 }
12620 for (p, drafts, targets) in rows.iter_mut() {
12621 for j in 0..drafts.len() {
12622 targets.push(bg[*p + 1 + j]);
12623 }
12624 }
12625 rows.sort_by_key(|r| r.0);
12626 if nll_cnt > 0 {
12627 let mean = nll_sum / nll_cnt as f64;
12628 println!(
12629 "[replay-nll] tokens={nll_cnt} nll/token={mean:.5} ppl={:.4}",
12630 mean.exp()
12631 );
12632 }
12633 Ok((rows, bg))
12634 }
12635}
12636
12637#[cfg(test)]
12638mod dspark_sparse_tests {
12639 use super::dspark_sparse_softmax_topk;
12640
12641 #[test]
12642 fn topk_keeps_full_softmax_mass_and_stable_ties() {
12643 let logits = [1.0f32, 3.0, 3.0, -2.0];
12644 let (ids, top_logits, probs, tail) = dspark_sparse_softmax_topk(&logits, 2, 1.0).unwrap();
12645 assert_eq!(ids, vec![1, 2]);
12646 assert_eq!(top_logits, vec![3.0, 3.0]);
12647 let denominator = logits.iter().map(|value| (value - 3.0).exp()).sum::<f32>();
12648 let expected = 1.0 / denominator;
12649 assert!((probs[0] - expected).abs() < 1.0e-6);
12650 assert!((probs[1] - expected).abs() < 1.0e-6);
12651 assert!((tail - (1.0 - 2.0 * expected)).abs() < 1.0e-6);
12652 assert!((probs.iter().sum::<f32>() + tail - 1.0).abs() < 1.0e-6);
12653 }
12654}
12655
12656#[cfg(test)]
12657mod spec_replay_env_tests {
12658 use super::spec_replay_env_on;
12659
12660 #[test]
12661 fn replay_requires_literal_one() {
12662 assert!(!spec_replay_env_on(None));
12663 assert!(!spec_replay_env_on(Some("")));
12664 assert!(!spec_replay_env_on(Some("0")));
12665 assert!(!spec_replay_env_on(Some("true")));
12666 assert!(!spec_replay_env_on(Some("2")));
12667 assert!(spec_replay_env_on(Some("1")));
12668 }
12669}
12670
12671#[cfg(test)]
12672mod telem_tests {
12673 use super::{SPEC_TELEM_POS, SpecTelemetry, SpecTelemetryCounters};
12674
12675 #[test]
12676 fn synthetic_accept_masks_produce_tau_and_position_histogram() {
12677 let counters = SpecTelemetryCounters::default();
12678 for mask in [
12679 [true, true, true],
12680 [true, true, false],
12681 [true, false, false],
12682 [false, false, false],
12683 ] {
12684 let accepted = mask.iter().take_while(|&&value| value).count();
12685 counters.record_round(mask.len(), accepted);
12686 }
12687
12688 let snapshot = counters.snapshot();
12689 assert_eq!(
12690 (snapshot.rounds, snapshot.drafted, snapshot.accepted),
12691 (4, 12, 6)
12692 );
12693 assert_eq!(&snapshot.pos_drafted[..3], &[4, 4, 4]);
12694 assert_eq!(&snapshot.pos_accepted[..3], &[3, 2, 1]);
12695 assert_eq!(snapshot.tau(), 1.5);
12696 assert_eq!(snapshot.pos_drafted[3..], [0; SPEC_TELEM_POS - 3]);
12697 assert_eq!(snapshot.pos_accepted[3..], [0; SPEC_TELEM_POS - 3]);
12698 }
12699
12700 /// The worker's per-burst pattern: stash, accumulate, diff — the delta must isolate
12701 /// exactly the burst's contribution (pool-resumed sessions carry prior requests' counts).
12702 #[test]
12703 fn delta_isolates_burst_contribution() {
12704 let mut t = SpecTelemetry::default();
12705 // "previous request": 2 rounds of k=3, accepts 3 then 1.
12706 for (kr, na) in [(3usize, 3usize), (3, 1)] {
12707 t.rounds += 1;
12708 t.drafted += kr as u64;
12709 t.accepted += na as u64;
12710 for j in 0..kr {
12711 t.pos_drafted[j] += 1;
12712 }
12713 for j in 0..na {
12714 t.pos_accepted[j] += 1;
12715 }
12716 }
12717 let before = t;
12718 // "this burst": 1 round k=3, accepts 2.
12719 t.rounds += 1;
12720 t.drafted += 3;
12721 t.accepted += 2;
12722 for j in 0..3 {
12723 t.pos_drafted[j] += 1;
12724 }
12725 for j in 0..2 {
12726 t.pos_accepted[j] += 1;
12727 }
12728 let d = t.delta_since(&before);
12729 assert_eq!((d.rounds, d.drafted, d.accepted), (1, 3, 2));
12730 assert_eq!(&d.pos_drafted[..3], &[1, 1, 1]);
12731 assert_eq!(&d.pos_accepted[..3], &[1, 1, 0]);
12732 assert_eq!(d.pos_drafted[3..], [0; SPEC_TELEM_POS - 3]);
12733 }
12734
12735 /// merge(delta) then merge(delta2) equals accumulating both — the per-model /metrics
12736 /// aggregation invariant.
12737 #[test]
12738 fn merge_accumulates_fieldwise() {
12739 let mut agg = SpecTelemetry::default();
12740 let mut d1 = SpecTelemetry {
12741 rounds: 2,
12742 drafted: 6,
12743 accepted: 4,
12744 ..Default::default()
12745 };
12746 d1.pos_drafted[0] = 2;
12747 d1.pos_accepted[0] = 2;
12748 let mut d2 = SpecTelemetry {
12749 rounds: 1,
12750 drafted: 3,
12751 accepted: 1,
12752 ..Default::default()
12753 };
12754 d2.pos_drafted[0] = 1;
12755 d2.pos_accepted[0] = 1;
12756 d2.pos_drafted[1] = 1;
12757 agg.merge(&d1);
12758 agg.merge(&d2);
12759 assert_eq!((agg.rounds, agg.drafted, agg.accepted), (3, 9, 5));
12760 assert_eq!(agg.pos_drafted[0], 3);
12761 assert_eq!(agg.pos_accepted[0], 3);
12762 assert_eq!(agg.pos_drafted[1], 1);
12763 assert_eq!(agg.pos_accepted[1], 0);
12764 }
12765
12766 /// Wrong-snapshot diff saturates to zero instead of wrapping — the counters feed a
12767 /// public metrics surface and must never publish a u64-wrapped garbage value.
12768 #[test]
12769 fn delta_saturates_never_wraps() {
12770 let small = SpecTelemetry {
12771 rounds: 1,
12772 drafted: 2,
12773 accepted: 1,
12774 ..Default::default()
12775 };
12776 let big = SpecTelemetry {
12777 rounds: 5,
12778 drafted: 15,
12779 accepted: 9,
12780 ..Default::default()
12781 };
12782 let d = small.delta_since(&big);
12783 assert_eq!((d.rounds, d.drafted, d.accepted), (0, 0, 0));
12784 }
12785}
12786
12787#[cfg(test)]
12788mod opti_fork_tests {
12789 use super::{
12790 OptiControllerPolicy, OptiForkAction, OptiForkGateMode, OptiForkGenerationTracker,
12791 };
12792
12793 #[test]
12794 fn controller_threshold_and_three_miss_breaker_are_exact() {
12795 let mut policy = OptiControllerPolicy {
12796 threshold: 0.7,
12797 consecutive_misses: 0,
12798 breaker_tripped: false,
12799 };
12800 assert!(!policy.admit(0.699_999));
12801 assert!(policy.admit(0.7));
12802 assert!(!policy.resolve(false));
12803 assert!(!policy.resolve(false));
12804 assert!(policy.resolve(false));
12805 assert!(policy.breaker_tripped);
12806 assert!(!policy.admit(1.0));
12807 assert!(
12808 !policy.resolve(true),
12809 "a resolved hit cannot re-arm a tripped request"
12810 );
12811 assert!(policy.breaker_tripped);
12812 }
12813
12814 #[test]
12815 fn zero_threshold_is_the_true_unconditional_measurement_arm() {
12816 let mut policy = OptiControllerPolicy {
12817 threshold: 0.0,
12818 consecutive_misses: 0,
12819 breaker_tripped: false,
12820 };
12821 for _ in 0..16 {
12822 assert!(policy.admit(0.0));
12823 assert!(!policy.resolve(false));
12824 }
12825 for invalid in [f32::NAN, f32::INFINITY, -0.01, 1.01] {
12826 assert!(
12827 !policy.admit(invalid),
12828 "invalid q proxy must fail closed: {invalid}"
12829 );
12830 }
12831 assert!(!policy.breaker_tripped);
12832 assert_eq!(policy.consecutive_misses, 0);
12833 }
12834
12835 #[test]
12836 fn alternating_mode_flips_by_generation_not_round_parity() {
12837 assert_eq!(OptiForkGateMode::Alternate.action(0), OptiForkAction::Hit);
12838 assert_eq!(OptiForkGateMode::Alternate.action(1), OptiForkAction::Miss);
12839 assert_eq!(OptiForkGateMode::Alternate.action(8), OptiForkAction::Hit);
12840 assert_eq!(OptiForkGateMode::Alternate.action(9), OptiForkAction::Miss);
12841 }
12842
12843 #[test]
12844 fn live_generation_cannot_be_overwritten() {
12845 let mut tracker = OptiForkGenerationTracker::default();
12846 let g0 = tracker.reserve().unwrap();
12847 let g1 = tracker.reserve().unwrap();
12848 let err = tracker.reserve().unwrap_err().to_string();
12849 assert!(
12850 err.contains("still owns generation 0"),
12851 "unexpected error: {err}"
12852 );
12853 tracker.retire(g0).unwrap();
12854 let g2 = tracker.reserve().unwrap();
12855 assert_eq!((g2.id, g2.slot), (2, 0));
12856 tracker.retire(g1).unwrap();
12857 tracker.retire(g2).unwrap();
12858 }
12859
12860 #[test]
12861 fn teardown_rejects_a_stale_generation_tag() {
12862 let mut tracker = OptiForkGenerationTracker::default();
12863 let g0 = tracker.reserve().unwrap();
12864 tracker.retire(g0).unwrap();
12865 let err = tracker.retire(g0).unwrap_err().to_string();
12866 assert!(err.contains("teardown mismatch"), "unexpected error: {err}");
12867 }
12868}
12869
12870#[cfg(test)]
12871mod draft_graph_fallback_tests {
12872 use super::DraftGraphFallback;
12873
12874 /// The Q2 contract, part (a): a fallback flip is LOUD — exactly once per flip.
12875 #[test]
12876 fn flip_is_loud_once_and_memoized_after() {
12877 let mut f = DraftGraphFallback::default();
12878 let line = f
12879 .mark_greedy("out of memory")
12880 .expect("first flip must return the warn line");
12881 assert!(
12882 line.contains("WARN"),
12883 "flip line must be warn-level: {line}"
12884 );
12885 assert!(
12886 line.contains("out of memory"),
12887 "flip line must carry the reason: {line}"
12888 );
12889 assert!(f.greedy_failed());
12890 // re-marking an already-failed graph is the memoization: quiet, still failed.
12891 assert!(f.mark_greedy("out of memory").is_none());
12892 assert!(f.greedy_failed());
12893 // the two graphs' flags are independent (greedy flip leaves sampled capturable).
12894 assert!(!f.sampled_failed());
12895 let line_s = f
12896 .mark_sampled("capture unsupported")
12897 .expect("sampled flip is its own flip");
12898 assert!(
12899 line_s.contains("sampled"),
12900 "sampled flip names itself: {line_s}"
12901 );
12902 assert!(f.mark_sampled("capture unsupported").is_none());
12903 }
12904
12905 /// The Q2 contract, part (b): resume-from-pool RESETS both flags (fresh capture chance),
12906 /// and says so exactly when there was something to reset.
12907 #[test]
12908 fn reset_on_resume_clears_flags_and_logs_once() {
12909 let mut f = DraftGraphFallback::default();
12910 // clean session: resume is silent, nothing to reset.
12911 assert!(f.reset_on_resume().is_none());
12912 f.mark_greedy("oom").unwrap();
12913 f.mark_sampled("oom").unwrap();
12914 let note = f
12915 .reset_on_resume()
12916 .expect("a set flag must produce the reset note");
12917 assert!(
12918 note.contains("greedy+sampled"),
12919 "note names what was reset: {note}"
12920 );
12921 assert!(
12922 !f.greedy_failed() && !f.sampled_failed(),
12923 "both flags cleared"
12924 );
12925 // and the NEXT failure after a reset is a fresh flip — loud again.
12926 assert!(f.mark_greedy("oom again").is_some());
12927 let note2 = f.reset_on_resume().expect("greedy-only reset");
12928 assert!(note2.contains("(greedy)"), "single-flag note: {note2}");
12929 }
12930
12931 /// Shape-change clears (dmask realloc / mask-shape mismatch / s_key change) stay silent —
12932 /// they precede a fresh capture attempt whose own failure re-flips loudly.
12933 #[test]
12934 fn shape_change_clears_are_silent() {
12935 let mut f = DraftGraphFallback::default();
12936 f.mark_greedy("oom").unwrap();
12937 f.clear_greedy();
12938 assert!(!f.greedy_failed());
12939 f.mark_sampled("oom").unwrap();
12940 f.clear_sampled();
12941 assert!(!f.sampled_failed());
12942 // after a silent clear there is nothing left for resume to report.
12943 assert!(f.reset_on_resume().is_none());
12944 }
12945}
12946
12947/// SAMPLED DRAFT-GRAPH KEY (lane/graph-s-key-exactness-20260819).
12948///
12949/// These are the CPU teeth for an exactness bug whose live reproduction needs a GPU, a trunk, a
12950/// drafter and a two-turn session: the key itself. Every test below fails against the pre-fix key
12951/// `(seed, temp.to_bits(), k)` — `legacy_key` restates it so the collision is explicit rather
12952/// than remembered.
12953#[cfg(test)]
12954mod sampled_graph_key_tests {
12955 use super::{SampledGraphKey, debug_t_pred0};
12956
12957 /// The pre-fix key, verbatim: `let s_key = (sp_seed, sp_temp.to_bits(), k);`
12958 fn legacy_key(k: &SampledGraphKey) -> (u64, u32, usize) {
12959 (k.seed, k.temp_bits, k.k)
12960 }
12961
12962 fn pure_temp_key() -> SampledGraphKey {
12963 // temperature 1.0, filters off — today's serve default, the shape that parks a graph.
12964 SampledGraphKey::new(12345, 1.0, 3, 0, 1.0, 0.0, false)
12965 }
12966
12967 /// THE COLLISION. Two requests that differ ONLY in the truncation filters shared one key, so
12968 /// a parked pure-temp graph survived into a filtered request and the launch site launched it.
12969 #[test]
12970 fn vendor_filters_change_the_key() {
12971 let parked = pure_temp_key();
12972 // qwen3.8 generation_config.json — what the vendor-default flip makes the default shape.
12973 let vendor = SampledGraphKey::new(12345, 1.0, 3, 20, 0.95, 0.0, false);
12974 assert_eq!(
12975 legacy_key(&parked),
12976 legacy_key(&vendor),
12977 "pre-fix key collided: this is the bug, and the reason a test asserts on it",
12978 );
12979 assert_ne!(parked, vendor, "post-fix key must separate the two regimes");
12980 assert!(parked.pure_temp());
12981 assert!(!vendor.pure_temp());
12982 }
12983
12984 /// Each distribution-shaping field alone is enough to drop the parked graph.
12985 #[test]
12986 fn every_filter_field_is_keyed() {
12987 let base = pure_temp_key();
12988 for (what, other) in [
12989 (
12990 "top_k",
12991 SampledGraphKey::new(12345, 1.0, 3, 20, 1.0, 0.0, false),
12992 ),
12993 (
12994 "top_p",
12995 SampledGraphKey::new(12345, 1.0, 3, 0, 0.95, 0.0, false),
12996 ),
12997 (
12998 "min_p",
12999 SampledGraphKey::new(12345, 1.0, 3, 0, 1.0, 0.05, false),
13000 ),
13001 (
13002 "penalties",
13003 SampledGraphKey::new(12345, 1.0, 3, 0, 1.0, 0.0, true),
13004 ),
13005 ] {
13006 assert_ne!(base, other, "{what} must be part of the key");
13007 assert!(!other.pure_temp(), "{what} leaves the pure-temp regime");
13008 assert_eq!(
13009 legacy_key(&base),
13010 legacy_key(&other),
13011 "{what} was invisible to the pre-fix key",
13012 );
13013 }
13014 }
13015
13016 /// The baked constants stay keyed (this half was always right — regression cover for it).
13017 #[test]
13018 fn baked_constants_stay_keyed() {
13019 let base = pure_temp_key();
13020 assert_ne!(
13021 base,
13022 SampledGraphKey::new(999, 1.0, 3, 0, 1.0, 0.0, false),
13023 "seed"
13024 );
13025 assert_ne!(
13026 base,
13027 SampledGraphKey::new(12345, 0.7, 3, 0, 1.0, 0.0, false),
13028 "temp"
13029 );
13030 assert_ne!(
13031 base,
13032 SampledGraphKey::new(12345, 1.0, 4, 0, 1.0, 0.0, false),
13033 "k"
13034 );
13035 // bitwise on temperature: 0.7f32 vs the same value re-derived must NOT differ.
13036 assert_eq!(
13037 SampledGraphKey::new(1, 0.7, 3, 0, 1.0, 0.0, false),
13038 SampledGraphKey::new(1, 7.0 / 10.0, 3, 0, 1.0, 0.0, false),
13039 );
13040 }
13041
13042 /// THE LOAD-BEARING HALF OF THE SEED DECISION (lane/session-resume-sampler-predicate-
13043 /// 20260820). The whole-session resume predicate deliberately does NOT compare `seed`: an
13044 /// omitted serve `seed` draws fresh per-request entropy, so comparing it would refuse every
13045 /// seed-omitting sampled conversation. That is only sound because the one piece of parked state
13046 /// that BAKES the seed — this graph — is re-keyed on it, so a seed change drops and recaptures.
13047 ///
13048 /// This test is the other end of that argument, asserted here rather than remembered in a
13049 /// comment: if a future change dropped `seed` from the key, the resume predicate's exclusion
13050 /// would silently become the unsound thing it is documented not to be.
13051 /// (Paired with `seed_alone_does_not_refuse` in `memra-sampling`.)
13052 #[test]
13053 fn seed_alone_still_rekeys_the_draft_graph() {
13054 let parked = pure_temp_key();
13055 let reseeded = SampledGraphKey::new(999, 1.0, 3, 0, 1.0, 0.0, false);
13056 assert_ne!(
13057 parked, reseeded,
13058 "a seed-only change MUST drop the parked sampled graph — the resume predicate's \
13059 decision not to compare seed rests on exactly this",
13060 );
13061 // Same regime on both sides: the drop is a recapture, not a fall to the eager chain
13062 // because of a filter difference.
13063 assert!(parked.pure_temp() && reseeded.pure_temp());
13064 }
13065
13066 /// `pure_temp()` is the capture guard's predicate, computed from the key so the two cannot
13067 /// drift. The equality below is the invariant the launch-site guard asserts: identical keys
13068 /// agree on the regime, so a graph that survives the drop is legal to launch.
13069 #[test]
13070 fn equal_keys_agree_on_the_regime() {
13071 let a = SampledGraphKey::new(7, 0.8, 3, 20, 0.95, 0.0, false);
13072 let b = SampledGraphKey::new(7, 0.8, 3, 20, 0.95, 0.0, false);
13073 assert_eq!(a, b);
13074 assert_eq!(a.pure_temp(), b.pure_temp());
13075 // top_p slightly above 1.0 (a client sending 1.0 exactly, or an operator default) is
13076 // still the unfiltered regime, matching the original `sp.top_p >= 1.0` test.
13077 assert!(SampledGraphKey::new(7, 0.8, 3, 0, 1.0, 0.0, false).pure_temp());
13078 assert!(SampledGraphKey::new(7, 0.8, 3, 0, 1.5, -1.0, false).pure_temp());
13079 }
13080
13081 /// MEMRA_DEBUG_SPEC on a SAMPLED spec request past round 0: the print must render without
13082 /// indexing the empty greedy `preds` vector (it panicked the GPU worker before this lane).
13083 #[test]
13084 fn debug_print_survives_the_sampled_arm() {
13085 // round >= 1 with a pending bonus == base 1, sampled == `preds` empty.
13086 assert_eq!(debug_t_pred0(true, 1, 4242, &[]), "n/a");
13087 assert_eq!(debug_t_pred0(true, 2, 4242, &[]), "n/a");
13088 // round 0 without a pending bonus still reports last_pred, in both arms.
13089 assert_eq!(debug_t_pred0(true, 0, 4242, &[]), "4242");
13090 assert_eq!(debug_t_pred0(false, 0, 4242, &[7, 8]), "4242");
13091 // greedy keeps the real prediction it always printed.
13092 assert_eq!(debug_t_pred0(false, 1, 4242, &[7, 8]), "7");
13093 assert_eq!(debug_t_pred0(false, 2, 4242, &[7, 8]), "8");
13094 }
13095}