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
31fn parse_prime_trows_width(value: Option<&str>) -> Result<usize, String> {
32 let Some(raw) = value else {
33 return Ok(8);
34 };
35 let width = raw
36 .parse::<usize>()
37 .map_err(|_| format!("MEMRA_PRIME_TROWS_T must be an integer in 2..=8, got {raw:?}"))?;
38 if !(2..=8).contains(&width) {
39 return Err(format!("MEMRA_PRIME_TROWS_T must be in 2..=8, got {width}"));
40 }
41 Ok(width)
42}
43
44#[cfg(test)]
45mod prime_trows_width_tests {
46 #[test]
47 fn width_defaults_to_eight_and_refuses_invalid_operator_values() {
48 assert_eq!(super::parse_prime_trows_width(None), Ok(8));
49 assert_eq!(super::parse_prime_trows_width(Some("2")), Ok(2));
50 assert_eq!(super::parse_prime_trows_width(Some("8")), Ok(8));
51 for invalid in ["", "1", "9", "32", "wide"] {
52 let err = super::parse_prime_trows_width(Some(invalid)).unwrap_err();
53 assert!(err.contains("MEMRA_PRIME_TROWS_T"), "{err}");
54 assert!(err.contains("2..=8"), "{err}");
55 }
56 }
57}
58
59/// One compact, anchor-bounded DSpark supervision record. `tokens[0]` is the anchor at p and
60/// `hidden` is its predecessor carrier h[p-1], matching the live NextN/DSpark pairing. Target
61/// rows p..p+gamma-1 score tokens p+1..p+gamma. They are the full-target softmax's top-k
62/// entries; `target_tail_probs[j]` is the probability mass outside those rows. All flattened
63/// target arrays are `[gamma, top_k]` in row-major order.
64pub struct DsparkAnchorRecord {
65 pub position: usize,
66 pub hidden: Vec<f32>,
67 pub tokens: Vec<u32>,
68 pub target_top_ids: Vec<u32>,
69 pub target_top_logits: Vec<f32>,
70 pub target_top_probs: Vec<f32>,
71 pub target_tail_probs: Vec<f32>,
72}
73
74fn dspark_sparse_softmax_topk(
75 logits: &[f32],
76 top_k: usize,
77 temperature: f32,
78) -> Result<(Vec<u32>, Vec<f32>, Vec<f32>, f32), Box<dyn std::error::Error>> {
79 if logits.is_empty() || top_k == 0 || top_k > logits.len() || temperature <= 0.0 {
80 return Err("invalid DSpark sparse-softmax shape or temperature".into());
81 }
82 if logits.iter().any(|value| !value.is_finite()) {
83 return Err("DSpark target logits contain a non-finite value".into());
84 }
85 let mut ranked: Vec<(u32, f32)> = logits
86 .iter()
87 .copied()
88 .enumerate()
89 .map(|(index, value)| (index as u32, value))
90 .collect();
91 let compare = |left: &(u32, f32), right: &(u32, f32)| {
92 right.1.total_cmp(&left.1).then(left.0.cmp(&right.0))
93 };
94 ranked.select_nth_unstable_by(top_k - 1, compare);
95 ranked[..top_k].sort_unstable_by(compare);
96
97 let max_logit = logits.iter().copied().fold(f32::NEG_INFINITY, f32::max);
98 let inv_temperature = 1.0f64 / temperature as f64;
99 let denominator: f64 = logits
100 .iter()
101 .map(|value| (((*value - max_logit) as f64) * inv_temperature).exp())
102 .sum();
103 let ids: Vec<u32> = ranked[..top_k].iter().map(|(index, _)| *index).collect();
104 let top_logits: Vec<f32> = ranked[..top_k].iter().map(|(_, value)| *value).collect();
105 let top_probs: Vec<f32> = top_logits
106 .iter()
107 .map(|value| ((((value - max_logit) as f64) * inv_temperature).exp() / denominator) as f32)
108 .collect();
109 let top_mass: f64 = top_probs.iter().map(|value| *value as f64).sum();
110 let tail = (1.0f64 - top_mass).clamp(0.0, 1.0) as f32;
111 Ok((ids, top_logits, top_probs, tail))
112}
113
114fn flatten_dspark_rows<T>(
115 rows: Vec<Option<Vec<T>>>,
116 position: usize,
117 label: &str,
118) -> Result<Vec<T>, Box<dyn std::error::Error>> {
119 let mut flattened = Vec::new();
120 for (slot, row) in rows.into_iter().enumerate() {
121 flattened.extend(
122 row.ok_or_else(|| format!("missing DSpark {label} at {position} slot {slot}"))?,
123 );
124 }
125 Ok(flattened)
126}
127
128/// H-SEED CONVENTION (MEMRA_SPEC_HPOST=1): feed the MTP head the POST-norm hidden — trunk rows
129/// hand over `output_norm(x)` and the draft chain recurrence hands over `shared_head_norm(h_nextn)`
130/// (= final_h) — matching the reference engines: llama.cpp #24025 ("qwen35: use post-norm hidden
131/// state for MTP", t_h_nextn is taken AFTER the final norm in both trunk and MTP graphs) and
132/// SGLang's qwen3_5_mtp (spec_info.hidden_states = the target model's post-norm output). memra's
133/// historical convention (default, MTP-PLAN §A) is PRE-norm x. Draft-quality-only: exactness is
134/// the verify's job either way; acceptance arbitrates. OnceLock: read once, hot-loop safe.
135pub(crate) fn spec_hpost() -> bool {
136 static H: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
137 *H.get_or_init(|| {
138 std::env::var("MEMRA_SPEC_HPOST")
139 .map(|v| v != "0")
140 .unwrap_or(false)
141 })
142}
143
144/// LEAN VERIFY (default ON since 2026-07-08; MEMRA_SPEC_LEAN=0 reverts — close35 lane): the verify m-scaling
145/// probe + nsys diff showed the verify t-path pays ~1.0ms/call at m=1 over eager decode on the
146/// 35B, and the kernels are NOT the cause (dev-MoE identical, kernel-time delta only +179us).
147/// The overhead is (a) ~250 extra cuMemsetD8Async/call from `e.zeros()` on buffers every kernel
148/// fully overwrites (~0.9ms host issue + ~0.35ms GPU) and (b) the t=1 FA rows dispatch (rows_v2 +
149/// combine_rows, +50us vs the eager fa_decode pair). This flag switches (a) fully-overwritten
150/// verify buffers to `e.uninit` (identical bytes: every element is written before read) and
151/// (b) t==1 verify FA to the eager `fa_decode` entry (byte-identical: kernel-check pins the
152/// rows-vs-loop identity and the per-row loop at t=1 IS fa_decode on the same q). Gates arbitrate.
153pub(crate) fn spec_lean() -> bool {
154 static L: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
155 // DEFAULT ON since 2026-07-08 (MEMRA_SPEC_LEAN=0 reverts): bit-identical (buffers fully
156 // overwritten; gates green incl maxdiff-identical run-gen) and measured +2.4% e2e p3 /
157 // +1.5% p2 at the daily 35B config. m=1 verify now costs eager-decode parity.
158 *L.get_or_init(|| {
159 std::env::var("MEMRA_SPEC_LEAN")
160 .map(|v| v != "0")
161 .unwrap_or(true)
162 })
163}
164
165/// SMALL-M BATCHED VERIFY (default ON since 2026-07-09; MEMRA_SPEC_M2=0 reverts — lane/spec-m2): extend the
166/// batched linear-attn verify arm down to t=2 and batch the MoE dev token loop over a
167/// grid.z=token axis at every verify t. The close35 m-scaling probe put the m=2 verify tier at
168/// x1.54 of m=1 (llama x1.14); the per-column linear chain (t<3) and the serial MoE dev token
169/// loop are the two launch-structure causes. Both changes are LAUNCH-STRUCTURE ONLY:
170/// (a) the batched conv's t<pad ring update is pure copies (ssm_conv_ring_rebuild from a cloned
171/// ring — the ring stores raw input columns); every arithmetic kernel is the same one the
172/// t>=3 arm already runs (matmul_decode_exact bit-identical at m=2-4, gdn_scan's internal
173/// t-loop == chained T=1 steps);
174/// (b) the MoE dev-rows twins run the serial loop's per-token warp program with tok-offset
175/// pointers (same sel/w/aq/ad bytes, same dot order, same slot-ordered FMA chain).
176/// Gates arbitrate: run-spec K=1..8 self-consistency (35B+9B), kernel-check, run-gen argmax.
177pub(crate) fn spec_m2() -> bool {
178 static M: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
179 // DEFAULT ON since 2026-07-09 (MEMRA_SPEC_M2=0 reverts): launch-structure only — t=2
180 // batched linear arm (ring-roll copies, zero new FP order) + MoE dev-rows kernels
181 // (grid.z=token, 4 launches/layer at any verify t). Acceptance bit-identical at every K;
182 // 35B p2 +3.4% / p3 +3.6%; the profitable-K plateau widens (new optimum K=3 at 223).
183 *M.get_or_init(|| {
184 std::env::var("MEMRA_SPEC_M2")
185 .map(|v| v != "0")
186 .unwrap_or(true)
187 })
188}
189pub(crate) fn spec_stream() -> bool {
190 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
191 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_STREAM").as_deref() == Ok("1"))
192}
193pub(crate) fn spec_stream_m() -> usize {
194 static M: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
195 *M.get_or_init(|| {
196 std::env::var("MEMRA_SPEC_STREAM_M")
197 .ok()
198 .and_then(|v| v.parse().ok())
199 .unwrap_or(4)
200 })
201}
202pub(crate) fn spec_devacc() -> bool {
203 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
204 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_DEVACC").as_deref() == Ok("1"))
205}
206/// Engine-bundle slice 2 (DSF-ROUNDCOST-20260820 §1.1 host/device round trips + §2 rows 2-3),
207/// DEFAULT ON (`MEMRA_DSPARK_DEFER_READBACK=0` reverts): the dspark round's draft-chain DtoH
208/// is DEFERRED past verify dispatch and merged with the verify-argmax readback into ONE host
209/// sync (2 blocking DtoH/round -> 1). Verify embeds DEVICE tokens (`chain_d`) through the
210/// resident embed table — `embed_gather_u32_t`, bit-identical rows to the host gather by its
211/// own pinned contract. The host therefore dispatches snap + the whole verify while the DRAFT
212/// is still executing, instead of blocking ~1.7 ms on the chain and letting the device drain.
213/// Ladder arm only: the confidence policies size vt from a pre-verify head readback (their
214/// chain readback merges into that same sync instead). Exactness unchanged BY CONSTRUCTION —
215/// same tokens, same kernels, same order; E2E + accept-bank gates arbitrate.
216pub(crate) fn dspark_defer_readback_on() -> bool {
217 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
218 *ON.get_or_init(|| {
219 std::env::var("MEMRA_DSPARK_DEFER_READBACK")
220 .map(|v| v != "0")
221 .unwrap_or(true)
222 })
223}
224/// Engine-bundle slice 1 (DSF-ROUNDCOST-20260820 §1.1, lane/dspark-engine-bundle-20260820),
225/// DEFAULT ON (`MEMRA_STATE_COPY_BATCH=0` reverts): batch the dspark round's GDN state
226/// snapshot and partial-accept restore into single `copy_batch_uniform_f32` launches
227/// instead of ~2 memcpy dispatches (+2 alloc_zeros on the snap side) per linear layer per
228/// round — measured 0.67 ms/round snap + 0.25 ms/round commit of pure dispatch on the q38
229/// route. Launch-structure only: bytes, buffers and stream order are unchanged, so
230/// acceptance and streams stay bit-identical (E2E-gated on the B1 packs).
231pub(crate) fn state_copy_batch_on() -> bool {
232 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
233 *ON.get_or_init(|| {
234 std::env::var("MEMRA_STATE_COPY_BATCH")
235 .map(|v| v != "0")
236 .unwrap_or(true)
237 })
238}
239/// Engine-bundle slice 3 + fa-execupdate slice 4c (DSF-ROUNDCOST-20260820 §5 rank 1),
240/// DEFAULT OFF — `MEMRA_DSPARK_VERIFY_GRAPH=1` opts in: per-(segment, vt) CUDA graphs
241/// for the LINEAR-layer runs, plus the full-verify single graph per (vt, rung) when a
242/// round's rows all ride one seqs rung — see [`DsparkVerifyGraphs`]. Requires the
243/// slice-2 deferred path (device tokens); the eager walk is the byte-identical fallback.
244///
245/// MEASURED disposition (box6 card0, agentic pack, 2026-08-20, both slices): exactness
246/// holds everywhere (ALL EXACT, accept lines byte-match the banks, ckpt-gate oracle
247/// green over the graph + slab-commit paths). Slice-3's AUTO_FREE launch-scan limiter
248/// (25.6 us x 16 launches ≈ 0.41 ms/round) is FIXED — the captured bodies' alloc nodes
249/// are balanced by in-graph frees (census 84/84 per segment, 1776/1776 full) so graphs
250/// instantiate USE_NODE_PRIORITY and the scan is gone. What remains at gate scale:
251/// segment graphs +0.1 tok/s over the batched-rows default (114.4 vs 114.3 x5
252/// interleaved — the linear launch overhead was only ~0.1 ms); the FULL-verify graph is
253/// NET NEGATIVE at gate scale (110.6 vs 114.2: ~14-21 (vt, rung) captures/process at
254/// 2 full-walk executions + ~2.9k-node instantiate each eat far more than the ~0.2-0.3
255/// ms/round of remaining launch overhead). The orchestration ceiling of §1.3 is spent —
256/// the fa/append recovery landed DEFAULT-ON as the batched rows arm
257/// (`dspark_fa_rows_on`), not as a graph. The serve-lifetime cell (DSF-ROUNDCOST §9,
258/// nj-ws-solo) measured the amortization: crossover K≈33 requests, steady −0.246
259/// ms/round, −1.25% session wall over 240 requests — and the graphs-serve lane wired
260/// the door into the session arm (`dspark_spec_session_burst`) as a model-owned
261/// capture pool shared across sessions. Stays opt-in pending the owner's default-ON
262/// ratification on the serve-surface battery.
263pub(crate) fn dspark_verify_graph_on() -> bool {
264 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
265 *ON.get_or_init(|| std::env::var("MEMRA_DSPARK_VERIFY_GRAPH").as_deref() == Ok("1"))
266}
267/// MTP-ROUTE verify graphs, DEFAULT ON for the GDN+MoE family since 2026-08-23
268/// (`MEMRA_SPEC_VERIFY_GRAPH=0` is the kill switch, `=1` opts other families in).
269///
270/// The slice-4c capture already lived inside `qwen35_verify_tparallel` and said so in its own
271/// comment — "stream rides the qwen35moe burst, graphs ride the dspark route" — with no caller
272/// on this route. The MTP spec round is that caller.
273///
274/// WHY it is worth a default (receipts: `research/orndecode-20260822/VGRAPH.md`). With
275/// `MEMRA_SPEC_PHASE=1` this route's round reads verify-ISSUE 44-58% and verify-WAIT **0.0%**:
276/// the host is never waiting for the device, it is spending its own time launching the trunk.
277/// Replay collapses that into one graph launch and the phase all but disappears (55-62 ms ->
278/// 8-10 ms per burst).
279///
280/// MEASURED, two host generations, forced ON/OFF, balanced 4+4 boots in both orders:
281/// * current-generation host (9950X, the serving class): OFF 266.0-266.5, ON 318.8-319.5
282/// tok/s — **+19.7%**, no overlap, sub-1% spread per arm; per-round 6.9 -> 5.7 ms.
283/// * Zen 3 host: +3-9% (that rig's own clock drift is wider than the effect, so the ratio
284/// comes from per-round phase totals, which are internal to each boot).
285/// The ON arm lands at ~320 tok/s on BOTH hosts while OFF tracks host speed — the arm moves
286/// the round off the host and onto the device, which is the whole point.
287///
288/// EXACTNESS is structural (same kernels, same order) and gated anyway: a fixed-seed SAMPLED
289/// completion hashes identically ON vs OFF **and across both hosts** (`08941d5bb9762b21`),
290/// greedy seed-pinned likewise, `run-spec` K=1..8 PASS on both arms with identical acceptance
291/// at every K, kernel-check ALL GREEN.
292///
293/// SCOPE, deliberately narrow: default ON only where it was measured — the GatedDeltaNet +
294/// MoE family (`vgraph_family_default`). Qwen3.8-27B is GDN + DENSE mlp and would otherwise
295/// inherit this default unmeasured, which is the family-by-family law this repo keeps; it can
296/// opt in with `=1` once it has its own interleave. Also never armed together with
297/// ROUND-STREAM, and a round wider than the pool declines it for the eager walk.
298pub(crate) fn spec_verify_graph_env() -> Option<bool> {
299 static ON: std::sync::OnceLock<Option<bool>> = std::sync::OnceLock::new();
300 *ON.get_or_init(
301 || match std::env::var("MEMRA_SPEC_VERIFY_GRAPH").as_deref() {
302 Ok("1") => Some(true),
303 Ok("0") => Some(false),
304 _ => None,
305 },
306 )
307}
308/// SERVE-ROUTE twin of [`dspark_verify_graph_on`], DEFAULT ON — owner-ratified
309/// 2026-08-22 on the §10 serve-lifetime battery (DSF-ROUNDCOST-20260820 §10.3:
310/// crossover K=36–43, steady −0.357 ms/round, session wall −1.55..−1.65%, byte-exact
311/// 240/240 ×3 pairs, pool bounded at 8,852 MiB under `MEMRA_DSPARK_VG_MAX`). The env
312/// stays as the kill-switch: `MEMRA_DSPARK_VERIFY_GRAPH=0` restores the eager walk
313/// (byte-identical body); `MEMRA_DSPARK_VG_MAX=0` is the finer freeze valve. The BIN
314/// arm keeps its own opt-in default (`dspark_verify_graph_on`): at gate scale the
315/// capture toll is never repaid (§8 measured disposition — 14–21 captures over a
316/// 256-token run vs the serve session's thousands of rounds), and the two
317/// instruments must keep their own measured dispositions rather than share one flag.
318pub(crate) fn dspark_verify_graph_serve_on() -> bool {
319 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
320 *ON.get_or_init(|| std::env::var("MEMRA_DSPARK_VERIFY_GRAPH").as_deref() != Ok("0"))
321}
322/// Capture-count ceiling for the dspark verify-graph pool (graphs-serve lane) — the
323/// pool's memory policy STATED instead of silently unbounded. The keyspace is
324/// intrinsically finite — segment keys (run_start, vt) ≤ 16 runs x 7 windows, full
325/// keys (vt, rung, hi) ≤ 7 windows x the split-rung ladder (8 rungs at 32k ctx), ~168
326/// on the q38 export — so the default (256) never engages there; the knob is the
327/// safety valve for a future export with a wider ladder. At the ceiling the pool
328/// FREEZES: existing keys keep replaying, rounds needing a new capture run the eager
329/// walk byte-identically (round-atomic — a partial refusal would mix slab- and
330/// cols-stashed layers inside one commit). No eviction by design: destroying a live
331/// exec graph re-opens the stale-address class the indirect tables exist to close,
332/// and the bounded keyspace makes reclaim worthless.
333pub(crate) fn dspark_vg_cap() -> usize {
334 static CAP: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
335 *CAP.get_or_init(|| {
336 std::env::var("MEMRA_DSPARK_VG_MAX")
337 .ok()
338 .and_then(|v| v.parse().ok())
339 .unwrap_or(256)
340 })
341}
342
343/// PROJECTED REMAINING GROWTH of the verify-graph pool, in bytes (lane/hermes-perf-fixes,
344/// 2026-08-23 — the admission accounting the "pool dwarfs spec admission reserve" finding
345/// asks for). The pool was measured at 8,852 MiB at storm-complete on the q38 export while
346/// admission's transient floor (`SPEC_SHRINK_RESERVE`) is 1.5 GiB and never charged for it:
347/// sessions admitted while the pool is cold overcommit VRAM the pool WILL hold, because the
348/// pool grows monotonically (no eviction by design) and is model-owned across sessions.
349///
350/// SELF-MEASURING, no per-model constant (generic-model law — the 8,852 MiB is a q38 number
351/// and proves nothing about another export): the debt is remaining capture slots x the
352/// MARGINAL bytes a capture adds to this device's graph mem pool.
353///
354/// MARGINAL, NOT MEAN — measured correction (box9 on-box receipt, 2026-08-23). The first
355/// version of this used the mean (`reserved / captures`) and the live serve log showed why
356/// that is wrong: with the pool's reservation flat at ~33.6 MiB across captures 1..3, the
357/// mean-based debt printed **8,556 MB, then 4,261, then 2,830** — it extrapolated capture
358/// #1's ONE-TIME shared allocation (staging buffers, stash slabs, pointer tables: sized
359/// once per pool, shared by every key) across all 256 slots. An 8.5 GB phantom reserve at
360/// boot can refuse admissions that would have fit, which is a worse defect than the
361/// under-charge this accounting exists to remove. The marginal reading prices what an
362/// ADDITIONAL key actually costs: two observations `(captures, reserved)` give
363/// `(r1 - r0) / (c1 - c0)`, which is ~0 on an export whose pool does not grow per key and
364/// tracks real growth on one that does.
365///
366/// BOOTSTRAP (only one observation so far, so growth is unmeasurable): reserve one more
367/// pool's worth — `min(remaining x mean, reserved)`. "We have measured `reserved` bytes for
368/// `captures` keys; until growth is measurable, assume at most a doubling" is fail-safe in
369/// the same direction as the old rule without the 255x extrapolation.
370///
371/// Before the FIRST capture the debt is 0 (a single capture lands well inside the existing
372/// 1.5 GiB floor). `cap` is the intrinsic freeze ceiling (`MEMRA_DSPARK_VG_MAX`; =0 freeze
373/// valve => the pool cannot grow => debt 0); at or past the cap the pool FREEZES, so the
374/// debt is 0 there too.
375pub fn dspark_vg_debt_projection(
376 captures: usize,
377 cap: usize,
378 reserved_bytes: usize,
379 prev: Option<(usize, usize)>,
380) -> usize {
381 if captures == 0 || cap == 0 {
382 return 0;
383 }
384 let remaining = cap.saturating_sub(captures);
385 if remaining == 0 {
386 return 0;
387 }
388 match prev {
389 // marginal growth between two observations of the same pool
390 Some((c0, r0)) if captures > c0 => {
391 let marginal = reserved_bytes.saturating_sub(r0) / (captures - c0);
392 remaining.saturating_mul(marginal)
393 }
394 // bootstrap: at most one more pool's worth
395 _ => remaining
396 .saturating_mul(reserved_bytes / captures)
397 .min(reserved_bytes),
398 }
399}
400/// Engine-bundle slice 4 (fa-execupdate lane, DSF-ROUNDCOST-20260820 §6 close: "the
401/// residual gap lives in the FULL-ATTENTION per-row section"), DEFAULT ON —
402/// `MEMRA_DSPARK_FA_ROWS=0` reverts to the per-row loop: when every row of a verify
403/// round takes the v4-seqs arm on ONE `fa_split_keys` rung (the straddle law, evaluated
404/// at the round's first and last t_kv — both eligibility gates are intervals in t_kv),
405/// the qwen35 t-parallel verify's per-row KV-append + fa-decode loop collapses into the
406/// z-batched serving twins: ONE `append_quantize_kv_q8_0_q5_1_seqs` + ONE
407/// `fa_decode_vec_q_seqs_v4` + ONE combine per full-attention layer, replacing
408/// T x (4 dtod row copies + append + 3 memsets + main + combine) launches. Bytes are
409/// pinned by the batched-tick increment-2 kernel-check (seqs-vs-per-seq-loop bit
410/// identity: per-row T_kv derives in-kernel from pos_seq[z]; splits >= ns_eff write the
411/// empty partial the combine never reads, so the shared n_splits_max stride changes no
412/// bytes) and re-gated e2e by this lane's battery.
413pub(crate) fn dspark_fa_rows_on() -> bool {
414 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
415 *ON.get_or_init(|| {
416 std::env::var("MEMRA_DSPARK_FA_ROWS")
417 .map(|v| v != "0")
418 .unwrap_or(true)
419 })
420}
421
422/// `t_pred0` for the `MEMRA_DEBUG_SPEC` per-round print, sampled-safe.
423///
424/// `generate_spec_inner2` fills its `preds` vector ONLY on the greedy path (`if !sampled`), and
425/// the per-round debug print was the sole consumer in the sampled arm: `t_pred(0)` survives round
426/// 0 (`base == 0` returns `last_pred`) and from round 1 (`base == 1`, a pending bonus) indexes an
427/// EMPTY vector — `index out of bounds: the len is 0 but the index is 0`, in the GPU worker
428/// thread, which then respawns and reloads weights while the request dies. So any sampled spec
429/// request longer than one round used to kill the worker whenever `MEMRA_DEBUG_SPEC` was set:
430/// the flag crashed precisely the regime it exists to investigate.
431///
432/// Fixed at the print site, not inside the closure, so the greedy accept walk keeps its strict
433/// indexing (an out-of-range pred there is a real bug and must still be loud).
434fn debug_t_pred0(sampled: bool, base: usize, last_pred: u32, preds: &[u32]) -> String {
435 if base == 0 {
436 return last_pred.to_string();
437 }
438 match preds.get(base - 1) {
439 Some(p) => p.to_string(),
440 // sampled: the greedy per-column argmax was never run for this round.
441 None => {
442 debug_assert!(
443 sampled,
444 "greedy spec: preds[{}] missing at base {base}",
445 base - 1
446 );
447 "n/a".to_string()
448 }
449 }
450}
451
452/// `MEMRA_SKEY_PROBE=1` — sampled-draft-graph key probe (lane/graph-s-key-exactness-20260819).
453///
454/// Reports, per burst and per round, which draft chain the sampled arm chose and under which
455/// filter regime, plus the ONE observable that separates a legal filtered draft from a stale
456/// pure-temp graph replayed under filters: an accept test whose gathered `q` is exactly 0.
457/// A draft token sampled from the FILTERED softmax can never gather q=0 (it was drawn from the
458/// kept set), so `q=0` in the verify means the draft came from a distribution the verify does
459/// not believe in — and `u * 0 < p` then accepts it unconditionally.
460///
461/// Its own env var, deliberately NOT `MEMRA_DEBUG_SPEC`: that flag panicked the GPU worker on
462/// any sampled spec request past round 0 until this lane fixed it (§2 of the bank note).
463pub(crate) fn skey_probe() -> bool {
464 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
465 *ON.get_or_init(|| std::env::var("MEMRA_SKEY_PROBE").as_deref() == Ok("1"))
466}
467
468/// GRAMMAR HOOK for constrained spec decode (lane/constrained-full, 2026-08-03). The engine
469/// stays llguidance-agnostic: the server adapts its per-session grammar state behind this
470/// trait. CONTRACT (the verify-side truncation rule — token-identical to constrained plain
471/// greedy decode): the exactness walk runs UNMASKED first; the hook then (a) truncates
472/// acceptance at the first grammar-illegal accepted token, and (b) when the truncation fired
473/// or the bonus is illegal, the engine recomputes that slot as the MASKED argmax of the
474/// target's own verify column (an unmasked argmax that is grammar-legal IS the masked argmax
475/// — masking only removes tokens — so the common case pays nothing). `consume` advances the
476/// state with each EMITTED token in order; EOS handling is the implementor's job (skip).
477pub trait SpecConstraint {
478 /// -inf the current state's banned ids on a HOST logits row (prompt-tail / init-feed
479 /// masked argmax).
480 fn mask_logits(&mut self, logits: &mut [f32]) -> Result<(), String>;
481 /// Packed 32-bit bitset words of the CURRENT state's allowed set (device-mask form).
482 fn mask_words(&mut self) -> Result<Vec<u32>, String>;
483 /// Is `tok` consumable in the CURRENT state?
484 fn is_allowed(&mut self, tok: u32) -> Result<bool, String>;
485 /// Advance the state with an emitted token.
486 fn consume(&mut self, tok: u32) -> Result<(), String>;
487
488 // --- DRAFT-SIDE MASKING (lane/draft-mask, 2026-08-04) ---
489 // The drafter proposed grammar-illegal tokens under tight schemas, so verify-side
490 // truncation cut nearly every round (measured acceptance 0.467-0.513 tight vs 0.62-0.82
491 // loose, research/constrained-full-20260803). These three methods let the engine mask the
492 // DRAFT model's own sampling with the grammar's legal set, so proposals are legal by
493 // construction. The state they walk is a SPECULATIVE CLONE of the session matcher — the
494 // real state is advanced only by `consume` (emitted tokens), so verify-side truncation
495 // stays the correctness backstop and the emitted stream is unchanged by construction
496 // (an accepted draft is the target's unmasked argmax AND grammar-legal, hence the masked
497 // argmax; a cut slot is recomputed as the masked argmax either way).
498 // Default impls = feature OFF (pre-lane behaviour: unmasked drafts).
499
500 /// Is draft-side masking available on this hook? Probed ONCE per burst, before the draft
501 /// graph is captured (the mask is an in-graph node — its presence is a capture-time shape).
502 fn draft_mask_enabled(&self) -> bool {
503 false
504 }
505 /// Start a draft chain: clone the CURRENT (committed) grammar state into the speculative
506 /// slot. Called once per spec round, before the first draft position.
507 fn draft_begin(&mut self) -> Result<(), String> {
508 Ok(())
509 }
510 /// Packed 32-bit bitset words of the SPECULATIVE state's allowed set (target-vocab ids),
511 /// for the draft position about to be sampled. `None` = draft masking off (no-op).
512 fn draft_mask_words(&mut self) -> Result<Option<Vec<u32>>, String> {
513 Ok(None)
514 }
515 /// Advance the SPECULATIVE state with a PROPOSED draft token. `false` = the chain cannot
516 /// continue (EOS proposed, or an unmasked position proposed something illegal) — the
517 /// engine stops drafting; the token already pushed still goes through verify.
518 fn draft_advance(&mut self, _tok: u32) -> Result<bool, String> {
519 Ok(false)
520 }
521}
522
523/// DRAFT-MASK UPLOAD (lane/draft-mask): pull the speculative state's allowed set (TARGET-id
524/// space) from the hook, project it into the DRAFT head's vocab space, and upload it into the
525/// stable device buffer the draft chain reads. Returns false when the chain must stop drafting:
526/// the hook handed out no mask, or NO draft-vocab row is grammar-legal at this position (a
527/// trimmed FR-Spec head genuinely cannot propose a legal token there — masking it would leave
528/// a fully-banned row whose argmax is meaningless, so the round drafts fewer tokens and the
529/// verify emits the masked argmax as usual).
530fn upload_draft_mask(
531 e: &Engine,
532 c: &mut dyn SpecConstraint,
533 dst: &mut CudaSlice<u32>,
534 d2t: Option<&Vec<u32>>,
535 d_vocab: usize,
536 words: usize,
537) -> Result<bool, Box<dyn std::error::Error>> {
538 let Some(tw) = c
539 .draft_mask_words()
540 .map_err(|e2| format!("constraint: {e2}"))?
541 else {
542 return Ok(false);
543 };
544 let bit = |t: usize| -> bool {
545 let w = t >> 5;
546 w < tw.len() && (tw[w] >> (t & 31)) & 1 == 1
547 };
548 let mut buf = vec![0u32; words];
549 match d2t {
550 // TRIMMED draft head: row i proposes target id d2t[i] — permute the mask accordingly.
551 Some(map) => {
552 for (i, &t) in map.iter().enumerate().take(d_vocab) {
553 if bit(t as usize) {
554 buf[i >> 5] |= 1u32 << (i & 31);
555 }
556 }
557 }
558 // UNTRIMMED: draft ids ARE target ids; the packed words transfer verbatim (a short
559 // mask leaves the padded tail zeroed == banned, same rule as constrained::apply_mask).
560 None => {
561 let n = tw.len().min(words);
562 buf[..n].copy_from_slice(&tw[..n]);
563 }
564 }
565 if buf.iter().all(|w| *w == 0) {
566 return Ok(false);
567 }
568 e.htod_u32_into(dst, &buf)?;
569 Ok(true)
570}
571
572/// Keep the full token-embedding table in host memory and upload only the rows needed by each
573/// MTP/verify step. This is an exact memory-capacity seam for very large BF16 vocab tables: host
574/// gather expands the same source bits to f32, and only O(T*n_embd) bytes cross PCIe per step.
575/// CUDA-graph/round-stream draft paths require device token ids and therefore stay disabled.
576pub(crate) fn spec_host_embd() -> bool {
577 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
578 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_HOST_EMBD").as_deref() == Ok("1"))
579}
580
581/// VERIFY-TIER TRUNK LAUNCH-FUSION (default ON since 2026-07-09; MEMRA_SPEC_FUSED_T=0 reverts — lane/close35b): extend
582/// the t=1 fused2/fused3 Q8_0 trunk launches to the batched verify tier (t=2-4, the K=1..3
583/// verify shapes). At t>1 the trunk pairs/triples (35B wqkv+wqkv_gate, wq/wk/wv,
584/// gate_shexp+up_shexp) each run a separate `matmul_decode_exact` — one q8_1 re-quantize of the
585/// SAME activation plus one _b2/_b4 launch per tensor. The fused twins share ONE quantize and
586/// ONE launch per group; per (tensor,token,row) the kernel body is q8_0_mmvq_batched verbatim
587/// with the identical row mapping -> BIT-IDENTICAL by construction (kernel-check pins it,
588/// run-spec K=1..8 + acceptance identity arbitrate e2e).
589pub(crate) fn spec_fused_t() -> bool {
590 static F: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
591 // DEFAULT ON since 2026-07-09 (MEMRA_SPEC_FUSED_T=0 reverts): verify t=2-4 trunk launch-fusion
592 // (fused2/fused3 Q8_0 batched twins, bit-identical by construction — m=1 block-offset split on
593 // the batched body). m=2 marginal token 2117->1762us; 35B daily: p3 +3.7% (crosses llama), p2 +5%.
594 *F.get_or_init(|| {
595 std::env::var("MEMRA_SPEC_FUSED_T")
596 .map(|v| v != "0")
597 .unwrap_or(true)
598 })
599}
600
601/// zeros/uninit switch for verify-path buffers that are FULLY OVERWRITTEN before any read.
602/// Only call this on such buffers — the lean contract is "identical bytes by construction".
603fn vbuf(e: &Engine, n: usize) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
604 if spec_lean() { e.uninit(n) } else { e.zeros(n) }
605}
606
607/// Scratch KV for the MTP block (one full-attn layer).
608///
609/// PERSISTENT MODE (default, 2026-07-03 — the acceptance lever): sized cap = max_ctx and kept in
610/// sync with the COMMITTED sequence — slot p holds the MTP block's K/V for committed token p
611/// (roped p+1, the chain's rope convention), so the draft chain's self-attention sees the FULL
612/// committed history instead of only the current round's 1..K+1 chain tokens (the reference
613/// engine's "mtp_update" design). Entries come from two sources:
614/// - chain appends: accepted positions KEEP their chain-computed entries (embedding exact,
615/// hidden chain-approximate — the reference engine accepts the same);
616/// - `mtp_kv_fill` batches: prompt positions + the last-draft position on full accept, computed
617/// from EXACT trunk hiddens (K/V-only MTP-block pass, no attention/FFN/lm_head).
618/// Rejected drafts / p-min extras / pseudo-seed appends are all discarded by the round-start
619/// `set_len` truncation (the KvLayer len mechanism — §C rollback for the draft side).
620/// Multi-turn spec-decode session (2026-07-05): trunk Cache + persistent MTP draft scratch +
621/// the committed token list, alive across generate_spec_session calls. Turn N+1 primes ONLY its
622/// suffix (chunked continuation prime over the quantized past) and mtp_kv_fill's its suffix rows,
623/// then the round loop runs unchanged. `last_h` carries the pre-output_norm hidden of the last
624/// committed row across turns (the predecessor-pairing seed + fill anchor).
625/// Per-request sampling config for the sampled-spec serve path.
626#[derive(Clone, Copy, Debug)]
627pub struct SpecSampling {
628 pub temp: f32,
629 pub seed: u64,
630 pub top_k: i32, // 0 = off
631 pub top_p: f32, // 1.0 = off
632 pub min_p: f32, // 0.0 = off
633 pub penalty_last_n: usize, // 0 = penalties off
634 pub penalty_repeat: f32,
635 pub penalty_freq: f32,
636 pub penalty_present: f32,
637}
638
639impl SpecSampling {
640 /// Non-identity penalties requested — THE `pen_on` predicate (one definition; the
641 /// same group-off rule `SamplerIdentity::of` canonicalizes: a window with neutral
642 /// coefficients is penalties-absent). Both spec routes and the dspark accept walk
643 /// key their penalty arms off this.
644 pub fn pen_on(&self) -> bool {
645 self.penalty_last_n > 0
646 && (self.penalty_repeat != 1.0
647 || self.penalty_freq != 0.0
648 || self.penalty_present != 0.0)
649 }
650}
651
652/// Host Philox4x32-10 uniform in (0,1) — mirrors spec_sample.cu's `philox4`/`u01` with the
653/// ctr_lo tag 0xFFFF_FFFE, so the host accept-test stream never collides with any device
654/// sampling event (device Gumbel uses (i>>2, stream_pos); device residual uses 0xFFFF_FFFD).
655/// One value per (seed, ctr) EVENT; callers own the counter discipline. Extracted verbatim
656/// from generate_spec_inner2's closure for the dspark sampled-admission walk (the two paths
657/// MUST consume the identical stream construction — two ad-hoc Philox copies drifting apart
658/// is a distributional bug, not a style problem).
659pub(crate) fn host_u01(seed: u64, ctr: u32) -> f32 {
660 let (m0, m1) = (0xD2511F53u32, 0xCD9E8D57u32);
661 let (mut c0, mut c1, mut c2, mut c3) = (0xFFFF_FFFEu32, ctr, 0u32, 0u32);
662 let (mut k0, mut k1) = ((seed & 0xFFFF_FFFF) as u32, (seed >> 32) as u32);
663 for _ in 0..10 {
664 let (h0, l0) = (((m0 as u64 * c0 as u64) >> 32) as u32, m0.wrapping_mul(c0));
665 let (h1, l1) = (((m1 as u64 * c2 as u64) >> 32) as u32, m1.wrapping_mul(c2));
666 let (n0, n1, n2, n3) = (h1 ^ c1 ^ k0, l1, h0 ^ c3 ^ k1, l0);
667 c0 = n0;
668 c1 = n1;
669 c2 = n2;
670 c3 = n3;
671 k0 = k0.wrapping_add(0x9E3779B9);
672 k1 = k1.wrapping_add(0xBB67AE85);
673 }
674 (c0 as f32 + 1.0) * (1.0 / 4294967296.0)
675}
676
677/// Tracked draft positions for [`SpecTelemetry`] (serve K defaults to 3; the run-spec gate
678/// sweeps K=1..8, and MEMRA_SPEC_CAPMAX defaults to 7 — 8 covers every tuned config).
679pub const SPEC_TELEM_POS: usize = 8;
680
681/// Always-on per-draft-position acceptance telemetry (lane/accept-telemetry, 2026-08-05 —
682/// the llama.cpp #26389 / vLLM spec-decode counter schema, upstream-sweeps 2026-08-05).
683/// Lives on the [`SpecSession`] and accumulates across bursts; the serve worker diffs a
684/// stashed copy per burst for its per-model /metrics aggregation and per-request usage.
685/// Same normalization as the `[spec-stats]` line: p-min-discarded chain tokens are counted
686/// in NEITHER drafted nor accepted.
687#[derive(Clone, Copy, Default, Debug)]
688pub struct SpecTelemetry {
689 /// verify rounds completed (a round-stream burst counts each of its M rounds).
690 pub rounds: u64,
691 /// tokens drafted / accepted across all rounds.
692 pub drafted: u64,
693 pub accepted: u64,
694 /// how often draft position j (0-based within a round's chain) was offered / accepted.
695 /// Positions >= SPEC_TELEM_POS are untracked (totals still count them). The opt-in
696 /// round-stream arm (MEMRA_SPEC_STREAM=1) reads back only totals, so under it these
697 /// arrays cover the standard-path rounds only and their sums may undercount the totals.
698 pub pos_drafted: [u64; SPEC_TELEM_POS],
699 pub pos_accepted: [u64; SPEC_TELEM_POS],
700}
701
702impl SpecTelemetry {
703 /// Fieldwise `self - prev` — the worker's per-burst delta off a copy stashed before the
704 /// burst call. Saturating: a caller diffing against the wrong snapshot gets zeros, not
705 /// a wrapped counter.
706 pub fn delta_since(&self, prev: &SpecTelemetry) -> SpecTelemetry {
707 let mut d = SpecTelemetry {
708 rounds: self.rounds.saturating_sub(prev.rounds),
709 drafted: self.drafted.saturating_sub(prev.drafted),
710 accepted: self.accepted.saturating_sub(prev.accepted),
711 ..Default::default()
712 };
713 for j in 0..SPEC_TELEM_POS {
714 d.pos_drafted[j] = self.pos_drafted[j].saturating_sub(prev.pos_drafted[j]);
715 d.pos_accepted[j] = self.pos_accepted[j].saturating_sub(prev.pos_accepted[j]);
716 }
717 d
718 }
719 /// Fieldwise `self += d` — the worker's per-model aggregation.
720 pub fn merge(&mut self, d: &SpecTelemetry) {
721 self.rounds += d.rounds;
722 self.drafted += d.drafted;
723 self.accepted += d.accepted;
724 for j in 0..SPEC_TELEM_POS {
725 self.pos_drafted[j] += d.pos_drafted[j];
726 self.pos_accepted[j] += d.pos_accepted[j];
727 }
728 }
729
730 /// Mean accepted draft-prefix length per verify round (tau).
731 pub fn tau(&self) -> f64 {
732 if self.rounds > 0 {
733 self.accepted as f64 / self.rounds as f64
734 } else {
735 0.0
736 }
737 }
738}
739
740/// Session-lifetime atomic acceptance counters. The verifier records only after the greedy or
741/// rejection-sampling walk has resolved on the host, so these relaxed increments add no GPU
742/// launch, synchronization, allocation, or ordering dependency to the numeric path.
743struct SpecTelemetryCounters {
744 rounds: AtomicU64,
745 drafted: AtomicU64,
746 accepted: AtomicU64,
747 pos_drafted: [AtomicU64; SPEC_TELEM_POS],
748 pos_accepted: [AtomicU64; SPEC_TELEM_POS],
749}
750
751impl Default for SpecTelemetryCounters {
752 fn default() -> Self {
753 Self {
754 rounds: AtomicU64::new(0),
755 drafted: AtomicU64::new(0),
756 accepted: AtomicU64::new(0),
757 pos_drafted: std::array::from_fn(|_| AtomicU64::new(0)),
758 pos_accepted: std::array::from_fn(|_| AtomicU64::new(0)),
759 }
760 }
761}
762
763impl SpecTelemetryCounters {
764 fn record_round(&self, drafted: usize, accepted: usize) {
765 debug_assert!(accepted <= drafted);
766 self.rounds.fetch_add(1, Ordering::Relaxed);
767 self.drafted.fetch_add(drafted as u64, Ordering::Relaxed);
768 self.accepted.fetch_add(accepted as u64, Ordering::Relaxed);
769 for counter in self.pos_drafted.iter().take(drafted) {
770 counter.fetch_add(1, Ordering::Relaxed);
771 }
772 for counter in self.pos_accepted.iter().take(accepted) {
773 counter.fetch_add(1, Ordering::Relaxed);
774 }
775 }
776
777 /// Round-stream keeps each round's accept length on device; retain exact scalar totals while
778 /// leaving the per-position arrays untouched, matching the pre-existing telemetry contract.
779 fn record_totals(&self, rounds: usize, drafted: usize, accepted: usize) {
780 self.rounds.fetch_add(rounds as u64, Ordering::Relaxed);
781 self.drafted.fetch_add(drafted as u64, Ordering::Relaxed);
782 self.accepted.fetch_add(accepted as u64, Ordering::Relaxed);
783 }
784
785 fn snapshot(&self) -> SpecTelemetry {
786 SpecTelemetry {
787 rounds: self.rounds.load(Ordering::Relaxed),
788 drafted: self.drafted.load(Ordering::Relaxed),
789 accepted: self.accepted.load(Ordering::Relaxed),
790 pos_drafted: std::array::from_fn(|j| self.pos_drafted[j].load(Ordering::Relaxed)),
791 pos_accepted: std::array::from_fn(|j| self.pos_accepted[j].load(Ordering::Relaxed)),
792 }
793 }
794}
795
796pub struct SpecSession {
797 pub(crate) cache: Cache,
798 pub(crate) scratch: MtpScratch,
799 /// Every token whose state the caches hold, in order (prompt turns + generated), INCLUDING
800 /// overshoot: spec commits accepted drafts past max_new; those rows are in the caches, so the
801 /// session must count them. Callers render output from this, not from their own echo.
802 pub committed: Vec<u32>,
803 /// Pre-output_norm hidden of the LAST committed row (device). None before the first turn.
804 pub(crate) last_h: Option<CudaSlice<f32>>,
805 /// Greedy argmax predicting the token AFTER committed.last() (from the last turn's final
806 /// logits). Fuels empty-suffix continuation bursts (serve): the next turn emits this token
807 /// first, feeds it, and the round loop resumes without any prime. None before the first turn.
808 pub next_pred: Option<u32>,
809 /// SAMPLED-SPEC stream continuity across bursts: Philox event counters persist here so a
810 /// session's randomness never repeats between generate_spec_session calls. (0,0) at admit.
811 pub sctr: u32,
812 pub uctr: u32,
813 /// PERSISTENT DRAFT-GRAPH CONTEXT (2026-08-01, the serve-burst fixed-cost fix): the captured
814 /// draft graph(s) + every device I/O buffer they bake, carried ACROSS generate_spec_session
815 /// calls. Before this, every serve burst re-captured the draft graph (2 warmup forwards +
816 /// instantiate) — measured ~16ms/burst on H100 q27 (MEMRA_SPEC_BURST sweep,
817 /// research/spec-serving-20260801). None before the first turn; error paths drop it
818 /// (next burst recaptures — serve retires errored sessions anyway).
819 pub(crate) draft_ctx: Option<DraftGraphCtx>,
820 /// PENDING-CARRY across bursts (2026-08-01, the serve burst-boundary fix): the bonus token
821 /// emitted by the last round but NOT committed to the caches. The old tail committed it with
822 /// a solo T=1 trunk pass (+ draft fill), and the next burst's setup fed the stashed next_pred
823 /// with ANOTHER solo pass — 2x ~11.5ms/burst measured on H100 q27 ([spec-setup] trace).
824 /// Carrying it lets the next empty-suffix greedy burst consume it as round-0 verify col 0,
825 /// exactly like a mid-burst full-accept boundary (no solo passes). INVARIANT: when set,
826 /// `committed` (== cache rows) EXCLUDES this token although it was already emitted in the
827 /// last burst's output, and `last_h` holds the hidden of the last COMMITTED row (its
828 /// predecessor — the chain-seed/fill anchor). `next_pred` is None (unknown without the
829 /// commit pass). Non-empty-suffix or sampled turns must flush first (spec_flush_pending);
830 /// generate_spec_session_sampled does this at entry, and serve parks only flushed sessions.
831 pub pending_tok: Option<u32>,
832 /// SESSION-AFFINITY TURN CHECKPOINT (lane/session-affinity, 2026-08-05): the state at this
833 /// turn's PROMPT-END boundary, retained so a later turn can REWIND here. See
834 /// [`SpecCheckpoint`]. Refreshed by every non-empty prime; None until the first one, and on
835 /// a rig too tight to hold it (a failed capture is silent — resume just isn't available).
836 pub(crate) turn_ckpt: Option<SpecCheckpoint>,
837 /// Session-lifetime acceptance telemetry. Relaxed atomics update at the host-side round
838 /// accounting the loop already does — no syncs, no allocation. NOTE a
839 /// pool-resumed session carries the PREVIOUS requests' counts; per-request consumers
840 /// diff with [`SpecTelemetry::delta_since`] around each burst.
841 telem: SpecTelemetryCounters,
842 /// PREFIX-CACHE publication request (lane/spec-prefix-cache): worker sets this to the
843 /// miss-LCP boundary before a cold burst; the prime captures at exactly that split (it must
844 /// coincide with the burst's `prime_split` or no capture happens). One-shot: consumed by the
845 /// prime, result lands in `boundary_captures`.
846 pub capture_at: Option<usize>,
847 /// The captures the last prime produced (see [`SpecBoundaryCapture`]). Worker drains them
848 /// post-burst to assemble prefix entries. A failed capture is silent, like `turn_ckpt` —
849 /// publication just isn't available for that request. Plural since
850 /// lane/frspec-multiturn-cache (2026-08-21): a cold burst can capture BOTH the miss-LCP
851 /// split (the shared-prefix class) and the stable pre-generation boundary (the
852 /// next-turn re-render class) — one entry per stop, exactly the boundary set the plain
853 /// prefill tick publishes/checkpoints.
854 pub boundary_captures: Vec<SpecBoundaryCapture>,
855 /// STABLE-BOUNDARY TURN CHECKPOINT REQUEST (lane/frspec-multiturn-cache, 2026-08-21): the
856 /// ABSOLUTE committed-length position the next non-empty prime should capture `turn_ckpt`
857 /// at, instead of prompt-end. The worker sets it to the STABLE PRE-GENERATION boundary
858 /// (`plain_checkpoint_boundary` — before the live generation header the client rewrites),
859 /// porting the 2026-08-09 plain-tier fix: a prompt-end spec checkpoint includes the
860 /// template's live assistant-generation header (`<|im_start|>assistant\n<think>\n`), which
861 /// the NEXT turn's re-render replaces, so `affinity_match` diverged a couple tokens below
862 /// the checkpoint and the spec pool declined 100% of multi-turn agent traffic (measured:
863 /// `spec-affinity: declined (history diverged at 6811 of checkpoint 6813)`,
864 /// research/multiturn-cache-20260821 B4). One-shot, `capture_at` convention; None = legacy
865 /// prompt-end capture.
866 pub ckpt_at: Option<usize>,
867}
868impl SpecSession {
869 /// Context capacity of the session's caches (the server's ContextFull guard).
870 pub fn cache_max_ctx(&self) -> usize {
871 self.cache.max_ctx
872 }
873 /// Read access to the live trunk cache (lane/spec-prefix-cache): the worker slices
874 /// full-attn KV rows `[0..capture.pos)` out of it when publishing a boundary capture —
875 /// those rows are append-only for the session's lifetime (rollbacks never truncate below
876 /// the prime boundary), so no copy was taken at prime time.
877 pub fn cache_ref(&self) -> &Cache {
878 &self.cache
879 }
880 /// Read access to the persistent draft-scratch plane (lane/spec-on-cache-hit): the
881 /// worker slices rows `[0..capture.pos)` when publishing a boundary capture, exactly
882 /// like the trunk KV — draft rows below the prompt end are append-only for the
883 /// session's lifetime (the prime fill wrote them once; rollbacks reset `len_d` to the
884 /// committed length, never below the prime boundary, and the true-hidden refresh
885 /// rewrites generated positions only). Returns `(k, v, k_tok_bytes, v_tok_bytes)`.
886 /// None when the scratch is ring-backed (Step35 SWA — physical rows are not
887 /// prefix-addressable; the prefix cache already refuses that class end to end).
888 pub fn draft_plane_ref(&self) -> Option<(&CudaSlice<u8>, &CudaSlice<u8>, usize, usize)> {
889 if self.scratch.kv.ring.is_some() {
890 return None;
891 }
892 Some((
893 &self.scratch.kv.k,
894 &self.scratch.kv.v,
895 self.scratch.kv.k_tok_bytes,
896 self.scratch.kv.v_tok_bytes,
897 ))
898 }
899 /// Snapshot the session's process-local acceptance counters for per-burst diffing.
900 pub fn telemetry(&self) -> SpecTelemetry {
901 self.telem.snapshot()
902 }
903 /// Committed position this session can REWIND to (its retained prompt-end boundary), if any.
904 /// A request whose prompt matches `committed[..pos]` exactly can resume from here — see
905 /// `spec_rewind_to_checkpoint`.
906 pub fn rewind_pos(&self) -> Option<usize> {
907 self.turn_ckpt.as_ref().map(|c| c.pos)
908 }
909 /// Whether every ring-backed trunk/draft row needed by the retained checkpoint is resident.
910 pub fn rewind_is_resident(&self) -> bool {
911 self.turn_ckpt.as_ref().is_some_and(|ckpt| {
912 self.cache.can_rollback(&ckpt.snap, 0) && self.scratch.can_rewind_to(ckpt.pos)
913 })
914 }
915 /// Is this session in the DEMOTION-READY shape (see [`SpecSession::into_demoted`])?
916 /// `false` means a carried pending must be flushed first (`spec_flush_pending`), or the
917 /// session has never run a turn and has no prediction to hand over.
918 pub fn demote_ready(&self) -> bool {
919 self.pending_tok.is_none() && self.next_pred.is_some()
920 }
921 /// Does this session hold a carried pending bonus (flush required before a handoff/park)?
922 pub fn has_pending(&self) -> bool {
923 self.pending_tok.is_some()
924 }
925 /// Committed row count == cache rows (the session invariant), for the caller's own
926 /// `fed`-length cross-check at a handoff boundary.
927 pub fn committed_len(&self) -> usize {
928 self.committed.len()
929 }
930 /// DEMOTION HANDOFF (lane/spec-gate, 2026-08-07): consume this session and hand its trunk
931 /// cache + next-token prediction to the plain batched-decode path.
932 ///
933 /// WHY THIS IS EXACT (greedy). The invariant at a burst boundary is `cache.pos ==
934 /// committed.len()`: every committed row has trunk KV + recurrent state, exactly as a plain
935 /// tokenwise prime of the same `committed` sequence would have left it (that is the
936 /// session-tail contract, and the same property `spec_rewind_to_checkpoint` and the reuse
937 /// pool already rely on). `next_pred` is the argmax of the verify's logits for the LAST
938 /// committed row — and verify-column logits are bit-identical to plain decode's logits at
939 /// that position, because `matmul_decode_exact` bit-identity IS the basis of the greedy
940 /// accept walk. So handing (cache, next_pred) to the batched path continues the stream from
941 /// a state indistinguishable from one the batched path produced itself: the batched tick
942 /// emits `next_pred`, feeds it into this same cache, and decodes on.
943 ///
944 /// `None` when the session is not in the handoff shape — a carried pending (its bonus row is
945 /// NOT in the cache, so `spec_flush_pending` must commit it first) or no `next_pred` yet
946 /// (never bursted). Callers must not force it: a half-committed cache handed to the batched
947 /// path would silently skip a token.
948 ///
949 /// The MTP draft scratch, the persistent draft-graph context and the turn checkpoint are
950 /// DROPPED here (freeing their VRAM): the batched path never drafts, and this handoff is
951 /// one-way by design — there is no cheap symmetric re-promotion (rebuilding the draft KV
952 /// would mean an `mtp_kv_fill` over the whole committed history).
953 pub fn into_demoted(self) -> Option<(Cache, u32)> {
954 if self.pending_tok.is_some() {
955 return None;
956 }
957 let np = self.next_pred?;
958 debug_assert_eq!(
959 self.cache.pos,
960 self.committed.len(),
961 "demotion handoff: cache rows != committed tokens"
962 );
963 Some((self.cache, np))
964 }
965 /// Pool-resume hook (audit Q2): clear the parked draft-graph failure memoization so a
966 /// NEW request resuming this session gets one fresh capture chance — a transient-pressure
967 /// capture failure must not persist for the pool's whole lifetime (the TRT #16072 class).
968 /// Logs once iff a flag was actually set; a no-fallback resume is silent and free.
969 pub fn reset_graph_fallback_on_resume(&mut self) {
970 if let Some(line) = self
971 .draft_ctx
972 .as_mut()
973 .and_then(|c| c.failed.reset_on_resume())
974 {
975 eprintln!("{line}");
976 }
977 }
978}
979
980/// A session's PROMPT-END boundary state, the rewind target for session-affinity resume.
981///
982/// WHY THIS BOUNDARY, AND WHY IT IS THE ONLY ONE WORTH KEEPING. The rewrite class this lane
983/// exists for (a client that strips `<think>` blocks out of prior assistant turns) mutates the
984/// text the session GENERATED, never the prompt it was given. So turn N's prompt agrees with
985/// turn N-1's committed tokens up to almost exactly where turn N-1's generation began — the
986/// prompt-end boundary. Keeping a checkpoint there means the next turn re-primes only its own
987/// delta (the rewritten answer + the new user turn) instead of the whole conversation.
988///
989/// WHAT IT MUST HOLD. Full-attn KV is append-only and position-addressed, so rewinding it is a
990/// `len` truncation (no data). Linear-attn (GDN) conv/ssm state is mutated IN PLACE with no
991/// position index, so it must be a real device COPY — that copy is the entire reason a spec
992/// session could not previously rewind. The MTP draft scratch needs no copy either: its rows
993/// below the boundary were written by this turn's fill and are never revisited (the per-round
994/// true-hidden refresh only rewrites the CURRENT burst's committed positions), so rewinding it
995/// is also just a `len` reset. `last_h` is the hidden of the last row below the boundary — the
996/// predecessor-pairing anchor the next prime's fill reads for its first row.
997///
998/// COST: one `Cache::snapshot` per TURN, on a code path that already takes one per ROUND.
999pub(crate) struct SpecCheckpoint {
1000 snap: crate::cache::CacheSnapshot,
1001 /// Committed length at the boundary (== cache.pos there, the session invariant).
1002 pos: usize,
1003 /// Pre-output_norm hidden of row `pos - 1`.
1004 last_h: CudaSlice<f32>,
1005}
1006
1007/// PREFIX-CACHE BOUNDARY CAPTURE (lane/spec-prefix-cache, 2026-08-14): the state a spec session
1008/// records at its cold-prime split so the WORKER can publish a cross-request prefix entry —
1009/// the commit-gated-publication port (research/cache-spec-design-20260814/PORT-PLAN.md item 1).
1010/// Only the pieces that are DESTROYED by continuing the prime need copies here: the in-place
1011/// GDN conv/ssm states (via `Cache::snapshot`, same mechanism as [`SpecCheckpoint`]) and the
1012/// boundary logits. Full-attn KV rows `[0..pos)` and draft-scratch rows `[0..pos)` are
1013/// append-only for the session's lifetime (rollbacks never truncate below the prime boundary),
1014/// so the worker slices those from the live caches post-burst instead of copying at prime time.
1015pub struct SpecBoundaryCapture {
1016 pub snap: crate::cache::CacheSnapshot,
1017 /// Token boundary (== cache.pos at capture; == the worker's miss-LCP split).
1018 pub pos: usize,
1019 /// Full-vocab logits after the prefix prime — the entry's boundary logits.
1020 pub logits: Vec<f32>,
1021 /// Pre-output_norm trunk hidden of row `pos - 1` (lane/spec-on-cache-hit): the
1022 /// predecessor-pairing anchor a RESTORED spec session's first suffix-fill row reads
1023 /// (the `SpecSession::last_h` convention). Empty = unavailable (capture stays valid;
1024 /// the fill's zeros row-0 fallback covers it at a bounded acceptance cost).
1025 pub last_h: Vec<f32>,
1026}
1027
1028/// D2H one hidden row out of a `[T, n_embd]` prime hidden stack — the boundary anchor a
1029/// spec boundary capture carries for later restored-session fills. Failure is silent
1030/// (`turn_ckpt` convention): the capture publishes without an anchor.
1031fn capture_boundary_hidden(
1032 e: &Engine,
1033 h_rows: &CudaSlice<f32>,
1034 pos: usize,
1035 n_embd: usize,
1036) -> Vec<f32> {
1037 if pos == 0 || h_rows.len() < pos * n_embd {
1038 return Vec::new();
1039 }
1040 let Ok(mut row) = e.uninit(n_embd) else {
1041 return Vec::new();
1042 };
1043 if e.copy_view_into(
1044 &mut row,
1045 0,
1046 &h_rows.slice((pos - 1) * n_embd..pos * n_embd),
1047 n_embd,
1048 )
1049 .is_err()
1050 {
1051 return Vec::new();
1052 }
1053 e.dtoh(&row).unwrap_or_default()
1054}
1055
1056/// ROLLBACK DOOR for sampled BOUNDARY tokens (lane/sampled-spec-quality, 2026-08-19).
1057/// Default ON: the token a burst emits at its own boundary is drawn from the request's
1058/// sampler. `MEMRA_SPEC_SAMPLED_BOUNDARY=0` restores the pre-lane posture (an ARGMAX at
1059/// every boundary) without touching greedy, which is byte-unaffected either way.
1060pub fn spec_sampled_boundary_on() -> bool {
1061 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1062 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_SAMPLED_BOUNDARY").as_deref() != Ok("0"))
1063}
1064
1065/// ROLLBACK DOOR for SESSION-SPANNING penalty history (lane/sampled-spec-quality).
1066/// Default ON: `pen_hist` is seeded from the session's committed tail, so repetition /
1067/// frequency / presence penalties see the whole stream. `MEMRA_SPEC_PEN_SESSION=0`
1068/// restores the pre-lane posture (each burst restarts the window from its own prompt
1069/// slice, i.e. from NOTHING on a continuation burst) — and with the door shut the worker
1070/// must keep refusing penalized sampled prefix-cache restores, because the restored
1071/// session's continuation burst is handed no prompt slice at all.
1072pub fn spec_pen_session_on() -> bool {
1073 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1074 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_PEN_SESSION").as_deref() != Ok("0"))
1075}
1076
1077/// ROLLBACK DOOR for extended-entry publication from a RESTORED session
1078/// (lane/sampled-spec-quality, Item 3). Default ON: a converted prefix-cache hit that fed a
1079/// suffix captures its own prompt-end boundary so the NEXT turn can hit a longer prefix.
1080/// `MEMRA_SPEC_RESTORE_REPUBLISH=0` restores the pre-lane posture (a namespace learns exactly
1081/// one boundary and never advances it). Whole-entry semantics only — the boundary is the
1082/// restored session's own prompt end, so `entry_pos != fed_len` still refuses on the way in.
1083pub fn spec_restore_republish_on() -> bool {
1084 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1085 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_RESTORE_REPUBLISH").as_deref() != Ok("0"))
1086}
1087
1088/// Diagnostics: name every boundary token on stderr (`MEMRA_SPEC_BOUNDARY_TRACE=1`), with
1089/// the argmax the pre-lane code would have emitted from the same row. This is how the
1090/// lane MEASURES the boundary rate and the deviation rate instead of estimating them.
1091fn spec_boundary_trace() -> bool {
1092 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1093 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_BOUNDARY_TRACE").as_deref() == Ok("1"))
1094}
1095
1096/// llama-parity floor for the penalty window when the request does not ask for a bigger
1097/// one (`repeat_last_n` default). The serve API arms `penalty_last_n = PEN_WINDOW_MAX` for any
1098/// non-identity penalty, so this floor only matters to explicit small windows and to the
1099/// CLI env path.
1100const PEN_WINDOW_FLOOR: usize = 64;
1101
1102/// CEILING on the penalty window, and it is a COST bound, not a semantic preference.
1103/// `penalize_logits_f32` (cu/spec_sample.cu) dedups on device by having thread `i` scan
1104/// `hist[0..i]`, so a pass is O(n_hist²) and it runs ~3x per verify round (the q rows, the
1105/// p column, the bonus column). The serve API uses this same bound for every non-identity
1106/// penalty so host/plain, sparse-device, and speculative sampling cannot change logits on
1107/// admission demotion. An uncapped 128k-token history would put ~1.7e10
1108/// comparisons per pass, tens of ms per round, i.e. penalties would silently destroy decode
1109/// throughput on exactly the long-context requests that most want them. 8192 keeps a pass
1110/// at ~7e7 comparisons (tens of microseconds) while still being **128x wider than the
1111/// pre-lane effective window** (64 prompt-tail tokens + whatever the current burst had
1112/// generated). A request that genuinely needs a window beyond this wants host-side dedup +
1113/// counts through a new kernel signature — a follow-up lane, named here rather than hidden.
1114/// `pub` since lane/dspark-penalized-sampled-20260821: the dspark route's accept walk and
1115/// the dspark_sample_gate binary trim their uploads with the SAME cap — a second constant
1116/// is a second thing to drift.
1117pub const PEN_WINDOW_MAX: usize = 8192;
1118
1119/// Seed a penalty window over the SESSION, not the burst (lane/sampled-spec-quality,
1120/// Item 2). The window is the last `max(penalty_last_n, 64)` tokens of
1121/// `session_committed ++ burst_prompt` — for a cold turn-1 burst (`session_committed`
1122/// empty, default `penalty_last_n`) that is byte-identically the pre-lane
1123/// `prompt.iter().rev().take(64).rev()`; for a continuation burst it is the stream the
1124/// client actually asked us to penalize, where the pre-lane code had NOTHING.
1125/// `pub` since lane/dspark-penalized-sampled-20260821: the dspark route seeds its session
1126/// window through the SAME function (one definition of "the window" across both spec
1127/// routes and the gate binary's trunk-only reference arm).
1128pub fn pen_window_seed(
1129 session_committed: &[u32],
1130 burst_prompt: &[u32],
1131 penalty_last_n: usize,
1132) -> Vec<u32> {
1133 let win = penalty_last_n.clamp(PEN_WINDOW_FLOOR, PEN_WINDOW_MAX);
1134 let take_prompt = burst_prompt.len().min(win);
1135 let take_sess = (win - take_prompt).min(session_committed.len());
1136 let mut hist = Vec::with_capacity(take_sess + take_prompt);
1137 hist.extend_from_slice(&session_committed[session_committed.len() - take_sess..]);
1138 hist.extend_from_slice(&burst_prompt[burst_prompt.len() - take_prompt..]);
1139 hist
1140}
1141
1142/// Draw a BOUNDARY token from the target distribution the request asked for
1143/// (lane/sampled-spec-quality, Item 1) — the fix for "sampled spec emits an ARGMAX token at
1144/// every burst boundary".
1145///
1146/// WHY THIS EXISTS. A spec burst's first emitted token is not produced by the accept walk:
1147/// it comes off a logits row that already exists (the prime's last row on a cold burst; the
1148/// row after the last committed token on a continuation burst; the prefix-cache entry's
1149/// boundary row on a restored one). Pre-lane that token was `argmax` in BOTH sampling
1150/// regimes, so a sampled stream took a greedy token once per burst — measured, not
1151/// estimated, in research/spec-cache-20260818/SAMPLED-QUALITY.md. At temperature > 0 the
1152/// customer asked for a sampled token, so this draws one.
1153///
1154/// THE PROGRAM IS THE FULL-ACCEPT BONUS'S PROGRAM, deliberately: penalize the row (over the
1155/// session's window), take this row's OWN filter stats (the sampfix-20260805 law — stats
1156/// from a neighbour row mis-scale every `e0` and can wipe the row to token 0), gumbel-perturb
1157/// with the session's Philox stream at `*sctr`, argmax the perturbed row. Reusing the bonus's
1158/// composition means `sample_check`'s distributional oracle covers this draw too, and the
1159/// boundary token is drawn from the same filtered/penalized `p` the accept walk targets.
1160///
1161/// THE STREAM IS THE SESSION'S, NOT A FRESH ONE. `sctr` is the caller's live counter and is
1162/// advanced by exactly one, so a boundary draw consumes the next value in the same Philox
1163/// stream the accept walk uses — never a second, independently seeded stream (which would be
1164/// a new distributional bug: two streams from one seed correlate wherever their counters
1165/// collide). That also makes a restored session's boundary draw at `sctr == 0` bit-identical
1166/// to the cold session's own first draw from the same logits row, which is what preserves the
1167/// sampled-hit lane's per-seed hit==cold byte identity.
1168#[allow(clippy::too_many_arguments)]
1169pub fn sample_boundary_token_dev(
1170 e: &Engine,
1171 logits: &CudaSlice<f32>,
1172 n_vocab: usize,
1173 sp: &SpecSampling,
1174 pen_hist: &[u32],
1175 sctr: &mut u32,
1176 site: &str,
1177) -> Result<u32, Box<dyn std::error::Error>> {
1178 debug_assert!(
1179 sp.temp > 0.0,
1180 "boundary sampling is the sampled regime only"
1181 );
1182 // Own copy: penalize_logits mutates in place and the caller's row is live state
1183 // (prime_logits back the constrained recompute; last_col_logits backs round 0's accept).
1184 let mut col = e.zeros(n_vocab)?;
1185 e.copy_into(&mut col, 0, logits, n_vocab)?;
1186 let pen_on = sp.penalty_last_n > 0
1187 && (sp.penalty_repeat != 1.0 || sp.penalty_freq != 0.0 || sp.penalty_present != 0.0);
1188 if pen_on && !pen_hist.is_empty() {
1189 // window trim mirrors the round loop's own upload (`pen_hist[w0..]`), cap included.
1190 let w0 = pen_hist
1191 .len()
1192 .saturating_sub(sp.penalty_last_n.min(PEN_WINDOW_MAX));
1193 let hist = &pen_hist[w0..];
1194 let hd = e.htod_u32_v(hist)?;
1195 e.penalize_logits(
1196 &mut col,
1197 &hd,
1198 hist.len(),
1199 sp.penalty_repeat,
1200 sp.penalty_freq,
1201 sp.penalty_present,
1202 n_vocab,
1203 )?;
1204 }
1205 let rows0 = e.htod_i32(&[0])?;
1206 let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
1207 e.filter_stats(
1208 &col, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1, sp.temp, sp.top_k,
1209 sp.top_p, sp.min_p,
1210 )?;
1211 let (th, mx) = (e.dtoh(&th_d)?[0], e.dtoh(&mx_d)?[0]);
1212 let mut perturb = e.zeros(n_vocab)?;
1213 e.gumbel_perturb_filtered(&col, &mut perturb, n_vocab, sp.seed, *sctr, sp.temp, mx, th)?;
1214 *sctr = sctr.wrapping_add(1);
1215 let td = e.argmax_token_device(&perturb, n_vocab)?;
1216 let tok = e.dtoh_u32_one(&td)?;
1217 if spec_boundary_trace() {
1218 // the pre-lane token, from the SAME row, so the deviation rate is measurable.
1219 let raw = e.argmax_token_device(logits, n_vocab)?;
1220 let greedy = e.dtoh_u32_one(&raw)?;
1221 eprintln!(
1222 "[spec-boundary] site={site} sampled={tok} argmax={greedy} \
1223 deviates={} temp={} sctr={}",
1224 (tok != greedy) as u8,
1225 sp.temp,
1226 sctr.wrapping_sub(1),
1227 );
1228 }
1229 Ok(tok)
1230}
1231
1232/// Host-row twin of [`sample_boundary_token_dev`] (the prime / feed / entry rows arrive as
1233/// host `Vec<f32>`).
1234#[allow(clippy::too_many_arguments)]
1235pub fn sample_boundary_token(
1236 e: &Engine,
1237 logits: &[f32],
1238 sp: &SpecSampling,
1239 pen_hist: &[u32],
1240 sctr: &mut u32,
1241 site: &str,
1242) -> Result<u32, Box<dyn std::error::Error>> {
1243 let n_vocab = logits.len();
1244 let d = e.htod(logits)?;
1245 sample_boundary_token_dev(e, &d, n_vocab, sp, pen_hist, sctr, site)
1246}
1247
1248struct SpecPipeTraceClock {
1249 pair: usize,
1250 started: std::time::Instant,
1251}
1252
1253#[derive(Clone)]
1254struct SpecPipeTraceCtx {
1255 clock: std::sync::Arc<SpecPipeTraceClock>,
1256 round: usize,
1257 lane: usize,
1258}
1259
1260struct SpecPipeTraceMarker {
1261 trace: SpecPipeTraceCtx,
1262 phase: &'static str,
1263 edge: &'static str,
1264 slot: Option<usize>,
1265}
1266
1267unsafe extern "C" fn spec_pipe_trace_marker(raw: *mut std::ffi::c_void) {
1268 let marker = unsafe { Box::from_raw(raw.cast::<SpecPipeTraceMarker>()) };
1269 let lane = if marker.trace.lane == 0 { "A" } else { "B" };
1270 let slot = marker
1271 .slot
1272 .map(|v| v.to_string())
1273 .unwrap_or_else(|| "-".into());
1274 let t_ms = marker.trace.clock.started.elapsed().as_secs_f64() * 1e3;
1275 use std::io::Write as _;
1276 let stderr = std::io::stderr();
1277 let mut stderr = stderr.lock();
1278 let _ = writeln!(
1279 stderr,
1280 "[spec-pipe-timeline] pair={} round={} lane={lane} phase={} edge={} \
1281 slot={slot} t_ms={t_ms:.3}",
1282 marker.trace.clock.pair, marker.trace.round, marker.phase, marker.edge,
1283 );
1284}
1285
1286fn enqueue_spec_pipe_trace_marker(
1287 stream: &cudarc::driver::CudaStream,
1288 trace: Option<&SpecPipeTraceCtx>,
1289 phase: &'static str,
1290 edge: &'static str,
1291 slot: Option<usize>,
1292) -> Result<(), Box<dyn std::error::Error>> {
1293 let Some(trace) = trace else {
1294 return Ok(());
1295 };
1296 let marker = Box::new(SpecPipeTraceMarker {
1297 trace: trace.clone(),
1298 phase,
1299 edge,
1300 slot,
1301 });
1302 let raw = Box::into_raw(marker);
1303 let result = unsafe {
1304 cudarc::driver::result::stream::launch_host_function(
1305 stream.cu_stream(),
1306 spec_pipe_trace_marker,
1307 raw.cast(),
1308 )
1309 };
1310 if let Err(err) = result {
1311 unsafe {
1312 drop(Box::from_raw(raw));
1313 }
1314 return Err(err.into());
1315 }
1316 Ok(())
1317}
1318
1319#[derive(Default)]
1320struct SpecPipeProgress {
1321 setup_done: [bool; 2],
1322 draft_done: [usize; 2],
1323 stage0_done: [usize; 2],
1324 verify_done: [usize; 2],
1325 accept_done: [usize; 2],
1326 finished: [bool; 2],
1327 aborted: bool,
1328}
1329
1330/// Host-side issue coordinator for the reduced two-session speculative pipeline. Each session
1331/// keeps its existing call stack and round locals; this object only orders phase entry. The
1332/// primary mutex spans whole draft/accept/tail issue regions so Engine's single-stream scratch
1333/// cannot be interleaved by the two host threads.
1334struct SpecPipeSync {
1335 progress: std::sync::Mutex<SpecPipeProgress>,
1336 changed: std::sync::Condvar,
1337 primary: std::sync::Mutex<()>,
1338 trace: Option<std::sync::Arc<SpecPipeTraceClock>>,
1339}
1340
1341impl SpecPipeSync {
1342 fn new() -> Self {
1343 static TRACE_PAIR: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1344 let trace = (std::env::var("MEMRA_SPEC_PIPE_TRACE").as_deref() == Ok("1")).then(|| {
1345 std::sync::Arc::new(SpecPipeTraceClock {
1346 pair: TRACE_PAIR.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1,
1347 started: std::time::Instant::now(),
1348 })
1349 });
1350 Self {
1351 progress: std::sync::Mutex::new(SpecPipeProgress::default()),
1352 changed: std::sync::Condvar::new(),
1353 primary: std::sync::Mutex::new(()),
1354 trace,
1355 }
1356 }
1357}
1358
1359#[derive(Clone)]
1360struct SpecPipeLane {
1361 sync: std::sync::Arc<SpecPipeSync>,
1362 lane: usize,
1363}
1364
1365impl SpecPipeLane {
1366 fn peer(&self) -> usize {
1367 1 - self.lane
1368 }
1369
1370 fn aborted() -> Box<dyn std::error::Error> {
1371 "paired speculative peer aborted".into()
1372 }
1373
1374 fn trace(&self, round: usize) -> Option<SpecPipeTraceCtx> {
1375 self.sync.trace.as_ref().map(|clock| SpecPipeTraceCtx {
1376 clock: clock.clone(),
1377 round,
1378 lane: self.lane,
1379 })
1380 }
1381
1382 fn setup_begin(&self) -> Result<(), Box<dyn std::error::Error>> {
1383 let mut p = self.sync.progress.lock().unwrap();
1384 while !p.aborted && self.lane == 1 && !p.setup_done[0] && !p.finished[0] {
1385 p = self.sync.changed.wait(p).unwrap();
1386 }
1387 if p.aborted {
1388 Err(Self::aborted())
1389 } else {
1390 Ok(())
1391 }
1392 }
1393
1394 fn setup_end(&self) {
1395 let mut p = self.sync.progress.lock().unwrap();
1396 p.setup_done[self.lane] = true;
1397 self.sync.changed.notify_all();
1398 }
1399
1400 fn draft_begin(
1401 &self,
1402 round: usize,
1403 ) -> Result<std::sync::MutexGuard<'_, ()>, Box<dyn std::error::Error>> {
1404 let peer = self.peer();
1405 let mut p = self.sync.progress.lock().unwrap();
1406 loop {
1407 if p.aborted {
1408 return Err(Self::aborted());
1409 }
1410 let setup_ready =
1411 (p.setup_done[0] || p.finished[0]) && (p.setup_done[1] || p.finished[1]);
1412 let prior_ready = p.accept_done[self.lane] >= round
1413 && (p.accept_done[peer] >= round || p.finished[peer]);
1414 let turn_ready = if self.lane == 0 {
1415 true
1416 } else {
1417 p.draft_done[0] > round || p.finished[0]
1418 };
1419 if setup_ready && prior_ready && turn_ready {
1420 break;
1421 }
1422 p = self.sync.changed.wait(p).unwrap();
1423 }
1424 drop(p);
1425 Ok(self.sync.primary.lock().unwrap())
1426 }
1427
1428 fn draft_end(&self, round: usize) {
1429 let mut p = self.sync.progress.lock().unwrap();
1430 p.draft_done[self.lane] = round + 1;
1431 self.sync.changed.notify_all();
1432 }
1433
1434 /// Admit stage 0 and return whether this lane owns the interval's one reverse fence.
1435 /// Lane B releases as soon as lane A has issued its boundary TX, not after A's full body.
1436 fn stage0_begin(&self, round: usize) -> Result<bool, Box<dyn std::error::Error>> {
1437 let peer = self.peer();
1438 let mut p = self.sync.progress.lock().unwrap();
1439 loop {
1440 if p.aborted {
1441 return Err(Self::aborted());
1442 }
1443 let ready = if self.lane == 0 {
1444 p.draft_done[0] > round && (p.draft_done[1] > round || p.finished[1])
1445 } else {
1446 p.draft_done[1] > round && (p.stage0_done[0] > round || p.finished[0])
1447 };
1448 if ready {
1449 return Ok(self.lane == 0 || p.finished[peer]);
1450 }
1451 p = self.sync.changed.wait(p).unwrap();
1452 }
1453 }
1454
1455 fn stage0_end(&self, round: usize) {
1456 let mut p = self.sync.progress.lock().unwrap();
1457 p.stage0_done[self.lane] = round + 1;
1458 self.sync.changed.notify_all();
1459 }
1460
1461 /// Stage 1 is single-owner per engine. A proceeds immediately after its own ticket; B waits
1462 /// for A's full stage1/head issue so only A.S1 and B.S0 can overlap.
1463 fn stage1_begin(&self, round: usize) -> Result<(), Box<dyn std::error::Error>> {
1464 let mut p = self.sync.progress.lock().unwrap();
1465 while !p.aborted
1466 && !(p.stage0_done[self.lane] > round
1467 && (self.lane == 0 || p.verify_done[0] > round || p.finished[0]))
1468 {
1469 p = self.sync.changed.wait(p).unwrap();
1470 }
1471 if p.aborted {
1472 Err(Self::aborted())
1473 } else {
1474 Ok(())
1475 }
1476 }
1477
1478 fn verify_end(&self, round: usize) {
1479 let mut p = self.sync.progress.lock().unwrap();
1480 p.verify_done[self.lane] = round + 1;
1481 self.sync.changed.notify_all();
1482 }
1483
1484 fn accept_begin(
1485 &self,
1486 round: usize,
1487 ) -> Result<std::sync::MutexGuard<'_, ()>, Box<dyn std::error::Error>> {
1488 let mut p = self.sync.progress.lock().unwrap();
1489 loop {
1490 if p.aborted {
1491 return Err(Self::aborted());
1492 }
1493 let ready = if self.lane == 0 {
1494 p.verify_done[0] > round && (p.verify_done[1] > round || p.finished[1])
1495 } else {
1496 p.verify_done[1] > round && (p.accept_done[0] > round || p.finished[0])
1497 };
1498 if ready {
1499 break;
1500 }
1501 p = self.sync.changed.wait(p).unwrap();
1502 }
1503 drop(p);
1504 Ok(self.sync.primary.lock().unwrap())
1505 }
1506
1507 fn accept_end(&self, round: usize) {
1508 let mut p = self.sync.progress.lock().unwrap();
1509 p.accept_done[self.lane] = round + 1;
1510 self.sync.changed.notify_all();
1511 }
1512
1513 fn primary(&self) -> std::sync::MutexGuard<'_, ()> {
1514 self.sync.primary.lock().unwrap()
1515 }
1516
1517 fn finish(&self, failed: bool) {
1518 let mut p = self.sync.progress.lock().unwrap();
1519 p.finished[self.lane] = true;
1520 p.aborted |= failed;
1521 self.sync.changed.notify_all();
1522 }
1523}
1524
1525struct SpecPipeFinish<'a> {
1526 lane: &'a SpecPipeLane,
1527 closed: bool,
1528}
1529
1530impl<'a> SpecPipeFinish<'a> {
1531 fn new(lane: &'a SpecPipeLane) -> Self {
1532 Self {
1533 lane,
1534 closed: false,
1535 }
1536 }
1537
1538 fn close(&mut self, failed: bool) {
1539 self.lane.finish(failed);
1540 self.closed = true;
1541 }
1542}
1543
1544impl Drop for SpecPipeFinish<'_> {
1545 fn drop(&mut self) {
1546 if !self.closed {
1547 self.lane.finish(true);
1548 }
1549 }
1550}
1551
1552/// Scoped transfer of one exclusively-borrowed session to the second host issue thread.
1553/// `CudaGraph` is not marked Send by cudarc because its raw driver handles carry no automatic
1554/// trait. CUDA driver graph handles are context-scoped rather than OS-thread-affine; the caller
1555/// binds that context before touching the session, joins before returning, and never aliases the
1556/// pointer. Keep this exception local to the experimental pair call instead of marking the public
1557/// session type Send.
1558struct SpecPipeSessionPtr(*mut SpecSession);
1559
1560unsafe impl Send for SpecPipeSessionPtr {}
1561
1562impl SpecPipeSessionPtr {
1563 unsafe fn get_mut(&mut self) -> &mut SpecSession {
1564 unsafe { &mut *self.0 }
1565 }
1566}
1567
1568/// Per-session persistent draft-graph context: the captured CUDA graph(s) plus the device
1569/// buffers whose POINTERS the capture bakes. Reuse legality: the greedy capture bakes only
1570/// session-stable pointers (the session's own MtpScratch KV — allocated once, never realloc'd;
1571/// the model's resident embedding; the process-wide OnceLock p_min) and the g_* buffers held
1572/// HERE — so one capture serves the session's whole lifetime. The sampled capture additionally
1573/// bakes (seed, temp) as capture-time constants and needs k q-slots — keyed by `s_key`, dropped
1574/// and recaptured when a pool-resumed request changes them. `*_failed` memoizes a failed capture
1575/// so the eager fallback doesn't pay a doomed capture attempt every burst.
1576/// Capture identity of the parked SAMPLED draft graph (`DraftGraphCtx::graph_s`).
1577///
1578/// EXACTNESS, not perf (lane/graph-s-key-exactness-20260819; receipts
1579/// `research/spec-cache-20260818/GRAPH-S-KEY.md`). Two classes of field live here, both
1580/// load-bearing:
1581///
1582/// - **Baked constants.** `seed` and `temp` are capture-time constants INSIDE the graph and `k`
1583/// sizes the q slots its replays write. A resumed request changing any of them must recapture.
1584/// This is all the key used to carry.
1585/// - **Regime fields.** `top_k`/`top_p`/`min_p`/`pen_on` are not baked, but they decide whether
1586/// the captured graph is a legal draft chain AT ALL. The in-graph draw is one gumbel-max over
1587/// the RAW softmax (`gumbel_perturb_ctr`, unfiltered by construction), while the verify builds
1588/// the accept test's `q` from `filter_stats(q_slots, top_k, top_p, min_p)`. If those disagree
1589/// the accept test evaluates a distribution the draft was never sampled from: a draft token
1590/// below the filter threshold gathers `q = 0` (`softmax_gather_filtered_f32`,
1591/// `cu/spec_sample.cu`) and `u * 0 < p` accepts it UNCONDITIONALLY.
1592///
1593/// Omitting the regime fields was reachable — not through the prefix-cache spec restore (that
1594/// path is greedy-only, `memra-server` `spec_restore_convertible`), but through WHOLE-SESSION
1595/// spec reuse: a parked `SpecSession` carries this `DraftGraphCtx`, and the pool-resume probe
1596/// applies no sampler predicate at all. Turn 1 pure-temp parks a graph; turn 2 of the same
1597/// conversation, same explicit seed and temperature, adds `top_p`/`top_k` and inherits it.
1598#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1599pub(crate) struct SampledGraphKey {
1600 seed: u64,
1601 temp_bits: u32,
1602 k: usize,
1603 top_k: i32,
1604 top_p_bits: u32,
1605 min_p_bits: u32,
1606 pen_on: bool,
1607}
1608
1609impl SampledGraphKey {
1610 pub(crate) fn new(
1611 seed: u64,
1612 temp: f32,
1613 k: usize,
1614 top_k: i32,
1615 top_p: f32,
1616 min_p: f32,
1617 pen_on: bool,
1618 ) -> Self {
1619 SampledGraphKey {
1620 seed,
1621 temp_bits: temp.to_bits(),
1622 k,
1623 top_k,
1624 top_p_bits: top_p.to_bits(),
1625 min_p_bits: min_p.to_bits(),
1626 pen_on,
1627 }
1628 }
1629
1630 /// The one regime the in-graph sampled chain may stand in for the eager one: nothing but
1631 /// temperature shapes `q`. Computed FROM THE KEY so the capture guard, the launch guard and
1632 /// the key can never drift apart (they were three separate expressions before this lane, and
1633 /// the launch site simply forgot to ask).
1634 pub(crate) fn pure_temp(&self) -> bool {
1635 self.top_k == 0
1636 && f32::from_bits(self.top_p_bits) >= 1.0
1637 && f32::from_bits(self.min_p_bits) <= 0.0
1638 && !self.pen_on
1639 }
1640}
1641
1642pub(crate) struct DraftGraphCtx {
1643 g_tok: CudaSlice<u32>,
1644 g_pos: CudaSlice<i32>,
1645 g_seed: CudaSlice<f32>,
1646 g_p: CudaSlice<f32>,
1647 g_ctr: CudaSlice<u32>,
1648 g_q: CudaSlice<f32>,
1649 g_perturb: CudaSlice<f32>,
1650 q_slots: Vec<CudaSlice<f32>>,
1651 /// DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): packed allowed-set words over the DRAFT
1652 /// head's vocab, at a STABLE address so the captured draft graph's mask node reads the
1653 /// per-position contents the host re-uploads before each replay (the graph-promote
1654 /// pattern from decode.rs). Empty unless the session drafts under a grammar.
1655 g_dmask: CudaSlice<u32>,
1656 /// was `graph` captured WITH the mask node? A parked graph of the wrong shape is dropped.
1657 graph_masked: bool,
1658 graph: Option<cudarc::driver::CudaGraph>,
1659 graph_s: Option<cudarc::driver::CudaGraph>,
1660 /// Failed-capture memoization for both graphs — LOUD on flip, cleared on pool resume
1661 /// (audit Q2, the TRT #16072 silent-permanent-coverage-loss class).
1662 failed: DraftGraphFallback,
1663 /// Capture identity of `graph_s` — see [`SampledGraphKey`]. `None` iff no sampled graph is
1664 /// parked; a request whose key differs drops the parked graph (and its q slots/keeper).
1665 s_key: Option<SampledGraphKey>,
1666 /// CAPTURE-RETAIN keepers (#68 root cause, 2026-08-04): the warmup-run transients whose
1667 /// pool addresses the captured graph(s) bake. Without these, the transients return to the
1668 /// pool at capture-body exit and later work (burst-boundary prime/fill/commit passes, or a
1669 /// co-served session in the worker) reuses those addresses — the persisted graph's replay
1670 /// then reads/writes live unrelated buffers (exactness corruption, first seen as the ST
1671 /// serve-spec 4B graph-arm corruption; one-shot CLI calls never re-shuffled the pool, which
1672 /// is why run-spec K=1..8 passed on the same checkpoint). Same fix class as
1673 /// capture_graph_retained's gemma/decode.rs sites — hold as long as the graph replays.
1674 keeper: Vec<Box<dyn std::any::Any + Send>>,
1675 keeper_s: Vec<Box<dyn std::any::Any + Send>>,
1676}
1677
1678/// Failed-capture memoization for the two draft graphs (audit Q2, 2026-08-05 — the
1679/// TRT #16072 trap class: pressure-triggered, silent, long-lived coverage loss).
1680///
1681/// Three contracts:
1682/// - LOUD FLIP: `mark_*` returns the warn line exactly on the false→true transition
1683/// (returned, not printed, so the once-per-flip contract is unit-testable); the caller
1684/// `eprintln!`s it UNCONDITIONALLY — a dropped draft graph is never silent. Re-marking
1685/// an already-failed graph returns None (the per-burst memoization that keeps the eager
1686/// fallback from paying a doomed capture attempt every burst).
1687/// - RESET ON RESUME: `reset_on_resume` clears both flags — a parked session resumed by a
1688/// NEW request gets one fresh capture chance instead of carrying a transient-pressure
1689/// failure for the pool's whole lifetime. Returns the note line only when a flag was
1690/// actually set (quiet on the common clean-resume path).
1691/// - Shape-change clears (`clear_*`) stay silent, exactly as before: they precede a fresh
1692/// capture attempt whose own failure would re-flip loudly.
1693#[derive(Default)]
1694pub(crate) struct DraftGraphFallback {
1695 greedy: bool,
1696 sampled: bool,
1697}
1698impl DraftGraphFallback {
1699 fn mark_greedy(&mut self, reason: &str) -> Option<String> {
1700 if self.greedy {
1701 return None;
1702 }
1703 self.greedy = true;
1704 Some(format!(
1705 "[spec] WARN: draft-graph capture failed ({reason}); eager fallback until session resume"
1706 ))
1707 }
1708 fn mark_sampled(&mut self, reason: &str) -> Option<String> {
1709 if self.sampled {
1710 return None;
1711 }
1712 self.sampled = true;
1713 Some(format!(
1714 "[spec] WARN: sampled draft-graph capture failed ({reason}); eager fallback until session resume"
1715 ))
1716 }
1717 fn greedy_failed(&self) -> bool {
1718 self.greedy
1719 }
1720 fn sampled_failed(&self) -> bool {
1721 self.sampled
1722 }
1723 fn clear_greedy(&mut self) {
1724 self.greedy = false;
1725 }
1726 fn clear_sampled(&mut self) {
1727 self.sampled = false;
1728 }
1729 /// Pool-resume reset: both graphs get a fresh capture chance. Some(note) iff any flag
1730 /// was set (so clean resumes stay quiet).
1731 pub(crate) fn reset_on_resume(&mut self) -> Option<String> {
1732 if !self.greedy && !self.sampled {
1733 return None;
1734 }
1735 let which = match (self.greedy, self.sampled) {
1736 (true, true) => "greedy+sampled",
1737 (true, false) => "greedy",
1738 _ => "sampled",
1739 };
1740 self.greedy = false;
1741 self.sampled = false;
1742 Some(format!(
1743 "[spec] draft-graph fallback reset on session resume ({which}); recapture eligible"
1744 ))
1745 }
1746}
1747
1748impl DraftGraphCtx {
1749 fn new(e: &Engine, n_embd: usize, qlen: usize) -> Result<Self, Box<dyn std::error::Error>> {
1750 Ok(DraftGraphCtx {
1751 g_tok: e.alloc_u32_zeroed(1)?,
1752 g_pos: e.htod_i32(&[0])?,
1753 g_seed: e.zeros(n_embd)?,
1754 g_p: e.zeros(1)?,
1755 g_ctr: e.alloc_u32_zeroed(1)?,
1756 g_q: e.zeros(qlen)?,
1757 g_perturb: e.zeros(qlen)?,
1758 q_slots: Vec::new(),
1759 g_dmask: e.alloc_u32_zeroed(1)?,
1760 graph_masked: false,
1761 graph: None,
1762 graph_s: None,
1763 failed: DraftGraphFallback::default(),
1764 s_key: None,
1765 keeper: Vec::new(),
1766 keeper_s: Vec::new(),
1767 })
1768 }
1769}
1770
1771pub(crate) struct MtpScratch {
1772 kv: KvLayer,
1773 /// Logical row capacity. On the graph/DC draft path it also doubles as fa_decode_dc's
1774 /// bucket_max: n_splits is sized from it ONCE, so the graph captured at round 0 stays valid
1775 /// for every later t_kv. Step35 refuses that path and may back this logical extent with the
1776 /// smaller host-indexed SWA ring instead.
1777 cap: usize,
1778 extra: Vec<MtpScratchPlane>,
1779}
1780
1781struct MtpScratchPlane {
1782 kv: KvLayer,
1783 cap: usize,
1784}
1785
1786fn mtp_scratch_layout(
1787 cfg: &memra_gguf::config::ModelConfig,
1788 geom: Option<&crate::hybrid::DraftGeom>,
1789) -> (usize, usize, usize, usize) {
1790 // Student draft heads carry fewer KV heads (head_dim unchanged) -> smaller scratch rows.
1791 let n_head_kv = geom.map(|g| g.n_head_kv).unwrap_or(cfg.n_head_kv as usize);
1792 let head_dim_k = cfg.head_dim_k as usize;
1793 let head_dim_v = cfg.head_dim_v as usize;
1794 assert!(
1795 head_dim_k % 32 == 0 && head_dim_v % 32 == 0,
1796 "KVQUANT requires head_dim%32==0 (MTP scratch)"
1797 );
1798 let kv_dim_k = head_dim_k * n_head_kv;
1799 let kv_dim_v = head_dim_v * n_head_kv;
1800 // The fp8-KV arm deliberately does not reach the draft scratch; keep the exact format
1801 // policy shared with `MtpScratch::new` so admission scales the same allocation.
1802 let (kbb, vbb) = crate::kv_blk_bytes();
1803 let k_tok_bytes = (kv_dim_k / 32) * kbb;
1804 let v_tok_bytes = (kv_dim_v / 32) * vbb;
1805 (kv_dim_k, kv_dim_v, k_tok_bytes, v_tok_bytes)
1806}
1807
1808fn mtp_chain_head_index(step: usize, head_count: usize) -> usize {
1809 assert!(head_count > 0, "MTP chain requires at least one head");
1810 step % head_count
1811}
1812
1813impl MtpScratch {
1814 fn alloc_plane(
1815 e: &Engine,
1816 cfg: &memra_gguf::config::ModelConfig,
1817 plan: &memra_gguf::model_plan::ModelPlan,
1818 cap: usize,
1819 geom: Option<&crate::hybrid::DraftGeom>,
1820 ) -> Result<MtpScratchPlane, Box<dyn std::error::Error>> {
1821 let (kv_dim_k, kv_dim_v, k_tok_bytes, v_tok_bytes) = mtp_scratch_layout(cfg, geom);
1822 let ring = if crate::cache::swa_ring_on()
1823 && crate::plan_backend::decode_batch_program(plan)
1824 == crate::plan_backend::DecodeBatchProgram::SlidingGatedMoe
1825 {
1826 let window = plan
1827 .layers
1828 .iter()
1829 .find_map(|layer| match layer.attention {
1830 memra_gguf::model_plan::AttentionPlan::SlidingWindow { window, .. } => {
1831 Some(window as usize)
1832 }
1833 _ => None,
1834 })
1835 .ok_or("sliding-gated-MoE draft scratch has no sliding-window layer")?;
1836 Some(crate::cache::KvRing::new(
1837 crate::cache::swa_ring_rows(window, cap),
1838 window,
1839 ))
1840 } else {
1841 None
1842 };
1843 let alloc_rows = ring.as_ref().map(crate::cache::KvRing::rows).unwrap_or(cap);
1844 Ok(MtpScratchPlane {
1845 kv: KvLayer {
1846 k: e.alloc_u8(alloc_rows * k_tok_bytes)?,
1847 v: e.alloc_u8(alloc_rows * v_tok_bytes)?,
1848 kv_dim_k,
1849 kv_dim_v,
1850 k_tok_bytes,
1851 v_tok_bytes,
1852 len: 0,
1853 ring,
1854 len_d: e.htod_i32(&[0])?,
1855 },
1856 cap,
1857 })
1858 }
1859
1860 fn new(
1861 e: &Engine,
1862 cfg: &memra_gguf::config::ModelConfig,
1863 plan: &memra_gguf::model_plan::ModelPlan,
1864 cap: usize,
1865 geom: Option<&crate::hybrid::DraftGeom>,
1866 ) -> Result<Self, Box<dyn std::error::Error>> {
1867 // env-selected KV formats (default 34/24). The fp8-KV arm (MEMRA_KV_FP8) deliberately
1868 // does NOT reach the draft scratch: fp8 drafts drifted acceptance 69-88% -> 46%
1869 // (2026-07-12 A/B); the scratch is tiny, so it keeps baseline q8_0/q5_1 numerics
1870 // while the TRUNK cache carries the fp8 depth win. Scratch append/fa pass g=false.
1871 let primary = Self::alloc_plane(e, cfg, plan, cap, geom)?;
1872 Ok(MtpScratch {
1873 kv: primary.kv,
1874 cap: primary.cap,
1875 extra: Vec::new(),
1876 })
1877 }
1878
1879 fn push_plane(
1880 &mut self,
1881 e: &Engine,
1882 cfg: &memra_gguf::config::ModelConfig,
1883 plan: &memra_gguf::model_plan::ModelPlan,
1884 geom: Option<&crate::hybrid::DraftGeom>,
1885 ) -> Result<(), Box<dyn std::error::Error>> {
1886 self.extra
1887 .push(Self::alloc_plane(e, cfg, plan, self.cap, geom)?);
1888 Ok(())
1889 }
1890
1891 fn plane_count(&self) -> usize {
1892 1 + self.extra.len()
1893 }
1894
1895 fn plane(&self, index: usize) -> (&KvLayer, usize) {
1896 if index == 0 {
1897 (&self.kv, self.cap)
1898 } else {
1899 let plane = &self.extra[index - 1];
1900 (&plane.kv, plane.cap)
1901 }
1902 }
1903
1904 fn plane_mut(&mut self, index: usize) -> (&mut KvLayer, usize) {
1905 if index == 0 {
1906 (&mut self.kv, self.cap)
1907 } else {
1908 let plane = &mut self.extra[index - 1];
1909 (&mut plane.kv, plane.cap)
1910 }
1911 }
1912
1913 fn set_plane_len(
1914 &mut self,
1915 e: &Engine,
1916 index: usize,
1917 n: usize,
1918 ) -> Result<(), Box<dyn std::error::Error>> {
1919 let (kv, _) = self.plane_mut(index);
1920 if kv.ring.as_ref().is_some_and(|ring| !ring.can_rewind_to(n)) {
1921 return Err("SWA ring MTP checkpoint has been lapped; full re-prime required".into());
1922 }
1923 kv.len = n;
1924 e.set_i32_one(&mut kv.len_d, n as i32)
1925 }
1926
1927 /// Set BOTH length counters: the host mirror AND the device len_d the captured append/fa read
1928 /// (a 4-byte in-place htod — the counter pointer is baked into the graph, never realloc'd).
1929 /// This is the ONLY truncation/rollback mechanism the persistent draft KV needs.
1930 fn set_len(&mut self, e: &Engine, n: usize) -> Result<(), Box<dyn std::error::Error>> {
1931 if !self.can_rewind_to(n) {
1932 return Err("SWA ring MTP checkpoint has been lapped; full re-prime required".into());
1933 }
1934 for index in 0..self.plane_count() {
1935 self.set_plane_len(e, index, n)?;
1936 }
1937 Ok(())
1938 }
1939
1940 fn can_rewind_to(&self, n: usize) -> bool {
1941 (0..self.plane_count()).all(|index| {
1942 self.plane(index)
1943 .0
1944 .ring
1945 .as_ref()
1946 .is_none_or(|ring| ring.can_rewind_to(n))
1947 })
1948 }
1949}
1950
1951/// Retained verify intermediates for the REPLAY-FREE partial accept (2026-07-03, the profiled
1952/// #1 spec cost at long ctx: the partial-accept replay was a DUPLICATE trunk pass — ~0.54 extra
1953/// full weight reads per round — recomputing columns the verify had already produced
1954/// bit-identically). Holds, per linear layer, everything needed to rebuild its recurrent state
1955/// to "after the first j verify columns" WITHOUT re-running the trunk:
1956/// - BATCHED-path layers (`gdn`): the exact token-major inputs the round's ONE gdn_scan
1957/// consumed. A prefix re-run of the SAME kernel (t=j) from the snapshot state is bit-identical
1958/// to the first j iterations of the verify's scan — the kernel's t-loop carries state in
1959/// registers and iteration t never depends on T. `qkv_mixed` (the conv input) feeds the
1960/// pure-copy ring rebuild.
1961/// - PER-COLUMN-path layers (`cols`): dtod clones of (conv_state, ssm_state) taken after each
1962/// column 0..t-2 — pure copies of the actual chain states (the last column is never a rebuild
1963/// target: j <= t-1).
1964/// Full-attn layers need nothing: their verify KV rows are bit-identical to eager's (the
1965/// decode-exact contract; verify-probe pins it), so rollback = len truncation.
1966struct GdnStash {
1967 qkv_mixed: CudaSlice<f32>, // [t, conv_dim] token-major (conv input)
1968 q_l2: CudaSlice<f32>,
1969 k_l2: CudaSlice<f32>,
1970 v_g: CudaSlice<f32>, // [t, num_v, d_state]
1971 g_log: CudaSlice<f32>,
1972 beta: CudaSlice<f32>, // [t, num_v]
1973}
1974pub(crate) struct VerifyCkpt {
1975 gdn: Vec<Option<GdnStash>>, // [n_layer], Some iff batched linear path ran
1976 cols: Vec<Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>>>, // [n_layer][col] = (conv, ssm) after col
1977}
1978/// Opaque handle for the dspark round (dflash.rs) — VerifyCkpt stays spec-private.
1979pub(crate) struct DsparkVerifyCkpt(VerifyCkpt);
1980
1981/// Engine-bundle slice 3 (DSF-ROUNDCOST-20260820 §2 row 4 / §5 rank 1): bucketed CUDA
1982/// graphs for the dspark verify's LINEAR-layer segments. The measured verify is ~2,800
1983/// eager launches whose residual cost is DEVICE-side per-launch overhead (slice 2 proved
1984/// host dispatch is not the binder: fully-deferred dispatch bought ~0 wall). The 48 GDN
1985/// layers between full-attention layers are shape-static given vt — no positions, no
1986/// t_kv, state addressed through pointer tables — so runs of them capture per
1987/// (segment, vt) and replay as ONE graph launch each. Full-attention layers stay eager
1988/// (their per-row append/fa arm picks are t_kv-driven — the exec-update extension).
1989///
1990/// Per round out-of-graph: one pointer-table refresh (gdn ping-pong moves the canonical
1991/// handles), one input-staging copy per segment, host parity bookkeeping. Captured via
1992/// `capture_graph_retained` (2 warmups + capture, keeper retains warmup transients so
1993/// pool addresses stay stable); the warmups EXECUTE, so segment conv/ssm state is saved
1994/// before and restored after — the graph's first real launch starts from the exact
1995/// pre-round state. The ckpt column stash rides persistent slabs (written inside the
1996/// graph as memcpy nodes); commit reads them via `dspark_commit_prefix_slab`.
1997/// `MEMRA_DSPARK_VERIFY_GRAPH=0` reverts to the eager walk (byte-identical body).
1998pub(crate) struct DsparkVerifyGraphs {
1999 /// Linear-attention layer indices ascending; `lin_pos[il]` = index into the vecs.
2000 lin: Vec<usize>,
2001 lin_pos: std::collections::HashMap<usize, usize>,
2002 /// [n_lin x 6] pointer table (conv, s0, s1, conv, s1, s0 per layer), refreshed per
2003 /// verify from the live handles; layer il's slice starts at lin_pos[il]*6.
2004 table_all: CudaSlice<u64>,
2005 host_table: Vec<u64>,
2006 /// Persistent per-layer ckpt stash slabs: row r of the verify at slab offset
2007 /// r*words. Shared by every (segment, vt) bucket — one verify runs at a time.
2008 stash_conv: Vec<CudaSlice<f32>>,
2009 stash_ssm: Vec<CudaSlice<f32>>,
2010 conv_words: usize,
2011 ssm_words: usize,
2012 /// Per-vt input/output staging (stable addresses the graphs bake).
2013 stage: std::collections::HashMap<usize, (CudaSlice<f32>, CudaSlice<f32>)>,
2014 /// Per-vt dflash tap-sink buffers — the captured segments bake the tap dst address,
2015 /// so the sink buffer must live (and persist) with the graphs, not with the round.
2016 pub(crate) tap_bufs: std::collections::HashMap<usize, CudaSlice<f32>>,
2017 graphs: std::collections::HashMap<(usize, usize), DsparkSegGraph>,
2018 /// Warmup-corruption guard scratch: pre-capture conv/ssm of every linear layer
2019 /// (sized n_lin — the slice-4c full-verify warmups execute the whole walk).
2020 save_conv: CudaSlice<f32>,
2021 save_ssm: CudaSlice<f32>,
2022 max_run: usize,
2023 n_embd: usize,
2024 /// Set by the verify walk: this round's linear ckpt lives in the slabs (the caller
2025 /// commits through `dspark_commit_prefix_slab` instead of the cols arm).
2026 pub(crate) round_slab: bool,
2027 // ---- slice 4c: full-verify single graph per (vt, rung) ----
2028 /// Full-attention layer indices ascending; `fa_pos[il]` = index into the vec.
2029 fa: Vec<usize>,
2030 fa_pos: std::collections::HashMap<usize, usize>,
2031 /// [n_fa x 2 x t_cap] interleaved (k,v) base-pointer pairs, refreshed per verify;
2032 /// layer il's slice starts at `fa_pos[il] * 2 * t_cap` (the seqs twins read pairs
2033 /// [2z], z < t <= t_cap, so one t_cap-sized table serves every vt).
2034 fa_table: CudaSlice<u64>,
2035 fa_host_table: Vec<u64>,
2036 t_cap: usize,
2037 /// Per-vt position staging for the captured bodies — contents refreshed per round
2038 /// (rope reads row r; the seqs twins derive append slot and T_kv per z from it).
2039 pos_stage: std::collections::HashMap<usize, CudaSlice<i32>>,
2040 /// Full-verify graphs keyed (vt, rung_end, hi).
2041 full: std::collections::HashMap<(usize, usize, usize), DsparkSegGraph>,
2042 /// Largest n with every layer in [0, n) linear or full-attention (walk coverage).
2043 covered: usize,
2044 /// Every layer in [0, n) is linear or full-attention (no MLA/unknown mixers) — the
2045 /// full-verify capture walks all of them.
2046 walk_uniform: bool,
2047 /// Last `(captures, device graph-mem reserved bytes)` reading taken by
2048 /// `HybridModel::dspark_vg_admission_debt` — the two-point base of the MARGINAL debt
2049 /// projection (see `dspark_vg_debt_projection`; a mean-based reading extrapolated the
2050 /// pool's one-time shared allocation and reserved 8.5 GB of phantom VRAM).
2051 debt_obs: Option<(usize, usize)>,
2052}
2053
2054struct DsparkSegGraph {
2055 graph: cudarc::driver::CudaGraph,
2056 _keeper: Vec<Box<dyn std::any::Any + Send>>,
2057}
2058
2059/// Per-call arguments of [`HybridModel::qwen35_tparallel_fa_layer`] — one struct so the
2060/// eager walk and the slice-4c captured full-verify graphs hand the SAME body its two
2061/// modes without a second copy of the math.
2062pub(crate) struct FaLayerArgs<'a> {
2063 /// [T] per-row positions (device): rope reads them row-indexed; the seqs twins read
2064 /// them per-z (append slot = pos, T_kv = pos + 1).
2065 pub pos_d: &'a CudaSlice<i32>,
2066 /// Verify-level lazy per-row 1-element position buffers — only the per-row fallback
2067 /// arm builds/uses them (graph mode refuses that arm).
2068 pub pos_rows: &'a mut Option<Vec<CudaSlice<i32>>>,
2069 pub pos0: usize,
2070 pub seqs_append: bool,
2071 pub batch_fa_on: bool,
2072 /// Some((kv pointer table, offset-in-u64s, rung_end)) = captured-graph mode.
2073 pub graph_cap: Option<(&'a CudaSlice<u64>, usize, usize)>,
2074 /// ROUND-STREAM (lane/draftcost-moe, v0.100 train merge): Some((token stream, device
2075 /// round counter)) routes the FA attend through the dc rows kernels and the Linear
2076 /// mixer through `linear_attn_verify_t` (the stream arms the old inline body carried).
2077 /// Never armed together with `graph_cap` (the verify-level merge guard refuses).
2078 pub stream: Option<(&'a CudaSlice<u32>, &'a CudaSlice<i32>)>,
2079 /// VerifyCkpt for the stream-Linear arm's GdnStash install; None in graph mode and
2080 /// for FA layers that never touch it.
2081 pub ckpt: Option<&'a mut VerifyCkpt>,
2082}
2083
2084// SAFETY: `CudaGraph` is not marked Send by cudarc because its raw driver handles carry
2085// no automatic trait; CUDA driver graph handles are context-scoped rather than
2086// OS-thread-affine (the SpecPipeSessionPtr precedent above). The ctx lives in
2087// `HybridModel::dspark_vgraphs` behind a Mutex and every touch happens on the engine's
2088// single decode-stream thread.
2089unsafe impl Send for DsparkVerifyGraphs {}
2090
2091impl DsparkVerifyGraphs {
2092 /// Live capture count (segment + full graphs) — the denominator of
2093 /// [`dspark_vg_debt_projection`]'s observed bytes/capture mean.
2094 pub(crate) fn captures(&self) -> usize {
2095 self.graphs.len() + self.full.len()
2096 }
2097
2098 /// Take the marginal-growth debt reading and record this observation for the next one.
2099 /// Called under the pool mutex by `HybridModel::dspark_vg_admission_debt`.
2100 pub(crate) fn admission_debt(&mut self, reserved_bytes: usize) -> usize {
2101 let captures = self.captures();
2102 let debt =
2103 dspark_vg_debt_projection(captures, dspark_vg_cap(), reserved_bytes, self.debt_obs);
2104 if captures > 0 {
2105 match self.debt_obs {
2106 Some((c0, _)) if captures <= c0 => {}
2107 _ => self.debt_obs = Some((captures, reserved_bytes)),
2108 }
2109 }
2110 debt
2111 }
2112
2113 /// Build for this cache's shape. None when there are no linear layers, sizes are
2114 /// non-uniform, or the trunk keeps a gemma4 config (never on the qwen35 family).
2115 pub(crate) fn new(
2116 e: &Engine,
2117 cache: &Cache,
2118 t_max: usize,
2119 n_embd: usize,
2120 ) -> Result<Option<Self>, Box<dyn std::error::Error>> {
2121 let lin: Vec<usize> = (0..cache.recur.len())
2122 .filter(|&il| cache.recur[il].is_some())
2123 .collect();
2124 if lin.is_empty() || t_max < 2 {
2125 return Ok(None);
2126 }
2127 let first = cache.recur[lin[0]].as_ref().unwrap();
2128 let (conv_words, ssm_words) = (first.conv_state.len(), first.ssm_state.len());
2129 for &il in &lin {
2130 let rl = cache.recur[il].as_ref().unwrap();
2131 if rl.conv_state.len() != conv_words || rl.ssm_state.len() != ssm_words {
2132 return Ok(None);
2133 }
2134 }
2135 let n = lin.len();
2136 let mut lin_pos = std::collections::HashMap::with_capacity(n);
2137 for (k, &il) in lin.iter().enumerate() {
2138 lin_pos.insert(il, k);
2139 }
2140 // longest run of consecutive linear layers (save-scratch sizing)
2141 let mut max_run = 1usize;
2142 let mut run = 1usize;
2143 for w in lin.windows(2) {
2144 if w[1] == w[0] + 1 {
2145 run += 1;
2146 max_run = max_run.max(run);
2147 } else {
2148 run = 1;
2149 }
2150 }
2151 let rows = t_max - 1;
2152 let mut stash_conv = Vec::with_capacity(n);
2153 let mut stash_ssm = Vec::with_capacity(n);
2154 for _ in 0..n {
2155 stash_conv.push(e.uninit(rows * conv_words)?);
2156 stash_ssm.push(e.uninit(rows * ssm_words)?);
2157 }
2158 let host_table = vec![0u64; n * 6];
2159 let table_all = e.htod_u64(&host_table)?;
2160 // slice 4c: full-attention census for the full-verify graphs.
2161 let fa: Vec<usize> = (0..cache.kv.len())
2162 .filter(|&il| cache.kv[il].is_some())
2163 .collect();
2164 let mut fa_pos = std::collections::HashMap::with_capacity(fa.len());
2165 for (k, &il) in fa.iter().enumerate() {
2166 fa_pos.insert(il, k);
2167 }
2168 let n_layers = cache.kv.len().max(cache.recur.len());
2169 // exactly one of (linear state, kv cache) per layer — no MLA/unknown mixers.
2170 let walk_uniform = (0..n_layers).all(|il| {
2171 cache.recur.get(il).is_some_and(|r| r.is_some())
2172 != cache.kv.get(il).is_some_and(|k| k.is_some())
2173 });
2174 // Contiguous covered prefix: the largest n such that every layer in [0, n) is
2175 // linear or full-attention. The TRUNK walk is [0, layers.len()) and the cache
2176 // vecs can carry EXTRA state slots past it (the q38 export keeps the MTP head
2177 // layer's kv at the tail — hi == lin+fa never held, the s4c battery's zero
2178 // 'full' captures). The full-graph guard is walk coverage, not slot arithmetic.
2179 let covered = (0..n_layers)
2180 .take_while(|il| lin_pos.contains_key(il) || fa_pos.contains_key(il))
2181 .count();
2182 let t_cap = t_max;
2183 let fa_host_table = vec![0u64; fa.len() * 2 * t_cap];
2184 let fa_table = e.htod_u64(&fa_host_table)?;
2185 Ok(Some(Self {
2186 lin,
2187 lin_pos,
2188 table_all,
2189 host_table,
2190 stash_conv,
2191 stash_ssm,
2192 conv_words,
2193 ssm_words,
2194 stage: std::collections::HashMap::new(),
2195 tap_bufs: std::collections::HashMap::new(),
2196 graphs: std::collections::HashMap::new(),
2197 save_conv: e.uninit(n * conv_words)?,
2198 save_ssm: e.uninit(n * ssm_words)?,
2199 max_run,
2200 n_embd,
2201 round_slab: false,
2202 fa,
2203 fa_pos,
2204 fa_table,
2205 fa_host_table,
2206 t_cap,
2207 pos_stage: std::collections::HashMap::new(),
2208 full: std::collections::HashMap::new(),
2209 covered,
2210 walk_uniform,
2211 debt_obs: None,
2212 }))
2213 }
2214
2215 /// Rebuild the pointer tables from the live handles (once per verify — the gdn
2216 /// ping-pong swaps the canonical/alt handles between rounds; a fresh generation's
2217 /// cache buffers land at new addresses; a stale table would read the wrong state).
2218 pub(crate) fn refresh_tables(
2219 &mut self,
2220 e: &Engine,
2221 cache: &Cache,
2222 ) -> Result<(), Box<dyn std::error::Error>> {
2223 use cudarc::driver::DevicePtr;
2224 {
2225 let s = &e.gpu.stream();
2226 for (k, &il) in self.lin.iter().enumerate() {
2227 let rl = cache.recur[il].as_ref().unwrap();
2228 let (pc, _g0) = rl.conv_state.device_ptr(s);
2229 let (p0, _g1) = rl.ssm_state.device_ptr(s);
2230 let (p1, _g2) = rl.ssm_state_alt.device_ptr(s);
2231 let o = k * 6;
2232 self.host_table[o] = pc as u64;
2233 self.host_table[o + 1] = p0 as u64;
2234 self.host_table[o + 2] = p1 as u64;
2235 self.host_table[o + 3] = pc as u64;
2236 self.host_table[o + 4] = p1 as u64;
2237 self.host_table[o + 5] = p0 as u64;
2238 }
2239 for (k, &il) in self.fa.iter().enumerate() {
2240 let kvl = cache.kv[il].as_ref().unwrap();
2241 let (pk, _g0) = kvl.k.device_ptr(s);
2242 let (pv, _g1) = kvl.v.device_ptr(s);
2243 let o = k * 2 * self.t_cap;
2244 for z in 0..self.t_cap {
2245 self.fa_host_table[o + 2 * z] = pk as u64;
2246 self.fa_host_table[o + 2 * z + 1] = pv as u64;
2247 }
2248 }
2249 }
2250 e.htod_u64_into(&self.host_table, &mut self.table_all)?;
2251 if !self.fa_host_table.is_empty() {
2252 e.htod_u64_into(&self.fa_host_table, &mut self.fa_table)?;
2253 }
2254 Ok(())
2255 }
2256
2257 /// Slice 4c eligibility: Some(rung_end) when this round can replay (or capture) a
2258 /// full-verify graph — the whole walk [lo, hi) is covered, every layer is linear or
2259 /// full-attention, and ALL of the round's per-row t_kv values take the v4-seqs arm
2260 /// on ONE `fa_split_keys` ladder step that the rung also sits on (the straddle law;
2261 /// both gates are t_kv intervals, so ends-inside means all-inside). The rung is the
2262 /// round's next power of two — grid/partial sizing only (`n_splits_max` is pure
2263 /// stride; splits >= ns_eff write the empty partial the combine never reads), so one
2264 /// captured graph is bit-identical for every round the rung covers.
2265 #[allow(clippy::too_many_arguments)]
2266 pub(crate) fn full_rung(
2267 &self,
2268 model: &crate::hybrid::HybridModel,
2269 cache: &Cache,
2270 lo: usize,
2271 hi: usize,
2272 t: usize,
2273 seqs_arms_on: bool,
2274 ) -> Option<usize> {
2275 if std::env::var("MEMRA_DSPARK_FULLG_DEBUG").as_deref() == Ok("1") {
2276 static ONCE: std::sync::Once = std::sync::Once::new();
2277 let len0 = self
2278 .fa
2279 .first()
2280 .and_then(|&il| cache.kv[il].as_ref())
2281 .map(|k| k.len);
2282 ONCE.call_once(|| {
2283 eprintln!(
2284 "[fullg-debug] walk_uniform={} covered={} seqs_arms_on={} fa_rows_on={} t={} lo={} hi={} lin={} fa={} t_cap={} len0={:?}",
2285 self.walk_uniform, self.covered, seqs_arms_on, dspark_fa_rows_on(), t, lo, hi,
2286 self.lin.len(), self.fa.len(), self.t_cap, len0
2287 );
2288 });
2289 }
2290 if !self.walk_uniform
2291 || !seqs_arms_on
2292 || !dspark_fa_rows_on()
2293 || t < 2
2294 || lo != 0
2295 || hi > self.covered
2296 || t > self.t_cap
2297 || self.fa.is_empty()
2298 {
2299 return None;
2300 }
2301 let cfg = &model.cfg;
2302 let head_dim_global = cfg.head_dim_k as usize;
2303 let nkv = cfg.n_head_kv as usize;
2304 let kvl0 = cache.kv[self.fa[0]].as_ref().unwrap();
2305 // the z-batched twins read stacked rows at the cache's kv dims — must equal the
2306 // projection stride (the body's guard, hoisted so ineligible models fall back
2307 // instead of refusing mid-capture).
2308 let geom = cfg.full_attention_geometry_at(self.fa[0] as u32);
2309 let kv_dim = geom.n_head_kv as usize * geom.head_dim_k as usize;
2310 if kvl0.kv_dim_k != kv_dim || kvl0.kv_dim_v != kv_dim {
2311 return None;
2312 }
2313 let len0 = kvl0.len;
2314 let (t_kv_first, t_kv_last) = (len0 + 1, len0 + t);
2315 if !crate::fa_seqs_eligible(t_kv_first, head_dim_global)
2316 || !crate::fa_seqs_eligible(t_kv_last, head_dim_global)
2317 || crate::fa_split_keys(t_kv_first, nkv) != crate::fa_split_keys(t_kv_last, nkv)
2318 {
2319 return None;
2320 }
2321 let rung = t_kv_last.next_power_of_two().max(256);
2322 if crate::fa_split_keys(rung, nkv) != crate::fa_split_keys(t_kv_last, nkv) {
2323 return None;
2324 }
2325 Some(rung)
2326 }
2327
2328 /// Run the WHOLE verify walk [lo, hi) as one captured graph at (vt=t, rung): stage
2329 /// the residual + refresh the per-vt position staging, capture on first encounter
2330 /// (2 executing warmups bracketed by a full linear-state save/restore; KV warmup
2331 /// appends write the exact slots the replay writes — idempotent), launch, then apply
2332 /// the host bookkeeping the captured body skipped (per-linear-layer parity swap for
2333 /// odd t, per-fa-layer len bump). Returns the fresh residual.
2334 #[allow(clippy::too_many_arguments)]
2335 pub(crate) fn run_full(
2336 &mut self,
2337 model: &crate::hybrid::HybridModel,
2338 e: &Engine,
2339 lo: usize,
2340 hi: usize,
2341 x: &CudaSlice<f32>,
2342 t: usize,
2343 pos0: usize,
2344 rung: usize,
2345 cache: &mut Cache,
2346 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2347 let n_embd = self.n_embd;
2348 if !self.stage.contains_key(&t) {
2349 let xin = e.uninit(t * n_embd)?;
2350 let xout = e.uninit(t * n_embd)?;
2351 self.stage.insert(t, (xin, xout));
2352 }
2353 if !self.pos_stage.contains_key(&t) {
2354 self.pos_stage.insert(t, e.htod_i32(&vec![0i32; t])?);
2355 }
2356 // Per-round refresh: position contents + input staging (both addresses are baked
2357 // by the captured bodies; only their CONTENTS change round to round).
2358 {
2359 let pos_host: Vec<i32> = (0..t).map(|r| (pos0 + r) as i32).collect();
2360 let pb = self.pos_stage.get_mut(&t).unwrap();
2361 e.htod_i32_into(pb, &pos_host)?;
2362 let (xin, _) = self.stage.get_mut(&t).unwrap();
2363 e.copy_into(xin, 0, x, t * n_embd)?;
2364 }
2365 let key = (t, rung, hi);
2366 if !self.full.contains_key(&key) {
2367 // The warmups EXECUTE the whole walk on live state — save every linear
2368 // layer's conv + canonical ssm first, restore after (KV needs no restore:
2369 // graph mode never bumps host lens and the appends write this round's own
2370 // slots).
2371 for (k, &il) in self.lin.iter().enumerate() {
2372 let rl = cache.recur[il].as_ref().unwrap();
2373 e.copy_into(
2374 &mut self.save_conv,
2375 k * self.conv_words,
2376 &rl.conv_state,
2377 self.conv_words,
2378 )?;
2379 e.copy_into(
2380 &mut self.save_ssm,
2381 k * self.ssm_words,
2382 &rl.ssm_state,
2383 self.ssm_words,
2384 )?;
2385 }
2386 let (graph, keeper) = {
2387 let table_all = &self.table_all;
2388 let lin_pos = &self.lin_pos;
2389 let fa_pos = &self.fa_pos;
2390 let fa_table = &self.fa_table;
2391 let t_cap = self.t_cap;
2392 let stash_conv = &mut self.stash_conv;
2393 let stash_ssm = &mut self.stash_ssm;
2394 let pos_d: &CudaSlice<i32> = &self.pos_stage[&t];
2395 let (xin, xout) = self
2396 .stage
2397 .get_mut(&t)
2398 .map(|(a, b)| (&*a, b))
2399 .expect("stage bucket created above");
2400 let cache_ref: &mut Cache = cache;
2401 let iflag = if std::env::var("MEMRA_DSPARK_VG_AUTOFREE").as_deref() == Ok("1") {
2402 cudarc::driver::sys::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH
2403 } else {
2404 cudarc::driver::sys::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY
2405 };
2406 e.capture_graph_retained_flags(iflag, move |e| {
2407 let mut xc: Option<CudaSlice<f32>> = None;
2408 for il in lo..hi {
2409 let xr: &CudaSlice<f32> = xc.as_ref().unwrap_or(xin);
2410 let nx = if let Some(&k) = lin_pos.get(&il) {
2411 model.qwen35_tparallel_linear_layer(
2412 e,
2413 il,
2414 xr,
2415 t,
2416 cache_ref,
2417 None,
2418 Some((&mut stash_conv[k], &mut stash_ssm[k])),
2419 Some((table_all, k * 6)),
2420 )?
2421 } else if let Some(&kf) = fa_pos.get(&il) {
2422 let mut no_rows: Option<Vec<CudaSlice<i32>>> = None;
2423 model.qwen35_tparallel_fa_layer(
2424 e,
2425 il,
2426 xr,
2427 t,
2428 cache_ref,
2429 FaLayerArgs {
2430 pos_d,
2431 pos_rows: &mut no_rows,
2432 pos0,
2433 seqs_append: true,
2434 batch_fa_on: true,
2435 graph_cap: Some((fa_table, kf * 2 * t_cap, rung)),
2436 stream: None,
2437 ckpt: None,
2438 },
2439 )?
2440 } else {
2441 return Err(format!(
2442 "run_full: layer {il} is neither linear nor full-attention"
2443 )
2444 .into());
2445 };
2446 xc = Some(nx);
2447 }
2448 e.copy_into(xout, 0, xc.as_ref().unwrap(), t * n_embd)?;
2449 Ok(())
2450 })?
2451 };
2452 // Undo the net host parity motion of the 3 body runs (each run swaps iff t
2453 // is odd -> 3 runs = net one swap), then restore the device state the
2454 // warmups consumed (walk scope only — layers past hi never executed). The
2455 // launch below then behaves exactly like one run.
2456 if t % 2 == 1 {
2457 for &il in &self.lin {
2458 if il < lo || il >= hi {
2459 continue;
2460 }
2461 let rl = cache.recur[il].as_mut().unwrap();
2462 std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
2463 }
2464 }
2465 for (k, &il) in self.lin.iter().enumerate() {
2466 if il < lo || il >= hi {
2467 continue;
2468 }
2469 let rl = cache.recur[il].as_mut().unwrap();
2470 let (cw, sw) = (self.conv_words, self.ssm_words);
2471 {
2472 let sv = e.view(&self.save_conv, self.lin.len() * cw);
2473 let win = sv.slice(k * cw..(k + 1) * cw);
2474 e.copy_view_into(&mut rl.conv_state, 0, &win, cw)?;
2475 }
2476 {
2477 let sv = e.view(&self.save_ssm, self.lin.len() * sw);
2478 let win = sv.slice(k * sw..(k + 1) * sw);
2479 e.copy_view_into(&mut rl.ssm_state, 0, &win, sw)?;
2480 }
2481 }
2482 if std::env::var("MEMRA_GRAPH_CENSUS").as_deref() == Ok("1") {
2483 if let Ok(c) = crate::graph_update::node_census(&graph) {
2484 eprintln!("[dspark-vg-census] full vt={t} rung={rung} {c:?}");
2485 }
2486 }
2487 self.full.insert(
2488 key,
2489 DsparkSegGraph {
2490 graph,
2491 _keeper: keeper,
2492 },
2493 );
2494 }
2495 self.full[&key].graph.launch()?;
2496 // Host bookkeeping for the replayed body (captured host code does not re-run):
2497 // gdn parity swap per linear layer (t odd), kv len bump per fa layer — scoped
2498 // to the WALK [lo, hi): the cache can carry extra state slots past it (the MTP
2499 // head layer's kv) that the walk never touches.
2500 if t % 2 == 1 {
2501 for &il in &self.lin {
2502 if il < lo || il >= hi {
2503 continue;
2504 }
2505 let rl = cache.recur[il].as_mut().unwrap();
2506 std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
2507 }
2508 }
2509 for &il in &self.fa {
2510 if il < lo || il >= hi {
2511 continue;
2512 }
2513 cache.kv[il].as_mut().unwrap().len += t;
2514 }
2515 let (_, xout) = self.stage.get(&t).unwrap();
2516 let mut out = e.uninit(t * n_embd)?;
2517 e.copy_into(&mut out, 0, xout, t * n_embd)?;
2518 Ok(out)
2519 }
2520
2521 /// Run layers [start, end) (all linear) as one captured graph at this vt: stage the
2522 /// residual into the bucket's x_in, capture on first encounter (2 executing warmups
2523 /// bracketed by a segment state save/restore), launch, then apply the host parity
2524 /// bookkeeping the captured body would have done. Returns the fresh residual.
2525 #[allow(clippy::too_many_arguments)]
2526 fn run_segment(
2527 &mut self,
2528 model: &crate::hybrid::HybridModel,
2529 e: &Engine,
2530 start: usize,
2531 end: usize,
2532 x: &CudaSlice<f32>,
2533 t: usize,
2534 cache: &mut Cache,
2535 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2536 let n_embd = self.n_embd;
2537 debug_assert!(end - start <= self.max_run);
2538 if !self.stage.contains_key(&t) {
2539 let xin = e.uninit(t * n_embd)?;
2540 let xout = e.uninit(t * n_embd)?;
2541 self.stage.insert(t, (xin, xout));
2542 }
2543 // Stage the residual at the bucket's baked input address.
2544 {
2545 let (xin, _) = self.stage.get_mut(&t).unwrap();
2546 e.copy_into(xin, 0, x, t * n_embd)?;
2547 }
2548 let key = (start, t);
2549 if !self.graphs.contains_key(&key) {
2550 // The 2 warmups EXECUTE the segment on live state — save conv + the canonical
2551 // ssm of every segment layer first, restore after, so the graph's first real
2552 // launch starts from the exact pre-round state (bytes gated e2e).
2553 for (k, il) in (start..end).enumerate() {
2554 let rl = cache.recur[il].as_ref().unwrap();
2555 e.copy_into(
2556 &mut self.save_conv,
2557 k * self.conv_words,
2558 &rl.conv_state,
2559 self.conv_words,
2560 )?;
2561 e.copy_into(
2562 &mut self.save_ssm,
2563 k * self.ssm_words,
2564 &rl.ssm_state,
2565 self.ssm_words,
2566 )?;
2567 }
2568 let (graph, keeper) = {
2569 let table_all = &self.table_all;
2570 let lin_pos = &self.lin_pos;
2571 let stash_conv = &mut self.stash_conv;
2572 let stash_ssm = &mut self.stash_ssm;
2573 let (xin, xout) = self
2574 .stage
2575 .get_mut(&t)
2576 .map(|(a, b)| (&*a, b))
2577 .expect("stage bucket created above");
2578 let cache_ref: &mut Cache = cache;
2579 // Slice 4 (fa-execupdate lane): USE_NODE_PRIORITY instead of
2580 // AUTO_FREE_ON_LAUNCH. The slice-3 measured limiter was AUTO_FREE's
2581 // launch-time mem-pool scan — 25.6 us per cuGraphLaunch x 16 segments
2582 // = ~0.41 ms/round, most of the eager-launch savings. The captured
2583 // body's cuMemAllocAsync transients are BALANCED by in-graph frees
2584 // (every transient drops inside the capture region — the generic
2585 // capture path's census precedent, 1589/1589), so AUTO_FREE has
2586 // nothing to reclaim and the graph is legal to instantiate without
2587 // it; PRIORITY is the flag the gemma slotted door ships for exactly
2588 // this reason (both alternatives drop the scan; UPLOAD via
2589 // cuGraphInstantiateWithFlags is WithParams-only and refused).
2590 // MEMRA_DSPARK_VG_AUTOFREE=1 reverts; MEMRA_GRAPH_CENSUS=1 prints
2591 // the node census at capture (the ALLOC==FREE receipt).
2592 let iflag = if std::env::var("MEMRA_DSPARK_VG_AUTOFREE").as_deref() == Ok("1") {
2593 cudarc::driver::sys::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH
2594 } else {
2595 cudarc::driver::sys::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY
2596 };
2597 e.capture_graph_retained_flags(iflag, move |e| {
2598 let mut xc: Option<CudaSlice<f32>> = None;
2599 for il in start..end {
2600 let k = lin_pos[&il];
2601 let xr: &CudaSlice<f32> = xc.as_ref().unwrap_or(xin);
2602 let nx = model.qwen35_tparallel_linear_layer(
2603 e,
2604 il,
2605 xr,
2606 t,
2607 cache_ref,
2608 None,
2609 Some((&mut stash_conv[k], &mut stash_ssm[k])),
2610 Some((table_all, k * 6)),
2611 )?;
2612 xc = Some(nx);
2613 }
2614 e.copy_into(xout, 0, xc.as_ref().unwrap(), t * n_embd)?;
2615 Ok(())
2616 })?
2617 };
2618 // Undo the net host parity motion of the 3 body runs (each run swaps iff t
2619 // is odd -> 3 runs = net one swap), then restore the device state the
2620 // warmups consumed. The launch below then behaves exactly like one run.
2621 if t % 2 == 1 {
2622 for il in start..end {
2623 let rl = cache.recur[il].as_mut().unwrap();
2624 std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
2625 }
2626 }
2627 for (k, il) in (start..end).enumerate() {
2628 let rl = cache.recur[il].as_mut().unwrap();
2629 let (cw, sw) = (self.conv_words, self.ssm_words);
2630 {
2631 let sv = e.view(&self.save_conv, self.lin.len() * cw);
2632 let win = sv.slice(k * cw..(k + 1) * cw);
2633 e.copy_view_into(&mut rl.conv_state, 0, &win, cw)?;
2634 }
2635 {
2636 let sv = e.view(&self.save_ssm, self.lin.len() * sw);
2637 let win = sv.slice(k * sw..(k + 1) * sw);
2638 e.copy_view_into(&mut rl.ssm_state, 0, &win, sw)?;
2639 }
2640 }
2641 if std::env::var("MEMRA_GRAPH_CENSUS").as_deref() == Ok("1") {
2642 if let Ok(c) = crate::graph_update::node_census(&graph) {
2643 eprintln!("[dspark-vg-census] seg={start}..{end} vt={t} {c:?}");
2644 }
2645 }
2646 self.graphs.insert(
2647 key,
2648 DsparkSegGraph {
2649 graph,
2650 _keeper: keeper,
2651 },
2652 );
2653 }
2654 self.graphs[&key].graph.launch()?;
2655 // Host parity bookkeeping for the replayed body (the captured host swaps do not
2656 // re-run at replay).
2657 if t % 2 == 1 {
2658 for il in start..end {
2659 let rl = cache.recur[il].as_mut().unwrap();
2660 std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
2661 }
2662 }
2663 let (_, xout) = self.stage.get(&t).unwrap();
2664 let mut out = e.uninit(t * n_embd)?;
2665 e.copy_into(&mut out, 0, xout, t * n_embd)?;
2666 Ok(out)
2667 }
2668
2669 /// Pool freeze check (`dspark_vg_cap`): below the ceiling new keys may capture.
2670 fn can_capture(&self) -> bool {
2671 self.graphs.len() + self.full.len() < dspark_vg_cap()
2672 }
2673
2674 /// Round-atomic segment-door readiness: TRUE when this round's walk can ride the
2675 /// per-(segment, vt) graphs without a NEW capture past the pool ceiling — every
2676 /// linear run in [lo, hi) already has its (run_start, t) key, or capture is still
2677 /// allowed. FALSE sends the WHOLE round down the eager cols-ckpt walk: a partial
2678 /// refusal would stash some layers in the ctx slabs and others in the round's cols
2679 /// while one commit reads only one of them.
2680 pub(crate) fn segments_ready(
2681 &self,
2682 model: &crate::hybrid::HybridModel,
2683 lo: usize,
2684 hi: usize,
2685 t: usize,
2686 ) -> bool {
2687 if self.can_capture() {
2688 return true;
2689 }
2690 let mut il = lo;
2691 while il < hi {
2692 if matches!(model.layers[il].mixer, Mixer::Linear(_)) {
2693 let start = il;
2694 while il < hi && matches!(model.layers[il].mixer, Mixer::Linear(_)) {
2695 il += 1;
2696 }
2697 if !self.graphs.contains_key(&(start, t)) {
2698 return false;
2699 }
2700 } else {
2701 il += 1;
2702 }
2703 }
2704 true
2705 }
2706
2707 /// Widest verify window this pool was built for. A caller whose round exceeds it must
2708 /// take the eager walk: the stash slabs hold `t_capacity() - 1` column rows, and slicing
2709 /// past them is a panic rather than a refusal.
2710 pub(crate) fn t_capacity(&self) -> usize {
2711 self.t_cap
2712 }
2713
2714 /// Slab row (conv, ssm) device pointers + lengths for the commit restore of column
2715 /// `row` (0-based) of layer `il`. None for non-linear layers.
2716 pub(crate) fn slab_row(
2717 &self,
2718 e: &Engine,
2719 il: usize,
2720 row: usize,
2721 ) -> Option<(u64, u64, usize, usize)> {
2722 use cudarc::driver::DevicePtr;
2723 let k = *self.lin_pos.get(&il)?;
2724 let s = &e.gpu.stream();
2725 let (pc, _g0) = self.stash_conv[k].device_ptr(s);
2726 let (ps, _g1) = self.stash_ssm[k].device_ptr(s);
2727 Some((
2728 pc as u64 + (row * self.conv_words * 4) as u64,
2729 ps as u64 + (row * self.ssm_words * 4) as u64,
2730 self.conv_words,
2731 self.ssm_words,
2732 ))
2733 }
2734}
2735
2736impl VerifyCkpt {
2737 fn new(n_layer: usize) -> Self {
2738 VerifyCkpt {
2739 gdn: (0..n_layer).map(|_| None).collect(),
2740 cols: (0..n_layer).map(|_| None).collect(),
2741 }
2742 }
2743}
2744
2745/// The stage-0/TX half of one PP verify. The boundary slot is the ownership token: stage 1
2746/// consumes exactly the slot selected by `tx()` / `tx_pipelined()`, never a slot inferred from
2747/// a logical round number.
2748struct VerifyBoundaryTicket {
2749 rt: &'static crate::pp::PpNRt,
2750 caller_stream: std::sync::Arc<cudarc::driver::CudaStream>,
2751 slot: usize,
2752 pos0: usize,
2753 t: usize,
2754 payload: usize,
2755 n_st: usize,
2756 pipelined: bool,
2757 pp_anatomy: bool,
2758 pp_started: std::time::Instant,
2759 reverse_ms: f64,
2760 stage0_ms: f64,
2761 tx_ms: f64,
2762 trace: Option<SpecPipeTraceCtx>,
2763}
2764
2765/// Explicit OPTIPIPE diagnostic control. Forced modes are set only by `optipipe-gate`; the
2766/// increment-2 controller can also be armed by the server's fresh-process research door.
2767#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2768pub enum OptiForkGateMode {
2769 Disabled,
2770 Hit,
2771 Miss,
2772 Alternate,
2773 Abort,
2774 Controller,
2775}
2776
2777static OPTI_FORK_GATE_MODE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
2778static OPTI_CONTROLLER_THRESHOLD: std::sync::atomic::AtomicU32 =
2779 std::sync::atomic::AtomicU32::new(0);
2780static OPTI_FORK_ATTEMPTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2781static OPTI_FORK_HITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2782static OPTI_FORK_MISSES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2783static OPTI_FORK_ABORT_DRAINS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2784static OPTI_FORK_REFUSALS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2785static OPTI_GATE_CHECKS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2786static OPTI_GATE_ADMITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2787static OPTI_GATE_REJECTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2788static OPTI_RECONCILES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2789static OPTI_WASTED_DRAFT_TOKENS: std::sync::atomic::AtomicU64 =
2790 std::sync::atomic::AtomicU64::new(0);
2791static OPTI_SHADOW_DRAFT_TOKENS: std::sync::atomic::AtomicU64 =
2792 std::sync::atomic::AtomicU64::new(0);
2793static OPTI_BREAKER_TRIPS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2794
2795impl OptiForkGateMode {
2796 fn code(self) -> u8 {
2797 match self {
2798 Self::Disabled => 0,
2799 Self::Hit => 1,
2800 Self::Miss => 2,
2801 Self::Alternate => 3,
2802 Self::Abort => 4,
2803 Self::Controller => 5,
2804 }
2805 }
2806
2807 fn configured() -> Self {
2808 match OPTI_FORK_GATE_MODE.load(std::sync::atomic::Ordering::Relaxed) {
2809 1 => Self::Hit,
2810 2 => Self::Miss,
2811 3 => Self::Alternate,
2812 4 => Self::Abort,
2813 5 => Self::Controller,
2814 _ => Self::Disabled,
2815 }
2816 }
2817
2818 fn action(self, generation: u64) -> OptiForkAction {
2819 match self {
2820 Self::Hit => OptiForkAction::Hit,
2821 Self::Miss => OptiForkAction::Miss,
2822 Self::Alternate if generation & 1 == 0 => OptiForkAction::Hit,
2823 Self::Alternate => OptiForkAction::Miss,
2824 Self::Abort => OptiForkAction::Abort,
2825 Self::Disabled | Self::Controller => {
2826 unreachable!("non-forced mode cannot choose a forced fork action")
2827 }
2828 }
2829 }
2830
2831 fn is_forced(self) -> bool {
2832 matches!(self, Self::Hit | Self::Miss | Self::Alternate | Self::Abort)
2833 }
2834}
2835
2836/// Arm or disarm the forced harness. Serving uses only `set_optipipe_controller_threshold`.
2837pub fn set_optipipe_gate_mode(mode: OptiForkGateMode) {
2838 OPTI_FORK_GATE_MODE.store(mode.code(), std::sync::atomic::Ordering::Relaxed);
2839}
2840
2841/// Arm the increment-2 diagnostic controller. The threshold applies to the uncalibrated
2842/// two-token draft-probability product. Serving can call this only through its explicit
2843/// fresh-process research door; the absent-door default remains byte-for-byte disabled.
2844pub fn set_optipipe_controller_threshold(threshold: f32) {
2845 assert!(threshold.is_finite() && (0.0..=1.0).contains(&threshold));
2846 OPTI_CONTROLLER_THRESHOLD.store(threshold.to_bits(), std::sync::atomic::Ordering::Relaxed);
2847 set_optipipe_gate_mode(OptiForkGateMode::Controller);
2848}
2849
2850#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2851pub struct OptiForkGateStats {
2852 pub attempts: u64,
2853 pub hits: u64,
2854 pub misses: u64,
2855 pub abort_drains: u64,
2856 pub refusals: u64,
2857 pub gate_checks: u64,
2858 pub gate_admits: u64,
2859 pub gate_rejects: u64,
2860 pub reconciles: u64,
2861 pub wasted_draft_tokens: u64,
2862 pub shadow_draft_tokens: u64,
2863 pub breaker_trips: u64,
2864}
2865
2866#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2867pub struct OptiForkStateIdentity {
2868 pub trunk_kv_bytes: usize,
2869 pub recurrent_bytes: usize,
2870 pub scratch_kv_bytes: usize,
2871 pub hidden_bytes: usize,
2872}
2873
2874pub fn reset_optipipe_gate_stats() {
2875 for counter in [
2876 &OPTI_FORK_ATTEMPTS,
2877 &OPTI_FORK_HITS,
2878 &OPTI_FORK_MISSES,
2879 &OPTI_FORK_ABORT_DRAINS,
2880 &OPTI_FORK_REFUSALS,
2881 &OPTI_GATE_CHECKS,
2882 &OPTI_GATE_ADMITS,
2883 &OPTI_GATE_REJECTS,
2884 &OPTI_RECONCILES,
2885 &OPTI_WASTED_DRAFT_TOKENS,
2886 &OPTI_SHADOW_DRAFT_TOKENS,
2887 &OPTI_BREAKER_TRIPS,
2888 ] {
2889 counter.store(0, std::sync::atomic::Ordering::Relaxed);
2890 }
2891}
2892
2893pub fn optipipe_gate_stats() -> OptiForkGateStats {
2894 let load = |v: &std::sync::atomic::AtomicU64| v.load(std::sync::atomic::Ordering::Relaxed);
2895 OptiForkGateStats {
2896 attempts: load(&OPTI_FORK_ATTEMPTS),
2897 hits: load(&OPTI_FORK_HITS),
2898 misses: load(&OPTI_FORK_MISSES),
2899 abort_drains: load(&OPTI_FORK_ABORT_DRAINS),
2900 refusals: load(&OPTI_FORK_REFUSALS),
2901 gate_checks: load(&OPTI_GATE_CHECKS),
2902 gate_admits: load(&OPTI_GATE_ADMITS),
2903 gate_rejects: load(&OPTI_GATE_REJECTS),
2904 reconciles: load(&OPTI_RECONCILES),
2905 wasted_draft_tokens: load(&OPTI_WASTED_DRAFT_TOKENS),
2906 shadow_draft_tokens: load(&OPTI_SHADOW_DRAFT_TOKENS),
2907 breaker_trips: load(&OPTI_BREAKER_TRIPS),
2908 }
2909}
2910
2911#[derive(Clone, Copy, Debug)]
2912struct OptiControllerPolicy {
2913 threshold: f32,
2914 consecutive_misses: u8,
2915 breaker_tripped: bool,
2916}
2917
2918impl OptiControllerPolicy {
2919 fn configured() -> Self {
2920 Self {
2921 threshold: f32::from_bits(
2922 OPTI_CONTROLLER_THRESHOLD.load(std::sync::atomic::Ordering::Relaxed),
2923 ),
2924 consecutive_misses: 0,
2925 breaker_tripped: false,
2926 }
2927 }
2928
2929 fn admit(&self, q_proxy: f32) -> bool {
2930 q_proxy.is_finite()
2931 && (0.0..=1.0).contains(&q_proxy)
2932 && (self.threshold == 0.0 || (!self.breaker_tripped && q_proxy >= self.threshold))
2933 }
2934
2935 /// Returns true exactly when this resolution newly trips the three-miss breaker.
2936 fn resolve(&mut self, hit: bool) -> bool {
2937 // q*=0 is the lane's explicit unconditional measurement arm. Its purpose is to price
2938 // every optimistic opportunity, so the safety breaker is measured separately and must
2939 // not silently turn this arm into "three attempts then serial".
2940 if self.threshold == 0.0 {
2941 self.consecutive_misses = 0;
2942 return false;
2943 }
2944 if hit {
2945 self.consecutive_misses = 0;
2946 return false;
2947 }
2948 self.consecutive_misses = self.consecutive_misses.saturating_add(1);
2949 if !self.breaker_tripped && self.consecutive_misses >= 3 {
2950 self.breaker_tripped = true;
2951 return true;
2952 }
2953 false
2954 }
2955}
2956
2957#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2958enum OptiForkAction {
2959 Hit,
2960 Miss,
2961 Abort,
2962}
2963
2964#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2965struct OptiForkGeneration {
2966 id: u64,
2967 slot: usize,
2968}
2969
2970#[derive(Default)]
2971struct OptiForkGenerationTracker {
2972 next: u64,
2973 live: [Option<u64>; 2],
2974}
2975
2976impl OptiForkGenerationTracker {
2977 fn reserve(&mut self) -> Result<OptiForkGeneration, Box<dyn std::error::Error>> {
2978 let generation = OptiForkGeneration {
2979 id: self.next,
2980 slot: (self.next & 1) as usize,
2981 };
2982 if let Some(live) = self.live[generation.slot] {
2983 return Err(format!(
2984 "optipipe snapshot slot {} still owns generation {live}; refusing to overwrite it",
2985 generation.slot,
2986 )
2987 .into());
2988 }
2989 self.next += 1;
2990 self.live[generation.slot] = Some(generation.id);
2991 Ok(generation)
2992 }
2993
2994 fn retire(&mut self, generation: OptiForkGeneration) -> Result<(), Box<dyn std::error::Error>> {
2995 match self.live[generation.slot] {
2996 Some(id) if id == generation.id => {
2997 self.live[generation.slot] = None;
2998 Ok(())
2999 }
3000 other => Err(format!(
3001 "optipipe generation teardown mismatch: ticket={} slot={} live={other:?}",
3002 generation.id, generation.slot,
3003 )
3004 .into()),
3005 }
3006 }
3007}
3008
3009struct OptiForkSeedGeneration {
3010 h_seed: CudaSlice<f32>,
3011 fill_prev: CudaSlice<f32>,
3012 scratch_len: usize,
3013}
3014
3015/// Allocate or refresh one full checkpoint through the engine that owns each PP stage. The
3016/// generic cache helper accepts one device and therefore cannot copy GDN state split across
3017/// devices. KV lengths and position stay host metadata; only recurrent buffers need stage-local
3018/// device ownership.
3019fn opti_snapshot_stage_owned(
3020 e: &Engine,
3021 cache: &Cache,
3022 rt: &'static crate::pp::PpNRt,
3023 fence: &[usize],
3024) -> Result<crate::cache::CacheSnapshot, Box<dyn std::error::Error>> {
3025 let n = cache.kv.len();
3026 let mut snapshot = crate::cache::CacheSnapshot {
3027 kv_len: vec![None; n],
3028 tp_kv_len: vec![None; n],
3029 conv: (0..n).map(|_| None).collect(),
3030 ssm: (0..n).map(|_| None).collect(),
3031 pos: cache.pos,
3032 };
3033 opti_snapshot_stage_owned_into(e, cache, rt, fence, &mut snapshot)?;
3034 Ok(snapshot)
3035}
3036
3037fn opti_snapshot_stage_owned_into(
3038 e: &Engine,
3039 cache: &Cache,
3040 rt: &'static crate::pp::PpNRt,
3041 fence: &[usize],
3042 snapshot: &mut crate::cache::CacheSnapshot,
3043) -> Result<(), Box<dyn std::error::Error>> {
3044 if fence.len() != rt.n_stages() + 1
3045 || snapshot.kv_len.len() != cache.kv.len()
3046 || snapshot.tp_kv_len.len() != cache.tp_kv.len()
3047 {
3048 return Err("optipipe stage-owned snapshot shape mismatch".into());
3049 }
3050 for stage in 0..rt.n_stages() {
3051 opti_snapshot_one_stage_owned_into(e, cache, rt, fence, stage, snapshot)?;
3052 }
3053 snapshot.pos = cache.pos;
3054 Ok(())
3055}
3056
3057/// Refresh one PP stage of a checkpoint. Increment 2 uses this split form so stage 0's
3058/// optimistic post-N state is captured before N+1 stage 0 is queued, while stage 1's matching
3059/// post-N state is captured only after N stage 1 is enqueued. Calling the all-stage helper at
3060/// either point would capture one side of the fork at the wrong generation.
3061fn opti_snapshot_one_stage_owned_into(
3062 e: &Engine,
3063 cache: &Cache,
3064 rt: &'static crate::pp::PpNRt,
3065 fence: &[usize],
3066 stage: usize,
3067 snapshot: &mut crate::cache::CacheSnapshot,
3068) -> Result<(), Box<dyn std::error::Error>> {
3069 if fence.len() != rt.n_stages() + 1
3070 || snapshot.kv_len.len() != cache.kv.len()
3071 || snapshot.tp_kv_len.len() != cache.tp_kv.len()
3072 || stage >= rt.n_stages()
3073 {
3074 return Err("optipipe single-stage snapshot shape mismatch".into());
3075 }
3076 let _scope = rt.enter(stage);
3077 let owner = rt.engine(stage, e);
3078 for il in fence[stage]..fence[stage + 1] {
3079 snapshot.kv_len[il] = cache.kv[il].as_ref().map(|kv| kv.len);
3080 snapshot.tp_kv_len[il] = cache.tp_kv[il]
3081 .as_ref()
3082 .map(crate::tp::ResidentTpKvCache::committed_len);
3083 match &cache.recur[il] {
3084 Some(recur) => {
3085 match snapshot.conv[il].as_mut() {
3086 Some(dst) => {
3087 owner.copy_into(dst, 0, &recur.conv_state, recur.conv_state.len())?
3088 }
3089 None => snapshot.conv[il] = Some(owner.clone_dtod(&recur.conv_state)?),
3090 }
3091 match snapshot.ssm[il].as_mut() {
3092 Some(dst) => {
3093 owner.copy_into(dst, 0, &recur.ssm_state, recur.ssm_state.len())?
3094 }
3095 None => snapshot.ssm[il] = Some(owner.clone_dtod(&recur.ssm_state)?),
3096 }
3097 }
3098 None if snapshot.conv[il].is_some() || snapshot.ssm[il].is_some() => {
3099 return Err(
3100 format!("optipipe stage-owned snapshot layer {il} changed shape").into(),
3101 );
3102 }
3103 None => {}
3104 }
3105 }
3106 snapshot.pos = cache.pos;
3107 Ok(())
3108}
3109
3110/// Increment-1 persistent fork state. Exactly two snapshot/seed slots alternate; a live ticket
3111/// names its generation and keeps teardown fail-closed. Only stage 0 is allowed to mutate before
3112/// resolve, so the reconcile tables and conditional restores are stage-local.
3113struct OptiForkState {
3114 mode: OptiForkGateMode,
3115 controller: Option<OptiControllerPolicy>,
3116 generations: OptiForkGenerationTracker,
3117 active_snapshot_slot: usize,
3118 alternate_snapshot: crate::cache::CacheSnapshot,
3119 seeds: [OptiForkSeedGeneration; 2],
3120 rt: &'static crate::pp::PpNRt,
3121 fence: [usize; 3],
3122 split: usize,
3123 len_ptrs: CudaSlice<u64>,
3124 saved_lens: CudaSlice<i32>,
3125 forced_acc: CudaSlice<u32>,
3126 valid: CudaSlice<u32>,
3127 stage0_stream: std::sync::Arc<cudarc::driver::CudaStream>,
3128 logical_payload_bytes: [usize; 2],
3129}
3130
3131struct OptiForkTicket {
3132 generation: OptiForkGeneration,
3133 boundary: Option<VerifyBoundaryTicket>,
3134 drain: std::sync::Arc<cudarc::driver::CudaStream>,
3135 settled: bool,
3136}
3137
3138struct OptiControllerTicket {
3139 generation: OptiForkGeneration,
3140 boundary: Option<VerifyBoundaryTicket>,
3141 ckpt: Option<VerifyCkpt>,
3142 verify_tokens: [u32; 2],
3143 draft_prob: f32,
3144 eager_seed: Option<CudaSlice<f32>>,
3145 q_proxy: f32,
3146 scratch_len: usize,
3147 issued_at: std::time::Instant,
3148 drain: std::sync::Arc<cudarc::driver::CudaStream>,
3149 settled: bool,
3150}
3151
3152struct OptiControllerPrepared {
3153 verify_tokens: [u32; 2],
3154 draft_prob: f32,
3155 eager_seed: Option<CudaSlice<f32>>,
3156 q_proxy: f32,
3157 scratch_len: usize,
3158}
3159
3160impl OptiControllerTicket {
3161 fn take_boundary(&mut self) -> VerifyBoundaryTicket {
3162 self.boundary
3163 .take()
3164 .expect("controller boundary ticket already consumed")
3165 }
3166
3167 fn take_ckpt(&mut self) -> VerifyCkpt {
3168 self.ckpt
3169 .take()
3170 .expect("controller verify checkpoint already consumed")
3171 }
3172
3173 fn take_eager_seed(&mut self) -> Option<CudaSlice<f32>> {
3174 self.eager_seed.take()
3175 }
3176
3177 fn settle(&mut self) {
3178 self.settled = true;
3179 }
3180}
3181
3182impl Drop for OptiControllerTicket {
3183 fn drop(&mut self) {
3184 if !self.settled {
3185 let _ = self.drain.synchronize();
3186 OPTI_FORK_ABORT_DRAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3187 }
3188 }
3189}
3190
3191impl OptiForkTicket {
3192 fn take_boundary(&mut self) -> VerifyBoundaryTicket {
3193 self.boundary
3194 .take()
3195 .expect("fork ticket boundary already consumed")
3196 }
3197
3198 fn settle(&mut self) {
3199 self.settled = true;
3200 }
3201}
3202
3203impl Drop for OptiForkTicket {
3204 fn drop(&mut self) {
3205 if !self.settled {
3206 let _ = self.drain.synchronize();
3207 OPTI_FORK_ABORT_DRAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3208 }
3209 }
3210}
3211
3212impl OptiForkState {
3213 #[allow(clippy::too_many_arguments)]
3214 fn new(
3215 e: &Engine,
3216 cache: &Cache,
3217 mode: OptiForkGateMode,
3218 alternate_snapshot: crate::cache::CacheSnapshot,
3219 h_seed: &CudaSlice<f32>,
3220 fill_prev: &CudaSlice<f32>,
3221 rt: &'static crate::pp::PpNRt,
3222 split: usize,
3223 n_layer: usize,
3224 ) -> Result<Self, Box<dyn std::error::Error>> {
3225 let fence = [0, split, n_layer];
3226 let mut logical_payload_bytes = [0usize; 2];
3227 for stage in 0..2 {
3228 for il in fence[stage]..fence[stage + 1] {
3229 logical_payload_bytes[stage] += alternate_snapshot.conv[il]
3230 .as_ref()
3231 .map_or(0, |v| v.len() * std::mem::size_of::<f32>());
3232 logical_payload_bytes[stage] += alternate_snapshot.ssm[il]
3233 .as_ref()
3234 .map_or(0, |v| v.len() * std::mem::size_of::<f32>());
3235 }
3236 }
3237 let seeds = [
3238 OptiForkSeedGeneration {
3239 h_seed: e.clone_dtod(h_seed)?,
3240 fill_prev: e.clone_dtod(fill_prev)?,
3241 scratch_len: 0,
3242 },
3243 OptiForkSeedGeneration {
3244 h_seed: e.clone_dtod(h_seed)?,
3245 fill_prev: e.clone_dtod(fill_prev)?,
3246 scratch_len: 0,
3247 },
3248 ];
3249 let (len_ptrs, saved_lens, forced_acc, valid, stage0_stream) = {
3250 let _stage = rt.enter(0);
3251 let e0 = rt.engine(0, e);
3252 (
3253 crate::round_stream::kv_len_ptr_table_range(e0, cache, 0..split, None)?,
3254 e0.htod_i32(&vec![0; split])?,
3255 e0.alloc_u32_zeroed(2)?,
3256 e0.alloc_u32_zeroed(1)?,
3257 e0.stream(),
3258 )
3259 };
3260 logical_payload_bytes[0] += seeds
3261 .iter()
3262 .map(|seed| (seed.h_seed.len() + seed.fill_prev.len()) * std::mem::size_of::<f32>())
3263 .sum::<usize>();
3264 logical_payload_bytes[0] += len_ptrs.len() * std::mem::size_of::<u64>()
3265 + saved_lens.len() * std::mem::size_of::<i32>()
3266 + forced_acc.len() * std::mem::size_of::<u32>()
3267 + valid.len() * std::mem::size_of::<u32>();
3268 Ok(Self {
3269 mode,
3270 controller: (mode == OptiForkGateMode::Controller)
3271 .then(OptiControllerPolicy::configured),
3272 generations: OptiForkGenerationTracker::default(),
3273 active_snapshot_slot: 0,
3274 alternate_snapshot,
3275 seeds,
3276 rt,
3277 fence,
3278 split,
3279 len_ptrs,
3280 saved_lens,
3281 forced_acc,
3282 valid,
3283 stage0_stream,
3284 logical_payload_bytes,
3285 })
3286 }
3287
3288 fn reserve(
3289 &mut self,
3290 current_snapshot: &mut crate::cache::CacheSnapshot,
3291 ) -> Result<OptiForkGeneration, Box<dyn std::error::Error>> {
3292 let generation = self.generations.reserve()?;
3293 if generation.slot != self.active_snapshot_slot {
3294 std::mem::swap(current_snapshot, &mut self.alternate_snapshot);
3295 self.active_snapshot_slot = generation.slot;
3296 }
3297 Ok(generation)
3298 }
3299
3300 fn capture_seed(
3301 &mut self,
3302 e: &Engine,
3303 generation: OptiForkGeneration,
3304 h_seed: &CudaSlice<f32>,
3305 fill_prev: &CudaSlice<f32>,
3306 scratch_len: usize,
3307 ) -> Result<(), Box<dyn std::error::Error>> {
3308 let seed = &mut self.seeds[generation.slot];
3309 e.copy_into(&mut seed.h_seed, 0, h_seed, h_seed.len())?;
3310 e.copy_into(&mut seed.fill_prev, 0, fill_prev, fill_prev.len())?;
3311 seed.scratch_len = scratch_len;
3312 Ok(())
3313 }
3314
3315 fn ticket(
3316 &self,
3317 generation: OptiForkGeneration,
3318 boundary: VerifyBoundaryTicket,
3319 ) -> OptiForkTicket {
3320 OptiForkTicket {
3321 generation,
3322 boundary: Some(boundary),
3323 drain: self.stage0_stream.clone(),
3324 settled: false,
3325 }
3326 }
3327
3328 #[allow(clippy::too_many_arguments)]
3329 fn controller_ticket(
3330 &self,
3331 generation: OptiForkGeneration,
3332 boundary: VerifyBoundaryTicket,
3333 ckpt: VerifyCkpt,
3334 verify_tokens: [u32; 2],
3335 draft_prob: f32,
3336 eager_seed: Option<CudaSlice<f32>>,
3337 q_proxy: f32,
3338 scratch_len: usize,
3339 ) -> OptiControllerTicket {
3340 OptiControllerTicket {
3341 generation,
3342 boundary: Some(boundary),
3343 ckpt: Some(ckpt),
3344 verify_tokens,
3345 draft_prob,
3346 eager_seed,
3347 q_proxy,
3348 scratch_len,
3349 issued_at: std::time::Instant::now(),
3350 drain: self.stage0_stream.clone(),
3351 settled: false,
3352 }
3353 }
3354
3355 fn reserve_successor(&mut self) -> Result<OptiForkGeneration, Box<dyn std::error::Error>> {
3356 self.generations.reserve()
3357 }
3358
3359 fn successor_snapshot_mut(&mut self) -> &mut crate::cache::CacheSnapshot {
3360 &mut self.alternate_snapshot
3361 }
3362
3363 fn promote_successor_snapshot(
3364 &mut self,
3365 current_snapshot: &mut crate::cache::CacheSnapshot,
3366 generation: OptiForkGeneration,
3367 ) {
3368 std::mem::swap(current_snapshot, &mut self.alternate_snapshot);
3369 self.active_snapshot_slot = generation.slot;
3370 }
3371
3372 fn queue_actual_reconcile(
3373 &mut self,
3374 e: &Engine,
3375 snapshot: &crate::cache::CacheSnapshot,
3376 acc: &CudaSlice<u32>,
3377 optimistic_pending: u32,
3378 base: usize,
3379 ) -> Result<(), Box<dyn std::error::Error>> {
3380 let saved: Vec<i32> = (0..self.split)
3381 .map(|il| snapshot.kv_len[il].map(|v| v as i32).unwrap_or(0))
3382 .collect();
3383 // Serving keeps the caller/accept walk on the head (stage-1) device. Record the accept
3384 // decision point there and append a wait to stage 0 after its optimistic successor/TX;
3385 // the validity/reconcile kernels must never peer-read acc before it is written. The
3386 // increment-1 harness uses primary stage 0, where stream order already provides this.
3387 if self.rt.engine(0, e).ctx().ordinal() != e.ctx().ordinal() {
3388 self.rt.fence_stages_behind(&e.stream())?;
3389 }
3390 let _stage = self.rt.enter(0);
3391 let e0 = self.rt.engine(0, e);
3392 e0.htod_i32_into(&mut self.saved_lens, &saved)?;
3393 e0.spec_fork_valid(acc, optimistic_pending, &mut self.valid)?;
3394 e0.spec_fork_reconcile_kv(
3395 &self.len_ptrs,
3396 &self.saved_lens,
3397 acc,
3398 &self.valid,
3399 base,
3400 self.split,
3401 )
3402 }
3403
3404 fn finish_actual_reconcile(
3405 &mut self,
3406 e: &Engine,
3407 cache: &mut Cache,
3408 snapshot: &crate::cache::CacheSnapshot,
3409 n_acc: usize,
3410 base: usize,
3411 hit: bool,
3412 ) -> Result<(), Box<dyn std::error::Error>> {
3413 if hit {
3414 return Ok(());
3415 }
3416 let len_delta = base + n_acc;
3417 for il in 0..self.split {
3418 if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
3419 kv.len = saved + len_delta;
3420 }
3421 }
3422 {
3423 let _stage = self.rt.enter(1);
3424 let e1 = self.rt.engine(1, e);
3425 for il in self.split..self.fence[2] {
3426 if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
3427 kv.len = saved + len_delta;
3428 e1.set_i32_one(&mut kv.len_d, kv.len as i32)?;
3429 }
3430 }
3431 }
3432 self.rt.publish_to(0, &e.stream())?;
3433 Ok(())
3434 }
3435
3436 fn cancel_controller_ticket(
3437 &mut self,
3438 e: &Engine,
3439 cache: &mut Cache,
3440 scratch: &mut MtpScratch,
3441 snapshot: &crate::cache::CacheSnapshot,
3442 ticket: &mut OptiControllerTicket,
3443 ) -> Result<(), Box<dyn std::error::Error>> {
3444 {
3445 let _stage = self.rt.enter(0);
3446 let e0 = self.rt.engine(0, e);
3447 for il in 0..self.split {
3448 if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
3449 kv.len = saved;
3450 e0.set_i32_one(&mut kv.len_d, saved as i32)?;
3451 }
3452 }
3453 }
3454 scratch.set_len(e, snapshot.pos)?;
3455 ticket.settle();
3456 self.generations.retire(ticket.generation)?;
3457 OPTI_FORK_ABORT_DRAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3458 OPTI_WASTED_DRAFT_TOKENS.fetch_add(2, std::sync::atomic::Ordering::Relaxed);
3459 eprintln!(
3460 "[opti-controller] tail-drain generation={} slot={}",
3461 ticket.generation.id, ticket.generation.slot,
3462 );
3463 Ok(())
3464 }
3465
3466 #[allow(clippy::too_many_arguments)]
3467 fn reconcile(
3468 &mut self,
3469 e: &Engine,
3470 cache: &mut Cache,
3471 scratch: &mut MtpScratch,
3472 snapshot: &crate::cache::CacheSnapshot,
3473 h_seed: &mut CudaSlice<f32>,
3474 fill_prev: &mut CudaSlice<f32>,
3475 generation: OptiForkGeneration,
3476 action: OptiForkAction,
3477 optimistic_pending: u32,
3478 ) -> Result<(), Box<dyn std::error::Error>> {
3479 debug_assert!(action != OptiForkAction::Abort);
3480 let miss_started = std::time::Instant::now();
3481 let keep = action == OptiForkAction::Hit;
3482 let saved: Vec<i32> = (0..self.split)
3483 .map(|il| snapshot.kv_len[il].map(|v| v as i32).unwrap_or(0))
3484 .collect();
3485 let seed = &self.seeds[generation.slot];
3486 {
3487 let _stage = self.rt.enter(0);
3488 let e0 = self.rt.engine(0, e);
3489 e0.htod_i32_into(&mut self.saved_lens, &saved)?;
3490 let forced = if keep {
3491 [1u32, optimistic_pending]
3492 } else {
3493 [0u32, optimistic_pending]
3494 };
3495 e0.htod_u32_into(&mut self.forced_acc, &forced)?;
3496 e0.spec_fork_valid(&self.forced_acc, optimistic_pending, &mut self.valid)?;
3497 e0.spec_fork_reconcile_kv(
3498 &self.len_ptrs,
3499 &self.saved_lens,
3500 &self.forced_acc,
3501 &self.valid,
3502 0,
3503 self.split,
3504 )?;
3505 for il in 0..self.split {
3506 if let Some(recur) = cache.recur[il].as_mut() {
3507 let conv = snapshot.conv[il]
3508 .as_ref()
3509 .ok_or("optipipe stage0 snapshot missing conv state")?;
3510 let ssm = snapshot.ssm[il]
3511 .as_ref()
3512 .ok_or("optipipe stage0 snapshot missing ssm state")?;
3513 e0.spec_fork_restore_f32(conv, &mut recur.conv_state, &self.valid)?;
3514 e0.spec_fork_restore_f32(ssm, &mut recur.ssm_state, &self.valid)?;
3515 }
3516 }
3517 e0.spec_fork_restore_f32(&seed.h_seed, h_seed, &self.valid)?;
3518 e0.spec_fork_restore_f32(&seed.fill_prev, fill_prev, &self.valid)?;
3519 }
3520
3521 if keep {
3522 OPTI_FORK_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3523 return Ok(());
3524 }
3525
3526 for il in 0..self.split {
3527 if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
3528 kv.len = saved;
3529 }
3530 }
3531 scratch.set_len(e, seed.scratch_len)?;
3532 // Targeted E_restart: publish only stage 0's reconcile to the caller, then bound the
3533 // forced diagnostic so the retained number is the actual miss cost, not enqueue time.
3534 let caller = e.stream();
3535 self.rt.publish_to(0, &caller)?;
3536 caller.synchronize()?;
3537 let miss_ms = miss_started.elapsed().as_secs_f64() * 1e3;
3538 eprintln!(
3539 "[opti-fork-reconcile] generation={} slot={} miss_ms={miss_ms:.3}",
3540 generation.id, generation.slot,
3541 );
3542 OPTI_FORK_MISSES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3543 Ok(())
3544 }
3545
3546 fn retire(&mut self, generation: OptiForkGeneration) -> Result<(), Box<dyn std::error::Error>> {
3547 self.generations.retire(generation)
3548 }
3549}
3550
3551fn rewind_tp_kv_verified_prefix(
3552 tp_kv: &mut [Option<crate::tp::ResidentTpKvCache>],
3553 saved_lens: &[Option<usize>],
3554 accepted: usize,
3555) -> Result<(), Box<dyn std::error::Error>> {
3556 if tp_kv.len() != saved_lens.len() {
3557 return Err("spec TP KV snapshot shape mismatch".into());
3558 }
3559 for (layer, (cache, saved)) in tp_kv.iter_mut().zip(saved_lens).enumerate() {
3560 match (cache.as_mut(), *saved) {
3561 (Some(cache), Some(saved)) => {
3562 let target = saved
3563 .checked_add(accepted)
3564 .ok_or("spec TP KV committed length overflow")?;
3565 cache.rewind_to(target)?;
3566 }
3567 (None, None) => {}
3568 _ => {
3569 return Err(
3570 format!("spec TP KV layer {layer} changed shape since its snapshot").into(),
3571 );
3572 }
3573 }
3574 }
3575 Ok(())
3576}
3577
3578impl HybridModel {
3579 fn mtp_head_count(&self) -> usize {
3580 usize::from(self.mtp.is_some()) + self.mtp_extra.len()
3581 }
3582
3583 fn mtp_head_at(&self, index: usize) -> &MtpHead {
3584 if index == 0 {
3585 self.mtp.as_ref().expect("MTP head 0 is unavailable")
3586 } else {
3587 &self.mtp_extra[index - 1]
3588 }
3589 }
3590
3591 fn new_mtp_scratch(
3592 &self,
3593 e: &Engine,
3594 cap: usize,
3595 ) -> Result<MtpScratch, Box<dyn std::error::Error>> {
3596 let mut scratch = MtpScratch::new(
3597 e,
3598 &self.cfg,
3599 &self.plan,
3600 cap,
3601 self.mtp.as_ref().and_then(|head| head.geom.as_ref()),
3602 )?;
3603 for head in &self.mtp_extra {
3604 scratch.push_plane(e, &self.cfg, &self.plan, head.geom.as_ref())?;
3605 }
3606 Ok(scratch)
3607 }
3608
3609 fn opti_graph_draft_step(
3610 &self,
3611 e: &Engine,
3612 mtp: &MtpHead,
3613 dctx: &mut DraftGraphCtx,
3614 scratch: &mut MtpScratch,
3615 d_vocab: usize,
3616 ) -> Result<(u32, f32), Box<dyn std::error::Error>> {
3617 dctx.graph
3618 .as_ref()
3619 .ok_or("optipipe controller requires the greedy draft graph")?
3620 .launch()?;
3621 scratch.kv.len += 1;
3622 let idx = e.dtoh_u32_one(&dctx.g_tok)?;
3623 if (idx as usize) >= d_vocab {
3624 return Err(
3625 format!("optipipe draft argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab}").into(),
3626 );
3627 }
3628 let probability = e.dtoh(&dctx.g_p)?[0];
3629 if !probability.is_finite() || !(0.0..=1.0).contains(&probability) {
3630 return Err(format!("optipipe draft probability is invalid: {probability}").into());
3631 }
3632 let token = match &mtp.d2t {
3633 Some(map) => map[idx as usize],
3634 None => idx,
3635 };
3636 if token != idx {
3637 e.set_u32_one(&mut dctx.g_tok, token)?;
3638 }
3639 Ok((token, probability))
3640 }
3641
3642 #[allow(clippy::too_many_arguments)]
3643 fn opti_controller_draft_step(
3644 &self,
3645 e: &Engine,
3646 mtp: &MtpHead,
3647 dctx: &mut DraftGraphCtx,
3648 scratch: &mut MtpScratch,
3649 d_vocab: usize,
3650 eager_state: &mut Option<(u32, CudaSlice<f32>)>,
3651 eager_pos: usize,
3652 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3653 ) -> Result<(u32, f32), Box<dyn std::error::Error>> {
3654 if dctx.graph.is_some() {
3655 return self.opti_graph_draft_step(e, mtp, dctx, scratch, d_vocab);
3656 }
3657 let (input_token, input_seed) = eager_state
3658 .take()
3659 .ok_or("optipipe eager continuation seed is unavailable")?;
3660 let (logits, next_seed) = self.mtp_head_forward_dev(
3661 e,
3662 mtp,
3663 input_token,
3664 &input_seed,
3665 scratch,
3666 eager_pos,
3667 embd_dev,
3668 None,
3669 )?;
3670 let token_d = e.argmax_token_device(&logits, d_vocab)?;
3671 let idx = e.dtoh_u32_one(&token_d)?;
3672 if (idx as usize) >= d_vocab {
3673 return Err(format!(
3674 "optipipe eager draft argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab}"
3675 )
3676 .into());
3677 }
3678 let probability_d = e.prob_of_token_device(&logits, &token_d, d_vocab)?;
3679 let probability = e.dtoh(&probability_d)?[0];
3680 if !probability.is_finite() || !(0.0..=1.0).contains(&probability) {
3681 return Err(
3682 format!("optipipe eager draft probability is invalid: {probability}").into(),
3683 );
3684 }
3685 let token = match &mtp.d2t {
3686 Some(map) => map[idx as usize],
3687 None => idx,
3688 };
3689 *eager_state = Some((token, next_seed));
3690 Ok((token, probability))
3691 }
3692
3693 /// NextN head forward for ONE draft token (§A ops 1-13, T=1).
3694 /// Inputs: `e_tok` = the token to predict FROM (last committed / previous draft); `h_seed` =
3695 /// the trunk's pre-output_norm hidden of that token (§A op 2 input). `mtp_pos` = absolute
3696 /// position of the token being predicted from. Returns (draft_logits[n_vocab] host, h_nextn dev).
3697 /// `h_nextn` (§A op 10) becomes `h_seed` for the next autoregressive draft step.
3698 /// Device-resident: returns draft logits ON DEVICE (no [n_vocab] dtoh). The greedy draft
3699 /// loop only needs argmax — paired with `argmax_token_device` this cuts the ~600KB logits
3700 /// transfer + host argmax per draft token from the K-token draft chain.
3701 #[allow(clippy::too_many_arguments)]
3702 fn mtp_head_forward_dev(
3703 &self,
3704 e: &Engine,
3705 mtp: &MtpHead,
3706 e_tok: u32,
3707 h_seed: &CudaSlice<f32>,
3708 scratch: &mut MtpScratch,
3709 mtp_pos: usize,
3710 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3711 mask: Option<(&CudaSlice<u32>, usize)>,
3712 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3713 self.mtp_head_forward_dev_at(e, mtp, e_tok, h_seed, scratch, 0, mtp_pos, embd_dev, mask)
3714 }
3715
3716 #[allow(clippy::too_many_arguments)]
3717 fn mtp_head_forward_dev_at(
3718 &self,
3719 e: &Engine,
3720 mtp: &MtpHead,
3721 e_tok: u32,
3722 h_seed: &CudaSlice<f32>,
3723 scratch: &mut MtpScratch,
3724 scratch_index: usize,
3725 mtp_pos: usize,
3726 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3727 // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): (packed draft-vocab allowed set, words).
3728 // Applied to the head logits BEFORE they are returned, so every consumer (argmax,
3729 // gumbel draw, p-min prob) sees the grammar-legal row. None = unmasked (pre-lane).
3730 mask: Option<(&CudaSlice<u32>, usize)>,
3731 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3732 // MEMRA_SPEC_ANATOMY=1 — eager-step phase timers (diagnostic only). Phase boundaries
3733 // sync the stream, so absolute time inflates; the BREAKDOWN is the signal. Cumulative
3734 // summary on stderr every 128 steps: glue (embed..attn_norm), attn, ffn, head.
3735 use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
3736 static ANAT_NS: [AtomicU64; 5] = [
3737 AtomicU64::new(0),
3738 AtomicU64::new(0),
3739 AtomicU64::new(0),
3740 AtomicU64::new(0),
3741 AtomicU64::new(0),
3742 ];
3743 static ANAT_STEPS: AtomicU64 = AtomicU64::new(0);
3744 let anat = {
3745 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
3746 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_ANATOMY").as_deref() == Ok("1"))
3747 };
3748 if anat {
3749 e.stream().synchronize()?; // drain prior queue so phase 0 starts clean
3750 }
3751 let t_all = std::time::Instant::now();
3752 let mut t_ph = std::time::Instant::now();
3753 let mut anat_mark = |i: usize,
3754 e: &Engine,
3755 t: &mut std::time::Instant|
3756 -> Result<(), Box<dyn std::error::Error>> {
3757 if anat {
3758 e.stream().synchronize()?;
3759 ANAT_NS[i].fetch_add(t.elapsed().as_nanos() as u64, Relaxed);
3760 *t = std::time::Instant::now();
3761 }
3762 Ok(())
3763 };
3764 let cfg = &self.cfg;
3765 let n_embd = cfg.n_embd as usize;
3766 // Distilled-student geometry: the block runs at the INNER width `di` (eh_proj out /
3767 // attn / ffn); the n_embd interface (embed, norms in, carrier out, head in) is unchanged.
3768 let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
3769 let eps = cfg.rms_eps;
3770 let pos_d = e.htod_i32(&[mtp_pos as i32])?;
3771
3772 // op A: a resident table transfers one 4B token id. The exact host-row capacity path
3773 // expands this one row on CPU and transfers n_embd f32 values instead.
3774 let e_emb = match embd_dev {
3775 Some((g, qt, rb)) => e.embed_gather_device_t(g, &[e_tok], n_embd, qt, rb)?,
3776 None => e.htod(&self.embd.gather(n_embd, &[e_tok]))?,
3777 };
3778
3779 // op 1/2: e_norm = RMSNorm(e, enorm); h_norm = RMSNorm(h_seed, hnorm)
3780 let mut e_norm = e.zeros(n_embd)?;
3781 e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, 1, eps)?;
3782 let mut h_norm = e.zeros(n_embd)?;
3783 e.rms_norm(h_seed, mtp.hnorm.float_data(), &mut h_norm, n_embd, 1, eps)?;
3784
3785 // op 3: concat = [e_norm ; h_norm] -> [2*n_embd], e_norm in [0,n_embd), h_norm in [n_embd,2n_embd)
3786 let mut concat = e.zeros(2 * n_embd)?;
3787 e.copy_into(&mut concat, 0, &e_norm, n_embd)?;
3788 e.copy_into(&mut concat, n_embd, &h_norm, n_embd)?;
3789
3790 // op 4: inpSA = eh_proj @ concat (eh_proj [2*n_embd, n_embd]) -> [n_embd]
3791 let inp_sa = e.matmul(&mtp.eh_proj, &concat, 1)?;
3792
3793 // op 5: a_norm = RMSNorm(inpSA, attn_norm)
3794 let mut a_norm = e.zeros(di)?;
3795 e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, 1, eps)?;
3796 anat_mark(0, e, &mut t_ph)?;
3797
3798 // op 6: attention on the scratch KV. SAME dc launcher as the graph path (bucket_max =
3799 // scratch.cap, length from the device len_d) so eager drafts match graph drafts
3800 // bit-for-bit at any t_kv (the parity gate). Host len mirrored here (the dc append
3801 // advances only the device counter).
3802 let attn_out = match (&mtp.mixer, mtp.step35.as_ref()) {
3803 // step35 MTP block: PER-LAYER geometry + a separate head-wise gate + an SWA window,
3804 // none of which the dc launcher can express (see `mtp_step35_attn`). Host-len arm.
3805 // Advances BOTH the host len and the device counter itself (unlike the dc arm,
3806 // whose host-side mirror the caller does).
3807 (Mixer::Full(fa), Some(g)) => {
3808 self.mtp_step35_attn(e, fa, g, &a_norm, &pos_d, scratch, scratch_index)?
3809 }
3810 (Mixer::Full(fa), None) => {
3811 let out = self.mtp_full_attn_dc(
3812 e,
3813 fa,
3814 &a_norm,
3815 &pos_d,
3816 scratch,
3817 scratch_index,
3818 mtp.geom.as_ref(),
3819 )?;
3820 scratch.plane_mut(scratch_index).0.len += 1;
3821 out
3822 }
3823 (Mixer::Linear(_), _) => {
3824 panic!("MTP block is full-attn in qwen35; linear MTP not supported")
3825 }
3826 (Mixer::Mla(_), _) => crate::hybrid::mla_forward_unimplemented(),
3827 };
3828 anat_mark(1, e, &mut t_ph)?;
3829
3830 // op 7: x1 = inpSA + attn_out
3831 let mut x1 = e.zeros(di)?;
3832 e.add(&inp_sa, &attn_out, &mut x1, di)?;
3833
3834 // op 8: z = RMSNorm(x1, post_attn_norm) (pre-FFN norm)
3835 let mut z = e.zeros(di)?;
3836 e.rms_norm(&x1, mtp.post_attn_norm.float_data(), &mut z, di, 1, eps)?;
3837
3838 // op 9: FFN (Dense or MoE) — same as the trunk decode FFN
3839 let ffn_out = match &mtp.ffn {
3840 crate::hybrid::Ffn::Dense {
3841 ffn_gate,
3842 ffn_up,
3843 ffn_down,
3844 } => {
3845 let n_ff = ffn_gate.out_features();
3846 let (gate, up) = if e.uses_q8_1_fast(ffn_gate) && e.uses_q8_1_fast(ffn_up) {
3847 let (zq, zd) = e.quantize_q8_1(&z, 1, di)?;
3848 (
3849 e.matmul_pre(ffn_gate, &zq, &zd, &z, 1)?,
3850 e.matmul_pre(ffn_up, &zq, &zd, &z, 1)?,
3851 )
3852 } else {
3853 (e.matmul(ffn_gate, &z, 1)?, e.matmul(ffn_up, &z, 1)?)
3854 };
3855 let mut act = e.zeros(n_ff)?;
3856 // step35: a DENSE FFN reads the per-layer SHEXP clamp (upstream's one `build_ffn`
3857 // serves the dense MLP and the shared expert off `swiglu_clamp_shexp` —
3858 // llama-graph.cpp:1751), resolved for the MTP block's OWN index. Every other arch
3859 // passes None, which is `ffn_act`'s dispatch verbatim.
3860 Self::ffn_act_lim(
3861 e,
3862 &self.cfg,
3863 &gate,
3864 &up,
3865 1.0,
3866 1.0,
3867 mtp.step35.as_ref().and_then(|s| s.clamp_shexp),
3868 &mut act,
3869 n_ff,
3870 )?;
3871 e.matmul(ffn_down, &act, 1)?
3872 }
3873 // MTP head is a distinct block — key its experts under a separate layer index (u16::MAX)
3874 // so they never alias trunk layer 0's cache keys.
3875 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, 1, u16::MAX)?,
3876 };
3877 anat_mark(2, e, &mut t_ph)?;
3878
3879 // op 10: h_nextn = x1 + ffn_out (at di)
3880 let mut h_inner = e.zeros(di)?;
3881 e.add(&x1, &ffn_out, &mut h_inner, di)?;
3882
3883 // op 10.5 (student): up-project the inner hidden back to n_embd — training semantics:
3884 // the chain carrier AND the head input are out_up(h_inner) (pre-final-norm).
3885 let h_nextn = match mtp.geom.as_ref() {
3886 Some(g) => e.matmul(&g.out_up, &h_inner, 1)?,
3887 None => h_inner,
3888 };
3889
3890 // op 11: final = RMSNorm(h_nextn, shared_head_norm OR output_norm)
3891 let final_norm = mtp.shared_head_norm.as_ref().unwrap_or(&self.output_norm);
3892 let mut final_h = e.zeros(n_embd)?;
3893 e.rms_norm(
3894 &h_nextn,
3895 final_norm.float_data(),
3896 &mut final_h,
3897 n_embd,
3898 1,
3899 eps,
3900 )?;
3901
3902 // op 12: draft_logits = (shared_head_head OR output) @ final — stays ON DEVICE.
3903 let head = mtp.shared_head_head.as_ref().unwrap_or(&self.output);
3904 let mut logits = e.matmul(head, &final_h, 1)?;
3905 // op 12b (lane/draft-mask): grammar mask over the DRAFT vocab, applied here so the
3906 // caller's argmax / gumbel draw / p-min prob all read the grammar-legal row.
3907 if let Some((mask_d, mw)) = mask {
3908 let d_vocab = head.out_features();
3909 e.mask_logits_col(&mut logits, mask_d, 0, d_vocab, mw)?;
3910 }
3911 anat_mark(3, e, &mut t_ph)?;
3912 if anat {
3913 ANAT_NS[4].fetch_add(t_all.elapsed().as_nanos() as u64, Relaxed);
3914 let n = ANAT_STEPS.fetch_add(1, Relaxed) + 1;
3915 if n % 128 == 0 {
3916 let us = |i: usize| ANAT_NS[i].load(Relaxed) / n / 1000;
3917 eprintln!(
3918 "[spec-anatomy] steps={n} avg us/step: glue={} attn={} ffn={} head={} total={}",
3919 us(0),
3920 us(1),
3921 us(2),
3922 us(3),
3923 us(4)
3924 );
3925 }
3926 }
3927 // Chain recurrence hand-over: pre-norm h_nextn (default) or post-norm final_h
3928 // (MEMRA_SPEC_HPOST — llama.cpp #24025's t_h_nextn is taken AFTER the head norm).
3929 Ok((logits, if spec_hpost() { final_h } else { h_nextn }))
3930 }
3931
3932 #[allow(clippy::too_many_arguments)]
3933 fn mtp_chain_forward_dev(
3934 &self,
3935 e: &Engine,
3936 tokens: &[u32],
3937 seeds: &[CudaSlice<f32>],
3938 scratch: &mut MtpScratch,
3939 committed_scratch_len: usize,
3940 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
3941 mask: Option<(&CudaSlice<u32>, usize)>,
3942 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
3943 if tokens.is_empty() || tokens.len() != seeds.len() {
3944 return Err("multi-head MTP prefix tokens/seeds are malformed".into());
3945 }
3946 let index = mtp_chain_head_index(tokens.len() - 1, self.mtp_head_count());
3947 let head = self.mtp_head_at(index);
3948 scratch.set_plane_len(e, index, committed_scratch_len)?;
3949
3950 let mut last = None;
3951 for row in 0..tokens.len() {
3952 let is_last = row + 1 == tokens.len();
3953 last = Some(self.mtp_head_forward_dev_at(
3954 e,
3955 head,
3956 tokens[row],
3957 &seeds[row],
3958 scratch,
3959 index,
3960 committed_scratch_len + row + 1,
3961 embd_dev,
3962 if is_last { mask } else { None },
3963 )?);
3964 }
3965 Ok(last.expect("non-empty MTP prefix produced no row"))
3966 }
3967
3968 /// step35 MTP-block attention, T=1, on the scratch KV — the EAGER-ONLY twin of
3969 /// `mtp_full_attn_dc`. Three things force a separate arm rather than a geometry parameter on
3970 /// the dc path, and all three are properties of this arch's MTP block:
3971 ///
3972 /// 1. **The SWA window.** Block 45 is an SWA-type block (`sliding_window_pattern[45]=true`,
3973 /// window 512). Windowed decode in memra is a token-aligned VIEW OFFSET into the quantized
3974 /// cache (the gemma4 R6 / `step35_decode_attn` pattern: keys carry absolute rope and the
3975 /// mask is purely positional, so one query at `len-1` attending the last `win` rows IS the
3976 /// windowed result). `fa_decode_dc` takes the key count from a DEVICE counter and always
3977 /// starts at row 0 — it cannot express a nonzero offset, so a windowed dc arm would need a
3978 /// new kernel. That is deliberately not built here: see the CUDA-graph note below.
3979 /// 2. **Per-layer head count.** 96 q heads over 8 KV (GQA 12) at this block, vs the trunk's 64
3980 /// on its full-attn layers. The trunk cfg's `n_head` scalar is the MAX over layers, and the
3981 /// trunk ARTIFACT's per-layer arrays stop at index 44 — so the count must come from the
3982 /// resolved `Step35MtpGeom`, never from `cfg`.
3983 /// 3. **The separate head-wise gate.** `blk.45.attn_gate.weight [n_embd, 96]` produces one
3984 /// sigmoid scalar per head (broadcast over head_dim) — `attn_head_gate`, not the qwen35
3985 /// fused-into-wq `q_gate_split` form the dc arm handles.
3986 ///
3987 /// WHY EAGER-ONLY IS NOT A GAP TODAY: `mtp_head_forward_cap` refuses step35 heads
3988 /// explicitly (the SWA-window refusal below), so the graph draft never engages for step35
3989 /// models regardless of eligibility — the eager chain IS the served path. `mtp_head_forward_cap` refuses step35 explicitly rather
3990 /// than silently capturing a window-less (wrong past `win` draft rows) graph.
3991 ///
3992 /// Unlike the dc arm this advances BOTH the host `kv.len` and the device counter, so the
3993 /// caller must not mirror.
3994 fn mtp_step35_attn(
3995 &self,
3996 e: &Engine,
3997 fa: &FullAttnLayer,
3998 g: &crate::hybrid::Step35MtpGeom,
3999 h: &CudaSlice<f32>,
4000 pos_d: &CudaSlice<i32>,
4001 scratch: &mut MtpScratch,
4002 scratch_index: usize,
4003 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
4004 let (nh, nkv, hd) = (g.n_head, g.n_head_kv, self.cfg.head_dim_k as usize);
4005 let eps = self.cfg.rms_eps;
4006 let scale = 1.0 / (hd as f32).sqrt(); // step35.cpp:255 kq_scale
4007 let n_embd = self.cfg.n_embd as usize;
4008 let gw = fa
4009 .attn_gate
4010 .as_ref()
4011 .ok_or("step35 MTP block is missing attn_gate.weight (head-wise attention gate)")?;
4012
4013 let (q0, k0, v0, gt) = if e.uses_q8_1_fast(&fa.wq)
4014 && e.uses_q8_1_fast(&fa.wk)
4015 && e.uses_q8_1_fast(&fa.wv)
4016 && e.uses_q8_1_fast(gw)
4017 {
4018 let (hq, hdq) = e.quantize_q8_1(h, 1, n_embd)?;
4019 let (a, b, c) = match e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, &hq, &hdq)? {
4020 Some(t3) => t3,
4021 None => (
4022 e.matmul_pre(&fa.wq, &hq, &hdq, h, 1)?,
4023 e.matmul_pre(&fa.wk, &hq, &hdq, h, 1)?,
4024 e.matmul_pre(&fa.wv, &hq, &hdq, h, 1)?,
4025 ),
4026 };
4027 (a, b, c, e.matmul_pre(gw, &hq, &hdq, h, 1)?)
4028 } else {
4029 (
4030 e.matmul(&fa.wq, h, 1)?,
4031 e.matmul(&fa.wk, h, 1)?,
4032 e.matmul(&fa.wv, h, 1)?,
4033 e.matmul(gw, h, 1)?,
4034 )
4035 };
4036
4037 let mut q = e.uninit(nh * hd)?;
4038 e.rms_norm(&q0, fa.q_norm.float_data(), &mut q, hd, nh, eps)?;
4039 let mut k = e.uninit(nkv * hd)?;
4040 e.rms_norm(&k0, fa.k_norm.float_data(), &mut k, hd, nkv, eps)?;
4041 // `rope_freqs.weight` (llama3 factors) applies to the FULL-attn layers ONLY; SWA passes
4042 // null (llama-hparams / step35.cpp). Block 45 is SWA, so `ff` is None there — but read
4043 // the resolved flag, not the constant, so an all-full sibling stays correct.
4044 let ff = if g.swa {
4045 None
4046 } else {
4047 self.step35_aux.as_ref().and_then(|a| a.rope_freqs(e))
4048 };
4049 #[cfg(debug_assertions)]
4050 if let Some(ff) = ff {
4051 crate::debug_assert_tensor_stream_device(ff, &e.stream(), "mtp_step35_attn.rope_freqs");
4052 }
4053 e.rope_neox2(
4054 &mut q,
4055 &mut k,
4056 pos_d,
4057 hd,
4058 g.n_rot,
4059 nh,
4060 nkv,
4061 1,
4062 g.rope_base,
4063 1.0,
4064 ff,
4065 )?;
4066
4067 // Append at the HOST slot, then re-stamp the device counter: the eager chain has the
4068 // length on the host anyway, and the windowed view below needs it there to compute the
4069 // offset. The device counter is kept in lockstep so `mtp_kv_fill`'s `set_i32_one` and any
4070 // dc-family consumer of this scratch still agree.
4071 let (kv, scratch_cap) = scratch.plane_mut(scratch_index);
4072 assert!(
4073 kv.len < scratch_cap,
4074 "step35 MTP scratch overflow ({} >= {})",
4075 kv.len,
4076 scratch_cap
4077 );
4078 let next_len = kv.len + 1;
4079 let (off, t_kv) = if g.swa && next_len > g.window {
4080 (next_len - g.window, g.window)
4081 } else {
4082 (0, next_len)
4083 };
4084 let write_row = e.prepare_kv_append(kv, off & !31usize, 1)?;
4085 e.append_kv_quantized(
4086 &k,
4087 &v0,
4088 &mut kv.k,
4089 &mut kv.v,
4090 write_row,
4091 kv.kv_dim_k,
4092 kv.kv_dim_v,
4093 kv.k_tok_bytes,
4094 kv.v_tok_bytes,
4095 false,
4096 )?;
4097 kv.len = next_len;
4098 e.set_i32_one(&mut kv.len_d, kv.len as i32)?;
4099 // SWA view offset (see note 1). The draft chain is short (k+2 rows), but the scratch is
4100 // PERSISTENT across rounds — `mtp_kv_fill` leaves one row per committed token behind, so
4101 // `kv.len` tracks absolute position and crosses 512 in any real generation. The window is
4102 // therefore live, not theoretical.
4103 let physical = kv.physical_rows(off, off + t_kv)?;
4104 let k_view = e.view_u8_range(
4105 &kv.k,
4106 physical.start * kv.k_tok_bytes,
4107 physical.end * kv.k_tok_bytes,
4108 );
4109 let v_view = e.view_u8_range(
4110 &kv.v,
4111 physical.start * kv.v_tok_bytes,
4112 physical.end * kv.v_tok_bytes,
4113 );
4114 let mut attn = e.uninit(nh * hd)?;
4115 e.fa_decode_kvmod(
4116 &q,
4117 &k_view,
4118 &v_view,
4119 &mut attn,
4120 hd,
4121 nh,
4122 nkv,
4123 t_kv,
4124 scale,
4125 kv.k_tok_bytes,
4126 kv.v_tok_bytes,
4127 false,
4128 )?;
4129
4130 let mut ag = e.uninit(nh * hd)?;
4131 e.attn_head_gate(&attn, >, &mut ag, None, hd, nh, 1)?;
4132 Ok(e.matmul(&fa.wo, &ag, 1)?)
4133 }
4134
4135 /// MTP-block full attention, T=1, on the scratch KV (BOTH draft paths — eager and graph):
4136 /// the scratch write slot and the attention bound come from `scratch.kv.len_d` (device i32[1])
4137 /// so the launch args are FIXED across draft steps — ONE captured graph serves the whole
4138 /// chain, and replays keep seeing KV growth through the device counter (no recapture).
4139 /// Geometry contract: n_splits is sized from `scratch.cap` (the persistent capacity); splits
4140 /// whose key range lies beyond the device t_kv exit empty and the shared combine skips them
4141 /// (fa_decode_dc bit-correct-for-any-t_kv<=bucket_max contract). The eager path uses the SAME
4142 /// launcher with the SAME bucket_max -> identical dispatch -> bit-identical draft tokens (the
4143 /// graph-vs-eager parity gate). Host len is NOT advanced here (graph contract); callers mirror.
4144 fn mtp_full_attn_dc(
4145 &self,
4146 e: &Engine,
4147 fa: &FullAttnLayer,
4148 h: &CudaSlice<f32>,
4149 pos_d: &CudaSlice<i32>,
4150 scratch: &mut MtpScratch,
4151 scratch_index: usize,
4152 geom: Option<&crate::hybrid::DraftGeom>,
4153 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
4154 let cfg = &self.cfg;
4155 let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
4156 let geometry = cfg.full_attention_geometry_at(mtp_il);
4157 let n_head = geom.map(|g| g.n_head).unwrap_or(geometry.n_head as usize);
4158 let n_head_kv = geom
4159 .map(|g| g.n_head_kv)
4160 .unwrap_or(geometry.n_head_kv as usize);
4161 let head_dim = geometry.head_dim_k as usize;
4162 let eps = cfg.rms_eps;
4163 let scale = geometry.attention_scale();
4164 let n_embd = geom.map(|g| g.d_inner).unwrap_or(cfg.n_embd as usize);
4165 let bucket_max = scratch.plane(scratch_index).1;
4166
4167 let (qf, mut k, v) =
4168 if e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk) && e.uses_q8_1_fast(&fa.wv) {
4169 let (hq, hd) = e.quantize_q8_1(h, 1, n_embd)?;
4170 (
4171 e.matmul_pre(&fa.wq, &hq, &hd, h, 1)?,
4172 e.matmul_pre(&fa.wk, &hq, &hd, h, 1)?,
4173 e.matmul_pre(&fa.wv, &hq, &hd, h, 1)?,
4174 )
4175 } else {
4176 (
4177 e.matmul(&fa.wq, h, 1)?,
4178 e.matmul(&fa.wk, h, 1)?,
4179 e.matmul(&fa.wv, h, 1)?,
4180 )
4181 };
4182 // M3/Hy3 have no attention output gate — wq out is exactly q; skip the split.
4183 let gated = geometry.attention_gate == memra_gguf::config::AttentionGateKind::FusedQ;
4184 let (mut q, gate) = if gated {
4185 let mut q = e.zeros(n_head * head_dim)?;
4186 let mut gate = e.zeros(n_head * head_dim)?;
4187 e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, 1)?;
4188 (q, Some(gate))
4189 } else {
4190 (qf, None)
4191 };
4192
4193 let mut qn = e.zeros(n_head * head_dim)?;
4194 e.rms_norm(&q, fa.q_norm.float_data(), &mut qn, head_dim, n_head, eps)?;
4195 q = qn;
4196 let mut kn = e.zeros(n_head_kv * head_dim)?;
4197 e.rms_norm(
4198 &k,
4199 fa.k_norm.float_data(),
4200 &mut kn,
4201 head_dim,
4202 n_head_kv,
4203 eps,
4204 )?;
4205 k = kn;
4206 let rope_dims = geometry.n_rot as usize;
4207 e.rope_neox(
4208 &mut q,
4209 pos_d,
4210 head_dim,
4211 rope_dims,
4212 n_head,
4213 1,
4214 geometry.rope_base,
4215 1.0,
4216 )?;
4217 e.rope_neox(
4218 &mut k,
4219 pos_d,
4220 head_dim,
4221 rope_dims,
4222 n_head_kv,
4223 1,
4224 geometry.rope_base,
4225 1.0,
4226 )?;
4227
4228 let kv = scratch.plane_mut(scratch_index).0;
4229 // append at the DEVICE slot (kv.len_d == old len), then advance the counter in-graph.
4230 e.append_kv_quantized_dc(
4231 &k,
4232 &v,
4233 &mut kv.k,
4234 &mut kv.v,
4235 &kv.len_d,
4236 kv.kv_dim_k,
4237 kv.kv_dim_v,
4238 kv.k_tok_bytes,
4239 kv.v_tok_bytes,
4240 false,
4241 )?;
4242 e.inc_seqlen(&mut kv.len_d)?;
4243 // full-buffer views (any in-round t_kv stays in range on replay); the kernel bounds the
4244 // key range from the device counter.
4245 let k_view = e.view_u8(&kv.k, kv.k.len());
4246 let v_view = e.view_u8(&kv.v, kv.v.len());
4247 let (ktb, vtb) = (kv.k_tok_bytes, kv.v_tok_bytes);
4248 let mut attn = e.zeros(n_head * head_dim)?;
4249 e.fa_decode_dc(
4250 &q, &k_view, &v_view, &mut attn, head_dim, n_head, n_head_kv, &kv.len_d, bucket_max,
4251 scale, ktb, vtb, false,
4252 )?;
4253
4254 let attn_g = match &gate {
4255 Some(gate) => {
4256 let mut gsig = e.zeros(n_head * head_dim)?;
4257 e.sigmoid(gate, &mut gsig, n_head * head_dim)?;
4258 let mut ag = e.zeros(n_head * head_dim)?;
4259 e.mul(&attn, &gsig, &mut ag, n_head * head_dim)?;
4260 ag
4261 }
4262 None => attn,
4263 };
4264 Ok(e.matmul(&fa.wo, &attn_g, 1)?)
4265 }
4266
4267 /// PERSISTENT-DRAFT-KV fill (the reference engine's "mtp_update" analogue): compute the MTP
4268 /// block's K/V for `tokens` (committed tokens at positions pos0..pos0+T) from their EXACT
4269 /// trunk hiddens `h` ([T, n_embd] token-major, pre-output_norm) and append at slots pos0.. of
4270 /// the scratch KV. K/V-ONLY — ops A/1-5 plus the K-side of op 6 (wk/wv + k_norm + rope +
4271 /// quantized append); no wq/attention/FFN/lm_head, so per-token cost ~= eh_proj + wk/wv (a
4272 /// small fraction of one trunk layer), T-batched. Rope follows the chain convention
4273 /// rope(token@p) = p+1. Runs at round boundaries OUTSIDE the captured graph in BOTH draft
4274 /// modes -> draft parity by construction. Caller must have scratch.kv.len == pos0.
4275 #[allow(clippy::too_many_arguments)]
4276 fn mtp_kv_fill_at(
4277 &self,
4278 e: &Engine,
4279 mtp: &MtpHead,
4280 tokens: &[u32],
4281 h: &CudaSlice<f32>,
4282 pos0: usize,
4283 scratch: &mut MtpScratch,
4284 scratch_index: usize,
4285 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4286 ) -> Result<(), Box<dyn std::error::Error>> {
4287 let cfg = &self.cfg;
4288 let n_embd = cfg.n_embd as usize;
4289 let eps = cfg.rms_eps;
4290 let t = tokens.len();
4291 let (scratch_kv, scratch_cap) = scratch.plane(scratch_index);
4292 assert_eq!(scratch_kv.len, pos0, "mtp_kv_fill: append slot mismatch");
4293 assert!(pos0 + t <= scratch_cap, "mtp_kv_fill: scratch overflow");
4294 let Mixer::Full(fa) = &mtp.mixer else {
4295 panic!("MTP block is full-attn in qwen35; linear MTP not supported")
4296 };
4297 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i + 1) as i32).collect();
4298 let pos_d = e.htod_i32(&pos_vec)?;
4299
4300 // ops A/1/2: embed + the two input norms, T-wide.
4301 let e_emb = match embd_dev {
4302 Some((g, qt, rb)) => e.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
4303 None => e.htod(&self.embd.gather(n_embd, tokens))?,
4304 };
4305 let mut e_norm = e.zeros(t * n_embd)?;
4306 e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, t, eps)?;
4307 let mut h_norm = e.zeros(t * n_embd)?;
4308 e.rms_norm(h, mtp.hnorm.float_data(), &mut h_norm, n_embd, t, eps)?;
4309
4310 // op 3: per-row [e_norm ; h_norm] concat, token-major [T, 2*n_embd].
4311 let mut concat = e.zeros(t * 2 * n_embd)?;
4312 for i in 0..t {
4313 e.copy_view_into(
4314 &mut concat,
4315 i * 2 * n_embd,
4316 &e_norm.slice(i * n_embd..(i + 1) * n_embd),
4317 n_embd,
4318 )?;
4319 e.copy_view_into(
4320 &mut concat,
4321 i * 2 * n_embd + n_embd,
4322 &h_norm.slice(i * n_embd..(i + 1) * n_embd),
4323 n_embd,
4324 )?;
4325 }
4326
4327 // ops 4/5: eh_proj + attn_norm, T-wide (at the student inner width when geom is set).
4328 let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
4329 let inp_sa = e.matmul(&mtp.eh_proj, &concat, t)?;
4330 let mut a_norm = e.zeros(t * di)?;
4331 e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, t, eps)?;
4332
4333 // op 6 (K/V half): wk/wv + k_norm + rope + per-row quantized append. No wq/attention —
4334 // the fill only has to leave correct K/V rows behind for later chains to attend over.
4335 let n_head_kv = mtp
4336 .geom
4337 .as_ref()
4338 .map(|g| g.n_head_kv)
4339 .or(mtp.step35.as_ref().map(|s| s.n_head_kv))
4340 .unwrap_or_else(|| {
4341 let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
4342 cfg.full_attention_geometry_at(mtp_il).n_head_kv as usize
4343 });
4344 let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
4345 let geometry = cfg.full_attention_geometry_at(mtp_il);
4346 let head_dim = geometry.head_dim_k as usize;
4347 let mut k = e.matmul(&fa.wk, &a_norm, t)?;
4348 let v = e.matmul(&fa.wv, &a_norm, t)?;
4349 let mut kn = e.zeros(t * n_head_kv * head_dim)?;
4350 e.rms_norm(
4351 &k,
4352 fa.k_norm.float_data(),
4353 &mut kn,
4354 head_dim,
4355 n_head_kv * t,
4356 eps,
4357 )?;
4358 k = kn;
4359 // step35: rotary width AND base are per-layer, and the MTP block's values come from the
4360 // resolved `Step35MtpGeom` — NOT from `cfg.rope_dim_count`/`cfg.rope_freq_base`, which
4361 // carry the arch defaults (128 / 5e6, i.e. the FULL-attn layers' base). Getting this wrong
4362 // writes K rows the attention arm then re-derives at a different theta: correct-looking
4363 // output with dead acceptance, invisible to the exactness gates.
4364 let (rope_dims, rope_base, ff) = match mtp.step35.as_ref() {
4365 Some(s) => (
4366 s.n_rot,
4367 s.rope_base,
4368 if s.swa {
4369 None
4370 } else {
4371 self.step35_aux.as_ref().and_then(|a| a.rope_freqs(e))
4372 },
4373 ),
4374 None => (geometry.n_rot as usize, geometry.rope_base, None),
4375 };
4376 #[cfg(debug_assertions)]
4377 if let Some(ff) = ff {
4378 crate::debug_assert_tensor_stream_device(ff, &e.stream(), "mtp_kv_fill.rope_freqs");
4379 }
4380 match ff {
4381 Some(f) => e.rope_neox_ff(
4382 &mut k, &pos_d, head_dim, rope_dims, n_head_kv, t, rope_base, 1.0, f,
4383 )?,
4384 None => e.rope_neox(
4385 &mut k, &pos_d, head_dim, rope_dims, n_head_kv, t, rope_base, 1.0,
4386 )?,
4387 }
4388
4389 let kv = scratch.plane_mut(scratch_index).0;
4390 // Match the trunk prime contract: a chunk may need the aligned window immediately before
4391 // its first row, so preserve that prefix when the physical tail rebases at wrap.
4392 let retain_from = kv
4393 .ring
4394 .as_ref()
4395 .map(|ring| pos0.saturating_sub(ring.window() - 1) & !31usize)
4396 .unwrap_or(0);
4397 let write_row = e.prepare_kv_append(kv, retain_from, t)?;
4398 for i in 0..t {
4399 let k_row = k.slice(i * kv.kv_dim_k..(i + 1) * kv.kv_dim_k);
4400 let v_row = v.slice(i * kv.kv_dim_v..(i + 1) * kv.kv_dim_v);
4401 e.append_kv_quantized_view(
4402 &k_row,
4403 &v_row,
4404 &mut kv.k,
4405 &mut kv.v,
4406 write_row + i,
4407 kv.kv_dim_k,
4408 kv.kv_dim_v,
4409 kv.k_tok_bytes,
4410 kv.v_tok_bytes,
4411 false,
4412 )?;
4413 }
4414 kv.len = pos0 + t;
4415 e.set_i32_one(&mut kv.len_d, kv.len as i32)?;
4416 Ok(())
4417 }
4418
4419 #[allow(clippy::too_many_arguments)]
4420 fn mtp_kv_fill_all(
4421 &self,
4422 e: &Engine,
4423 tokens: &[u32],
4424 h: &CudaSlice<f32>,
4425 pos0: usize,
4426 scratch: &mut MtpScratch,
4427 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4428 ) -> Result<(), Box<dyn std::error::Error>> {
4429 debug_assert_eq!(self.mtp_head_count(), scratch.plane_count());
4430 for index in 0..self.mtp_head_count() {
4431 self.mtp_kv_fill_at(
4432 e,
4433 self.mtp_head_at(index),
4434 tokens,
4435 h,
4436 pos0,
4437 scratch,
4438 index,
4439 embd_dev,
4440 )?;
4441 }
4442 Ok(())
4443 }
4444
4445 /// CAPTURE body for the GRAPH DRAFT (stage 2 of graph-grade spec): ONE MTP head forward with
4446 /// every varying input device-resident —
4447 /// - token id from the persistent `tok_d` (the previous replay's in-graph argmax wrote it,
4448 /// so the chain feeds itself; the host reads the same 4 bytes for the draft list),
4449 /// - h_seed from the persistent `h_seed_d` (h_nextn is copied BACK into it at the end),
4450 /// - rope pos from the persistent `pos_d` counter (inc'd in-graph),
4451 /// - scratch KV slot/bound from `scratch.kv.len_d` (see mtp_full_attn_dc).
4452 /// The p-min confidence lands in the persistent `p_d` iff `with_prob` (env is fixed per run).
4453 /// Same kernels, same dispatch as the eager mtp_head_forward_dev chain -> same draft tokens
4454 /// (exactness never depends on drafts — the verify arbitrates — but acceptance parity does).
4455 /// `with_head=false` captures the HEAD-LESS twin for the pseudo-seed replay (2026-07-03):
4456 /// the pseudo pass only needs h_nextn (op 10) + the scratch append — the lm_head read
4457 /// (~1.06ms q6_K on the 9B), argmax and prob are dead weight there. h_nextn's inputs are
4458 /// untouched, so the seed value is identical; round-start resets overwrite tok_d/p_d anyway.
4459 /// `sampled_cap` = Some((ctr_d, perturb_d, q_out_d, seed, temp)) captures the SAMPLED twin
4460 /// (step 3 of the sampled-spec arc): head logits are retained in the persistent `q_out_d`
4461 /// (host D2Ds them to the round's q slot after each replay), the DEVICE event counter is
4462 /// bumped in-graph, and the argmax reads GUMBEL-PERTURBED logits — one categorical draw per
4463 /// replay, bit-identical to the eager arm's gumbel_perturb at the same (seed, sctr, temp).
4464 /// seed/temp are capture-time constants (fixed per generate call, like p_min).
4465 #[allow(clippy::too_many_arguments)]
4466 fn mtp_head_forward_cap(
4467 &self,
4468 e: &Engine,
4469 mtp: &MtpHead,
4470 tok_d: &mut CudaSlice<u32>,
4471 pos_d: &mut CudaSlice<i32>,
4472 h_seed_d: &mut CudaSlice<f32>,
4473 p_d: &mut CudaSlice<f32>,
4474 scratch: &mut MtpScratch,
4475 with_prob: bool,
4476 with_head: bool,
4477 embd_gpu: &CudaSlice<u8>,
4478 embd_qt: i32,
4479 embd_rb: usize,
4480 d_vocab: usize,
4481 sampled_cap: Option<(
4482 &mut CudaSlice<u32>,
4483 &mut CudaSlice<f32>,
4484 &mut CudaSlice<f32>,
4485 u64,
4486 f32,
4487 )>,
4488 stream_pack: Option<(&mut CudaSlice<u32>, usize, Option<&CudaSlice<u32>>)>,
4489 // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): (packed draft-vocab allowed-set buffer,
4490 // word count). Captured as ONE mask_logits_f32 node between the head matmul and the
4491 // in-graph argmax; the buffer address is baked, its CONTENTS are re-uploaded by the
4492 // host before every replay (the decode.rs graph-mask pattern). All-ones contents = a
4493 // no-op ban, so a position the grammar cannot constrain costs one pass over the row.
4494 mask_cap: Option<(&CudaSlice<u32>, usize)>,
4495 ) -> Result<(), Box<dyn std::error::Error>> {
4496 let cfg = &self.cfg;
4497 let n_embd = cfg.n_embd as usize;
4498 // step35 REFUSAL (deliberate, named): the graph body's attention is `mtp_full_attn_dc`,
4499 // whose device-counter key bound always starts at row 0 — it cannot express this block's
4500 // SWA view offset, so a captured chain would silently attend OUTSIDE the window once the
4501 // persistent scratch passes 512 rows. Nothing is lost today: `mtp_head_forward_cap`
4502 // refuses step35 heads explicitly (SWA refusal), so the eager chain
4503 // (`mtp_head_forward_dev` -> `mtp_step35_attn`) is the served path. Returning Err (not a
4504 // panic) is what the two capture sites and the round-stream capture already handle by
4505 // degrading to eager / stream-off.
4506 if mtp.step35.is_some() {
4507 return Err(
4508 "step35 has no captured draft chain (fa_decode_dc cannot express the MTP \
4509 block's SWA view offset; same root cause as the dc decode refusal) — the \
4510 eager draft chain serves this arch"
4511 .into(),
4512 );
4513 }
4514 // student inner width (see mtp_head_forward_dev) — interface dims stay n_embd.
4515 let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
4516 let eps = cfg.rms_eps;
4517 let e_emb = e.embed_gather_device(embd_gpu, tok_d, n_embd, embd_qt, embd_rb)?;
4518 let mut e_norm = e.zeros(n_embd)?;
4519 e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, 1, eps)?;
4520 let mut h_norm = e.zeros(n_embd)?;
4521 e.rms_norm(
4522 &*h_seed_d,
4523 mtp.hnorm.float_data(),
4524 &mut h_norm,
4525 n_embd,
4526 1,
4527 eps,
4528 )?;
4529 let mut concat = e.zeros(2 * n_embd)?;
4530 e.copy_into(&mut concat, 0, &e_norm, n_embd)?;
4531 e.copy_into(&mut concat, n_embd, &h_norm, n_embd)?;
4532 let inp_sa = e.matmul(&mtp.eh_proj, &concat, 1)?;
4533 let mut a_norm = e.zeros(di)?;
4534 e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, 1, eps)?;
4535 let attn_out = match &mtp.mixer {
4536 Mixer::Full(fa) => {
4537 self.mtp_full_attn_dc(e, fa, &a_norm, pos_d, scratch, 0, mtp.geom.as_ref())?
4538 }
4539 Mixer::Linear(_) => {
4540 panic!("MTP block is full-attn in qwen35; linear MTP not supported")
4541 }
4542 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
4543 };
4544 let mut x1 = e.zeros(di)?;
4545 e.add(&inp_sa, &attn_out, &mut x1, di)?;
4546 let mut z = e.zeros(di)?;
4547 e.rms_norm(&x1, mtp.post_attn_norm.float_data(), &mut z, di, 1, eps)?;
4548 let ffn_out = match &mtp.ffn {
4549 crate::hybrid::Ffn::Dense {
4550 ffn_gate,
4551 ffn_up,
4552 ffn_down,
4553 } => {
4554 let n_ff = ffn_gate.out_features();
4555 let (gate, up) = if e.uses_q8_1_fast(ffn_gate) && e.uses_q8_1_fast(ffn_up) {
4556 let (zq, zd) = e.quantize_q8_1(&z, 1, di)?;
4557 (
4558 e.matmul_pre(ffn_gate, &zq, &zd, &z, 1)?,
4559 e.matmul_pre(ffn_up, &zq, &zd, &z, 1)?,
4560 )
4561 } else {
4562 (e.matmul(ffn_gate, &z, 1)?, e.matmul(ffn_up, &z, 1)?)
4563 };
4564 let mut act = e.zeros(n_ff)?;
4565 Self::ffn_act(e, &self.cfg, &gate, &up, &mut act, n_ff)?;
4566 e.matmul(ffn_down, &act, 1)?
4567 }
4568 // ROUND-STREAM: the 35B NextN block carries a MoE FFN. With RESIDENT experts the
4569 // dev path is pure device launches (device top-k + rows kernels, ZERO-DtoH by
4570 // design) — capture-legal. Non-resident (SLRU-lock) stays rejected: the capture
4571 // error arm degrades the caller to eager/stream-off.
4572 crate::hybrid::Ffn::Moe(m) if m.dev_exps.is_some() => {
4573 self.moe_ffn_il(e, m, &z, 1, u16::MAX)?
4574 }
4575 crate::hybrid::Ffn::Moe(_) => {
4576 return Err("graph draft requires a Dense (or resident-MoE) MTP FFN".into());
4577 }
4578 };
4579 let mut h_inner = e.zeros(di)?;
4580 e.add(&x1, &ffn_out, &mut h_inner, di)?;
4581 // student: up-project back to n_embd (carrier + head input; see mtp_head_forward_dev).
4582 let h_nextn = match mtp.geom.as_ref() {
4583 Some(g) => e.matmul(&g.out_up, &h_inner, 1)?,
4584 None => h_inner,
4585 };
4586 // MEMRA_SPEC_HPOST needs final_h even head-less (it IS the next seed under that convention).
4587 let final_h = if with_head || spec_hpost() {
4588 let final_norm = mtp.shared_head_norm.as_ref().unwrap_or(&self.output_norm);
4589 let mut fh = e.zeros(n_embd)?;
4590 e.rms_norm(&h_nextn, final_norm.float_data(), &mut fh, n_embd, 1, eps)?;
4591 Some(fh)
4592 } else {
4593 None
4594 };
4595 if with_head {
4596 let head = mtp.shared_head_head.as_ref().unwrap_or(&self.output);
4597 let mut logits = e.matmul(head, final_h.as_ref().unwrap(), 1)?;
4598 // DRAFT-SIDE GRAMMAR MASK: ban the grammar-illegal draft ids IN the captured chain,
4599 // before the argmax — proposals become legal by construction. Contents-only
4600 // per-replay upload keeps the capture valid.
4601 if let Some((mask_d, mw)) = mask_cap {
4602 e.mask_logits_col(&mut logits, mask_d, 0, d_vocab, mw)?;
4603 }
4604 if let Some((ctr_d, perturb_d, q_out_d, seed, temp)) = sampled_cap {
4605 // SAMPLED chain: retain q (raw head logits -> persistent q_out_d; the matmul's
4606 // own buffer is pool-recycled after the capture body returns, so it can't be the
4607 // retention target), bump the device event counter, gumbel-perturb reading it,
4608 // and argmax the PERTURBED logits into tok_d — the in-graph categorical draw.
4609 e.copy_into(q_out_d, 0, &logits, d_vocab)?;
4610 e.sctr_inc(ctr_d)?;
4611 e.gumbel_perturb_ctr(&logits, perturb_d, d_vocab, seed, ctr_d, temp)?;
4612 e.argmax_token_device_into(perturb_d, tok_d, d_vocab)?;
4613 // p-min prob = the head's RAW softmax confidence in the SAMPLED pick — same
4614 // semantics as the eager sampled arm's prob_of_token_device(dl_d, tok_d).
4615 if with_prob {
4616 e.prob_of_token_device_into(&logits, tok_d, p_d, d_vocab)?;
4617 }
4618 } else {
4619 // draft token -> persistent tok_d (next replay's embed reads it; host reads the 4 bytes).
4620 e.argmax_token_device_into(&logits, tok_d, d_vocab)?;
4621 // p-min under a draft mask reads the MASKED row: confidence relative to the
4622 // grammar-LEGAL alternatives (illegal ids leave the softmax denominator), which
4623 // is the right semantics for "does the drafter know what comes next here" and
4624 // the same row the pick came from. Draft-quality only — verify arbitrates.
4625 if with_prob {
4626 e.prob_of_token_device_into(&logits, tok_d, p_d, d_vocab)?;
4627 }
4628 }
4629 }
4630 // ROUND-STREAM K-chain: pack (tok, p) into slot j, then remap tok through d2t so the
4631 // NEXT chained body's embed reads the TARGET id — zero host involvement per step.
4632 if let Some((out, slot, d2t)) = stream_pack {
4633 e.pack_tok_p(tok_d, p_d, out, slot)?;
4634 if let Some(map) = d2t {
4635 e.tok_map_u32(tok_d, map)?;
4636 }
4637 }
4638 // Next draft step's h_seed: pre-norm h_nextn (default) or post-norm final_h (HPOST).
4639 if spec_hpost() {
4640 e.copy_into(h_seed_d, 0, final_h.as_ref().unwrap(), n_embd)?;
4641 } else {
4642 e.copy_into(h_seed_d, 0, &h_nextn, n_embd)?;
4643 }
4644 // advance the draft rope position in-graph.
4645 e.inc_seqlen(pos_d)?;
4646 Ok(())
4647 }
4648
4649 /// Batched target verify forward over `tokens` at positions `pos0..pos0+T` (§D.3, T=K+1).
4650 /// Returns ALL T logit columns (host f32, [T*n_vocab]); appends T cols to every full-attn KV
4651 /// and advances every linear-attn recur state by T steps (the recur steps are SEQUENTIAL T=1).
4652 /// Advances `cache.pos` by T.
4653 pub fn decode_step_t(
4654 &self,
4655 e: &Engine,
4656 tokens: &[u32],
4657 pos0: usize,
4658 cache: &mut Cache,
4659 ) -> Result<Vec<f32>, Box<dyn std::error::Error>> {
4660 if self.is_gemma4_e4b() {
4661 return Ok(self.gemma4_e4b_decode_step_t_h(e, tokens, pos0, cache)?.0);
4662 }
4663 if self.gemma_batch_program() {
4664 return self.gemma4_decode_step_t(e, tokens, pos0, cache);
4665 }
4666 Ok(self.decode_step_t_h(e, tokens, pos0, cache)?.0)
4667 }
4668
4669 /// Like `decode_step_t` but ALSO returns the LAST column's pre-output_norm hidden (h_seed for
4670 /// the next draft round). This lets partial-accept replay run as ONE batched T=(n_acc+1) forward
4671 /// (single weight read) instead of n_acc+1 separate T=1 decode_steps (n_acc+1 weight reads).
4672 /// At batch=1 decode is bandwidth-bound, so batching the replay is THE MTP profitability lever.
4673 pub fn decode_step_t_h(
4674 &self,
4675 e: &Engine,
4676 tokens: &[u32],
4677 pos0: usize,
4678 cache: &mut Cache,
4679 ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4680 self.decode_step_t_h_emb(e, tokens, pos0, cache, None)
4681 }
4682
4683 /// Like `decode_step_t_h` with an optional RESIDENT embed table (spec hot loop): device
4684 /// gather instead of host dequant + [T, n_embd] f32 htod. Bit-identical rows.
4685 pub fn decode_step_t_h_emb(
4686 &self,
4687 e: &Engine,
4688 tokens: &[u32],
4689 pos0: usize,
4690 cache: &mut Cache,
4691 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4692 ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4693 let (logits_d, h_seed) = self.decode_step_t_h_emb_dev(e, tokens, pos0, cache, embd_dev)?;
4694 Ok((e.dtoh(&logits_d)?, h_seed))
4695 }
4696
4697 /// DEVICE-LOGITS verify forward (spec device-argmax lever): identical kernel chain to
4698 /// `decode_step_t_h_emb` but returns the [T, n_vocab] logits ON DEVICE — the accept walk
4699 /// argmaxes each column on-device and reads back ONE [T] u32 instead of dtoh'ing the full
4700 /// T x n_vocab f32 block (~1-4 MB + T host argmaxes, every round). Kernel dispatch is
4701 /// UNCHANGED (same decode-exact kernels); only the post-logits transfer moves.
4702 pub fn decode_step_t_h_emb_dev(
4703 &self,
4704 e: &Engine,
4705 tokens: &[u32],
4706 pos0: usize,
4707 cache: &mut Cache,
4708 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4709 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4710 let n_embd = self.cfg.n_embd as usize;
4711 let t = tokens.len();
4712 let (logits, x) = self.decode_step_t_core(e, tokens, pos0, cache, embd_dev, None)?;
4713 // h_seed for the next round = LAST column's pre-output_norm hidden ([n_embd]).
4714 let mut hs = vbuf(e, n_embd)?; // fully written by copy_view_into below
4715 e.copy_view_into(&mut hs, 0, &x.slice((t - 1) * n_embd..t * n_embd), n_embd)?;
4716 Ok((logits, hs))
4717 }
4718
4719 /// CORE verify forward: the `decode_step_t_h_emb_dev` kernel chain, returning the FULL
4720 /// pre-output_norm hidden stack x ([T, n_embd], any column extractable) and optionally
4721 /// filling a `VerifyCkpt` (retained per-layer state-rebuild inputs) for the REPLAY-FREE
4722 /// partial accept. `ckpt: None` => byte-for-byte the old behavior (the ckpt writes are pure
4723 /// retains/copies — they never change what any kernel computes).
4724 fn decode_step_t_core(
4725 &self,
4726 e: &Engine,
4727 tokens: &[u32],
4728 pos0: usize,
4729 cache: &mut Cache,
4730 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4731 mut ckpt: Option<&mut VerifyCkpt>,
4732 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4733 self.decode_step_t_core_stream(
4734 e,
4735 tokens,
4736 pos0,
4737 cache,
4738 embd_dev,
4739 ckpt.take(),
4740 None,
4741 None,
4742 None,
4743 None,
4744 )
4745 }
4746
4747 /// [`Self::decode_step_t_core`] with the MTP route's verify-graph pool armed
4748 /// (`MEMRA_SPEC_VERIFY_GRAPH`). `graphs: None` reproduces `decode_step_t_core`
4749 /// argument-for-argument, so the eager walk stays the byte-identical fallback.
4750 fn decode_step_t_core_vg(
4751 &self,
4752 e: &Engine,
4753 tokens: &[u32],
4754 pos0: usize,
4755 cache: &mut Cache,
4756 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4757 mut ckpt: Option<&mut VerifyCkpt>,
4758 graphs: Option<&mut DsparkVerifyGraphs>,
4759 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4760 self.decode_step_t_core_stream(
4761 e,
4762 tokens,
4763 pos0,
4764 cache,
4765 embd_dev,
4766 ckpt.take(),
4767 None,
4768 None,
4769 None,
4770 graphs,
4771 )
4772 }
4773
4774 /// Increment-0 two-session PP seam: release the peer after this lane's stage-0 boundary TX.
4775 /// The two independent sessions keep their own cache/checkpoint state; only issue order moves.
4776 fn decode_step_t_core_pipelined(
4777 &self,
4778 e: &Engine,
4779 tokens: &[u32],
4780 pos0: usize,
4781 cache: &mut Cache,
4782 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4783 mut ckpt: Option<&mut VerifyCkpt>,
4784 pipe: &SpecPipeLane,
4785 round: usize,
4786 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4787 let fence = crate::pp::pp_cuts(self.layers.len())
4788 .ok_or("two-session speculative pipeline requires a PP stage cut")?;
4789 if crate::pp::pp2_streams_off() || !crate::pp::spec_pp_on() {
4790 return Err("two-session speculative pipeline requires the PP verify split".into());
4791 }
4792 let interval_fence = pipe.stage0_begin(round)?;
4793 let ticket = self.verify_stage0_issue(
4794 e,
4795 tokens,
4796 pos0,
4797 cache,
4798 embd_dev,
4799 ckpt.as_deref_mut(),
4800 None,
4801 &fence,
4802 Some(interval_fence),
4803 pipe.trace(round),
4804 )?;
4805 pipe.stage0_end(round);
4806 pipe.stage1_begin(round)?;
4807 let result = self.verify_stage1_finish(e, ticket, cache, ckpt, None, &fence, true)?;
4808 pipe.verify_end(round);
4809 Ok(result)
4810 }
4811
4812 /// ROUND-STREAM stage (c) 4: `stream` = (device verify tokens [t], device pos counter) —
4813 /// when Some, rope positions come from pos_iota over the counter, the embed gathers the
4814 /// device tokens, and full_attn_verify routes appends/FA through the _dc twins reading the
4815 /// SAME counter (every layer's kvl.len == cache.pos, one counter drives all three). The
4816 /// host `tokens`/`pos0` args still size buffers (t is FIXED K+1 in stream mode).
4817 /// `vtok_dev` (engine-bundle slice 2): device verify tokens for the EMBED only —
4818 /// unlike `stream` mode it changes nothing else (host pos iota, host-len KV appends).
4819 /// `tokens` then only sizes buffers (the dummy-slice pattern the round-stream arm uses).
4820 #[allow(clippy::too_many_arguments)]
4821 fn decode_step_t_core_stream(
4822 &self,
4823 e: &Engine,
4824 tokens: &[u32],
4825 pos0: usize,
4826 cache: &mut Cache,
4827 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4828 mut ckpt: Option<&mut VerifyCkpt>,
4829 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
4830 pp_pipe: Option<bool>,
4831 vtok_dev: Option<&CudaSlice<u32>>,
4832 graphs: Option<&mut DsparkVerifyGraphs>,
4833 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4834 // PP DOOR (lane/pp2-spec 2026-08-06): the verify trunk now takes its OWN stage split,
4835 // exactly as the eager and batched steps do. This is the single funnel every verify
4836 // forward reaches (decode_step_t / _h / _h_emb / _h_emb_dev / _core all land here), so
4837 // wiring it here wires the whole spec surface — the draft/accept/commit machinery above
4838 // is untouched.
4839 //
4840 // History: pp2-hardening (2026-08-06) made this funnel FAIL CLOSED, because its trunk
4841 // walk was unsplit on one stream and a sharded cross-device placement peer-read every
4842 // remote layer's weights on every spec round (measured 13.9-28x on the batched twin).
4843 // The refusal below survives to cover the residue — MEMRA_SPEC_PP=0, MEMRA_PP_STREAMS=0,
4844 // or a placement whose PpNRt fails to build — so a config that would still walk the
4845 // whole trunk on one stream refuses instead of regressing 28x.
4846 if let Some(fence) = crate::pp::pp_cuts(self.layers.len()) {
4847 if !crate::pp::pp2_streams_off() && crate::pp::spec_pp_on() {
4848 if vtok_dev.is_some() {
4849 return Err(
4850 "device-token dspark verify (slice-2 deferred readback) has no PP \
4851 stage-split arm; set MEMRA_DSPARK_DEFER_READBACK=0 or run the dspark \
4852 route on one device"
4853 .into(),
4854 );
4855 }
4856 return self.decode_step_t_core_ppn(
4857 e,
4858 tokens,
4859 pos0,
4860 cache,
4861 embd_dev,
4862 ckpt.take(),
4863 stream,
4864 &fence,
4865 pp_pipe,
4866 );
4867 }
4868 }
4869 crate::pp::refuse_unsplit_if_remote(
4870 "decode_step_t (spec verify)",
4871 "drop MEMRA_SPEC_PP=0 / MEMRA_PP_STREAMS=0 so the verify trunk takes its OWN stage \
4872 split (decode_step_t_core_ppn); or run spec on one device",
4873 )?;
4874 let cfg = &self.cfg;
4875 let n_embd = cfg.n_embd as usize;
4876 let eps = cfg.rms_eps;
4877 let t = tokens.len();
4878 let pos_d = match stream {
4879 Some((_, ctr)) => {
4880 let mut p = e.alloc_uninit::<i32>(t)?;
4881 e.pos_iota(ctr, &mut p, t)?;
4882 p
4883 }
4884 None => {
4885 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
4886 e.htod_i32(&pos_vec)?
4887 }
4888 };
4889
4890 // embed T tokens -> [T, n_embd] token-major (device gather on the spec hot loop)
4891 let x = match (stream, embd_dev) {
4892 (Some((vtok, _)), Some((g, qt, rb))) => {
4893 e.embed_gather_device_td(g, vtok, t, n_embd, qt, rb)?
4894 }
4895 (None, Some((g, qt, rb))) => match vtok_dev {
4896 // slice 2: device verify tokens, same embed_gather_u32_t kernel —
4897 // bit-identical rows to the host-token arm (same per-dtype deq).
4898 Some(vt_d) => e.embed_gather_device_td(g, vt_d, t, n_embd, qt, rb)?,
4899 None => e.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
4900 },
4901 _ => {
4902 assert!(
4903 vtok_dev.is_none(),
4904 "device-token verify requires the resident embed table (embd_dev)"
4905 );
4906 e.htod(&self.embd.gather(n_embd, tokens))?
4907 }
4908 };
4909
4910 // TRUNK WALK: layers [0, n_layers) through the SAME range-scoped subgraph the PP-N
4911 // stage split calls per stage (`verify_layers`) — one code path, so the split cannot
4912 // drift from the unsplit dispatch mirroring. lane/pp2-spec 2026-08-06.
4913 let x = self.verify_layers(
4914 e,
4915 x,
4916 0,
4917 self.layers.len(),
4918 &pos_d,
4919 pos0,
4920 t,
4921 cache,
4922 ckpt.take(),
4923 stream,
4924 graphs,
4925 )?;
4926
4927 let mut hn = vbuf(e, t * n_embd)?;
4928 // Stage-A door: with the serving-class row-outer verify walk, the TAIL must be the
4929 // t=1 decode program per row too (rms_norm t=1 + the single-row bf16 head — the
4930 // split head's concat is receipted bit-identical to it). The batched cuBLASLt head
4931 // is a different ULP class and flips near-tie argmaxes off the greedy tape.
4932 let eager_tail = self.sliding_gated_moe_batch_program()
4933 && std::env::var("MEMRA_SPEC_VERIFY_EAGER").as_deref() == Ok("1");
4934 if eager_tail {
4935 let n_vocab = self.cfg.n_vocab as usize;
4936 let mut logits = vbuf(e, t * n_vocab)?;
4937 for r in 0..t {
4938 let mut row = e.uninit(n_embd)?;
4939 e.dtod_copy_view(&x.slice(r * n_embd..(r + 1) * n_embd), &mut row)?;
4940 let mut hr = e.uninit(n_embd)?;
4941 e.rms_norm(&row, self.output_norm.float_data(), &mut hr, n_embd, 1, eps)?;
4942 let lr = e.matmul(&self.output, &hr, 1)?;
4943 e.dtod_copy_into(&lr, &mut logits, r * n_vocab)?;
4944 e.dtod_copy_into(&hr, &mut hn, r * n_embd)?;
4945 }
4946 if stream.is_none() {
4947 cache.pos += t;
4948 }
4949 return Ok((logits, if spec_hpost() { hn } else { x }));
4950 }
4951 let serving_head =
4952 self.sliding_gated_moe_batch_program() || self.batched_serving_numeric_class();
4953 let logits = if serving_head {
4954 // Step35 and the qwen35 family (MoE 2026-08-14 AM, dense-hybrid same day PM — the
4955 // Q3.8 bring-up reproduced the identical near-tie class on dense: eager-class verify
4956 // vs batched-class live serving, ULP drift amplified through the GDN recurrence)
4957 // serve one batched numeric class at every live width, including B=1. Keep the
4958 // verify head in that same class; other generic families retain the decode-exact
4959 // head that their run-spec contract pins.
4960 e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
4961 e.matmul(&self.output, &hn, t)?
4962 } else {
4963 e.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
4964 e.matmul_decode_exact(&self.output, &hn, t)?
4965 };
4966 // stream: the device pos counter owns position; host mirror reconciles at drain.
4967 if stream.is_none() {
4968 cache.pos += t;
4969 }
4970 // Hidden stack for seeds/refresh-fills: pre-norm x (default) or post-norm hn (HPOST).
4971 Ok((logits, if spec_hpost() { hn } else { x }))
4972 }
4973
4974 /// THE VERIFY TRUNK OVER PP-N (lane/pp2-spec 2026-08-06): `decode_step_t_core_stream`'s walk
4975 /// as N stage subgraphs, each on its own engine/stream (and, under `MEMRA_PP_DEVICES`, its own
4976 /// device), with a `[T, n_embd]` boundary transfer between them. T = K+1 (the verify batch),
4977 /// so this is the batched-boundary shape the pp2-batch lane's grow-only slots already handle
4978 /// (`tx(b, x, t*n_embd)`; the slot grows to the high-water T and the transport moves exactly
4979 /// the payload).
4980 ///
4981 /// Structure is `decode_step_batch_ppn`'s, which is `decode_step_h_ppn`'s. FOUR THINGS ARE
4982 /// PER-STAGE and each for a measured reason (see `decode_step_batch_ppn`'s header for the
4983 /// receipts):
4984 ///
4985 /// 1. THE ENGINE (`rt.engine(s, e)`) — `Engine` owns lazily-grown stable-pointer scratch
4986 /// (`fa_part_pool`, `fa_vf16_scratch`, `argmax_partials`) that is single-stream-safe BY
4987 /// DESIGN. Two stage streams through one Engine is the 2026-08-02 shared-scratch race
4988 /// (35% flake, nondeterministic all-logits divergence). `PpNRt::build` gives every stage
4989 /// s>0 its own Engine even on the primary device; honouring it here is what scopes the
4990 /// pools. The verify path allocates MORE of that scratch than eager decode does (FA at
4991 /// m=T, and the per-layer `GdnStash` retains), so this is load-bearing, not inherited.
4992 ///
4993 /// 2. `pos_d` — each stage uploads its OWN copy of the T rope positions on ITS stream, so the
4994 /// buffer is allocated, consumed and freed on one stream. In `stream` mode that means each
4995 /// stage runs its own `pos_iota` over the SHARED device counter (`pos_ctr`): the counter is
4996 /// read-only during the forward (the round's `inc`/`copy_add` happen outside it), so every
4997 /// stage derives the identical iota, and each stage's own output buffer is stream-local.
4998 ///
4999 /// 3. THE EMBED lives with stage 0 (`self.embd` / `embd_gpu` are host/primary-side; the
5000 /// sharded loader leaves the table with stage 0 by construction).
5001 ///
5002 /// 4. THE HEAD (`output_norm` + `output`) runs on the LAST stage — the sharded loader uploaded
5003 /// both through that stage's engine (`hybrid.rs`: `e_head = layer_engine(e, n_trunk,
5004 /// n_trunk-1)`), so reading them anywhere else is a peer read of the biggest tensor in the
5005 /// model, every round.
5006 ///
5007 /// WHAT STAYS ON THE PRIMARY, deliberately: the returned logits and hidden stack `x`. Both are
5008 /// last-stage-allocated device buffers, and every consumer (the device argmax walk, the accept
5009 /// kernels, `spec_seed_gather`, the ckpt rebuild in `commit_verified_prefix`) reads them
5010 /// through the primary context by UVA — the same read the batched serving epilogue's
5011 /// `last_logits_dev` park does. Those consumers are per-round O(T x n_vocab) and O(n_embd),
5012 /// not per-layer, so they are not the 28x class; splitting them is a separate lane.
5013 ///
5014 /// The MTP HEAD (draft side) is NOT split: it is one block, it lives wherever the loader put
5015 /// it (`load_mtp` uses the primary engine), and it is ~1-2 GB against the trunk's tens. Draft
5016 /// placement is measured, not assumed — see `research/pp2-spec-20260806`.
5017 ///
5018 /// EXACTNESS: PP-N adds ZERO deviation. Each stage runs the SAME kernels on the SAME bytes in
5019 /// the same order via the SAME `verify_layers` the unsplit body calls; the only change is
5020 /// where the residual is materialized, and the boundary is a straight f32 copy (dtod
5021 /// same-device / `cudaMemcpyPeerAsync` cross-device, no conversion). So the split MUST be
5022 /// BIT-IDENTICAL to the unsplit verify at the same T, in both placement orders. Gate:
5023 /// `decode-batch-gate --mode ppspec`. Acceptance counts are a DERIVED consequence — greedy
5024 /// accept argmaxes these logits, so bit-identical logits force identical accept walks; the
5025 /// `run-spec` K=1..8 arm checks that end-to-end rather than trusting the implication.
5026 #[allow(clippy::too_many_arguments)]
5027 fn decode_step_t_core_ppn(
5028 &self,
5029 e: &Engine,
5030 tokens: &[u32],
5031 pos0: usize,
5032 cache: &mut Cache,
5033 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
5034 mut ckpt: Option<&mut VerifyCkpt>,
5035 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
5036 fence: &[usize],
5037 pp_pipe: Option<bool>,
5038 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
5039 let ticket = self.verify_stage0_issue(
5040 e,
5041 tokens,
5042 pos0,
5043 cache,
5044 embd_dev,
5045 ckpt.as_deref_mut(),
5046 stream,
5047 fence,
5048 pp_pipe,
5049 None,
5050 )?;
5051 self.verify_stage1_finish(e, ticket, cache, ckpt, stream, fence, true)
5052 }
5053
5054 /// Enqueue embed, stage 0, and the first boundary TX, then return the actual boundary slot.
5055 /// The ordinary PP verify wrapper calls `verify_stage1_finish` immediately after this return.
5056 #[allow(clippy::too_many_arguments)]
5057 fn verify_stage0_issue(
5058 &self,
5059 e: &Engine,
5060 tokens: &[u32],
5061 pos0: usize,
5062 cache: &mut Cache,
5063 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
5064 mut ckpt: Option<&mut VerifyCkpt>,
5065 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
5066 fence: &[usize],
5067 pp_pipe: Option<bool>,
5068 trace: Option<SpecPipeTraceCtx>,
5069 ) -> Result<VerifyBoundaryTicket, Box<dyn std::error::Error>> {
5070 assert!(
5071 !self.is_gemma4_e4b() && !self.gemma_batch_program(),
5072 "decode_step_t_core_ppn covers the hybrid non-gemma4 verify trunk only \
5073 (the gemma4 arms have their own decode_step_t twins)"
5074 );
5075 if crate::pp::pp_host_bounce_active() && (stream.is_some() || embd_dev.is_some()) {
5076 return Err(
5077 "decode_step_t_core_ppn: refused with MEMRA_PP_HOST_BOUNCE=1 — the trunk \
5078 boundary itself is host-staged, but device-resident verify still peer-reads \
5079 primary-device token/position/embedding buffers from stage 0. Run plain PP \
5080 serving on this host class; spec requires local per-stage inputs first."
5081 .into(),
5082 );
5083 }
5084 let rt = crate::pp::PpNRt::get(e)?;
5085 let n_st = fence.len() - 1;
5086 assert_eq!(
5087 rt.n_stages(),
5088 n_st,
5089 "PpNRt stage count {} != fence stages {n_st}",
5090 rt.n_stages()
5091 );
5092 let n_embd = self.cfg.n_embd as usize;
5093 let t = tokens.len();
5094 let payload = t * n_embd;
5095 if pp_pipe.is_some() {
5096 assert_eq!(n_st, 2, "spec pipeline requires exactly two PP stages");
5097 }
5098 // One-shot lane diagnostic: force natural PP-2 boundaries to completion so the server
5099 // log can price stage 0, the peer hop, the RX copy, and stage 1 + head separately without
5100 // nsys. The ordinary path keeps every enqueue asynchronous. N>2 is deliberately excluded:
5101 // the report below names exactly two stages and must never imply it measured middle ones.
5102 let pp_anatomy = n_st == 2 && std::env::var("MEMRA_SPEC_PP_ANATOMY").as_deref() == Ok("1");
5103 let pp_started = std::time::Instant::now();
5104 let (mut reverse_ms, mut stage0_ms, mut tx_ms) = (0.0f64, 0.0f64, 0.0f64);
5105 // The CALLER's ambient stream, captured BEFORE any `rt.enter()` pushes a stage stream:
5106 // this body returns DEVICE-RESIDENT buffers (the device-argmax accept walk's contract),
5107 // so the exit needs the same publication the boundaries get — see `PpNRt::publish_to`.
5108 // Taken here, not at the end, because inside the last-stage scope `e.stream()` IS the
5109 // stage stream and the wait would self-order into a no-op.
5110 let caller_stream = e.stream();
5111 // #87 ROOT-CAUSE FENCE (lane/pp2spec-crash): the PREVIOUS round's stage-allocated
5112 // outputs (logits/hidden/ckpt stashes) freed stream-ordered on the STAGE streams while
5113 // the primary stream still holds queued reads of them — with event tracking elided,
5114 // nothing stops the pool from reusing those blocks for THIS round's stage allocations,
5115 // whose writes then race the queued reads (measured: 13/4096-NaN random-bits garbage in
5116 // the spec round seed; the full anatomy is on `PpNRt::fence_stages_behind`). Order every
5117 // stage stream behind the caller before enqueueing new stage work.
5118 let reverse_started = std::time::Instant::now();
5119 if pp_pipe != Some(false) {
5120 rt.fence_stages_behind(&caller_stream)?;
5121 }
5122 if pp_pipe == Some(true) {
5123 // Both session verifies must alternate boundary slots even when the ordinary
5124 // decode overlap experiment is off. Prewarm before A's stage 0 so B cannot grow
5125 // slot 1 by synchronizing the RX stream while A's stage 1 is in flight.
5126 rt.prepare_overlap_slots(0, payload)?;
5127 }
5128 if pp_anatomy {
5129 // Drain the reverse-publication dependency before timing stage 0 itself. At c=1 this
5130 // prices any primary-stream rollback/refresh tail inherited from the prior round.
5131 for s in 0..n_st {
5132 let _st = rt.enter(s);
5133 rt.engine(s, e).stream().synchronize()?;
5134 }
5135 reverse_ms = reverse_started.elapsed().as_secs_f64() * 1e3;
5136 }
5137
5138 // Per-stage rope positions: in host mode the same [T] iota each stage uploads itself; in
5139 // stream mode each stage's own `pos_iota` over the shared read-only device counter.
5140 let stage_pos = |es: &Engine| -> Result<CudaSlice<i32>, Box<dyn std::error::Error>> {
5141 match stream {
5142 Some((_, ctr)) => {
5143 let mut p = es.alloc_uninit::<i32>(t)?;
5144 es.pos_iota(ctr, &mut p, t)?;
5145 Ok(p)
5146 }
5147 None => {
5148 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
5149 es.htod_i32(&pos_vec)
5150 }
5151 }
5152 };
5153
5154 // ---- STAGE 0: embed (the table lives with stage 0) + layers [0, fence[1]) + TX ----
5155 let slot = {
5156 let _st0 = rt.enter(0);
5157 let e0 = rt.engine(0, e);
5158 enqueue_spec_pipe_trace_marker(&e0.stream(), trace.as_ref(), "S0", "start", None)?;
5159 let stage0_started = std::time::Instant::now();
5160 let pos_d = stage_pos(e0)?;
5161 let x = match (stream, embd_dev) {
5162 (Some((vtok, _)), Some((g, qt, rb))) => {
5163 e0.embed_gather_device_td(g, vtok, t, n_embd, qt, rb)?
5164 }
5165 (None, Some((g, qt, rb))) => e0.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
5166 _ => e0.htod(&self.embd.gather(n_embd, tokens))?,
5167 };
5168 let x = self.verify_layers(
5169 e0,
5170 x,
5171 fence[0],
5172 fence[1],
5173 &pos_d,
5174 pos0,
5175 t,
5176 cache,
5177 ckpt.as_deref_mut(),
5178 stream,
5179 None,
5180 )?;
5181 if pp_anatomy {
5182 e0.stream().synchronize()?;
5183 stage0_ms = stage0_started.elapsed().as_secs_f64() * 1e3;
5184 }
5185 let tx_started = std::time::Instant::now();
5186 let slot = if pp_pipe.is_some() {
5187 rt.tx_pipelined(0, &x, payload)?
5188 } else {
5189 rt.tx(0, &x, payload)?
5190 };
5191 enqueue_spec_pipe_trace_marker(&e0.stream(), trace.as_ref(), "S0", "end", Some(slot))?;
5192 if pp_anatomy {
5193 e0.stream().synchronize()?;
5194 tx_ms = tx_started.elapsed().as_secs_f64() * 1e3;
5195 }
5196 slot
5197 // x + pos_d drop here: freed stream-ordered on stage-0's stream after use.
5198 };
5199
5200 Ok(VerifyBoundaryTicket {
5201 rt,
5202 caller_stream,
5203 slot,
5204 pos0,
5205 t,
5206 payload,
5207 n_st,
5208 pipelined: pp_pipe.is_some(),
5209 pp_anatomy,
5210 pp_started,
5211 reverse_ms,
5212 stage0_ms,
5213 tx_ms,
5214 trace,
5215 })
5216 }
5217
5218 /// Consume a stage-0 boundary ticket and enqueue the remaining PP stages plus the head.
5219 /// On PP-2 this is exactly stage 1; PP-N keeps its pre-existing middle-stage walk here.
5220 #[allow(clippy::too_many_arguments)]
5221 fn verify_stage1_finish(
5222 &self,
5223 e: &Engine,
5224 ticket: VerifyBoundaryTicket,
5225 cache: &mut Cache,
5226 mut ckpt: Option<&mut VerifyCkpt>,
5227 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
5228 fence: &[usize],
5229 publish_to_caller: bool,
5230 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
5231 let VerifyBoundaryTicket {
5232 rt,
5233 caller_stream,
5234 slot,
5235 pos0,
5236 t,
5237 payload,
5238 n_st,
5239 pipelined,
5240 pp_anatomy,
5241 pp_started,
5242 reverse_ms,
5243 stage0_ms,
5244 tx_ms,
5245 trace,
5246 } = ticket;
5247 let n_embd = self.cfg.n_embd as usize;
5248 let eps = self.cfg.rms_eps;
5249 let mut slot = slot;
5250 let (mut rx_ms, mut stage1_ms) = (0.0f64, 0.0f64);
5251 let stage_pos = |es: &Engine| -> Result<CudaSlice<i32>, Box<dyn std::error::Error>> {
5252 match stream {
5253 Some((_, ctr)) => {
5254 let mut p = es.alloc_uninit::<i32>(t)?;
5255 es.pos_iota(ctr, &mut p, t)?;
5256 Ok(p)
5257 }
5258 None => {
5259 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
5260 es.htod_i32(&pos_vec)
5261 }
5262 }
5263 };
5264
5265 // ---- MIDDLE STAGES: RX boundary s-1 -> range -> TX boundary s ----
5266 for s in 1..n_st - 1 {
5267 let _st = rt.enter(s);
5268 let es = rt.engine(s, e);
5269 let pos_d = stage_pos(es)?;
5270 let x = rt.rx(s - 1, slot, payload)?;
5271 let x = self.verify_layers(
5272 es,
5273 x,
5274 fence[s],
5275 fence[s + 1],
5276 &pos_d,
5277 pos0,
5278 t,
5279 cache,
5280 ckpt.as_deref_mut(),
5281 stream,
5282 None,
5283 )?;
5284 slot = if pipelined {
5285 rt.tx_pipelined(s, &x, payload)?
5286 } else {
5287 rt.tx(s, &x, payload)?
5288 };
5289 }
5290
5291 // ---- LAST STAGE: RX + final range + output_norm + lm head ----
5292 let _stl = rt.enter(n_st - 1);
5293 let el = rt.engine(n_st - 1, e);
5294 let pos_d = stage_pos(el)?;
5295 let rx_started = std::time::Instant::now();
5296 let x = rt.rx(n_st - 2, slot, payload)?;
5297 if pp_anatomy {
5298 el.stream().synchronize()?;
5299 rx_ms = rx_started.elapsed().as_secs_f64() * 1e3;
5300 }
5301 enqueue_spec_pipe_trace_marker(&el.stream(), trace.as_ref(), "S1", "start", Some(slot))?;
5302 let stage1_started = std::time::Instant::now();
5303 let x = self.verify_layers(
5304 el,
5305 x,
5306 fence[n_st - 1],
5307 fence[n_st],
5308 &pos_d,
5309 pos0,
5310 t,
5311 cache,
5312 ckpt.as_deref_mut(),
5313 stream,
5314 None,
5315 )?;
5316
5317 let mut hn = vbuf(el, payload)?;
5318 let logits = if self.sliding_gated_moe_batch_program() {
5319 // The PP Step35 serving path uses rms_norm + matmul for B=1 as well as B>1.
5320 // Verify must not switch numeric class merely because the same session speculates.
5321 el.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
5322 el.matmul(&self.output, &hn, t)?
5323 } else {
5324 el.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
5325 el.matmul_decode_exact(&self.output, &hn, t)?
5326 };
5327 enqueue_spec_pipe_trace_marker(&el.stream(), trace.as_ref(), "S1", "end", Some(slot))?;
5328 if pp_anatomy {
5329 el.stream().synchronize()?;
5330 stage1_ms = stage1_started.elapsed().as_secs_f64() * 1e3;
5331 }
5332 // EXIT PUBLICATION: both returned buffers are still being produced on the last stage's
5333 // stream. Order the caller's stream behind that work before the buffers escape this
5334 // scope (the 2026-08-06 same-device ppspec find: without it the caller's primary-stream
5335 // consumer read unwritten logits — nondeterministic, one-device-only, and it poisoned
5336 // the following arm's KV in the same process).
5337 if publish_to_caller {
5338 rt.publish_to(n_st - 1, &caller_stream)?;
5339 }
5340 if pp_anatomy {
5341 if publish_to_caller {
5342 caller_stream.synchronize()?;
5343 }
5344 eprintln!(
5345 "[spec-pp-anatomy] t={t} reverse={reverse_ms:.3}ms stage0={stage0_ms:.3}ms \
5346 tx={tx_ms:.3}ms rx={rx_ms:.3}ms stage1-head={stage1_ms:.3}ms total={:.3}ms",
5347 pp_started.elapsed().as_secs_f64() * 1e3,
5348 );
5349 }
5350 // stream: the device pos counter owns position; host mirror reconciles at drain.
5351 if stream.is_none() {
5352 cache.pos += t;
5353 }
5354 Ok((logits, if spec_hpost() { hn } else { x }))
5355 }
5356
5357 /// Step3.5/Step3.7 verify trunk in the serving batched numeric class.
5358 ///
5359 /// `step35_decode_batch_layers` is now authoritative at every live serving width, including
5360 /// B=1 (lane/cx-b1fix). The older verify walk deliberately mirrored the eager T=1 class:
5361 /// it replayed `step35_decode_attn` per row and used the eager/decode-exact FFN dispatch.
5362 /// Those classes are individually stable, but a near-tie prompt can choose different greedy
5363 /// bytes when a request moves from batched plain serving into speculative verify. Run the
5364 /// same authoritative B=1 stage subgraph for each verify row here. Rows still advance
5365 /// layer-by-layer, so every layer sees the preceding verify rows in its attention cache while
5366 /// every norm/projection/FFN uses exactly the live serving dispatch.
5367 #[allow(clippy::too_many_arguments)]
5368 /// PRIME-BY-T-ROWS (MEMRA_PRIME_TROWS=1): prefill the prompt through the same-session
5369 /// t-row walk in 32-row chunks — every row runs the t=1 decode program bit-for-bit
5370 /// (the TOKENWISE-prime ORACLE class), so this door is exact against the exactness
5371 /// reference while replacing the host-canonical per-token prime. Requires the walk
5372 /// doors (MEMRA_SPEC_VERIFY_EAGER/TCOL); returns the prime contract trio.
5373 #[allow(clippy::type_complexity)]
5374 pub(crate) fn step35_prime_trows(
5375 &self,
5376 e: &Engine,
5377 tokens: &[u32],
5378 cache: &mut Cache,
5379 ) -> Result<Option<(Vec<f32>, CudaSlice<f32>, CudaSlice<f32>)>, Box<dyn std::error::Error>>
5380 {
5381 let dbg = std::env::var("MEMRA_SPEC_FA2_DEBUG").as_deref() == Ok("1");
5382 if std::env::var("MEMRA_PRIME_TROWS").as_deref() != Ok("1") {
5383 return Ok(None);
5384 }
5385 if !self.uses_sliding_gated_moe_program()
5386 || cache.pos != 0
5387 || cache.dflash_taps.is_some()
5388 || std::env::var("MEMRA_SPEC_VERIFY_EAGER").as_deref() != Ok("1")
5389 || std::env::var("MEMRA_SPEC_VERIFY_TCOL").as_deref() != Ok("1")
5390 {
5391 if dbg {
5392 eprintln!(
5393 "[prime-trows] refuse: program={} pos={} taps={} eager={:?} tcol={:?}",
5394 self.uses_sliding_gated_moe_program(),
5395 cache.pos,
5396 cache.dflash_taps.is_some(),
5397 std::env::var("MEMRA_SPEC_VERIFY_EAGER").ok(),
5398 std::env::var("MEMRA_SPEC_VERIFY_TCOL").ok()
5399 );
5400 }
5401 return Ok(None);
5402 }
5403 let n_embd = self.cfg.n_embd as usize;
5404 let n_layers = self.layers.len();
5405 let t_total = tokens.len();
5406 let Some(embd_gpu) = self.embd_gpu_try(e) else {
5407 if dbg {
5408 eprintln!("[prime-trows] refuse: no device embed table");
5409 }
5410 return Ok(None);
5411 };
5412 let embd_qtype = match self.embd.ggml_type {
5413 memra_gguf::GgmlType::BF16 => crate::QT_BF16,
5414 memra_gguf::GgmlType::Q8_0 => crate::QT_Q8_0,
5415 other => {
5416 if dbg {
5417 eprintln!("[prime-trows] refuse: embed dtype {other:?}");
5418 }
5419 return Ok(None);
5420 }
5421 };
5422 let embd_row_bytes = self.embd.raw.len() / self.cfg.n_vocab as usize;
5423 // Chunk plan: 32-row chunks; a 1-token tail folds into the previous chunk
5424 // (the walk floor is t >= 2).
5425 let mut bounds = Vec::new();
5426 let mut start = 0usize;
5427 while start < t_total {
5428 let mut end = (start + 32).min(t_total);
5429 if t_total - end == 1 {
5430 end -= 1;
5431 }
5432 bounds.push((start, end));
5433 start = end;
5434 }
5435 if bounds.iter().any(|(a, b)| b - a < 2) {
5436 return Ok(None); // degenerate short prompt keeps the ordinary prime
5437 }
5438 let mut hiddens = e.uninit(t_total * n_embd)?;
5439 let mut last: Option<CudaSlice<f32>> = None;
5440 for &(a, b) in &bounds {
5441 let tc = b - a;
5442 let tok_d = e.stream().clone_htod(&tokens[a..b])?;
5443 let x =
5444 e.embed_gather_device_td(embd_gpu, &tok_d, tc, n_embd, embd_qtype, embd_row_bytes)?;
5445 let out = self.step35_verify_batch_layers(e, x, 0, n_layers, a, tc, cache)?;
5446 e.copy_into(&mut hiddens, a * n_embd, &out, tc * n_embd)?;
5447 if b == t_total {
5448 let mut h = e.uninit(n_embd)?;
5449 e.dtod_copy_view(&out.slice((tc - 1) * n_embd..tc * n_embd), &mut h)?;
5450 last = Some(h);
5451 }
5452 }
5453 let h_seed = last.expect("last chunk produced the seed row");
5454 let mut hn = e.uninit(n_embd)?;
5455 e.rms_norm_decode(
5456 &h_seed,
5457 self.output_norm.float_data(),
5458 &mut hn,
5459 n_embd,
5460 1,
5461 self.cfg.rms_eps,
5462 )?;
5463 let logits_d = e.matmul_decode_exact(&self.output, &hn, 1)?;
5464 let logits = e.dtoh(&logits_d)?;
5465 cache.pos = t_total;
5466 Ok(Some((logits, h_seed, hiddens)))
5467 }
5468
5469 fn step35_verify_batch_layers(
5470 &self,
5471 e: &Engine,
5472 mut x: CudaSlice<f32>,
5473 lo: usize,
5474 hi: usize,
5475 pos0: usize,
5476 t: usize,
5477 cache: &mut Cache,
5478 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5479 let n_embd = self.cfg.n_embd as usize;
5480 if !self.uses_sliding_gated_moe_program() {
5481 return Err(
5482 "serving-class verify requires sliding-gated-MoE canonical operations".into(),
5483 );
5484 }
5485 // SERVING-CLASS VERIFY (MEMRA_SPEC_VERIFY_EAGER=1, step37 MTP bring-up): each verify
5486 // column rides decode_layers_eager — the EXACT t=1 program live serving runs (all TP2
5487 // doors) — row-outer, so row r's appends land before row r+1 attends: bit-equal to
5488 // plain greedy by construction. Only the unsplit full-range walk qualifies; PP splits
5489 // and the tap path keep the batch-layer class.
5490 static VE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
5491 let eager_verify = *VE
5492 .get_or_init(|| std::env::var("MEMRA_SPEC_VERIFY_EAGER").as_deref() == Ok("1"))
5493 && lo == 0
5494 && hi == self.layers.len();
5495 if eager_verify {
5496 // T-COLUMN LAYER-OUTER WALK (MEMRA_SPEC_VERIFY_TCOL=1): per layer, one t-grid
5497 // attn norm + ONE weight-amortized QKV(+gate) over all T columns, then each
5498 // column runs the UNMODIFIED t=1 attention program via the col-select door and
5499 // the ordinary residual/FFN body. Values per column are bit-equal to the
5500 // row-outer walk: rms over the materialized residual == the fused add+norm
5501 // (kernel_check identity), the tcol kernel's per-column FP order == the t=1
5502 // kernel, and every downstream op IS the t=1 program.
5503 static TCOL: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
5504 let tcol =
5505 *TCOL.get_or_init(|| std::env::var("MEMRA_SPEC_VERIFY_TCOL").as_deref() == Ok("1"));
5506 // T > 32 (prefill-class): run the SAME walk in 32-row chunks — each chunk's
5507 // rows are the t=1 program bit-for-bit and the rope pass advances the cache,
5508 // so a chunked call is value-identical to the row-outer loop it replaces.
5509 static TROWS_PREFILL: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
5510 let trows_prefill = *TROWS_PREFILL
5511 .get_or_init(|| std::env::var("MEMRA_PRIME_TROWS").as_deref() == Ok("1"));
5512 // MEMRA_PRIME_TROWS_T=<w>: chunk width, default 8 = the REAL cap of this walk.
5513 // The workspace slabs go to 32 rows, but `matvec_bf16_qkvg_tcol_into` refuses
5514 // t > 8 (compile-time-T twins exist for 2/4/8 only; the runtime-t kernel spills
5515 // its accumulators to local memory), so a wider chunk fails the request with
5516 // "matvec_bf16_qkvg_tcol geometry" — which is exactly how the first server-path
5517 // TROWS arm died. Measured at 193 tokens: w=8 2.459 s, w=4 2.574 s.
5518 static TROWS_W: std::sync::OnceLock<Result<usize, String>> = std::sync::OnceLock::new();
5519 let trows_w = match TROWS_W.get_or_init(|| {
5520 let value = std::env::var("MEMRA_PRIME_TROWS_T").ok();
5521 parse_prime_trows_width(value.as_deref())
5522 }) {
5523 Ok(width) => *width,
5524 Err(err) => return Err(err.clone().into()),
5525 };
5526 if tcol && trows_prefill && t > trows_w {
5527 // One-time engagement receipt: without it a prefill gate cannot tell a
5528 // chunked walk from the row-outer fallback it is supposed to replace
5529 // (the first PRIME_TROWS gate passed vacuously on exactly that).
5530 static SEEN: std::sync::atomic::AtomicBool =
5531 std::sync::atomic::AtomicBool::new(false);
5532 if !SEEN.swap(true, std::sync::atomic::Ordering::Relaxed) {
5533 eprintln!(
5534 "[prime-trows] ENGAGED t={t} width={trows_w} chunks={} layers={}..{}",
5535 t.div_ceil(trows_w),
5536 lo,
5537 hi
5538 );
5539 }
5540 let mut out = e.uninit(t * n_embd)?;
5541 let mut start = 0usize;
5542 while start < t {
5543 let mut end = (start + trows_w).min(t);
5544 if t - end == 1 {
5545 end -= 1;
5546 }
5547 let tc = end - start;
5548 let mut xc = e.uninit(tc * n_embd)?;
5549 e.dtod_copy_view(&x.slice(start * n_embd..end * n_embd), &mut xc)?;
5550 let oc =
5551 self.step35_verify_batch_layers(e, xc, lo, hi, pos0 + start, tc, cache)?;
5552 e.copy_into(&mut out, start * n_embd, &oc, tc * n_embd)?;
5553 start = end;
5554 }
5555 return Ok(out);
5556 }
5557 if tcol && t >= 2 && t <= 32 {
5558 // MEMRA_TCOL_PROF=1: synchronized per-segment wall profile of the walk
5559 // (norm+QKV precompute / per-col attention / per-col residual+FFN). The
5560 // syncs serialize the stream, so the split is for TARGETING amortization
5561 // work only — never a perf claim.
5562 static PROF: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
5563 let prof =
5564 *PROF.get_or_init(|| std::env::var("MEMRA_TCOL_PROF").as_deref() == Ok("1"));
5565 let mut prof_ms = [0f64; 3];
5566 let eps = self.cfg.rms_eps;
5567 let mut x_t = x;
5568 let mut h_t = e.uninit(t * n_embd)?;
5569 let mut h_row = e.uninit(n_embd)?; // real row: the non-dcw fallback reads it
5570 // Per-column pos buffers hoisted out of the layer loop (a per-col-per-layer
5571 // pageable htod was an in-stream engine turnaround x t x 45).
5572 let mut pos_rows = Vec::with_capacity(t);
5573 for r in 0..t {
5574 pos_rows.push(e.htod_i32(&[(pos0 + r) as i32])?);
5575 }
5576 let mut ok = true;
5577 // MEMRA_TCOL_OPROJ=1: defer each column's o_proj — the finish seam
5578 // stashes `gated` instead of joining per column; one b4_tcol per rank +
5579 // one slab join produce every column's `mixed` after the attention pass.
5580 // Bit-exact per column (t=1 b4 program per column; elementwise join).
5581 // MEMRA_TCOL_FFN=1 (implies the o_proj defer): when every column of a
5582 // MoE layer deferred, the residual norm runs as one t-grid launch
5583 // (per-row program == t=1) and the FFN as ONE two-column device-routed
5584 // sweep + per-column shexp — the two columns' expert weights dedup
5585 // through L2 instead of reading HBM twice.
5586 static FFN2: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
5587 let ffn_batch =
5588 *FFN2.get_or_init(|| std::env::var("MEMRA_TCOL_FFN").as_deref() == Ok("1"));
5589 let oproj_batch = crate::tp::tcol_oproj_on() || ffn_batch;
5590 // MEMRA_SPEC_FA2=1 (T=2 only): eligible layers defer BOTH columns' fa —
5591 // the per-column pass norms/ropes/appends and stashes q+gate, then one
5592 // shared-KV fa_decode_dcw2 per rank + the o_proj join produce the
5593 // [2, o_out] mixed slab. The precheck runs before arming (stashing is
5594 // unrecoverable); ineligible/boundary layers run the ordinary program.
5595 let fa2 = crate::tp::spec_fa2_on() && t <= 32;
5596 let mut mixed_row = e.uninit(n_embd)?;
5597 let mut pos_staged = false;
5598 for il in lo..hi {
5599 let layer = &self.layers[il];
5600 let fa2_layer = fa2 && self.step35_fa_rows_precheck(cache, il, pos0, t)?;
5601 let mut seg = std::time::Instant::now();
5602 e.rms_norm(&x_t, layer.attn_norm.float_data(), &mut h_t, n_embd, t, eps)?;
5603 if !self.step35_verify_qkv_precompute(e, il, &h_t, t)? {
5604 ok = false;
5605 break;
5606 }
5607 // FULL t-row attention pass (rope/append + fa + combine + o_proj in
5608 // 3 launches/rank): same-session rows, slot = len-base+r, one len
5609 // advance by t. Host cache bookkeeping mirrors the per-column tail.
5610 if fa2_layer {
5611 if let Some(mixed_t) =
5612 self.step35_verify_rope_fa_pass(e, il, cache, pos0, t, !pos_staged)?
5613 {
5614 pos_staged = true;
5615 {
5616 let tp_kv = cache.tp_kv[il]
5617 .as_mut()
5618 .expect("precheck verified the distributed cache");
5619 let transaction = tp_kv.begin_transaction()?;
5620 let crate::hybrid::Mixer::Full(fa) = &layer.mixer else {
5621 return Err("verify rope pass expects full attention".into());
5622 };
5623 let tp = fa
5624 .step_tp_qkv
5625 .as_ref()
5626 .ok_or("verify rope pass lost its TP state")?;
5627 let empty: [CudaSlice<f32>; 0] = [];
5628 tp.runtime.append_tp_kv_transaction_inner(
5629 tp_kv,
5630 transaction,
5631 &empty,
5632 &empty,
5633 t,
5634 true,
5635 )?;
5636 tp.runtime.commit_tp_kv_transaction_external(
5637 tp_kv,
5638 transaction,
5639 t,
5640 )?;
5641 if let Some(local) = cache.kv[il].as_mut() {
5642 local.len = pos0 + t;
5643 if !crate::tp::len_mirror_lazy_on() {
5644 e.set_i32_one(&mut local.len_d, local.len as i32)?;
5645 }
5646 }
5647 }
5648 if prof {
5649 e.stream().synchronize()?;
5650 prof_ms[1] += seg.elapsed().as_secs_f64() * 1e3;
5651 seg = std::time::Instant::now();
5652 }
5653 let o_out = mixed_t.len() / t;
5654 let mut next = e.uninit(t * n_embd)?;
5655 let mut batched = false;
5656 if ffn_batch && o_out == n_embd {
5657 let mut x1_t = e.uninit(t * n_embd)?;
5658 let mut z_t = e.uninit(t * n_embd)?;
5659 e.add_rms_norm(
5660 &x_t,
5661 &mixed_t,
5662 layer.post_attn_norm.float_data(),
5663 &mut x1_t,
5664 &mut z_t,
5665 n_embd,
5666 t,
5667 eps,
5668 )?;
5669 if let Some(ffn_t) = self.step35_verify_moe_tn(e, il, &z_t, t)? {
5670 let mut x2_t = e.uninit(t * n_embd)?;
5671 e.add(&x1_t, &ffn_t, &mut x2_t, t * n_embd)?;
5672 next = x2_t;
5673 batched = true;
5674 }
5675 }
5676 if !batched {
5677 for r in 0..t {
5678 e.dtod_copy_view(
5679 &mixed_t.slice(r * o_out..(r + 1) * o_out),
5680 &mut mixed_row,
5681 )?;
5682 let mut x_row = e.uninit(n_embd)?;
5683 e.dtod_copy_view(
5684 &x_t.slice(r * n_embd..(r + 1) * n_embd),
5685 &mut x_row,
5686 )?;
5687 let (x1, ffn_out) = self.residual_norm_ffn(
5688 e, layer, &x_row, &mixed_row, n_embd, il, eps,
5689 )?;
5690 let mut x2 = e.uninit(n_embd)?;
5691 e.add(&x1, &ffn_out, &mut x2, n_embd)?;
5692 e.dtod_copy_into(&x2, &mut next, r * n_embd)?;
5693 }
5694 }
5695 if prof {
5696 e.stream().synchronize()?;
5697 prof_ms[2] += seg.elapsed().as_secs_f64() * 1e3;
5698 }
5699 x_t = next;
5700 continue;
5701 }
5702 }
5703 if prof {
5704 e.stream().synchronize()?;
5705 prof_ms[0] += seg.elapsed().as_secs_f64() * 1e3;
5706 seg = std::time::Instant::now();
5707 }
5708 let mut next = e.uninit(t * n_embd)?;
5709 // Columns whose o_proj was deferred (their FFN runs after the join).
5710 // A NON-deferred column's FFN must run INSIDE the column loop: the
5711 // oproj-tail handoff is a single cell that the same column's
5712 // residual_norm_ffn consumes before the next column's finish.
5713 let mut deferred: Vec<usize> = Vec::new();
5714 let mut fa2_deferred: Vec<usize> = Vec::new();
5715 let mut ffn_col =
5716 |r: usize,
5717 mixed: &CudaSlice<f32>,
5718 next: &mut CudaSlice<f32>|
5719 -> Result<(), Box<dyn std::error::Error>> {
5720 let mut x_row = e.uninit(n_embd)?;
5721 e.dtod_copy_view(&x_t.slice(r * n_embd..(r + 1) * n_embd), &mut x_row)?;
5722 let (x1, ffn_out) =
5723 self.residual_norm_ffn(e, layer, &x_row, mixed, n_embd, il, eps)?;
5724 let mut x2 = e.uninit(n_embd)?;
5725 e.add(&x1, &ffn_out, &mut x2, n_embd)?;
5726 e.dtod_copy_into(&x2, next, r * n_embd)?;
5727 Ok(())
5728 };
5729 for r in 0..t {
5730 e.dtod_copy_view(&h_t.slice(r * n_embd..(r + 1) * n_embd), &mut h_row)?;
5731 let row_pos = &pos_rows[r];
5732 crate::tp::set_verify_tcol(Some(r));
5733 if fa2_layer {
5734 crate::tp::set_spec_fa2_defer(Some(r));
5735 } else if oproj_batch {
5736 crate::tp::set_tcol_oproj_defer(Some(r));
5737 }
5738 let mixed = match &layer.mixer {
5739 crate::hybrid::Mixer::Full(fa) => {
5740 self.full_attn_decode(e, fa, &h_row, row_pos, pos0 + r, cache, il)
5741 }
5742 _ => Err("step35 verify expects full attention".into()),
5743 };
5744 crate::tp::set_verify_tcol(None);
5745 crate::tp::set_spec_fa2_defer(None);
5746 crate::tp::set_tcol_oproj_defer(None);
5747 let mixed = mixed?;
5748 if fa2_layer && crate::tp::take_spec_fa2_stashed() {
5749 fa2_deferred.push(r);
5750 } else if oproj_batch && crate::tp::take_tcol_oproj_stashed() {
5751 deferred.push(r);
5752 } else {
5753 ffn_col(r, &mixed, &mut next)?;
5754 }
5755 }
5756 if !fa2_deferred.is_empty() && fa2_deferred.len() != t {
5757 // The precheck guarantees both columns stash or neither; a strict
5758 // subset means a column's output was never produced anywhere.
5759 return Err("spec fa2 stash engaged for a subset of columns".into());
5760 }
5761 if prof {
5762 e.stream().synchronize()?;
5763 prof_ms[1] += seg.elapsed().as_secs_f64() * 1e3;
5764 seg = std::time::Instant::now();
5765 }
5766 if !fa2_deferred.is_empty() {
5767 deferred = fa2_deferred;
5768 }
5769 if !deferred.is_empty() {
5770 let mixed_t = if fa2_layer {
5771 self.step35_verify_fa_rows_join(e, il, cache, pos0, t)?
5772 } else {
5773 self.step35_verify_oproj_tcol(e, il, t)?
5774 };
5775 let o_out = mixed_t.len() / t;
5776 // Batched t=2 residual+MoE: one t-grid add_rms_norm (per-row
5777 // program == t=1; bit-identical to the oproj-tail join per the
5778 // M2 verbatim-program contract) feeding the two-column routed
5779 // sweep. Ineligible layers (dense FFN, non-nvfp4) fall through
5780 // to the per-column body.
5781 let mut batched = false;
5782 if ffn_batch && deferred.len() == t && o_out == n_embd {
5783 let mut x1_t = e.uninit(t * n_embd)?;
5784 let mut z_t = e.uninit(t * n_embd)?;
5785 e.add_rms_norm(
5786 &x_t,
5787 &mixed_t,
5788 layer.post_attn_norm.float_data(),
5789 &mut x1_t,
5790 &mut z_t,
5791 n_embd,
5792 t,
5793 eps,
5794 )?;
5795 if let Some(ffn_t) = self.step35_verify_moe_tn(e, il, &z_t, t)? {
5796 let mut x2_t = e.uninit(t * n_embd)?;
5797 e.add(&x1_t, &ffn_t, &mut x2_t, t * n_embd)?;
5798 next = x2_t;
5799 batched = true;
5800 }
5801 }
5802 if !batched {
5803 for &r in &deferred {
5804 e.dtod_copy_view(
5805 &mixed_t.slice(r * o_out..(r + 1) * o_out),
5806 &mut mixed_row,
5807 )?;
5808 ffn_col(r, &mixed_row, &mut next)?;
5809 }
5810 }
5811 }
5812 if prof {
5813 e.stream().synchronize()?;
5814 prof_ms[2] += seg.elapsed().as_secs_f64() * 1e3;
5815 }
5816 drop(ffn_col);
5817 x_t = next;
5818 }
5819 if prof {
5820 eprintln!(
5821 "[tcol-prof] t={t} norm+qkv={:.3}ms attn={:.3}ms ffn={:.3}ms",
5822 prof_ms[0], prof_ms[1], prof_ms[2]
5823 );
5824 }
5825 if ok {
5826 return Ok(x_t);
5827 }
5828 // fall through to the row-outer walk on ineligible layers
5829 x = x_t;
5830 }
5831 let mut next = e.uninit(t * n_embd)?;
5832 for r in 0..t {
5833 let mut row = e.uninit(n_embd)?;
5834 e.dtod_copy_view(&x.slice(r * n_embd..(r + 1) * n_embd), &mut row)?;
5835 let row_pos = e.htod_i32(&[(pos0 + r) as i32])?;
5836 let out = self.decode_layers_eager(e, row, lo, hi, &row_pos, pos0 + r, cache)?;
5837 e.dtod_copy_into(&out, &mut next, r * n_embd)?;
5838 }
5839 // dflash taps are NOT produced on this arm (they need per-layer hiddens the
5840 // row-outer walk does not materialize); the door is a step37 MTP bring-up
5841 // surface where taps are unused.
5842 return Ok(next);
5843 }
5844 let mut ph_last = std::time::Instant::now();
5845 for il in lo..hi {
5846 let mut next = e.uninit(t * n_embd)?;
5847 for r in 0..t {
5848 let mut row = e.uninit(n_embd)?;
5849 e.dtod_copy_view(&x.slice(r * n_embd..(r + 1) * n_embd), &mut row)?;
5850 // The caller owns this verify's position. During controller overlap, cache.pos
5851 // still describes generation N while this stage-0 walk belongs to N+1.
5852 let row_pos = e.htod_i32(&[(pos0 + r) as i32])?;
5853 let mut one = [&mut *cache];
5854 let out = self.step35_decode_batch_layers(
5855 e,
5856 row,
5857 &mut one,
5858 &[(pos0 + r) as i32],
5859 &row_pos,
5860 il,
5861 il + 1,
5862 &mut ph_last,
5863 )?;
5864 e.dtod_copy_into(&out, &mut next, r * n_embd)?;
5865 }
5866 self.dflash_tap(e, cache, il, &next, t)?;
5867 x = next;
5868 }
5869 Ok(x)
5870 }
5871
5872 /// DSpark drafter verify (lane/dspark-q38-recover): one t-row forward through the
5873 /// SERVING-CLASS verify funnel (`decode_step_t_core_stream` — the same numeric class
5874 /// MTP verify rides, GDN state advanced in place), returning per-row argmax tokens.
5875 /// Advances `cache.pos += t`; the caller owns snapshot/rollback (block acceptance is
5876 /// prefix-keep, not all-or-nothing).
5877 pub(crate) fn dspark_verify_t_am(
5878 &self,
5879 e: &Engine,
5880 tokens: &[u32],
5881 pos0: usize,
5882 cache: &mut Cache,
5883 ) -> Result<Vec<u32>, Box<dyn std::error::Error>> {
5884 let (logits, _hn) = self.decode_step_t_core_stream(
5885 e, tokens, pos0, cache, None, None, None, None, None, None,
5886 )?;
5887 let t = tokens.len();
5888 let v = self.output.out_features();
5889 let mut am_d = e.stream().alloc_zeros::<u32>(t)?;
5890 for r in 0..t {
5891 e.argmax_token_device_col(&logits, r, v, &mut am_d, r)?;
5892 }
5893 Ok(e.dtoh_u32(&am_d)?)
5894 }
5895
5896 /// DSpark verify returning the RAW verify logits [t, n_vocab] (device-resident) instead
5897 /// of per-row argmaxes — the sampled-admission arm's input (rejection-sampling accept
5898 /// gathers filtered p from these columns; lane/dspark-sampled-admission-20260820). Same
5899 /// forward as `dspark_verify_t_am`; the greedy arm keeps its argmax wrapper untouched.
5900 pub(crate) fn dspark_verify_t_logits(
5901 &self,
5902 e: &Engine,
5903 tokens: &[u32],
5904 pos0: usize,
5905 cache: &mut Cache,
5906 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5907 let (logits, _hn) = self.decode_step_t_core_stream(
5908 e, tokens, pos0, cache, None, None, None, None, None, None,
5909 )?;
5910 Ok(logits)
5911 }
5912
5913 /// DSpark verify with the MTP column-stash armed: identical forward to
5914 /// `dspark_verify_t_am`, but fills a `VerifyCkpt` so a partial accept can restore
5915 /// column state directly (`dspark_commit_prefix`) instead of snapshot-replay.
5916 /// The ckpt type is opaque outside spec.rs (newtype) — dflash.rs threads it through.
5917 pub(crate) fn dspark_verify_t_am_ckpt(
5918 &self,
5919 e: &Engine,
5920 tokens: &[u32],
5921 pos0: usize,
5922 cache: &mut Cache,
5923 ) -> Result<(Vec<u32>, DsparkVerifyCkpt), Box<dyn std::error::Error>> {
5924 let mut ck = VerifyCkpt::new(self.layers.len());
5925 let (logits, _hn) = self.decode_step_t_core_stream(
5926 e,
5927 tokens,
5928 pos0,
5929 cache,
5930 None,
5931 Some(&mut ck),
5932 None,
5933 None,
5934 None,
5935 None,
5936 )?;
5937 let t = tokens.len();
5938 let v = self.output.out_features();
5939 let mut am_d = e.stream().alloc_zeros::<u32>(t)?;
5940 for r in 0..t {
5941 e.argmax_token_device_col(&logits, r, v, &mut am_d, r)?;
5942 }
5943 Ok((e.dtoh_u32(&am_d)?, DsparkVerifyCkpt(ck)))
5944 }
5945
5946 /// Engine-bundle slice 2: `dspark_verify_t_am_ckpt` with DEVICE tokens and NO readback.
5947 /// The verify tokens are the round's `chain_d` (cand layout: [anchor, drafts...]); the
5948 /// embed gathers its first `t` entries on-device (`embed_gather_u32_t` — bit-identical
5949 /// rows to the host arm), so the host never blocks on the draft chain before dispatching
5950 /// verify. Returns the device per-row argmax buffer; the caller merges its readback with
5951 /// the chain's into ONE sync. Forward, ckpt fill and argmax walk are `_ckpt` verbatim.
5952 pub(crate) fn dspark_verify_t_am_ckpt_dev(
5953 &self,
5954 e: &Engine,
5955 vtok: &CudaSlice<u32>,
5956 t: usize,
5957 pos0: usize,
5958 cache: &mut Cache,
5959 embd_dev: (&CudaSlice<u8>, i32, usize),
5960 graphs: Option<&mut DsparkVerifyGraphs>,
5961 ) -> Result<(CudaSlice<u32>, DsparkVerifyCkpt), Box<dyn std::error::Error>> {
5962 debug_assert!(
5963 vtok.len() >= t,
5964 "verify window exceeds the device token buffer"
5965 );
5966 // The slab flag is a per-round statement: clear it here so a verify that never
5967 // reaches the graphs door (rowwise env, a non-tparallel arm) cannot leave a
5968 // stale `true` steering the commit at slabs the round never wrote.
5969 let mut graphs = graphs;
5970 if let Some(g) = graphs.as_deref_mut() {
5971 g.round_slab = false;
5972 }
5973 let mut ck = VerifyCkpt::new(self.layers.len());
5974 // Dummy host tokens size the funnel; the embed reads `vtok` (the round-stream
5975 // arm's established pattern — spec.rs stream-mode verify does the same).
5976 let dummy = vec![0u32; t];
5977 let (logits, _hn) = self.decode_step_t_core_stream(
5978 e,
5979 &dummy,
5980 pos0,
5981 cache,
5982 Some(embd_dev),
5983 Some(&mut ck),
5984 None,
5985 None,
5986 Some(vtok),
5987 graphs,
5988 )?;
5989 let v = self.output.out_features();
5990 let mut am_d = e.stream().alloc_zeros::<u32>(t)?;
5991 for r in 0..t {
5992 e.argmax_token_device_col(&logits, r, v, &mut am_d, r)?;
5993 }
5994 Ok((am_d, DsparkVerifyCkpt(ck)))
5995 }
5996
5997 /// Ckpt-armed twin of [`Self::dspark_verify_t_logits`] (sampled-admission arm).
5998 pub(crate) fn dspark_verify_t_logits_ckpt(
5999 &self,
6000 e: &Engine,
6001 tokens: &[u32],
6002 pos0: usize,
6003 cache: &mut Cache,
6004 ) -> Result<(CudaSlice<f32>, DsparkVerifyCkpt), Box<dyn std::error::Error>> {
6005 let mut ck = VerifyCkpt::new(self.layers.len());
6006 let (logits, _hn) = self.decode_step_t_core_stream(
6007 e,
6008 tokens,
6009 pos0,
6010 cache,
6011 None,
6012 Some(&mut ck),
6013 None,
6014 None,
6015 None,
6016 None,
6017 )?;
6018 Ok((logits, DsparkVerifyCkpt(ck)))
6019 }
6020
6021 /// Restore the round to `keep` accepted columns from the verify stash: KV lens and
6022 /// pos from the pre-verify snapshot + keep, GDN conv/ssm from the stashed column
6023 /// state — no replay forward. The exact `commit_verified_prefix` the MTP path ships.
6024 pub(crate) fn dspark_commit_prefix(
6025 &self,
6026 e: &Engine,
6027 cache: &mut Cache,
6028 snap: &crate::cache::CacheSnapshot,
6029 ckpt: &DsparkVerifyCkpt,
6030 keep: usize,
6031 ) -> Result<(), Box<dyn std::error::Error>> {
6032 self.commit_verified_prefix(e, cache, snap, &ckpt.0, keep, false, None)
6033 }
6034
6035 /// Slice-3 commit twin: restore to `keep` accepted columns when the round's linear
6036 /// column stash lives in the graphs ctx's persistent slabs (`DsparkVerifyGraphs`) —
6037 /// the cols arm's exact semantics (KV lens + pos from the snapshot, GDN conv/ssm
6038 /// from the stash of column keep-1), slab-addressed and batched into two copy
6039 /// launches. `MEMRA_STATE_COPY_BATCH=0` falls back to per-layer view copies.
6040 pub(crate) fn dspark_commit_prefix_slab(
6041 &self,
6042 e: &Engine,
6043 cache: &mut Cache,
6044 snap: &crate::cache::CacheSnapshot,
6045 ctx: &DsparkVerifyGraphs,
6046 keep: usize,
6047 ) -> Result<(), Box<dyn std::error::Error>> {
6048 use cudarc::driver::DevicePtr;
6049 debug_assert!(keep >= 1, "keep==0 rounds take the legacy rollback");
6050 let mut conv_src: Vec<u64> = Vec::new();
6051 let mut ssm_src: Vec<u64> = Vec::new();
6052 let mut conv_dst: Vec<u64> = Vec::new();
6053 let mut ssm_dst: Vec<u64> = Vec::new();
6054 for il in 0..self.layers.len() {
6055 if let (Some(kvl), Some(saved)) = (cache.kv[il].as_mut(), snap.kv_len[il]) {
6056 kvl.len = saved + keep;
6057 e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
6058 }
6059 if let Some(rl) = cache.recur[il].as_ref() {
6060 let (pc, ps, _cw, _sw) = ctx
6061 .slab_row(e, il, keep - 1)
6062 .ok_or("slab commit: linear layer missing from the graphs ctx")?;
6063 conv_src.push(pc);
6064 ssm_src.push(ps);
6065 let st = &e.gpu.stream();
6066 let (dc, _g0) = rl.conv_state.device_ptr(st);
6067 let (ds, _g1) = rl.ssm_state.device_ptr(st);
6068 conv_dst.push(dc as u64);
6069 ssm_dst.push(ds as u64);
6070 }
6071 }
6072 let n = conv_src.len();
6073 if n > 0 {
6074 if state_copy_batch_on() {
6075 let mut tt = vec![0u64; 2 * n];
6076 tt[..n].copy_from_slice(&conv_src);
6077 tt[n..].copy_from_slice(&conv_dst);
6078 let ct = e.htod_u64(&tt)?;
6079 tt[..n].copy_from_slice(&ssm_src);
6080 tt[n..].copy_from_slice(&ssm_dst);
6081 let st = e.htod_u64(&tt)?;
6082 e.copy_batch_uniform_f32(&ct, n, ctx.conv_words)?;
6083 e.copy_batch_uniform_f32(&st, n, ctx.ssm_words)?;
6084 } else {
6085 let (cw, sw) = (ctx.conv_words, ctx.ssm_words);
6086 let row = keep - 1;
6087 for il in 0..self.layers.len() {
6088 let Some(rl) = cache.recur[il].as_mut() else {
6089 continue;
6090 };
6091 let k = ctx.lin_pos[&il];
6092 {
6093 let sv = e.view(&ctx.stash_conv[k], (row + 1) * cw);
6094 let win = sv.slice(row * cw..(row + 1) * cw);
6095 e.copy_view_into(&mut rl.conv_state, 0, &win, cw)?;
6096 }
6097 {
6098 let sv = e.view(&ctx.stash_ssm[k], (row + 1) * sw);
6099 let win = sv.slice(row * sw..(row + 1) * sw);
6100 e.copy_view_into(&mut rl.ssm_state, 0, &win, sw)?;
6101 }
6102 }
6103 }
6104 }
6105 cache.pos = snap.pos + keep;
6106 Ok(())
6107 }
6108
6109 /// Qwen35-family verify trunk in the live serving numeric class.
6110 ///
6111 /// Serving intentionally keeps this architecture in the generic batched program even at
6112 /// B=1. The older verify walk used its own mirrored dispatch and can flip near-tie argmaxes.
6113 ///
6114 /// Two arms, one numeric class:
6115 /// - DENSE GDN (`DenseMlp`, t<=16): `qwen35_verify_tparallel` — the weight ops (norms,
6116 /// projections, FFN) hoist to m=T through the exact-tier batched kernels whose per-row
6117 /// program IS the m=1 program (`matmul_pre == fused2 per (tensor,row); _bN mmvq per-row
6118 /// == m=1` — decode_batch.rs v2 note), while the state ops (conv ring, gdn scan, KV
6119 /// append, fa decode) stay a per-row loop running the b_n=1 serving kernels with each
6120 /// row's own t_kv-driven arm pick (the straddle law: every row executes the exact
6121 /// program its isolated serving step would). One weight read per layer per round
6122 /// instead of T — this is what makes MTP profitable in the exact class (the per-row
6123 /// walk measured verify(K+1) ~= (K+1) plain steps: 69 -> 44 tok/s served, 2026-08-15).
6124 /// - MoE / t>16 / `MEMRA_SPEC_VERIFY_ROWWISE=1`: the per-row replay of the authoritative
6125 /// serving layer body, preserving single-session autoregressive cache order (the
6126 /// correctness reference; also the rollback seam for the t-parallel arm).
6127 ///
6128 /// Bit-identity of the t-parallel arm vs the rowwise arm is gated by spec-serve-gate
6129 /// (zero differing logits at T=1..4, K arms) + the 8-prompt ON/OFF canary before ship.
6130 #[allow(clippy::too_many_arguments)]
6131 fn qwen35_verify_batch_layers(
6132 &self,
6133 e: &Engine,
6134 x: CudaSlice<f32>,
6135 lo: usize,
6136 hi: usize,
6137 pos0: usize,
6138 t: usize,
6139 cache: &mut Cache,
6140 ckpt: Option<&mut VerifyCkpt>,
6141 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
6142 graphs: Option<&mut DsparkVerifyGraphs>,
6143 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
6144 // Qwen35Moe admitted 2026-08-20 (lane/draftcost-moe): the t-parallel arm already
6145 // carries the MoE FFN (`moe_ffn_il_zq8` at m=T) and the GDN per-row state loop; the
6146 // arch fence was a qualification gate, not a mechanism gap. Measured disease on the
6147 // 35B-A3B class: rowwise verify ~= 5.6 ms per drafted token (one full trunk step
6148 // each) — the same (K+1)-plain-steps wall the dense admission fixed on 2026-08-15.
6149 // Rollback seam unchanged: MEMRA_SPEC_VERIFY_ROWWISE=1.
6150 let rowwise = std::env::var("MEMRA_SPEC_VERIFY_ROWWISE").as_deref() == Ok("1")
6151 || !self.batched_serving_numeric_class()
6152 || t > 16;
6153 if rowwise {
6154 if stream.is_some() {
6155 // rowwise replays per row with host cache.pos — irreconcilable with a
6156 // device position counter. Burst callers must keep t <= 16 and the
6157 // ROWWISE env unset; refusing beats silently mispositioned rows.
6158 return Err("qwen35 rowwise verify has no ROUND-STREAM arm \
6159 (t > 16 or MEMRA_SPEC_VERIFY_ROWWISE=1)"
6160 .into());
6161 }
6162 self.qwen35_verify_rowwise(e, x, lo, hi, pos0, t, cache, ckpt)
6163 } else {
6164 self.qwen35_verify_tparallel(e, x, lo, hi, pos0, t, cache, ckpt, stream, graphs)
6165 }
6166 }
6167
6168 /// The per-row correctness reference: replay each verify row through the authoritative
6169 /// serving layer body (`decode_batch_layers` at b_n=1). T full weight reads per layer.
6170 #[allow(clippy::too_many_arguments)]
6171 fn qwen35_verify_rowwise(
6172 &self,
6173 e: &Engine,
6174 mut x: CudaSlice<f32>,
6175 lo: usize,
6176 hi: usize,
6177 pos0: usize,
6178 t: usize,
6179 cache: &mut Cache,
6180 mut ckpt: Option<&mut VerifyCkpt>,
6181 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
6182 let n_embd = self.cfg.n_embd as usize;
6183 let saved_pos = cache.pos;
6184 let mut ph_last = std::time::Instant::now();
6185 for il in lo..hi {
6186 let mut next = e.uninit(t * n_embd)?;
6187 let mut col_states: Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>> =
6188 if ckpt.is_some() && t >= 2 && matches!(self.layers[il].mixer, Mixer::Linear(_)) {
6189 Some(Vec::with_capacity(t - 1))
6190 } else {
6191 None
6192 };
6193 for r in 0..t {
6194 cache.pos = pos0 + r;
6195 let mut row = e.uninit(n_embd)?;
6196 e.dtod_copy_view(&x.slice(r * n_embd..(r + 1) * n_embd), &mut row)?;
6197 let row_pos = e.htod_i32(&[(pos0 + r) as i32])?;
6198 let mut one = [&mut *cache];
6199 let ctx = self.batch_layer_ctx(e, &one, il, il + 1)?;
6200 let out = match self.decode_batch_layers(
6201 e,
6202 row,
6203 &mut one,
6204 &ctx,
6205 &row_pos,
6206 &mut ph_last,
6207 ) {
6208 Ok(out) => out,
6209 Err(error) => {
6210 cache.pos = saved_pos;
6211 return Err(error);
6212 }
6213 };
6214 e.dtod_copy_into(&out, &mut next, r * n_embd)?;
6215 if r + 1 < t {
6216 if let Some(states) = col_states.as_mut() {
6217 let recur = cache.recur[il]
6218 .as_ref()
6219 .ok_or("Qwen35-MoE linear verify layer has no recurrent state")?;
6220 states.push((
6221 e.clone_dtod(&recur.conv_state)?,
6222 e.clone_dtod(&recur.ssm_state)?,
6223 ));
6224 }
6225 }
6226 }
6227 if let (Some(checkpoint), Some(states)) = (ckpt.as_deref_mut(), col_states) {
6228 checkpoint.cols[il] = Some(states);
6229 }
6230 x = next;
6231 }
6232 cache.pos = saved_pos;
6233 Ok(x)
6234 }
6235
6236 /// T-PARALLEL VERIFY IN THE SERVING NUMERIC CLASS (lane/tparallel-verify, 2026-08-15).
6237 ///
6238 /// The weight ops run ONCE per layer at m=T; the state ops run per row through the same
6239 /// b_n=1 serving kernels the rowwise replay uses. Per-row bit-identity rests on the two
6240 /// pins the serving batch tier already carries:
6241 /// * `matmul_pre` / `_bN` mmvq: per-row program == m=1 program (decode_batch.rs v2 note,
6242 /// kernel-check pinned) — so a [T, n_embd] projection row equals the row projected
6243 /// alone;
6244 /// * row-indexed norms/elementwise (`rms_norm`, `quantize_q8_1`, `add_rms_norm`,
6245 /// `gated_rmsnorm[_q8_1]`, `silu_mul`, `rope_neox` with per-row positions): the T-row
6246 /// launch is the per-row program (same pin the generic verify's fused norms rely on).
6247 /// The sequential dependencies keep their exact serving order: the conv ring / gdn scan
6248 /// chain state row -> row through the `_b` kernels at b_n=1 (ping-pong via a 6-entry
6249 /// alternating pointer table, host handles swapped per row so VerifyCkpt clones the
6250 /// canonical state exactly as the rowwise arm does), and each row's KV append + fa decode
6251 /// picks its arm from ITS OWN t_kv (append: format-only; fa: `fa_seqs_eligible` + its own
6252 /// `fa_split_keys` rung at b_n=1) — the straddle law per row, so every row executes the
6253 /// program its isolated B=1 serving step would.
6254 ///
6255 /// Cost: 1 weight read per layer per round + T state micro-launches, vs the rowwise arm's
6256 /// T weight reads. Gated bit-identical vs the rowwise arm by spec-serve-gate + canary.
6257 #[allow(clippy::too_many_arguments)]
6258 fn qwen35_verify_tparallel(
6259 &self,
6260 e: &Engine,
6261 mut x: CudaSlice<f32>,
6262 lo: usize,
6263 hi: usize,
6264 pos0: usize,
6265 t: usize,
6266 cache: &mut Cache,
6267 mut ckpt: Option<&mut VerifyCkpt>,
6268 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
6269 mut graphs: Option<&mut DsparkVerifyGraphs>,
6270 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
6271 let seqs_append =
6272 std::env::var("MEMRA_BATCH_APPEND").as_deref() != Ok("0") && !Engine::kv_fp8_on();
6273 let batch_fa_on = std::env::var("MEMRA_BATCH_FA").as_deref() != Ok("0");
6274
6275 // Merge guard (v0.98 train, re-affirmed on the v0.100 train over slice 4c): the
6276 // ROUND-STREAM arm (lane/draftcost-moe, device position counter) and the dspark
6277 // verify graphs (engine-bundle slice 3 / trunk slice 4c) have no common caller —
6278 // stream rides the qwen35moe burst, graphs ride the dspark route. If a future
6279 // caller arms both, refuse loudly instead of silently dropping the graphs ctx
6280 // (the stream linear arm takes linear_attn_verify_t, not the graphed segment or
6281 // full-verify bodies).
6282 if stream.is_some() && graphs.is_some() {
6283 return Err(
6284 "qwen35 tparallel verify: ROUND-STREAM and dspark verify graphs \
6285 cannot arm together"
6286 .into(),
6287 );
6288 }
6289 // Engine-bundle slice 3 + slice 4c: with a graphs ctx armed, pointer tables are
6290 // refreshed once per verify (the gdn ping-pong moves handles; a fresh generation
6291 // moves the kv caches). Then:
6292 // - slice 4c: when the WHOLE round rides one seqs rung (every row batchable, one
6293 // split-ladder step, rung covers the round), the ENTIRE walk replays as ONE
6294 // full-verify graph per (vt, rung) — linear layers through the shared
6295 // `qwen35_tparallel_linear_layer` body, full-attention layers through the
6296 // shared `qwen35_tparallel_fa_layer` body in graph mode.
6297 // - fallback (straddle rounds, below the vec floor, partial walks): runs of
6298 // consecutive LINEAR layers replay the slice-3 per-(segment, vt) graphs and
6299 // the full-attention layers run eager (batched rows when eligible).
6300 if let Some(g) = graphs.as_deref_mut() {
6301 g.refresh_tables(e, cache)?;
6302 g.round_slab = false;
6303 if let Some(rung) = g.full_rung(self, cache, lo, hi, t, seqs_append && batch_fa_on) {
6304 // Pool ceiling (dspark_vg_cap): an existing key always replays; a NEW
6305 // full capture past the ceiling falls through to the segment/eager arms.
6306 if g.full.contains_key(&(t, rung, hi)) || g.can_capture() {
6307 let out = g.run_full(self, e, lo, hi, &x, t, pos0, rung, cache)?;
6308 g.round_slab = true;
6309 return Ok(out);
6310 }
6311 }
6312 // Round-atomic ceiling check for the segment door: if any linear run in this
6313 // walk would need a NEW capture past the ceiling, the whole round runs the
6314 // eager cols-ckpt walk (mixing slab- and cols-stashed layers in one round
6315 // would corrupt the commit).
6316 if !g.segments_ready(self, lo, hi, t) {
6317 graphs = None;
6318 }
6319 }
6320 // STREAM (2b, lane/draftcost-moe): positions come from the device round counter
6321 // (pos_iota / i32_copy_add) so a burst round needs no host position knowledge.
6322 let pos_d = match stream {
6323 Some((_, ctr)) => {
6324 let mut p = e.alloc_uninit::<i32>(t)?;
6325 e.pos_iota(ctr, &mut p, t)?;
6326 p
6327 }
6328 None => {
6329 let pos_host: Vec<i32> = (0..t).map(|r| (pos0 + r) as i32).collect();
6330 e.htod_i32(&pos_host)?
6331 }
6332 };
6333 // Per-row 1-element position buffers, built ONCE per verify (the append/fa wrappers
6334 // take owned pos slices; building these inside the layer x row loops cost 16xT H2Ds).
6335 // LAZY since slice 4: the batched fa/append arm never touches them — they are built
6336 // on the first per-row fallback layer only (stream-aware there; the stream FA arm
6337 // rides the dc rows kernels and never reaches the fallback).
6338 let mut pos_rows: Option<Vec<CudaSlice<i32>>> = None;
6339 let mut il = lo;
6340 while il < hi {
6341 if graphs.is_some() && matches!(self.layers[il].mixer, Mixer::Linear(_)) {
6342 let mut end = il;
6343 while end < hi && matches!(self.layers[end].mixer, Mixer::Linear(_)) {
6344 end += 1;
6345 }
6346 let g = graphs.as_deref_mut().expect("checked above");
6347 x = g.run_segment(self, e, il, end, &x, t, cache)?;
6348 g.round_slab = true;
6349 il = end;
6350 continue;
6351 }
6352 let layer = &self.layers[il];
6353 if stream.is_none() && matches!(layer.mixer, Mixer::Linear(_)) {
6354 // Eager linear layer (no graphs ctx): the shared body, legacy cols-ckpt arm.
6355 // Under ROUND-STREAM the linear layers ride the fa-body match's stream arm
6356 // below (linear_attn_verify_t — the stream COMMIT needs its GdnStash).
6357 x = self.qwen35_tparallel_linear_layer(
6358 e,
6359 il,
6360 &x,
6361 t,
6362 cache,
6363 ckpt.as_deref_mut(),
6364 None,
6365 None,
6366 )?;
6367 il += 1;
6368 continue;
6369 }
6370 // Full-attention (or stream-Linear, or MLA-refusing) layer: the extracted
6371 // shared body — eager arm (fresh per-verify pos/table, exact t_kv sizing,
6372 // in-body len bump). The slice-4c captured full-verify graphs run the SAME
6373 // body in graph mode; under ROUND-STREAM the body's dc-rows / GDN stream arms
6374 // run (lane/draftcost-moe).
6375 x = self.qwen35_tparallel_fa_layer(
6376 e,
6377 il,
6378 &x,
6379 t,
6380 cache,
6381 FaLayerArgs {
6382 pos_d: &pos_d,
6383 pos_rows: &mut pos_rows,
6384 pos0,
6385 seqs_append,
6386 batch_fa_on,
6387 graph_cap: None,
6388 stream,
6389 ckpt: ckpt.as_deref_mut(),
6390 },
6391 )?;
6392 il += 1;
6393 }
6394 Ok(x)
6395 }
6396
6397 /// SHARED dense-FFN body for the qwen35 t-parallel layers (trunk-kernels slice B) —
6398 /// ONE copy for the fa and linear layer bodies (the verify_layers extraction lesson).
6399 /// Dual arm (MEMRA_TK_FFN_DUAL, default on): gate+up in ONE dual launch from the
6400 /// pre-quantized activation with macro-scales DEFERRED into the fused SwiGLU+q8_1
6401 /// epilogue, then ffn_down from the fused (aq, ad) — the q27 verify chain verbatim.
6402 /// Every door is the bit-identical proven one: `matmul_decode_exact_dual_pre` (per
6403 /// (tensor,token,row) == the two singles), `silu_mul_scaled_q8_1` (y*s inline == the
6404 /// scale_inplace store, value-exact; fused quantize == quantize_q8_1 bytes),
6405 /// `matmul_decode_exact_pre` (dispatch mirror of the singles' q8_1-fast tail).
6406 /// Dual-refused (t outside 2..=7, non-NVFP4, layout mismatch) or seam off -> the
6407 /// original singles chain, byte-for-byte.
6408 #[allow(clippy::too_many_arguments)]
6409 fn qwen35_tparallel_dense_ffn(
6410 &self,
6411 e: &Engine,
6412 ffn_gate: &crate::model::GpuTensor,
6413 ffn_up: &crate::model::GpuTensor,
6414 ffn_down: &crate::model::GpuTensor,
6415 zn: &CudaSlice<f32>,
6416 t: usize,
6417 n_embd: usize,
6418 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
6419 let n_ff = ffn_gate.out_features();
6420 let (zq, zd) = e.quantize_q8_1(zn, t, n_embd)?;
6421 if Engine::tk_ffn_dual_on() {
6422 if let Some(((g, gs), (u, us))) =
6423 e.matmul_decode_exact_dual_pre(ffn_gate, ffn_up, &zq, &zd, t)?
6424 {
6425 if e.uses_q8_1_fast(ffn_down) {
6426 let (aq, ad) = e.silu_mul_scaled_q8_1(&g, &u, gs, us, t * n_ff)?;
6427 return e.matmul_decode_exact_pre(ffn_down, &aq, &ad, t);
6428 }
6429 let mut act = e.uninit(t * n_ff)?;
6430 e.silu_mul_scaled(&g, &u, gs, us, &mut act, t * n_ff)?;
6431 let (aq, ad) = e.quantize_q8_1(&act, t, n_ff)?;
6432 return e.matmul_pre(ffn_down, &aq, &ad, &act, t);
6433 }
6434 }
6435 // v1 singles chain (seam off or dual-refused) — the pre-slice-B body verbatim.
6436 let g = e.matmul_pre(ffn_gate, &zq, &zd, zn, t)?;
6437 let u = e.matmul_pre(ffn_up, &zq, &zd, zn, t)?;
6438 let mut act = e.uninit(t * n_ff)?;
6439 e.silu_mul(&g, &u, &mut act, t * n_ff)?;
6440 let (aq, ad) = e.quantize_q8_1(&act, t, n_ff)?;
6441 e.matmul_pre(ffn_down, &aq, &ad, &act, t)
6442 }
6443
6444 /// ONE t-parallel FULL-ATTENTION layer (attn_norm + fa mixer + post_attn_norm + FFN +
6445 /// tap) — extracted from the walk exactly like `qwen35_tparallel_linear_layer` so the
6446 /// eager walk and the slice-4c captured full-verify graphs execute the SAME body (a
6447 /// second copy is how dispatch mirrors drift — the verify_layers extraction lesson).
6448 ///
6449 /// `args.graph_cap = Some((table, off, rung_end))` is the captured-graph mode:
6450 /// - kv base-pointer pairs come from the ctx-owned persistent table at `off` (a fresh
6451 /// generation's cache lands at new addresses that only the per-verify table refresh
6452 /// knows — the slice-3 baked-address lesson);
6453 /// - the seqs twins size partials/grid at `rung_end` and pin `split_keys` to the
6454 /// rung's ladder value: `n_splits_max` is pure stride, splits >= ns_eff write the
6455 /// EMPTY partial the combine never reads, and every per-row T_kv derives in-kernel
6456 /// from `pos_seq[z]` — so one captured launch replays bit-identically for every
6457 /// round whose rows all sit inside the rung;
6458 /// - the host len bump moves to the replay caller (captured host code does not
6459 /// re-run at replay).
6460 /// Graph mode REFUSES any round the batched arm cannot take: the per-row fallback
6461 /// host-branches on t_kv and must never be captured.
6462 #[allow(clippy::too_many_arguments)]
6463 fn qwen35_tparallel_fa_layer(
6464 &self,
6465 e: &Engine,
6466 il: usize,
6467 x: &CudaSlice<f32>,
6468 t: usize,
6469 cache: &mut Cache,
6470 args: FaLayerArgs<'_>,
6471 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
6472 use cudarc::driver::DevicePtr;
6473 let cfg = &self.cfg;
6474 let n_embd = cfg.n_embd as usize;
6475 let eps = cfg.rms_eps;
6476 let head_dim_global = cfg.head_dim_k as usize;
6477 let layer = &self.layers[il];
6478 let FaLayerArgs {
6479 pos_d,
6480 pos_rows,
6481 pos0,
6482 seqs_append,
6483 batch_fa_on,
6484 graph_cap,
6485 stream,
6486 mut ckpt,
6487 } = args;
6488
6489 // ---- attn_norm + q8_1 quantize at m=T (row-indexed == per-row) ----
6490 let anorm = layer.attn_norm.float_data();
6491 let mut xn = e.uninit(t * n_embd)?;
6492 e.rms_norm(x, anorm, &mut xn, n_embd, t, eps)?;
6493 let (hq, hd) = e.quantize_q8_1(&xn, t, n_embd)?;
6494
6495 let mixed: CudaSlice<f32> = match &layer.mixer {
6496 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
6497 // STREAM ARM (2b, lane/draftcost-moe): under a device position counter the
6498 // per-row serving-kernel chain cannot run (host state swaps keyed on host
6499 // row index are fine, but the stream COMMIT needs the GdnStash for its _dc
6500 // rebuild — the per-row chain only produces per-column clones). GDN rides
6501 // `linear_attn_verify_t`: batched q8_1-class projections, stash-producing,
6502 // and its one-scan recurrence is pinned bit-identical to T chained T=1
6503 // steps (its header + kernel-check). Position-independent, so no counter
6504 // plumbing is needed. Guards mirror the generic call site exactly.
6505 Mixer::Linear(la) if stream.is_some() => {
6506 if !(t >= 3 || (t == 2 && spec_m2()))
6507 || !self.mixer_in_q8_1_fast(e, &layer.mixer)
6508 || !e.uses_q8_1_fast(&la.ssm_out)
6509 {
6510 return Err("qwen35 stream verify: GDN batched arm requires t>=3 \
6511 (or MEMRA_SPEC_M2 at t=2) and q8_1-fast projections"
6512 .into());
6513 }
6514 let want = ckpt.is_some();
6515 let (out, stash) =
6516 self.linear_attn_verify_t(e, la, &xn, Some((&hq, &hd)), t, cache, il, want)?;
6517 if let (Some(ck), Some(st)) = (ckpt.as_deref_mut(), stash) {
6518 ck.gdn[il] = Some(st);
6519 }
6520 out
6521 }
6522 Mixer::Linear(_) => {
6523 unreachable!("linear layers ride qwen35_tparallel_linear_layer")
6524 }
6525 Mixer::Full(fa) => {
6526 let geometry = cfg.full_attention_geometry_at(il as u32);
6527 let n_head = geometry.n_head as usize;
6528 let n_head_kv = geometry.n_head_kv as usize;
6529 let head_dim = geometry.head_dim_k as usize;
6530 let rope_dims = geometry.n_rot as usize;
6531 let rope_base = geometry.rope_base;
6532 let scale = geometry.attention_scale();
6533 // Batched projections: one weight read serves all T rows.
6534 // GROUP-3 twin (trunk-kernels slice D): q/k/v in ONE launch — the group4
6535 // kernel with n3=0, bit-identical per (tensor, token, row) to the three
6536 // singles; refused or MEMRA_TK_FA_GROUP=0 -> singles byte-for-byte.
6537 let (qf, mut k, v) = match e.matmul_decode_exact_group3_pre(
6538 [&fa.wq, &fa.wk, &fa.wv],
6539 &hq,
6540 &hd,
6541 t,
6542 )? {
6543 Some(mut g3) => {
6544 let v = g3.pop().unwrap();
6545 let k = g3.pop().unwrap();
6546 let qf = g3.pop().unwrap();
6547 (qf, k, v)
6548 }
6549 None => (
6550 e.matmul_pre(&fa.wq, &hq, &hd, &xn, t)?,
6551 e.matmul_pre(&fa.wk, &hq, &hd, &xn, t)?,
6552 e.matmul_pre(&fa.wv, &hq, &hd, &xn, t)?,
6553 ),
6554 };
6555 let gated =
6556 geometry.attention_gate == memra_gguf::config::AttentionGateKind::FusedQ;
6557 let (mut q, gate) = if gated {
6558 let mut qs = e.uninit(t * n_head * head_dim)?;
6559 let mut gs = e.uninit(t * n_head * head_dim)?;
6560 e.q_gate_split(&qf, &mut qs, &mut gs, head_dim, n_head, t)?;
6561 (qs, Some(gs))
6562 } else {
6563 (qf, None)
6564 };
6565 let mut qn = e.uninit(t * n_head * head_dim)?;
6566 e.rms_norm(
6567 &q,
6568 fa.q_norm.float_data(),
6569 &mut qn,
6570 head_dim,
6571 t * n_head,
6572 eps,
6573 )?;
6574 q = qn;
6575 let mut kn = e.uninit(t * n_head_kv * head_dim)?;
6576 e.rms_norm(
6577 &k,
6578 fa.k_norm.float_data(),
6579 &mut kn,
6580 head_dim,
6581 t * n_head_kv,
6582 eps,
6583 )?;
6584 k = kn;
6585 e.rope_neox(
6586 &mut q, pos_d, head_dim, rope_dims, n_head, t, rope_base, 1.0,
6587 )?;
6588 e.rope_neox(
6589 &mut k, pos_d, head_dim, rope_dims, n_head_kv, t, rope_base, 1.0,
6590 )?;
6591
6592 // Per-row append + attend: row r sees rows 0..r in KV (causal within the
6593 // draft), each through the b_n=1 serving kernels at its own t_kv.
6594 let q_dim = n_head * head_dim;
6595 let kv_dim = n_head_kv * head_dim;
6596 let mut attn = e.uninit(t * q_dim)?;
6597 let (kdk, kdv, ktb, vtb, len0, kv_local) = {
6598 let kvl = cache.kv[il].as_ref().unwrap();
6599 // [2T] interleaved k,v base pointers: entry pair z serves row z of
6600 // the batched twins; the per-row fallback reads pair 0 (same cache
6601 // for every row of one layer). Graph mode reads the ctx table.
6602 let local: Option<CudaSlice<u64>> = match graph_cap {
6603 Some(_) => None,
6604 None => {
6605 let s = &e.gpu.stream();
6606 let (pk, _g) = kvl.k.device_ptr(s);
6607 let (pv, _g2) = kvl.v.device_ptr(s);
6608 let mut tbl = Vec::with_capacity(2 * t);
6609 for _ in 0..t {
6610 tbl.push(pk as u64);
6611 tbl.push(pv as u64);
6612 }
6613 Some(e.htod_u64(&tbl)?)
6614 }
6615 };
6616 (
6617 kvl.kv_dim_k,
6618 kvl.kv_dim_v,
6619 kvl.k_tok_bytes,
6620 kvl.v_tok_bytes,
6621 kvl.len,
6622 local,
6623 )
6624 };
6625 let (kv_tbl, kv_off): (&CudaSlice<u64>, usize) = match graph_cap {
6626 Some((tb, off, _)) => (tb, off),
6627 None => (kv_local.as_ref().expect("built above"), 0),
6628 };
6629 // Slice 4 (fa/append rows — see dspark_fa_rows_on): the whole per-row
6630 // section batches into the z-batched serving twins when every row of
6631 // this round takes the v4-seqs arm on ONE fa_split_keys rung. Both
6632 // guards are evaluated at the round's FIRST and LAST t_kv — the
6633 // eligibility window (vec floor .. v4 max) and each split-ladder rung
6634 // are intervals in t_kv, so ends-inside means all-inside (the straddle
6635 // law). Appending all T rows before any attend is read-equivalent to
6636 // the interleaved order: row r's walk reads keys 0..len0+r only, and
6637 // rows > r land at slots it never touches; every written cache row is
6638 // the per-token appender's exact warp program (kernel-check pinned).
6639 let t_kv_first = len0 + 1;
6640 let t_kv_last = len0 + t;
6641 let rows_batched = t >= 2
6642 && seqs_append
6643 && batch_fa_on
6644 && dspark_fa_rows_on()
6645 // the z-batched twins read stacked rows at the CACHE's kv dims;
6646 // the projection stack is [T, n_head_kv*head_dim] — they must be
6647 // the same stride or row z misaligns (true for this family; the
6648 // guard keeps any asymmetric-kv model on the per-row loop).
6649 && kdk == kv_dim
6650 && kdv == kv_dim
6651 && crate::fa_seqs_eligible(t_kv_first, head_dim_global)
6652 && crate::fa_seqs_eligible(t_kv_last, head_dim_global)
6653 && crate::fa_split_keys(t_kv_first, cfg.n_head_kv as usize)
6654 == crate::fa_split_keys(t_kv_last, cfg.n_head_kv as usize);
6655 // Sizing: eager = exact round bound; graph mode = the rung end (stride +
6656 // grid only — bytes proven equal above). Capture-time invariants refuse
6657 // loudly rather than bake a divergent body.
6658 let (size_kv_max, sp) = match graph_cap {
6659 Some((_, _, rung)) => {
6660 if !rows_batched {
6661 return Err(format!(
6662 "fa graph capture: layer {il} round is not batchable \
6663 (t_kv {t_kv_first}..{t_kv_last}) — the per-row fallback \
6664 must never be captured"
6665 )
6666 .into());
6667 }
6668 let sp_r = crate::fa_split_keys(rung, cfg.n_head_kv as usize);
6669 if t_kv_last > rung
6670 || sp_r != crate::fa_split_keys(t_kv_last, cfg.n_head_kv as usize)
6671 {
6672 return Err(format!(
6673 "fa graph capture: rung {rung} does not cover round \
6674 t_kv {t_kv_first}..{t_kv_last} on one split ladder step"
6675 )
6676 .into());
6677 }
6678 (rung, sp_r)
6679 }
6680 None => (
6681 t_kv_last,
6682 crate::fa_split_keys(t_kv_last, cfg.n_head_kv as usize),
6683 ),
6684 };
6685 if let Some((_, ctr)) = stream {
6686 // STREAM ARM (2b): one batched dc append + the multi-row dc attention
6687 // — the generic stream arm's exact shape (rows kernels are pinned
6688 // byte-identical to the per-row programs by kernel-check). Host len
6689 // stays a stale lower bound; the burst drain reconciles it.
6690 let kvl = cache.kv[il].as_mut().unwrap();
6691 e.append_kv_quantized_rows_dc(
6692 &k,
6693 &v,
6694 &mut kvl.k,
6695 &mut kvl.v,
6696 ctr,
6697 t,
6698 kdk,
6699 kdv,
6700 ktb,
6701 vtb,
6702 Engine::kv_fp8_on(),
6703 )?;
6704 let upper = (kvl.len + t + 64).min(cache.max_ctx);
6705 let k_view = e.view_u8(&kvl.k, upper * ktb);
6706 let v_view = e.view_u8(&kvl.v, upper * vtb);
6707 e.fa_decode_rows_dc(
6708 &q, &k_view, &v_view, &mut attn, head_dim, n_head, n_head_kv, ctr, upper,
6709 t, scale, ktb, vtb, 0, false,
6710 )?;
6711 } else if rows_batched {
6712 e.append_kv_quantized_seqs(
6713 &k,
6714 &v,
6715 &kv_tbl.slice(kv_off..kv_off + 2 * t),
6716 pos_d,
6717 t,
6718 kdk,
6719 kdv,
6720 ktb,
6721 vtb,
6722 )?;
6723 if graph_cap.is_none() {
6724 cache.kv[il].as_mut().unwrap().len += t;
6725 }
6726 e.fa_decode_batch_seqs_v4(
6727 &q,
6728 &kv_tbl.slice(kv_off..kv_off + 2 * t),
6729 pos_d,
6730 &mut attn,
6731 head_dim,
6732 n_head,
6733 n_head_kv,
6734 t,
6735 size_kv_max,
6736 scale,
6737 sp,
6738 ktb,
6739 vtb,
6740 )?;
6741 } else {
6742 if pos_rows.is_none() {
6743 // Stream-aware for symmetry with pos_d (the stream FA arm rides
6744 // the dc rows kernels above and never reaches this fallback).
6745 *pos_rows = Some(match stream {
6746 Some((_, ctr)) => (0..t)
6747 .map(|r| {
6748 let mut b = e.alloc_uninit::<i32>(1)?;
6749 e.i32_copy_add(ctr, &mut b, r as i32)?;
6750 Ok(b)
6751 })
6752 .collect::<Result<_, Box<dyn std::error::Error>>>()?,
6753 None => (0..t)
6754 .map(|r| e.htod_i32(&[(pos0 + r) as i32]))
6755 .collect::<Result<_, _>>()?,
6756 });
6757 }
6758 let pos_rows = pos_rows.as_ref().unwrap();
6759 for r in 0..t {
6760 // Owned per-row scratch: the b_n=1 kernels take packed batch buffers
6761 // whose row 0 is this row (arithmetic-free materialization copies,
6762 // same as decode's per-seq fallback arm).
6763 let mut k_row = e.uninit(kv_dim)?;
6764 e.dtod_copy_view(&k.slice(r * kv_dim..(r + 1) * kv_dim), &mut k_row)?;
6765 let mut v_row = e.uninit(kv_dim)?;
6766 e.dtod_copy_view(&v.slice(r * kv_dim..(r + 1) * kv_dim), &mut v_row)?;
6767 let pos_row = &pos_rows[r];
6768 let kvl = cache.kv[il].as_mut().unwrap();
6769 if seqs_append {
6770 e.append_kv_quantized_seqs(
6771 &k_row,
6772 &v_row,
6773 &kv_tbl.slice(kv_off..kv_off + 2),
6774 pos_row,
6775 1,
6776 kdk,
6777 kdv,
6778 ktb,
6779 vtb,
6780 )?;
6781 kvl.len += 1;
6782 } else {
6783 e.append_kv_quantized_view(
6784 &k_row.slice(0..kv_dim),
6785 &v_row.slice(0..kv_dim),
6786 &mut kvl.k,
6787 &mut kvl.v,
6788 kvl.len,
6789 kvl.kv_dim_k,
6790 kvl.kv_dim_v,
6791 kvl.k_tok_bytes,
6792 kvl.v_tok_bytes,
6793 Engine::kv_fp8_on(),
6794 )?;
6795 kvl.len += 1;
6796 }
6797 let t_kv = kvl.len;
6798 let mut q_row = e.uninit(q_dim)?;
6799 e.dtod_copy_view(&q.slice(r * q_dim..(r + 1) * q_dim), &mut q_row)?;
6800 let mut a_row = e.uninit(q_dim)?;
6801 if batch_fa_on && crate::fa_seqs_eligible(t_kv, head_dim_global) {
6802 let sp0_r = crate::fa_split_keys(t_kv, cfg.n_head_kv as usize);
6803 e.fa_decode_batch_seqs_v4(
6804 &q_row,
6805 &kv_tbl.slice(kv_off..kv_off + 2),
6806 pos_row,
6807 &mut a_row,
6808 head_dim,
6809 n_head,
6810 n_head_kv,
6811 1,
6812 t_kv,
6813 scale,
6814 sp0_r,
6815 ktb,
6816 vtb,
6817 )?;
6818 } else {
6819 let k_view = e.view_u8(&kvl.k, t_kv * kvl.k_tok_bytes);
6820 let v_view = e.view_u8(&kvl.v, t_kv * kvl.v_tok_bytes);
6821 let mut a_view = a_row.slice_mut(0..q_dim);
6822 e.fa_decode_kvmod_view(
6823 &q_row.slice(0..q_dim),
6824 &k_view,
6825 &v_view,
6826 &mut a_view,
6827 head_dim,
6828 n_head,
6829 n_head_kv,
6830 t_kv,
6831 scale,
6832 kvl.k_tok_bytes,
6833 kvl.v_tok_bytes,
6834 Engine::kv_fp8_on(),
6835 )?;
6836 }
6837 e.dtod_copy_into(&a_row, &mut attn, r * q_dim)?;
6838 }
6839 }
6840
6841 // Output gate (element-wise) + o-proj at m=T.
6842 let attn_g = match &gate {
6843 Some(g) => {
6844 let n = t * q_dim;
6845 let mut gsig = e.uninit(n)?;
6846 e.sigmoid(g, &mut gsig, n)?;
6847 let mut ag = e.uninit(n)?;
6848 e.mul(&attn, &gsig, &mut ag, n)?;
6849 ag
6850 }
6851 None => attn,
6852 };
6853 e.matmul(&fa.wo, &attn_g, t)?
6854 }
6855 };
6856
6857 // ---- residual add + post_attn_norm + FFN at m=T (serving dispatch verbatim) ----
6858 let pnorm = layer.post_attn_norm.float_data();
6859 let mut x1 = e.uninit(t * n_embd)?;
6860 let mut zn = e.uninit(t * n_embd)?;
6861 e.add_rms_norm(x, &mixed, pnorm, &mut x1, &mut zn, n_embd, t, eps)?;
6862 let ffn_out = match &layer.ffn {
6863 crate::hybrid::Ffn::Dense {
6864 ffn_gate,
6865 ffn_up,
6866 ffn_down,
6867 } => {
6868 assert!(
6869 self.cfg.m3.is_none(),
6870 "qwen35 t-parallel verify: M3 swigluoai FFN not yet batched"
6871 );
6872 self.qwen35_tparallel_dense_ffn(e, ffn_gate, ffn_up, ffn_down, &zn, t, n_embd)?
6873 }
6874 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il_zq8(e, m, &zn, None, t, il as u16)?,
6875 };
6876 let mut x2 = e.uninit(t * n_embd)?;
6877 e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
6878 // dspark drafter tap (no-op when no sink armed): post-layer residual verify rows
6879 self.dflash_tap(e, cache, il, &x2, t)?;
6880 Ok(x2)
6881 }
6882
6883 /// ONE t-parallel LINEAR layer (attn_norm + gdn mixer + post_attn_norm + FFN + tap) —
6884 /// the exact body the old in-loop Linear arm ran, extracted so the eager walk and the
6885 /// slice-3 captured segments execute the SAME code (a second copy is how dispatch
6886 /// mirrors drift — the verify_layers extraction lesson). Two deliberate changes, both
6887 /// bit-identical by construction:
6888 /// - the gdn ping-pong host swap moves from per-row to ONE end-of-body swap (t odd):
6889 /// the device sequence is driven entirely by the 6-entry pointer table, which
6890 /// already encodes both parities; the ckpt stash reads name row r's out buffer
6891 /// directly (r even -> alt handle, odd -> canonical) — the same physical bytes the
6892 /// legacy post-swap clone read.
6893 /// - `stash` (slice-3 ctx): persistent per-layer slabs written by copy_into instead of
6894 /// per-row clone_dtod allocs — same bytes, capture-legal (no per-round host objects).
6895 /// `table_src` = (persistent pointer table, offset) when the ctx owns the tables;
6896 /// None builds the per-verify table exactly as before.
6897 #[allow(clippy::too_many_arguments)]
6898 fn qwen35_tparallel_linear_layer(
6899 &self,
6900 e: &Engine,
6901 il: usize,
6902 x: &CudaSlice<f32>,
6903 t: usize,
6904 cache: &mut Cache,
6905 mut ckpt: Option<&mut VerifyCkpt>,
6906 stash: Option<(&mut CudaSlice<f32>, &mut CudaSlice<f32>)>,
6907 table_src: Option<(&CudaSlice<u64>, usize)>,
6908 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
6909 use cudarc::driver::DevicePtr;
6910 let cfg = &self.cfg;
6911 let n_embd = cfg.n_embd as usize;
6912 let eps = cfg.rms_eps;
6913 let layer = &self.layers[il];
6914 let Mixer::Linear(la) = &layer.mixer else {
6915 return Err("qwen35_tparallel_linear_layer on a non-linear layer".into());
6916 };
6917 // ---- attn_norm + q8_1 quantize at m=T (row-indexed == per-row) ----
6918 let anorm = layer.attn_norm.float_data();
6919 let mut xn = e.uninit(t * n_embd)?;
6920 e.rms_norm(x, anorm, &mut xn, n_embd, t, eps)?;
6921 let (hq, hd) = e.quantize_q8_1(&xn, t, n_embd)?;
6922
6923 let geometry = la.geometry;
6924 let d_state = geometry.key_head_dim as usize;
6925 let num_k = geometry.key_heads as usize;
6926 let num_v = geometry.value_heads as usize;
6927 let d_conv = geometry.conv_kernel as usize;
6928 let key_dim = d_state * num_k;
6929 let value_dim = geometry.value_head_dim as usize * num_v;
6930 let conv_dim = key_dim * 2 + value_dim;
6931 let gdn_scale = 1.0 / (d_state as f32).sqrt();
6932
6933 // ---- batched projections: one weight read for all T rows ----
6934 // GROUP-4 twin (trunk-kernels slice C): the whole 4-tuple in ONE launch, bit-identical
6935 // per (tensor, token, row) to the four singles; refused (layout/tier) or
6936 // MEMRA_TK_GDN_GROUP=0 -> the singles chain byte-for-byte.
6937 let (qkv_mixed, z, beta_raw, alpha) = match e.matmul_decode_exact_group4_pre(
6938 [&la.wqkv, &la.wqkv_gate, &la.ssm_beta, &la.ssm_alpha],
6939 &hq,
6940 &hd,
6941 t,
6942 )? {
6943 Some(mut g4) => {
6944 let alpha = g4.pop().unwrap();
6945 let beta_raw = g4.pop().unwrap();
6946 let z = g4.pop().unwrap();
6947 let qkv_mixed = g4.pop().unwrap();
6948 (qkv_mixed, z, beta_raw, alpha)
6949 }
6950 None => (
6951 e.matmul_pre(&la.wqkv, &hq, &hd, &xn, t)?,
6952 e.matmul_pre(&la.wqkv_gate, &hq, &hd, &xn, t)?,
6953 e.matmul_pre(&la.ssm_beta, &hq, &hd, &xn, t)?,
6954 e.matmul_pre(&la.ssm_alpha, &hq, &hd, &xn, t)?,
6955 ),
6956 };
6957 let beta_w = la.ssm_beta.out_features();
6958 let alpha_w = la.ssm_alpha.out_features();
6959 let qkv_w = la.wqkv.out_features();
6960
6961 // ---- per-row state chain through the b_n=1 serving kernels ----
6962 // 6-entry alternating pointer table expresses the ping-pong without a rebuild per
6963 // row: even rows scan s0 -> s1, odd rows s1 -> s0.
6964 let table_local: Option<CudaSlice<u64>> = match table_src {
6965 Some(_) => None,
6966 None => {
6967 let rl = cache.recur[il].as_ref().unwrap();
6968 let s = &e.gpu.stream();
6969 let (pc, _g0) = rl.conv_state.device_ptr(s);
6970 let (p0, _g1) = rl.ssm_state.device_ptr(s);
6971 let (p1, _g2) = rl.ssm_state_alt.device_ptr(s);
6972 Some(e.htod_u64(&[
6973 pc as u64, p0 as u64, p1 as u64, pc as u64, p1 as u64, p0 as u64,
6974 ])?)
6975 }
6976 };
6977 let (table, toff): (&CudaSlice<u64>, usize) = match table_src {
6978 Some((tb, off)) => (tb, off),
6979 None => (table_local.as_ref().unwrap(), 0),
6980 };
6981 let mut o_all = e.uninit(t * value_dim)?;
6982 let mut col_states: Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>> =
6983 if ckpt.is_some() && stash.is_none() && t >= 2 {
6984 Some(Vec::with_capacity(t - 1))
6985 } else {
6986 None
6987 };
6988 let mut stash = stash;
6989 // Per-row scratch reused across rows (uninit is cheap but not free at
6990 // 48 layers x T rows); row inputs/outputs pass as VIEWS into the packed
6991 // [T, ...] buffers — zero arithmetic-free copies in this loop.
6992 let mut conv_out = e.uninit(conv_dim)?;
6993 let mut q_l2 = e.uninit(value_dim)?;
6994 let mut k_l2 = e.uninit(value_dim)?;
6995 let mut v_gd = e.uninit(value_dim)?;
6996 let mut beta_b = e.uninit(num_v)?;
6997 let mut g_log = e.uninit(num_v)?;
6998 for r in 0..t {
6999 let base = toff + if r % 2 == 0 { 0 } else { 3 };
7000 let conv_view = table.slice(base..base + 1);
7001 let in_view = table.slice(base + 1..base + 2);
7002 let out_view = table.slice(base + 2..base + 3);
7003 e.ssm_conv1d_fused_decode_b_view(
7004 &qkv_mixed.slice(r * qkv_w..(r + 1) * qkv_w),
7005 &conv_view,
7006 la.ssm_conv1d.float_data(),
7007 &mut conv_out,
7008 conv_dim,
7009 d_conv,
7010 1,
7011 )?;
7012 e.gdn_prep_decode_b_view(
7013 &conv_out,
7014 &beta_raw.slice(r * beta_w..(r + 1) * beta_w),
7015 &alpha.slice(r * alpha_w..(r + 1) * alpha_w),
7016 la.ssm_dt.float_data(),
7017 la.ssm_a.float_data(),
7018 &mut q_l2,
7019 &mut k_l2,
7020 &mut v_gd,
7021 &mut beta_b,
7022 &mut g_log,
7023 d_state,
7024 num_v,
7025 num_k,
7026 key_dim,
7027 eps,
7028 conv_dim,
7029 1,
7030 )?;
7031 let mut o_row = o_all.slice_mut(r * value_dim..(r + 1) * value_dim);
7032 e.gdn_scan_s128_batched_view(
7033 &q_l2, &k_l2, &v_gd, &g_log, &beta_b, &in_view, &out_view, &mut o_row, num_v, 1,
7034 gdn_scale,
7035 )?;
7036 if r + 1 < t {
7037 // Row r's out buffer: even rows write s1 (the alt handle — no swaps ran),
7038 // odd rows write s0 — the same physical state the legacy post-swap
7039 // canonical clone read.
7040 let rl = cache.recur[il]
7041 .as_ref()
7042 .ok_or("qwen35 linear verify layer has no recurrent state")?;
7043 let ssm_src = if r % 2 == 0 {
7044 &rl.ssm_state_alt
7045 } else {
7046 &rl.ssm_state
7047 };
7048 match stash.as_mut() {
7049 Some((conv_slab, ssm_slab)) => {
7050 // BOTH stash reads go through the pointer table at run time: the
7051 // ssm handles ping-pong between rounds, and the ctx (with its
7052 // captured graphs) outlives the Cache — a fresh generation's
7053 // conv/ssm buffers land at new addresses that only the per-round
7054 // table refresh knows. A baked direct copy would read freed
7055 // memory (parity was the slice-3 smoke divergence; cache
7056 // lifetime is the cross-generation twin).
7057 e.copy_indirect_src_f32(
7058 &conv_view,
7059 conv_slab,
7060 r * conv_dim * (d_conv - 1),
7061 conv_dim * (d_conv - 1),
7062 )?;
7063 // The ssm handles PING-PONG between rounds: a captured direct
7064 // copy would bake the capture-time physical buffer and read the
7065 // wrong parity after any odd-vt round (the slice-3 smoke
7066 // divergence). Read the src address from row r's OUT table
7067 // entry at run time — the same entry the scan just wrote.
7068 e.copy_indirect_src_f32(
7069 &out_view,
7070 ssm_slab,
7071 r * d_state * d_state * num_v,
7072 d_state * d_state * num_v,
7073 )?;
7074 }
7075 None => {
7076 if let Some(states) = col_states.as_mut() {
7077 states.push((e.clone_dtod(&rl.conv_state)?, e.clone_dtod(ssm_src)?));
7078 }
7079 }
7080 }
7081 }
7082 }
7083 // ONE end-of-body parity swap (t odd) — the legacy loop swapped per row; the net
7084 // handle motion is identical and the device sequence never read the handles.
7085 if t % 2 == 1 {
7086 let rl = cache.recur[il].as_mut().unwrap();
7087 std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
7088 }
7089 if let (Some(checkpoint), Some(states)) = (ckpt.as_deref_mut(), col_states) {
7090 checkpoint.cols[il] = Some(states);
7091 }
7092
7093 // ---- batched gated norm + out-projection at m=T ----
7094 let mixed = if e.uses_q8_1_fast(&la.ssm_out) {
7095 let (gq, gd) = e.gated_rmsnorm_q8_1(
7096 &o_all,
7097 la.ssm_norm.float_data(),
7098 &z,
7099 d_state,
7100 t * num_v,
7101 eps,
7102 )?;
7103 let g0 = e.zeros(0)?;
7104 e.matmul_pre(&la.ssm_out, &gq, &gd, &g0, t)?
7105 } else {
7106 let mut gn = e.uninit(t * value_dim)?;
7107 e.gated_rmsnorm(
7108 &o_all,
7109 la.ssm_norm.float_data(),
7110 &z,
7111 &mut gn,
7112 d_state,
7113 t * num_v,
7114 eps,
7115 )?;
7116 e.matmul(&la.ssm_out, &gn, t)?
7117 };
7118
7119 // ---- residual add + post_attn_norm + FFN at m=T (serving dispatch verbatim) ----
7120 let pnorm = layer.post_attn_norm.float_data();
7121 let mut x1 = e.uninit(t * n_embd)?;
7122 let mut zn = e.uninit(t * n_embd)?;
7123 e.add_rms_norm(x, &mixed, pnorm, &mut x1, &mut zn, n_embd, t, eps)?;
7124 let ffn_out = match &layer.ffn {
7125 crate::hybrid::Ffn::Dense {
7126 ffn_gate,
7127 ffn_up,
7128 ffn_down,
7129 } => {
7130 assert!(
7131 self.cfg.m3.is_none(),
7132 "qwen35 t-parallel verify: M3 swigluoai FFN not yet batched"
7133 );
7134 self.qwen35_tparallel_dense_ffn(e, ffn_gate, ffn_up, ffn_down, &zn, t, n_embd)?
7135 }
7136 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il_zq8(e, m, &zn, None, t, il as u16)?,
7137 };
7138 let mut x2 = e.uninit(t * n_embd)?;
7139 e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
7140 // dspark drafter tap (no-op when no sink armed): post-layer residual verify rows
7141 self.dflash_tap(e, cache, il, &x2, t)?;
7142 Ok(x2)
7143 }
7144
7145 /// PP-N STAGE SUBGRAPH of the verify trunk: layers `[lo, hi)` of `decode_step_t_core_stream`'s
7146 /// walk, verbatim. Enters with a MATERIALIZED `[T, n_embd]` residual (no pending fusion pair
7147 /// carried in from outside the range) and exits with the range's final residual materialized
7148 /// (the trailing add executed) — exactly the `decode_layers_eager(lo, hi)` contract, T rows
7149 /// instead of one.
7150 ///
7151 /// EXTRACTED (lane/pp2-spec 2026-08-06) rather than duplicated: `decode_step_t_core_stream` IS
7152 /// the single funnel every verify forward reaches, and its per-layer dispatch MIRRORING (norm
7153 /// fusion per layer, the t>=3/spec_m2 batched-linear window, the fused-q8 FFN chain, the
7154 /// decode-exact projections) is what makes verify bit-identical to eager decode. A second copy
7155 /// for the split arm is how those mirrors drift apart on the next lever. The unsplit body now
7156 /// calls this with `(0, n_layers)`, so the whole-trunk path and every stage range run the SAME
7157 /// code — there is no "split version" of the verify math.
7158 ///
7159 /// Bit-identity of a cut rests on the same kernel-check-pinned identity the eager arm's cut
7160 /// does — `add_rms_norm_q8_1 == add then rms_norm_q8_1` at nrows=T — because the ONLY thing a
7161 /// fence changes is that the cross-layer fusion carry breaks at `hi-1` and is re-materialized
7162 /// as an explicit `add`. `decode-batch-gate --mode ppspec` verifies end-to-end on real weights.
7163 #[allow(clippy::too_many_arguments)]
7164 fn verify_layers(
7165 &self,
7166 e: &Engine,
7167 mut x: CudaSlice<f32>,
7168 lo: usize,
7169 hi: usize,
7170 pos_d: &CudaSlice<i32>,
7171 pos0: usize,
7172 t: usize,
7173 cache: &mut Cache,
7174 mut ckpt: Option<&mut VerifyCkpt>,
7175 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
7176 graphs: Option<&mut DsparkVerifyGraphs>,
7177 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
7178 if self.sliding_gated_moe_batch_program() {
7179 if stream.is_some() {
7180 return Err(
7181 "step35 has no ROUND-STREAM verify arm (the device-counter _dc twins \
7182 cannot express the SWA offset KV view)"
7183 .into(),
7184 );
7185 }
7186 return self.step35_verify_batch_layers(e, x, lo, hi, pos0, t, cache);
7187 }
7188 if self.batched_serving_numeric_class() {
7189 return self.qwen35_verify_batch_layers(
7190 e,
7191 x,
7192 lo,
7193 hi,
7194 pos0,
7195 t,
7196 cache,
7197 ckpt.take(),
7198 stream,
7199 graphs,
7200 );
7201 }
7202 let n_embd = self.cfg.n_embd as usize;
7203 let eps = self.cfg.rms_eps;
7204 // CROSS-LAYER ADD+NORM FUSION (lane/vt-fixes fix 2, mirroring decode_step_h's
7205 // launch-arc form): layer il's post-FFN residual add (x2 = x1 + ffn_out) and layer
7206 // il+1's attn_norm(+quantize) are consecutive row-wise ops — ONE add_rms_norm_q8_1
7207 // launch at nrows=t does all three (bit-identity pinned by the T-row kernel-check
7208 // arms). Carry the un-added (x1, ffn_out) pair; the fused launch materializes x2 (the
7209 // residual the next layer needs) as its `res` output. Falls back to the separate add
7210 // when the next layer is off the fused-q8 path.
7211 let mut pending: Option<(CudaSlice<f32>, CudaSlice<f32>)> = None;
7212 for il in lo..hi {
7213 let layer = &self.layers[il];
7214 // DISPATCH-MIRRORED attn-input RMSNorm (FP-order lesson #8): eager decode fuses the
7215 // 1024-thread rms_norm_q8_1 ONLY when every mixer projection is q8_1-fast; layers with
7216 // Float projections (ssm_beta/ssm_alpha on layers 1/2/4 of the 9B NVFP4 GGUF) take the
7217 // UNFUSED 256-thread rms_norm. The verify norm must mirror that PER-LAYER choice —
7218 // blockDim changes the sum-of-squares reduce order, and the ULP shift amplifies through
7219 // the GDN recurrence into argmax flips (measured: 9B text prompt, 1 ULP at layer 2 ->
7220 // 2.3e-1 logit maxdiff at the head -> K=1..8 divergence at a 0.03-margin token).
7221 let mixer_fast = self.mixer_in_q8_1_fast(e, &layer.mixer);
7222 let norm_fused = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err() && mixer_fast;
7223 // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2, 2026-08-03): when the norm is
7224 // dispatch-fused AND every consumer of `h` reads only its q8_1 form (Full mixer:
7225 // projections only; Linear mixer: the batched arm — the per-column fallback needs
7226 // f32 h), emit the attn-input norm DIRECTLY as q8_1 via `rms_norm_q8_1` at nrows=t
7227 // (row-indexed kernel — the T-row launch is the per-row m=1 program, kernel-check
7228 // pins bit-identity vs rms_norm_decode -> quantize_q8_1). Kills the standalone
7229 // quantize launch(es) + the f32 h HBM round-trip that decode never pays.
7230 // step35 (Full mixer) is the third case that needs f32 `h`: its verify arm is a
7231 // per-ROW replay of the eager decode mixer, whose `pre_q` contract is a single row —
7232 // a T-row q8_1 pair cannot be handed to it, and re-deriving per-row q8_1 from the f32
7233 // rows is exactly the dispatch being mirrored. Keep step35 on the unfused arm.
7234 let lin_q8_only = match &layer.mixer {
7235 Mixer::Linear(la) => {
7236 (t >= 3 || (t == 2 && spec_m2())) && e.uses_q8_1_fast(&la.ssm_out)
7237 }
7238 Mixer::Full(_) if self.sliding_gated_moe_batch_program() => false,
7239 _ => true,
7240 };
7241 // NOTE decode.rs's take()-first lesson: take the pending pair BEFORE branching so
7242 // a non-fused layer still performs the residual add.
7243 let taken = pending.take();
7244 let (h, h_q8) = if norm_fused && lin_q8_only {
7245 let pair = match taken {
7246 // fused add + attn_norm + q8_1: ONE launch resolves the carried residual
7247 // AND emits this layer's mixer input pre-quantized. res -> x2 (= new x).
7248 Some((x1p, f1p)) => {
7249 let mut x2 = vbuf(e, t * n_embd)?; // fully written (res output)
7250 let p = e.add_rms_norm_q8_1(
7251 &x1p,
7252 &f1p,
7253 layer.attn_norm.float_data(),
7254 &mut x2,
7255 n_embd,
7256 t,
7257 eps,
7258 )?;
7259 x = x2;
7260 p
7261 }
7262 None => e.rms_norm_q8_1(&x, layer.attn_norm.float_data(), n_embd, t, eps)?,
7263 };
7264 (e.zeros(0)?, Some(pair)) // h unused on this path (q8-only consumers)
7265 } else {
7266 if let Some((x1p, f1p)) = taken {
7267 let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
7268 e.add(&x1p, &f1p, &mut x2, t * n_embd)?;
7269 x = x2;
7270 }
7271 let mut h = vbuf(e, t * n_embd)?; // fully written by either rms_norm arm
7272 if norm_fused {
7273 e.rms_norm_decode(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
7274 } else {
7275 e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
7276 }
7277 (h, None)
7278 };
7279 let h_q8_ref = h_q8.as_ref().map(|(q, d)| (q, d));
7280
7281 let mixed = match &layer.mixer {
7282 Mixer::Full(fa) => self.full_attn_verify(
7283 e,
7284 fa,
7285 &h,
7286 h_q8_ref,
7287 pos_d,
7288 t,
7289 cache,
7290 il,
7291 stream.map(|(_, c)| c),
7292 )?,
7293 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
7294 Mixer::Linear(la) => {
7295 // BATCHED linear verify (2026-07-03, the MTP-profit lever): one T-token pass —
7296 // batched projections (weight read ONCE, hits the m=2-4 weight-resident matvec),
7297 // carried-state conv (ssm_conv1d_tm_state), GDN prep on the prefill kernels, and
7298 // ONE gdn_scan whose internal sequential t-loop is the SAME recurrence as T
7299 // chained T=1 steps (bit-identical). Falls back to the sequential per-column
7300 // chain when T < d_conv-1 (conv ring update needs T >= pad) — or when ANY
7301 // projection is off the q8_1 fast path: matmul_decode_exact would route a Float
7302 // tensor to cuBLAS at m=t (different FP accumulation than eager's per-token
7303 // GEMV), so mixed-dtype layers stay on the eager-identical per-column chain.
7304 // MEMRA_SPEC_M2 (lane/spec-m2): the t==2 batch rides the same arm — the conv
7305 // wrapper handles t<pad with a pure-copy ring rebuild; see spec_m2() header.
7306 if (t >= 3 || (t == 2 && spec_m2()))
7307 && mixer_fast
7308 && e.uses_q8_1_fast(&la.ssm_out)
7309 {
7310 let want = ckpt.is_some();
7311 let (out, stash) =
7312 self.linear_attn_verify_t(e, la, &h, h_q8_ref, t, cache, il, want)?;
7313 if let (Some(ck), Some(st)) = (ckpt.as_deref_mut(), stash) {
7314 ck.gdn[il] = Some(st);
7315 }
7316 out
7317 } else {
7318 let mut out = vbuf(e, t * n_embd)?; // every col written by copy_into
7319 let mut col_states: Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>> =
7320 if ckpt.is_some() && t >= 2 {
7321 Some(Vec::with_capacity(t - 1))
7322 } else {
7323 None
7324 };
7325 for col in 0..t {
7326 let mut h_col = vbuf(e, n_embd)?; // fully written by copy_view_into
7327 let src = h.slice(col * n_embd..(col + 1) * n_embd);
7328 e.copy_view_into(&mut h_col, 0, &src, n_embd)?;
7329 let m_col = self.linear_attn_decode(e, la, &h_col, cache, il)?;
7330 e.copy_into(&mut out, col * n_embd, &m_col, n_embd)?;
7331 // REPLAY-FREE ckpt: clone the chain's ACTUAL state after this column
7332 // (pure dtod — cannot change any computed value). Last column skipped:
7333 // rebuild targets are j <= t-1 columns.
7334 if let Some(cs) = col_states.as_mut() {
7335 if col + 1 < t {
7336 let rl = cache.recur[il].as_ref().unwrap();
7337 cs.push((
7338 e.clone_dtod(&rl.conv_state)?,
7339 e.clone_dtod(&rl.ssm_state)?,
7340 ));
7341 }
7342 }
7343 }
7344 if let (Some(ck), Some(cs)) = (ckpt.as_deref_mut(), col_states) {
7345 // ReplaySSM-assessment instrumentation (2026-07-30): the
7346 // per-column clones are the only true state snapshots left in
7347 // the verify (the batched path stashes INPUTS and replays).
7348 if std::env::var("MEMRA_SPEC_STATS").as_deref() == Ok("1") {
7349 static ONCE: std::sync::Once = std::sync::Once::new();
7350 let bytes: usize =
7351 cs.iter().map(|(c, s)| (c.len() + s.len()) * 4).sum();
7352 ONCE.call_once(|| eprintln!(
7353 "[verify-ckpt] per-column layer il={il}: {} clones, {:.2} MB/layer/round",
7354 cs.len(), bytes as f64 / 1e6));
7355 }
7356 ck.cols[il] = Some(cs);
7357 }
7358 out
7359 }
7360 }
7361 };
7362
7363 // DISPATCH-MIRRORED post-attn norm: eager residual_norm_ffn fuses add+norm+quant
7364 // (1024-thread add_rms_norm_q8_1) only for Dense FFNs whose gate+up are q8_1-fast;
7365 // otherwise (and for MoE) it runs the 256-thread fused add_rms_norm. Mirror per layer.
7366 let ffn_fuse = match &layer.ffn {
7367 crate::hybrid::Ffn::Dense {
7368 ffn_gate, ffn_up, ..
7369 } => {
7370 std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
7371 && e.uses_q8_1_fast(ffn_gate)
7372 && e.uses_q8_1_fast(ffn_up)
7373 }
7374 crate::hybrid::Ffn::Moe(_) => false,
7375 };
7376 // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): on the ffn_fuse path (Dense,
7377 // gate+up q8_1-fast, non-M3) the FFN input is emitted DIRECTLY as q8_1 by ONE
7378 // add_rms_norm_q8_1 launch at nrows=t (row-indexed kernel: the T-row launch is the
7379 // per-row m=1 program; kernel-check pins bit-identity vs the unfused
7380 // add_f32 -> rms_norm_decode -> quantize_q8_1 chain at T=2/4/5/8) — replacing the
7381 // add + rms_norm_decode launches AND the dual/singles' internal re-quantize.
7382 // M3's swigluoai must keep the f32 chain (the fused SwiGLU epilogue encodes plain
7383 // SiLU), mirroring residual_norm_ffn's m3 guard on the decode path.
7384 // step35: same guard per LAYER. A dense FFN's clamp is the SHEXP array (upstream's
7385 // one build_ffn serves dense + shared expert, llama-graph.cpp:1751), and verify MUST
7386 // mirror decode's dispatch or spec self-consistency fails.
7387 let dense_lim = self.cfg.clamp_shexp_at(il as u32);
7388 let fuse_q8 = ffn_fuse && self.cfg.m3.is_none() && dense_lim.is_none();
7389 let mut x1 = vbuf(e, t * n_embd)?; // fully written by add / add_rms_norm*
7390 let mut z = e.zeros(0)?; // replaced below on the unfused arms
7391 let z_q8 = if fuse_q8 {
7392 Some(e.add_rms_norm_q8_1(
7393 &x,
7394 &mixed,
7395 layer.post_attn_norm.float_data(),
7396 &mut x1,
7397 n_embd,
7398 t,
7399 eps,
7400 )?)
7401 } else {
7402 let mut zf = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode / add_rms_norm
7403 if ffn_fuse {
7404 e.add(&x, &mixed, &mut x1, t * n_embd)?;
7405 e.rms_norm_decode(
7406 &x1,
7407 layer.post_attn_norm.float_data(),
7408 &mut zf,
7409 n_embd,
7410 t,
7411 eps,
7412 )?;
7413 } else {
7414 e.add_rms_norm(
7415 &x,
7416 &mixed,
7417 layer.post_attn_norm.float_data(),
7418 &mut x1,
7419 &mut zf,
7420 n_embd,
7421 t,
7422 eps,
7423 )?;
7424 }
7425 z = zf;
7426 None
7427 };
7428 // DECODE-EXACT FFN projections: force MMVQ for gate/up/down at any T to match the
7429 // T=1 decode FP accumulation order. At T>=5 the generic matmul/matmul_pre falls to dp4a
7430 // (128-thread, different FP sum order). At T=2-4 the batched MMVQ is already bit-identical.
7431 let ffn_out = match &layer.ffn {
7432 crate::hybrid::Ffn::Dense {
7433 ffn_gate,
7434 ffn_up,
7435 ffn_down,
7436 } => {
7437 let n_ff = ffn_gate.out_features();
7438 if let Some((zq, zd)) = z_q8.as_ref() {
7439 // FUSED CHAIN (fix 2): pre-quantized z feeds the projections; the SwiGLU
7440 // epilogue emits act pre-quantized for ffn_down (silu_mul_scaled_q8_1,
7441 // bit-identical to silu_mul + quantize — kernel-check-pinned) with the
7442 // NVFP4 macro-scales folded (deferred-scale dual: y*s inline == the
7443 // scale_inplace store, value-exact) — the exact m=1 decode epilogue
7444 // structure at nrows=t.
7445 let pair =
7446 match e.matmul_decode_exact_dual_pre(ffn_gate, ffn_up, zq, zd, t)? {
7447 Some(((g, gs), (u, us))) => Some((g, gs, u, us)),
7448 None => None,
7449 };
7450 let (gate, gs, up, us) = match pair {
7451 Some(x4) => x4,
7452 None => (
7453 e.matmul_decode_exact_pre(ffn_gate, zq, zd, t)?,
7454 1.0, // scale already applied inside _pre
7455 e.matmul_decode_exact_pre(ffn_up, zq, zd, t)?,
7456 1.0,
7457 ),
7458 };
7459 if e.uses_q8_1_fast(ffn_down) {
7460 let (aq, ad) = e.silu_mul_scaled_q8_1(&gate, &up, gs, us, t * n_ff)?;
7461 e.matmul_decode_exact_pre(ffn_down, &aq, &ad, t)?
7462 } else {
7463 let mut act = vbuf(e, t * n_ff)?;
7464 e.silu_mul_scaled(&gate, &up, gs, us, &mut act, t * n_ff)?;
7465 e.matmul_decode_exact(ffn_down, &act, t)?
7466 }
7467 } else {
7468 // UNFUSED (pre-fix) chain — MoE-adjacent/M3/off-fast layers, unchanged.
7469 // DUAL gate+up batched twin (lane/verify-economics, 2026-08-02): one launch
7470 // for the pair at t=2..8 — bit-identical per (tensor,token,row) to the two
7471 // singles (kernel-check pins bitwise; MEMRA_SPEC_DUAL_T=0 reverts). None
7472 // (non-NVFP4 / t outside the tier / seam off) -> the two singles, unchanged.
7473 let (gate, up) =
7474 match e.matmul_decode_exact_dual(ffn_gate, ffn_up, &z, t)? {
7475 Some(pair) => pair,
7476 None => (
7477 e.matmul_decode_exact(ffn_gate, &z, t)?,
7478 e.matmul_decode_exact(ffn_up, &z, t)?,
7479 ),
7480 };
7481 let mut act = vbuf(e, t * n_ff)?; // fully written by ffn_act_lim
7482 Self::ffn_act_lim(
7483 e,
7484 &self.cfg,
7485 &gate,
7486 &up,
7487 1.0,
7488 1.0,
7489 dense_lim,
7490 &mut act,
7491 t * n_ff,
7492 )?;
7493 e.matmul_decode_exact(ffn_down, &act, t)?
7494 }
7495 }
7496 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, t, il as u16)?,
7497 };
7498 // CROSS-LAYER fusion: defer this layer's post-FFN residual add — the next layer's
7499 // fused-q8 attn norm folds it in (add_rms_norm_q8_1 == add; rms_norm; quantize,
7500 // kernel-check-pinned at nrows=T). Non-fused next layers add explicitly above.
7501 pending = Some((x1, ffn_out));
7502 }
7503 // RANGE's final add (no next norm INSIDE the range to fuse with; for the
7504 // whole-trunk call that is the last layer, whose next norm is output_norm — f32-out).
7505 if let Some((x1p, f1p)) = pending.take() {
7506 let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
7507 e.add(&x1p, &f1p, &mut x2, t * n_embd)?;
7508 x = x2;
7509 }
7510 Ok(x)
7511 }
7512 /// BATCHED linear-attn verify (T=K+1): the whole layer in ~10 launches instead of T x the
7513 /// T=1 decode chain (T x ~12 launches + T weight reads of the four projections). The GDN
7514 /// recurrence itself is inherently sequential — gdn_scan_s128 runs its internal t-loop with
7515 /// the SAME per-token math as chained T=1 calls (bit-identical state evolution); everything
7516 /// around it (projections, conv, prep, gated norm, out-proj) batches. Advances conv ring +
7517 /// ssm state exactly like T sequential decode steps.
7518 /// `want_stash`: additionally RETAIN the gdn-scan inputs (pure buffer keep-alives, zero extra
7519 /// kernels) so a partial accept can rebuild the state after any column prefix (REPLAY-FREE).
7520 #[allow(clippy::too_many_arguments)]
7521 fn linear_attn_verify_t(
7522 &self,
7523 e: &Engine,
7524 la: &LinearAttnLayer,
7525 h: &CudaSlice<f32>,
7526 h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
7527 t: usize,
7528 cache: &mut Cache,
7529 il: usize,
7530 want_stash: bool,
7531 ) -> Result<(CudaSlice<f32>, Option<GdnStash>), Box<dyn std::error::Error>> {
7532 let cfg = &self.cfg;
7533 let geometry = la.geometry;
7534 let d_state = geometry.key_head_dim as usize;
7535 let num_k = geometry.key_heads as usize;
7536 let num_v = geometry.value_heads as usize;
7537 let d_conv = geometry.conv_kernel as usize;
7538 let key_dim = d_state * num_k;
7539 let conv_dim = key_dim * 2 + geometry.value_head_dim as usize * num_v;
7540 let eps = cfg.rms_eps;
7541 let scale = 1.0 / (d_state as f32).sqrt();
7542
7543 // DECODE-EXACT projections: matmul_decode_exact forces the MMVQ (warp-per-row, 32-thread)
7544 // accumulation order for EVERY m, matching the T=1 decode path bit-for-bit. The generic
7545 // `matmul` at m>=5 falls to dp4a (128-thread, two-level reduce) which has a different FP
7546 // sum order — ULP differences propagate through gdn_scan and flip argmax on the 27B.
7547 // Q8 TRUNK-FUSION at T=1 (35B: wqkv+wqkv_gate both Q8_0): one fused2 launch, bit-identical
7548 // per (tensor,row) to the two m=1 MMVQ dispatches below — decode-exact contract holds.
7549 // VERIFY-TIER TRUNK FUSION (MEMRA_SPEC_FUSED_T, t=2-4): quantize h ONCE for every
7550 // fused-eligible same-input Q8_0 pair of this layer (35B wqkv+wqkv_gate; 9B
7551 // ssm_beta+ssm_alpha) — each fused2 batched launch then replaces two decode-exact
7552 // calls (each of which re-quantizes the same h + runs its own _b2/_b4 launch).
7553 // Bit-identical per (tensor,token,row) — see spec_fused_t().
7554 // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): `h_q8` = the attn-input norm emitted
7555 // directly as q8_1 by the caller's fused rms_norm_q8_1 (bit-identical to the unfused
7556 // chain, kernel-check-pinned). When present it REPLACES the standalone quantize below
7557 // and feeds every projection; the caller guaranteed all four input projections are
7558 // q8_1-fast. When absent, the old shared-quantize (fused-t window) stands.
7559 let h_q8_t = if h_q8.is_none()
7560 && spec_fused_t()
7561 && (2..=4).contains(&t)
7562 && ((e.uses_q8_1_fast(&la.wqkv) && e.uses_q8_1_fast(&la.wqkv_gate))
7563 || (e.uses_q8_1_fast(&la.ssm_beta) && e.uses_q8_1_fast(&la.ssm_alpha)))
7564 {
7565 Some(e.quantize_q8_1(h, t, cfg.n_embd as usize)?)
7566 } else {
7567 None
7568 };
7569 // one view: the caller's fused-norm q8 or this fn's own shared quantize.
7570 let hq8_any: Option<(&CudaSlice<i8>, &CudaSlice<f32>)> =
7571 h_q8.or(h_q8_t.as_ref().map(|(q, d)| (q, d)));
7572 let (qkv_mixed, z) = {
7573 let mut fused = None;
7574 if t == 1 && e.uses_q8_1_fast(&la.wqkv) && e.uses_q8_1_fast(&la.wqkv_gate) {
7575 let (hq, hd) = e.quantize_q8_1(h, 1, cfg.n_embd as usize)?;
7576 fused = e.matmul_q8_fused2(&la.wqkv, &la.wqkv_gate, &hq, &hd)?;
7577 } else if let Some((hq, hd)) = hq8_any {
7578 if spec_fused_t() && (2..=4).contains(&t) {
7579 fused = e.matmul_q8_fused2_t(&la.wqkv, &la.wqkv_gate, hq, hd, t)?;
7580 }
7581 }
7582 match (fused, hq8_any) {
7583 (Some(pair), _) => pair,
7584 (None, Some((hq, hd))) if h_q8.is_some() => (
7585 e.matmul_decode_exact_pre(&la.wqkv, hq, hd, t)?,
7586 e.matmul_decode_exact_pre(&la.wqkv_gate, hq, hd, t)?,
7587 ),
7588 (None, _) => (
7589 e.matmul_decode_exact(&la.wqkv, h, t)?,
7590 e.matmul_decode_exact(&la.wqkv_gate, h, t)?,
7591 ),
7592 }
7593 };
7594 // beta+alpha DUAL at T=1 (75% of p3 rounds run T=1 verify — p-min chain cuts): the dual
7595 // mr2 kernel is bit-identical per element to the m=1 MMVQ matmul_decode_exact dispatches
7596 // (same warp-per-row body, blockIdx.y picks the weight), so the decode-exact contract
7597 // holds; the run-spec battery is the arbiter. T>1 keeps the per-tensor decode-exact path.
7598 let (beta_raw, alpha) = if t == 1 {
7599 let (hq, hd) = e.quantize_q8_1(h, 1, cfg.n_embd as usize)?;
7600 match e.matmul_pre_dual_noscale(&la.ssm_beta, &la.ssm_alpha, &hq, &hd, 1)? {
7601 Some(((mut b, bs), (mut a, as_))) => {
7602 if bs != 1.0 {
7603 e.scale_inplace(&mut b, bs, la.ssm_beta.out_features())?;
7604 }
7605 if as_ != 1.0 {
7606 e.scale_inplace(&mut a, as_, la.ssm_alpha.out_features())?;
7607 }
7608 (b, a)
7609 }
7610 // Q8_0 fused2 twin (9B stores beta/alpha as Q8_0): DISPATCH-MIRRORS the eager
7611 // decode's beta_alpha closure — the fused body is qmatvec_q8_0_mmvq verbatim,
7612 // bit-identical per row (kernel-check rel=0.00e0 gate), so decode==verify holds.
7613 None => match e.matmul_q8_fused2(&la.ssm_beta, &la.ssm_alpha, &hq, &hd)? {
7614 Some((b, a)) => (b, a),
7615 None => (
7616 e.matmul_decode_exact(&la.ssm_beta, h, 1)?,
7617 e.matmul_decode_exact(&la.ssm_alpha, h, 1)?,
7618 ),
7619 },
7620 }
7621 } else {
7622 // fused-t twin (9B stores beta/alpha as Q8_0): same shared-quantize + one launch
7623 // contract as the wqkv pair above; 35B beta/alpha are Float -> None -> fallback.
7624 let mut nvfp4_fused = None;
7625 let mut q8_fused = None;
7626 if let Some((hq, hd)) = hq8_any {
7627 if t == 3 && std::env::var("MEMRA_NVFP4_AUX_DUAL").as_deref() != Ok("0") {
7628 nvfp4_fused =
7629 e.matmul_decode_exact_dual_pre(&la.ssm_beta, &la.ssm_alpha, hq, hd, t)?;
7630 if nvfp4_fused.is_some() && std::env::var("MEMRA_DEBUG").is_ok() {
7631 static ONCE: std::sync::Once = std::sync::Once::new();
7632 ONCE.call_once(|| {
7633 eprintln!("[memra] NVFP4 beta+alpha batched aux dual ENGAGED (t={t})")
7634 });
7635 }
7636 }
7637 if nvfp4_fused.is_none() && spec_fused_t() && (2..=4).contains(&t) {
7638 q8_fused = e.matmul_q8_fused2_t(&la.ssm_beta, &la.ssm_alpha, hq, hd, t)?;
7639 }
7640 }
7641 if let Some(((mut b, bs), (mut a, as_))) = nvfp4_fused {
7642 if bs != 1.0 {
7643 e.scale_inplace(&mut b, bs, t * la.ssm_beta.out_features())?;
7644 }
7645 if as_ != 1.0 {
7646 e.scale_inplace(&mut a, as_, t * la.ssm_alpha.out_features())?;
7647 }
7648 (b, a)
7649 } else if let Some(pair) = q8_fused {
7650 pair
7651 } else {
7652 match hq8_any {
7653 Some((hq, hd)) if h_q8.is_some() => (
7654 e.matmul_decode_exact_pre(&la.ssm_beta, hq, hd, t)?,
7655 e.matmul_decode_exact_pre(&la.ssm_alpha, hq, hd, t)?,
7656 ),
7657 _ => (
7658 e.matmul_decode_exact(&la.ssm_beta, h, t)?,
7659 e.matmul_decode_exact(&la.ssm_alpha, h, t)?,
7660 ),
7661 }
7662 }
7663 };
7664
7665 // conv with CARRIED state + ring roll (T >= pad rides the input-column update kernel;
7666 // T < pad — the MEMRA_SPEC_M2 t=2 arm — rolls via the pure-copy ring rebuild).
7667 let rl = cache.recur[il].as_mut().unwrap();
7668 let mut conv_out = e.uninit(conv_dim * t)?;
7669 e.ssm_conv1d_tm_state(
7670 &qkv_mixed,
7671 &mut rl.conv_state,
7672 la.ssm_conv1d.float_data(),
7673 &mut conv_out,
7674 conv_dim,
7675 t,
7676 d_conv,
7677 )?;
7678
7679 // GDN prep via the prefill kernels (repack + L2 + sigmoid + glog), T-wide.
7680 let mut q_g = e.uninit(d_state * num_v * t)?;
7681 let mut k_g = e.uninit(d_state * num_v * t)?;
7682 let mut v_g = e.uninit(d_state * num_v * t)?;
7683 e.qkv_to_gdn_repack(
7684 &conv_out, &mut q_g, &mut k_g, &mut v_g, d_state, num_v, num_k, key_dim, t,
7685 )?;
7686 let mut q_l2 = e.uninit(d_state * num_v * t)?;
7687 e.l2_norm_decode(&q_g, &mut q_l2, d_state, num_v * t, eps)?;
7688 let mut k_l2 = e.uninit(d_state * num_v * t)?;
7689 e.l2_norm_decode(&k_g, &mut k_l2, d_state, num_v * t, eps)?;
7690 let mut beta = e.uninit(t * num_v)?;
7691 e.sigmoid(&beta_raw, &mut beta, t * num_v)?;
7692 let mut g_log = e.uninit(t * num_v)?;
7693 e.gdn_glog(
7694 &alpha,
7695 la.ssm_dt.float_data(),
7696 la.ssm_a.float_data(),
7697 &mut g_log,
7698 num_v,
7699 t,
7700 )?;
7701
7702 // ONE gdn_scan over T tokens from the carried state (internal sequential loop ==
7703 // T chained T=1 steps). Ping-pong the resident buffers like eager decode.
7704 let mut o = e.uninit(d_state * num_v * t)?;
7705 {
7706 let crate::cache::RecurLayer {
7707 ssm_state,
7708 ssm_state_alt,
7709 ..
7710 } = rl;
7711 e.gdn_scan_s128(
7712 &q_l2,
7713 &k_l2,
7714 &v_g,
7715 &g_log,
7716 &beta,
7717 ssm_state,
7718 ssm_state_alt,
7719 &mut o,
7720 num_v,
7721 t,
7722 scale,
7723 )?;
7724 }
7725 std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
7726
7727 // gated RMSNorm + out projection, T-wide. FUSED-QUANTIZE ARM (lane/vt-fixes fix 2,
7728 // mirroring the T=1 decode's launch-arc form): when ssm_out rides the q8_1 fast path,
7729 // emit q8_1 straight from the gated norm at nrows=num_v*t (row-indexed kernel, the
7730 // T-wide launch is the per-row program; kernel-check pins bit-identity vs
7731 // gated_rmsnorm -> quantize_q8_1 at T=1 and T=5) and feed the decode-exact dispatch
7732 // pre-quantized — one launch replaces norm + quantize. Fallback = the f32 chain.
7733 let out = if e.uses_q8_1_fast(&la.ssm_out) {
7734 let (gq, gd) =
7735 e.gated_rmsnorm_q8_1(&o, la.ssm_norm.float_data(), &z, d_state, num_v * t, eps)?;
7736 e.matmul_decode_exact_pre(&la.ssm_out, &gq, &gd, t)?
7737 } else {
7738 let mut gn = e.uninit(d_state * num_v * t)?;
7739 e.gated_rmsnorm(
7740 &o,
7741 la.ssm_norm.float_data(),
7742 &z,
7743 &mut gn,
7744 d_state,
7745 num_v * t,
7746 eps,
7747 )?;
7748 // DECODE-EXACT out-projection: same MMVQ path as the T=1 decode (ssm_out at m>=5
7749 // would fall to dp4a with a different FP reduction order — same class of bug as
7750 // the input projs).
7751 e.matmul_decode_exact(&la.ssm_out, &gn, t)?
7752 };
7753 let stash = if want_stash {
7754 Some(GdnStash {
7755 qkv_mixed,
7756 q_l2,
7757 k_l2,
7758 v_g,
7759 g_log,
7760 beta,
7761 })
7762 } else {
7763 None
7764 };
7765 Ok((out, stash))
7766 }
7767
7768 /// REPLAY-FREE partial-accept commit (2026-07-03): make the cache state == "committed through
7769 /// the first `j` verify columns" WITHOUT the legacy rollback + duplicate trunk replay.
7770 /// - Full-attn KV: truncate both the owning-stage shadow and every TP rank to snapshot + j.
7771 /// The verify's appended rows for those columns are bit-identical to what an eager T=1
7772 /// chain writes (the decode-exact contract the verify-probe gates), so keeping them ==
7773 /// replaying them.
7774 /// - Linear layers, batched path: rebuild the conv ring by PURE COPIES (ring holds raw input
7775 /// columns) and the ssm state by a prefix re-run of the SAME gdn_scan kernel (t=j) from the
7776 /// snapshot state over the stash's identical inputs — the kernel's t-loop carries state in
7777 /// registers and writes it once at the end, so iterations 0..j-1 are independent of T:
7778 /// bit-identical to the verify's own state after j tokens == the eager chain state.
7779 /// - Linear layers, per-column path: restore the cloned actual state after column j-1.
7780 /// Caller guarantees 1 <= j <= t-1 (j==0 rounds take the legacy rollback; j==t is full accept).
7781 fn commit_verified_prefix(
7782 &self,
7783 e: &Engine,
7784 cache: &mut Cache,
7785 snap: &crate::cache::CacheSnapshot,
7786 ckpt: &VerifyCkpt,
7787 j: usize,
7788 kv_lens_done: bool,
7789 dev_j: Option<(&CudaSlice<u32>, usize, usize)>,
7790 ) -> Result<(), Box<dyn std::error::Error>> {
7791 // GDN geometry derives lazily inside recurrent-layer arms. Full-attention plans carry no
7792 // recurrent state and must never be forced through a synthetic SSM geometry.
7793 // Engine-bundle slice 1 (DSF-ROUNDCOST-20260820 §1.1): the per-column-arm restores
7794 // are 2 tiny D2D copies per linear layer (~96 dispatches/partial round on the q38
7795 // route). When every cols-arm layer shares uniform state sizes (single ssm cfg —
7796 // always true today), batch them into two `copy_batch_uniform_f32` launches. Bytes,
7797 // buffers and stream order are identical to the per-layer memcpy sequence; the
7798 // kernel-rebuild (gdn-stash) arm below is untouched. MEMRA_STATE_COPY_BATCH=0 reverts.
7799 let mut batched_cols = false;
7800 if state_copy_batch_on() && dev_j.is_none() {
7801 use cudarc::driver::DevicePtr;
7802 let s = &e.gpu.stream();
7803 let mut conv_pairs: Vec<(u64, u64)> = Vec::new();
7804 let mut ssm_pairs: Vec<(u64, u64)> = Vec::new();
7805 let (mut conv_words, mut ssm_words) = (0usize, 0usize);
7806 let mut uniform = true;
7807 for il in 0..self.layers.len() {
7808 let Some(rl) = cache.recur[il].as_ref() else {
7809 continue;
7810 };
7811 if ckpt.gdn[il].is_some() {
7812 continue; // kernel-rebuild arm restores below, per layer
7813 }
7814 let Some(cols) = &ckpt.cols[il] else {
7815 continue; // missing-ckpt error surfaces in the main loop
7816 };
7817 let (c, st) = &cols[j - 1];
7818 if conv_pairs.is_empty() {
7819 conv_words = c.len();
7820 ssm_words = st.len();
7821 } else if c.len() != conv_words || st.len() != ssm_words {
7822 uniform = false;
7823 break;
7824 }
7825 let (pc, _g0) = c.device_ptr(s);
7826 let (dc, _g1) = rl.conv_state.device_ptr(s);
7827 let (ps, _g2) = st.device_ptr(s);
7828 let (ds, _g3) = rl.ssm_state.device_ptr(s);
7829 conv_pairs.push((pc as u64, dc as u64));
7830 ssm_pairs.push((ps as u64, ds as u64));
7831 }
7832 if uniform && !conv_pairs.is_empty() {
7833 let n = conv_pairs.len();
7834 let mut t = vec![0u64; 2 * n];
7835 for (k, &(src, dst)) in conv_pairs.iter().enumerate() {
7836 t[k] = src;
7837 t[n + k] = dst;
7838 }
7839 let conv_t = e.htod_u64(&t)?;
7840 for (k, &(src, dst)) in ssm_pairs.iter().enumerate() {
7841 t[k] = src;
7842 t[n + k] = dst;
7843 }
7844 let ssm_t = e.htod_u64(&t)?;
7845 e.copy_batch_uniform_f32(&conv_t, n, conv_words)?;
7846 e.copy_batch_uniform_f32(&ssm_t, n, ssm_words)?;
7847 batched_cols = true;
7848 }
7849 }
7850 rewind_tp_kv_verified_prefix(&mut cache.tp_kv, &snap.tp_kv_len, j)?;
7851 for il in 0..self.layers.len() {
7852 if let (Some(kvl), Some(saved)) = (cache.kv[il].as_mut(), snap.kv_len[il]) {
7853 kvl.len = saved + j;
7854 // devacc 3a: spec_rollback_kv already wrote len_d on-device (same value).
7855 if !kv_lens_done {
7856 e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
7857 }
7858 }
7859 if let Some(rl) = cache.recur[il].as_mut() {
7860 let Mixer::Linear(linear) = &self.layers[il].mixer else {
7861 return Err(format!("recurrent cache layer {il} has no GDN plan").into());
7862 };
7863 let geometry = linear.geometry;
7864 let d_state = geometry.key_head_dim as usize;
7865 let num_k = geometry.key_heads as usize;
7866 let num_v = geometry.value_heads as usize;
7867 let d_conv = geometry.conv_kernel as usize;
7868 let conv_dim = d_state * num_k * 2 + geometry.value_head_dim as usize * num_v;
7869 let scale = 1.0 / (d_state as f32).sqrt();
7870 if let Some(st) = &ckpt.gdn[il] {
7871 let ring_old = snap.conv[il].as_ref().expect("snapshot missing conv");
7872 let state_in = snap.ssm[il].as_ref().expect("snapshot missing ssm");
7873 if let Some((acc, base, t_v)) = dev_j {
7874 // 3b: j read on-device (_dc twins, same bodies; full accept early-exits).
7875 e.ssm_conv_ring_rebuild_dc(
7876 &st.qkv_mixed,
7877 ring_old,
7878 &mut rl.conv_state,
7879 conv_dim,
7880 acc,
7881 base,
7882 t_v,
7883 d_conv,
7884 )?;
7885 let mut o = e.uninit(d_state * num_v * j.max(1))?;
7886 e.gdn_scan_s128_dc(
7887 &st.q_l2,
7888 &st.k_l2,
7889 &st.v_g,
7890 &st.g_log,
7891 &st.beta,
7892 state_in,
7893 &mut rl.ssm_state,
7894 &mut o,
7895 num_v,
7896 acc,
7897 base,
7898 t_v,
7899 scale,
7900 )?;
7901 } else {
7902 e.ssm_conv_ring_rebuild(
7903 &st.qkv_mixed,
7904 ring_old,
7905 &mut rl.conv_state,
7906 conv_dim,
7907 j,
7908 d_conv,
7909 )?;
7910 let mut o = e.uninit(d_state * num_v * j)?; // scan output, discarded
7911 e.gdn_scan_s128(
7912 &st.q_l2,
7913 &st.k_l2,
7914 &st.v_g,
7915 &st.g_log,
7916 &st.beta,
7917 state_in,
7918 &mut rl.ssm_state,
7919 &mut o,
7920 num_v,
7921 j,
7922 scale,
7923 )?;
7924 }
7925 } else if let Some(cols) = &ckpt.cols[il] {
7926 if !batched_cols {
7927 let (c, s) = &cols[j - 1];
7928 e.copy_into(&mut rl.conv_state, 0, c, c.len())?;
7929 e.copy_into(&mut rl.ssm_state, 0, s, s.len())?;
7930 }
7931 } else {
7932 return Err(
7933 "commit_verified_prefix: verify ckpt missing for linear layer".into(),
7934 );
7935 }
7936 }
7937 }
7938 cache.pos = snap.pos + j;
7939 Ok(())
7940 }
7941
7942 /// ROUND-STREAM: recur restore with device-j (the _dc twins; full accept early-exits
7943 /// in-kernel). Requires the batched-linear stash on every linear layer (stream gate).
7944 fn commit_verified_prefix_stream(
7945 &self,
7946 e: &Engine,
7947 cache: &mut Cache,
7948 snap: &crate::cache::CacheSnapshot,
7949 ckpt: &VerifyCkpt,
7950 acc: &CudaSlice<u32>,
7951 base: usize,
7952 t_v: usize,
7953 ) -> Result<(), Box<dyn std::error::Error>> {
7954 for il in 0..self.layers.len() {
7955 if let Some(rl) = cache.recur[il].as_mut() {
7956 let Mixer::Linear(linear) = &self.layers[il].mixer else {
7957 return Err(format!("recurrent cache layer {il} has no GDN plan").into());
7958 };
7959 let geometry = linear.geometry;
7960 let d_state = geometry.key_head_dim as usize;
7961 let num_k = geometry.key_heads as usize;
7962 let num_v = geometry.value_heads as usize;
7963 let d_conv = geometry.conv_kernel as usize;
7964 let conv_dim = d_state * num_k * 2 + geometry.value_head_dim as usize * num_v;
7965 let scale = 1.0 / (d_state as f32).sqrt();
7966 let st = ckpt.gdn[il]
7967 .as_ref()
7968 .ok_or("stream restore: batched-linear stash missing")?;
7969 let ring_old = snap.conv[il].as_ref().expect("snapshot missing conv");
7970 let state_in = snap.ssm[il].as_ref().expect("snapshot missing ssm");
7971 e.ssm_conv_ring_rebuild_dc(
7972 &st.qkv_mixed,
7973 ring_old,
7974 &mut rl.conv_state,
7975 conv_dim,
7976 acc,
7977 base,
7978 t_v,
7979 d_conv,
7980 )?;
7981 let mut o = e.uninit(d_state * num_v * t_v)?;
7982 e.gdn_scan_s128_dc(
7983 &st.q_l2,
7984 &st.k_l2,
7985 &st.v_g,
7986 &st.g_log,
7987 &st.beta,
7988 state_in,
7989 &mut rl.ssm_state,
7990 &mut o,
7991 num_v,
7992 acc,
7993 base,
7994 t_v,
7995 scale,
7996 )?;
7997 }
7998 }
7999 Ok(())
8000 }
8001
8002 /// EAGLE3 aux-capturing verify forward over `tokens` (T) — mirrors `decode_step_t_h` exactly
8003 /// (same KV append, same causal verify, same recur advance) but ALSO clones the aux residual-
8004 /// stream hiddens (blocks in `aux_layers`) for TWO columns: the LAST column (always) and the
8005 /// optional `pred_col` (the EAGLE seed = bonus's predecessor). Returns
8006 /// (all_T_logits host, last_col_aux, pred_col_aux?). Used by the EAGLE3 orchestrator's commit.
8007 pub fn decode_step_t_aux2(
8008 &self,
8009 e: &Engine,
8010 tokens: &[u32],
8011 pos0: usize,
8012 cache: &mut Cache,
8013 aux_layers: &[usize],
8014 pred_col: Option<usize>,
8015 ) -> Result<
8016 (Vec<f32>, Vec<CudaSlice<f32>>, Option<Vec<CudaSlice<f32>>>),
8017 Box<dyn std::error::Error>,
8018 > {
8019 let cfg = &self.cfg;
8020 let n_embd = cfg.n_embd as usize;
8021 let eps = cfg.rms_eps;
8022 let t = tokens.len();
8023 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
8024 let pos_d = e.htod_i32(&pos_vec)?;
8025 let mut x = e.htod(&self.embd.gather(n_embd, tokens))?;
8026 let mut aux_last: Vec<CudaSlice<f32>> = Vec::with_capacity(aux_layers.len());
8027 let mut aux_pred: Vec<CudaSlice<f32>> = Vec::new();
8028 let want_pred = pred_col.is_some();
8029
8030 for (il, layer) in self.layers.iter().enumerate() {
8031 // DISPATCH-MIRRORED norms (FP-order lesson #8) — see decode_step_t_h_emb.
8032 let mixer_fast = self.mixer_in_q8_1_fast(e, &layer.mixer);
8033 let norm_fused = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err() && mixer_fast;
8034 let mut h = vbuf(e, t * n_embd)?; // fully written by either rms_norm arm
8035 if norm_fused {
8036 e.rms_norm_decode(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
8037 } else {
8038 e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
8039 }
8040 let mixed = match &layer.mixer {
8041 Mixer::Full(fa) => {
8042 self.full_attn_verify(e, fa, &h, None, &pos_d, t, cache, il, None)?
8043 }
8044 Mixer::Mla(_) => crate::hybrid::mla_forward_unimplemented(),
8045 Mixer::Linear(la) => {
8046 let mut out = e.zeros(t * n_embd)?;
8047 for col in 0..t {
8048 let mut h_col = e.zeros(n_embd)?;
8049 let src = h.slice(col * n_embd..(col + 1) * n_embd);
8050 e.copy_view_into(&mut h_col, 0, &src, n_embd)?;
8051 let m_col = self.linear_attn_decode(e, la, &h_col, cache, il)?;
8052 e.copy_into(&mut out, col * n_embd, &m_col, n_embd)?;
8053 }
8054 out
8055 }
8056 };
8057 let ffn_fuse = match &layer.ffn {
8058 crate::hybrid::Ffn::Dense {
8059 ffn_gate, ffn_up, ..
8060 } => {
8061 std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
8062 && e.uses_q8_1_fast(ffn_gate)
8063 && e.uses_q8_1_fast(ffn_up)
8064 }
8065 crate::hybrid::Ffn::Moe(_) => false,
8066 };
8067 let mut x1 = vbuf(e, t * n_embd)?; // fully written by add / add_rms_norm
8068 let mut z = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode / add_rms_norm
8069 if ffn_fuse {
8070 e.add(&x, &mixed, &mut x1, t * n_embd)?;
8071 e.rms_norm_decode(
8072 &x1,
8073 layer.post_attn_norm.float_data(),
8074 &mut z,
8075 n_embd,
8076 t,
8077 eps,
8078 )?;
8079 } else {
8080 e.add_rms_norm(
8081 &x,
8082 &mixed,
8083 layer.post_attn_norm.float_data(),
8084 &mut x1,
8085 &mut z,
8086 n_embd,
8087 t,
8088 eps,
8089 )?;
8090 }
8091 let ffn_out = match &layer.ffn {
8092 crate::hybrid::Ffn::Dense {
8093 ffn_gate,
8094 ffn_up,
8095 ffn_down,
8096 } => {
8097 let n_ff = ffn_gate.out_features();
8098 let gate = e.matmul_decode_exact(ffn_gate, &z, t)?;
8099 let up = e.matmul_decode_exact(ffn_up, &z, t)?;
8100 let mut act = vbuf(e, t * n_ff)?; // fully written by ffn_act_lim
8101 // dense FFN clamp = the SHEXP array (upstream build_ffn serves both).
8102 Self::ffn_act_lim(
8103 e,
8104 &self.cfg,
8105 &gate,
8106 &up,
8107 1.0,
8108 1.0,
8109 self.cfg.clamp_shexp_at(il as u32),
8110 &mut act,
8111 t * n_ff,
8112 )?;
8113 e.matmul_decode_exact(ffn_down, &act, t)?
8114 }
8115 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, t, il as u16)?,
8116 };
8117 let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
8118 e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
8119 if aux_layers.contains(&il) {
8120 let mut a = e.zeros(n_embd)?;
8121 e.copy_view_into(&mut a, 0, &x2.slice((t - 1) * n_embd..t * n_embd), n_embd)?;
8122 aux_last.push(a);
8123 if let Some(pc) = pred_col {
8124 let mut ap = e.zeros(n_embd)?;
8125 e.copy_view_into(
8126 &mut ap,
8127 0,
8128 &x2.slice(pc * n_embd..(pc + 1) * n_embd),
8129 n_embd,
8130 )?;
8131 aux_pred.push(ap);
8132 }
8133 }
8134 x = x2;
8135 }
8136 let mut hn = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode
8137 e.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
8138 let logits = e.matmul_decode_exact(&self.output, &hn, t)?;
8139 let host = e.dtoh(&logits)?;
8140 cache.pos += t;
8141 Ok((
8142 host,
8143 aux_last,
8144 if want_pred { Some(aux_pred) } else { None },
8145 ))
8146 }
8147
8148 /// step35 SPEC-VERIFY attention over T query tokens — a per-row REPLAY of the eager
8149 /// `step35_decode_attn`.
8150 ///
8151 /// WHY A REPLAY AND NOT A BATCHED TWIN. The verify's whole job is to be bit-identical to what
8152 /// the eager decode would have computed for the same tokens; that is what makes greedy spec
8153 /// decode exact (run-spec asserts token identity for K=1..8). Every other verify arm in this
8154 /// file earns that identity by carefully mirroring dispatch (`matmul_decode_exact` to force
8155 /// MMVQ at any m, per-layer `ffn_fuse` mirroring, per-row `fa_decode` key bounds). step35
8156 /// stacks FOUR more per-layer degrees of freedom on top of that — per-layer `n_head`
8157 /// (64 full / 96 SWA), per-layer rotary width (64 full / 128 SWA), per-layer rope base, and a
8158 /// SEPARATE `attn_gate` tensor whose projection shares the attn-normed input — and its SWA
8159 /// layers attend through a token-OFFSET view whose offset is a function of the ABSOLUTE
8160 /// position of each query row. A batched twin would have to reproduce all of that AND the
8161 /// per-row offset in one launch; the offset alone rules out the existing rows kernels (they
8162 /// take one `base_len`, not a per-row offset).
8163 ///
8164 /// So this arm calls the eager path itself, once per row, on the same cache. Identity is then
8165 /// true BY CONSTRUCTION rather than by mirroring: row r runs exactly the kernel sequence that
8166 /// eager decode step r runs (same projections, same q8_1 fusion decision, same append, same
8167 /// view arithmetic, same `fa_decode_kvmod`, same gate), because it IS that code. Cost: T x the
8168 /// eager decode mixer instead of one batched pass — the same trade the generic arm's `else`
8169 /// per-row loop already accepts when `fa_rows_eligible` says no. Correctness first; a batched
8170 /// step35 twin is a perf lane's job and must be gated against this arm.
8171 ///
8172 /// The `h_q8` pre-quantized pair from the caller's fused norm is NOT forwarded: it is a
8173 /// T-row buffer and `step35_decode_attn`'s `pre_q` contract is one row. Instead each row's
8174 /// f32 `h` slice is handed over and the callee re-derives its own q8_1 exactly as eager decode
8175 /// does (`quantize_q8_1(h, 1, n_embd)`) — which is the dispatch being mirrored. Callers that
8176 /// took the fused arm therefore MUST still pass a live `h`; `step35_verify` asserts that.
8177 #[allow(clippy::too_many_arguments)]
8178 fn step35_verify(
8179 &self,
8180 e: &Engine,
8181 fa: &FullAttnLayer,
8182 h: &CudaSlice<f32>,
8183 h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
8184 t: usize,
8185 cache: &mut Cache,
8186 il: usize,
8187 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
8188 let n_embd = self.cfg.n_embd as usize;
8189 // The fused (h-less) attn-norm arm hands `h` as a zero-length placeholder. This arm needs
8190 // the f32 rows, so the caller must not take that lever for step35 — enforced at the call
8191 // site by the sliding-gated-MoE `Mixer::Full(_) => false` arm of
8192 // `lin_q8_only` in `decode_step_t_core_stream`, and asserted here so a future caller
8193 // cannot regress it into silently reading an empty buffer.
8194 assert_eq!(
8195 h.len(),
8196 t * n_embd,
8197 "step35_verify needs the f32 attn-normed rows ([t*n_embd]); the caller took the \
8198 fused q8-only norm arm (h_q8={}) — step35 must stay on the unfused arm",
8199 h_q8.is_some()
8200 );
8201 // ROW WIDTH IS n_embd, NOT n_head*head_dim: `step35_decode_attn` returns the mixer output
8202 // AFTER `wo`, so a row is [n_embd] — the same contract the generic arm's
8203 // `matmul_decode_exact(&fa.wo, &attn_g, t)` return has. Sizing this buffer from the
8204 // per-layer head geometry (8192 on full-attn, 12288 on SWA) instead overran the row on the
8205 // FIRST copy and panicked inside `copy_into`'s `CudaView::slice` unwrap
8206 // (raw/mtp-bt-20260806T212127Z.log frames 12-13).
8207 let mut out = vbuf(e, t * n_embd)?; // each row fully written by the copy below
8208 for r in 0..t {
8209 // Absolute position of this query row. `cache.pos` is the committed length at round
8210 // start and every row before r has already been appended by this loop, so the r-th
8211 // verify token sits at cache.pos + r — the same position eager decode would give it.
8212 let pos_d = e.htod_i32(&[(cache.pos + r) as i32])?;
8213 let mut h_row = vbuf(e, n_embd)?; // fully written by copy_view_into
8214 e.copy_view_into(
8215 &mut h_row,
8216 0,
8217 &h.slice(r * n_embd..(r + 1) * n_embd),
8218 n_embd,
8219 )?;
8220 // THE eager decode mixer: appends this row's K/V at kvl.len, advances it, then
8221 // attends over the (SWA-offset) view. Post-`wo`, same contract as this fn returns.
8222 let o = self.step35_decode_attn(e, fa, il, &h_row, None, &pos_d, cache)?;
8223 debug_assert_eq!(
8224 o.len(),
8225 n_embd,
8226 "step35_decode_attn returns post-wo [n_embd]"
8227 );
8228 e.copy_into(&mut out, r * n_embd, &o, n_embd)?;
8229 }
8230 Ok(out)
8231 }
8232
8233 /// Full-attention mixer over T query tokens with a GROWING resident KV (verify path, §D.3).
8234 /// Appends the T new K/V columns to cache.kv[il] then attends causally over [0..len) via
8235 /// fa_prefill. Token-major [T, kv_dim] projection layout == cache row layout (single copy).
8236 #[allow(clippy::too_many_arguments)]
8237 fn full_attn_verify(
8238 &self,
8239 e: &Engine,
8240 fa: &FullAttnLayer,
8241 h: &CudaSlice<f32>,
8242 h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
8243 pos_d: &CudaSlice<i32>,
8244 t: usize,
8245 cache: &mut Cache,
8246 il: usize,
8247 stream_ctr: Option<&CudaSlice<i32>>,
8248 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
8249 // step35: the generic geometry below is wrong for this arch (per-layer n_head, partial
8250 // per-layer rope, the SWA offset view, and a SEPARATE head-wise gate tensor), so it takes
8251 // its own arm. A verify that silently computes different attention than decode defeats the
8252 // whole self-consistency gate, so the arm is a per-row REPLAY of `step35_decode_attn`
8253 // rather than a batched twin — see `step35_verify` for why that is the exactness-correct
8254 // shape and not laziness.
8255 if self.sliding_gated_moe_batch_program() {
8256 if stream_ctr.is_some() {
8257 return Err(
8258 "step35 has no ROUND-STREAM verify arm (the device-counter _dc twins \
8259 cannot express the SWA offset KV view; same root cause as the dc \
8260 decode refusal) — run spec without the stream arm"
8261 .into(),
8262 );
8263 }
8264 return self.step35_verify(e, fa, h, h_q8, t, cache, il);
8265 }
8266 let cfg = &self.cfg;
8267 let geometry = cfg.full_attention_geometry_at(il as u32);
8268 let n_head = geometry.n_head as usize;
8269 let n_head_kv = geometry.n_head_kv as usize;
8270 let head_dim = geometry.head_dim_k as usize;
8271 let eps = cfg.rms_eps;
8272 let scale = geometry.attention_scale();
8273 let n_embd = cfg.n_embd as usize;
8274
8275 // DECODE-EXACT Q/K/V projections: matmul_decode_exact forces the MMVQ (warp-per-row) path
8276 // for every m, matching the T=1 decode's FP accumulation order. matmul_pre at m>=5 would
8277 // fall to dp4a (128-thread, two-level reduce) with a different FP sum order.
8278 // Q8 TRUNK-FUSION at T=1: DISPATCH-MIRRORS the eager decode's fused3 (bit-identical body).
8279 // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): `h_q8` = the attn-input norm's q8_1
8280 // form emitted by the fused rms_norm_q8_1 (bit-identical to rms_norm_decode ->
8281 // quantize_q8_1, kernel-check-pinned). When present (caller checked mixer q8_1-fast),
8282 // every projection consumes it — `h` may be a zero-len placeholder and must not be read.
8283 let (qf, mut k, v) = {
8284 let mut fused = None;
8285 let qkv_fast =
8286 e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk) && e.uses_q8_1_fast(&fa.wv);
8287 if t == 1 && qkv_fast {
8288 let (hq_o, hd_o);
8289 let (hq, hd): (&CudaSlice<i8>, &CudaSlice<f32>) = match h_q8 {
8290 Some(p) => p,
8291 None => {
8292 (hq_o, hd_o) = e.quantize_q8_1(h, 1, n_embd)?;
8293 (&hq_o, &hd_o)
8294 }
8295 };
8296 fused = e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, hq, hd)?;
8297 } else if spec_fused_t() && (2..=4).contains(&t) && qkv_fast {
8298 // VERIFY-TIER TRUNK FUSION (MEMRA_SPEC_FUSED_T): one shared quantize + one
8299 // fused3 batched launch replaces three decode-exact calls (3 re-quantizes of
8300 // the same h + 3 _b2/_b4 launches). Bit-identical per (tensor,token,row).
8301 let (hq_o, hd_o);
8302 let (hq, hd): (&CudaSlice<i8>, &CudaSlice<f32>) = match h_q8 {
8303 Some(p) => p,
8304 None => {
8305 (hq_o, hd_o) = e.quantize_q8_1(h, t, n_embd)?;
8306 (&hq_o, &hd_o)
8307 }
8308 };
8309 fused = e.matmul_q8_fused3_t(&fa.wq, &fa.wk, &fa.wv, hq, hd, t)?;
8310 }
8311 match (fused, h_q8) {
8312 (Some(triple), _) => triple,
8313 // shared pre-quantized activation (q8_1-fast guaranteed by the caller): the
8314 // decode-exact dispatch consumes (hq, hd) instead of re-quantizing 3x.
8315 (None, Some((hq, hd))) if qkv_fast => (
8316 e.matmul_decode_exact_pre(&fa.wq, hq, hd, t)?,
8317 e.matmul_decode_exact_pre(&fa.wk, hq, hd, t)?,
8318 e.matmul_decode_exact_pre(&fa.wv, hq, hd, t)?,
8319 ),
8320 (None, _) => (
8321 e.matmul_decode_exact(&fa.wq, h, t)?,
8322 e.matmul_decode_exact(&fa.wk, h, t)?,
8323 e.matmul_decode_exact(&fa.wv, h, t)?,
8324 ),
8325 }
8326 };
8327 // M3/Hy3 have no attention output gate — wq out is exactly q; skip the split.
8328 let gated = geometry.attention_gate == memra_gguf::config::AttentionGateKind::FusedQ;
8329 let (mut q, gate) = if gated {
8330 let mut q = vbuf(e, t * n_head * head_dim)?; // fully written by q_gate_split
8331 let mut gate = vbuf(e, t * n_head * head_dim)?; // fully written by q_gate_split
8332 e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, t)?;
8333 (q, Some(gate))
8334 } else {
8335 (qf, None)
8336 };
8337
8338 let mut qn = vbuf(e, t * n_head * head_dim)?; // fully written by rms_norm
8339 e.rms_norm(
8340 &q,
8341 fa.q_norm.float_data(),
8342 &mut qn,
8343 head_dim,
8344 n_head * t,
8345 eps,
8346 )?;
8347 q = qn;
8348 let mut kn = vbuf(e, t * n_head_kv * head_dim)?; // fully written by rms_norm
8349 e.rms_norm(
8350 &k,
8351 fa.k_norm.float_data(),
8352 &mut kn,
8353 head_dim,
8354 n_head_kv * t,
8355 eps,
8356 )?;
8357 k = kn;
8358 let rope_dims = geometry.n_rot as usize;
8359 e.rope_neox(
8360 &mut q,
8361 pos_d,
8362 head_dim,
8363 rope_dims,
8364 n_head,
8365 t,
8366 geometry.rope_base,
8367 1.0,
8368 )?;
8369 e.rope_neox(
8370 &mut k,
8371 pos_d,
8372 head_dim,
8373 rope_dims,
8374 n_head_kv,
8375 t,
8376 geometry.rope_base,
8377 1.0,
8378 )?;
8379
8380 // append T new K/V columns to the resident QUANTIZED cache. k/v are token-major [T, kv_dim]
8381 // f32; append-quantize each of the T token rows into the byte cache (q8_0 K / q5_1 V).
8382 let kvl = cache.kv[il].as_mut().unwrap();
8383 let (kv_dim_k, kv_dim_v, ktb, vtb) =
8384 (kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes, kvl.v_tok_bytes);
8385 if let Some(ctr) = stream_ctr {
8386 // stream: ONE batched append at the device counter (rows kernel = the per-view warp
8387 // math on a (block, token) grid, documented byte-identical); host len is a stale
8388 // LOWER BOUND under pre-issue (drain reconciles it).
8389 e.append_kv_quantized_rows_dc(
8390 &k,
8391 &v,
8392 &mut kvl.k,
8393 &mut kvl.v,
8394 ctr,
8395 t,
8396 kv_dim_k,
8397 kv_dim_v,
8398 ktb,
8399 vtb,
8400 crate::Engine::kv_fp8_on(),
8401 )?;
8402 } else {
8403 for i in 0..t {
8404 let k_row = k.slice(i * kv_dim_k..(i + 1) * kv_dim_k);
8405 let v_row = v.slice(i * kv_dim_v..(i + 1) * kv_dim_v);
8406 e.append_kv_quantized_view(
8407 &k_row,
8408 &v_row,
8409 &mut kvl.k,
8410 &mut kvl.v,
8411 kvl.len + i,
8412 kv_dim_k,
8413 kv_dim_v,
8414 ktb,
8415 vtb,
8416 crate::Engine::kv_fp8_on(),
8417 )?;
8418 }
8419 kvl.len += t;
8420 }
8421
8422 // BIT-IDENTICAL VERIFY ATTENTION (spec-exactness fix): the FP accumulation order must be
8423 // byte-for-byte identical to the eager decode path. fa_prefill uses a different tile size
8424 // (BLOCK_Q=64, BK=32) and online-softmax structure than fa_decode's split-K + combine,
8425 // which changes FP summation order and can flip argmax at tight logit margins. Query row r
8426 // attends to keys [0..base_len+r+1) — each successive row sees one more key (the causal
8427 // property). This matches eager: decode appends k at len, then fa_decode sees t_kv = len+1
8428 // keys. The verify appends all T tokens first but bounds the key range per row.
8429 //
8430 // MULTI-ROW FUSED PATH (the long-ctx spec fix, 2026-07-03): when every row takes the vec
8431 // kernel (base_len+1 >= FA_VEC_MIN_TKV), ONE fa_decode_rows launch executes the exact
8432 // per-row program for all T rows (grid.z = row, per-row n_splits from the same
8433 // fa_split_keys formula) — replacing T x (2 launches + 2 dtod copies + 5 partial allocs)
8434 // and multiplying resident CTAs by T on a latency-bound kernel. Bit-identical per row by
8435 // construction; kernel-check pins rows-vs-loop byte identity, run-spec is the end gate.
8436 // Short ctx (any row below the vec crossover) and MEMRA_NO_FA_VEC/MEMRA_FA_ROWS_OFF keep the
8437 // per-row loop (whose fa_decode picks scalar/vec per row exactly like eager decode).
8438 let mut attn = vbuf(e, t * n_head * head_dim)?; // fully written by every FA arm below
8439 let base_len = kvl.len - t; // KV len BEFORE this round's T tokens were appended
8440 // T=1 INCLUDED (2026-07-05): p-min cuts the draft to 1 in ~75% of rounds on hard
8441 // (agentic) content — the old t>1 gate sent those rounds to the per-row loop (262us/row
8442 // + q-row copy + per-row allocs vs 93us/row through the fused kernel at grid.z=1, same
8443 // program). nsys accounting: 1088 of 1456 verify FA launches were T=1 escapees.
8444 // LEAN T=1 ARM (MEMRA_SPEC_LEAN, close35): at t==1, q IS one row and fa_decode on it is
8445 // the EXACT eager decode dispatch (vec_q_v2 + combine_f32; the rows pair measured +50us
8446 // at m=1). Byte-identical: kernel-check pins rows-vs-loop identity, and the per-row loop
8447 // at t=1 is fa_decode on the same q with zero-offset copies. Gates arbitrate.
8448 if let Some(ctr) = stream_ctr {
8449 // STREAM ARM: causal base from the device counter; host kvl.len is a stale lower
8450 // bound used only for the split-sizing upper bound (+64 slack covers M pre-issued
8451 // rounds at K<=8). Views span the bound; per-row limits derive in-kernel.
8452 let upper = kvl.len + t + 64;
8453 let k_view = e.view_u8(&kvl.k, (upper.min(cache.max_ctx)) * ktb);
8454 let v_view = e.view_u8(&kvl.v, (upper.min(cache.max_ctx)) * vtb);
8455 e.fa_decode_rows_dc(
8456 &q,
8457 &k_view,
8458 &v_view,
8459 &mut attn,
8460 head_dim,
8461 n_head,
8462 n_head_kv,
8463 ctr,
8464 upper.min(cache.max_ctx),
8465 t,
8466 scale,
8467 ktb,
8468 vtb,
8469 0,
8470 false,
8471 )?;
8472 } else if spec_lean() && t == 1 {
8473 let t_kv = base_len + 1;
8474 let k_view = e.view_u8(&kvl.k, t_kv * ktb);
8475 let v_view = e.view_u8(&kvl.v, t_kv * vtb);
8476 e.fa_decode_kvmod(
8477 &q,
8478 &k_view,
8479 &v_view,
8480 &mut attn,
8481 head_dim,
8482 n_head,
8483 n_head_kv,
8484 t_kv,
8485 scale,
8486 ktb,
8487 vtb,
8488 crate::Engine::kv_fp8_on(),
8489 )?;
8490 } else if e.fa_rows_eligible(base_len, head_dim) {
8491 let k_view = e.view_u8(&kvl.k, (base_len + t) * ktb);
8492 let v_view = e.view_u8(&kvl.v, (base_len + t) * vtb);
8493 e.fa_decode_rows(
8494 &q,
8495 &k_view,
8496 &v_view,
8497 &mut attn,
8498 head_dim,
8499 n_head,
8500 n_head_kv,
8501 base_len,
8502 t,
8503 scale,
8504 ktb,
8505 vtb,
8506 None,
8507 false,
8508 crate::Engine::kv_fp8_on(),
8509 None,
8510 )?;
8511 } else {
8512 for r in 0..t {
8513 let t_kv_r = base_len + r + 1; // this row sees keys [0..t_kv_r)
8514 let k_view_r = e.view_u8(&kvl.k, t_kv_r * ktb);
8515 let v_view_r = e.view_u8(&kvl.v, t_kv_r * vtb);
8516 // copy q row into an owned buffer (fa_decode takes &CudaSlice, not CudaView)
8517 let mut q_row = vbuf(e, n_head * head_dim)?; // fully written by copy_view_into
8518 let q_src = q.slice(r * n_head * head_dim..(r + 1) * n_head * head_dim);
8519 e.copy_view_into(&mut q_row, 0, &q_src, n_head * head_dim)?;
8520 let mut attn_row = vbuf(e, n_head * head_dim)?; // fully written by fa_decode
8521 e.fa_decode_kvmod(
8522 &q_row,
8523 &k_view_r,
8524 &v_view_r,
8525 &mut attn_row,
8526 head_dim,
8527 n_head,
8528 n_head_kv,
8529 t_kv_r,
8530 scale,
8531 ktb,
8532 vtb,
8533 crate::Engine::kv_fp8_on(),
8534 )?;
8535 e.copy_into(
8536 &mut attn,
8537 r * n_head * head_dim,
8538 &attn_row,
8539 n_head * head_dim,
8540 )?;
8541 }
8542 }
8543
8544 let attn_g = match &gate {
8545 Some(gate) => {
8546 let mut gsig = vbuf(e, t * n_head * head_dim)?; // fully written by sigmoid
8547 e.sigmoid(gate, &mut gsig, t * n_head * head_dim)?;
8548 let mut ag = vbuf(e, t * n_head * head_dim)?; // fully written by mul
8549 e.mul(&attn, &gsig, &mut ag, t * n_head * head_dim)?;
8550 ag
8551 }
8552 None => attn,
8553 };
8554 // DECODE-EXACT wo projection: at m>=5 (K=4+ with pending) the generic matmul would use dp4a
8555 // (128-thread, different FP sum order than MMVQ). Force MMVQ for bit-identity with decode.
8556 Ok(e.matmul_decode_exact(&fa.wo, &attn_g, t)?)
8557 }
8558
8559 /// Context-linear bytes for a plain serving session's trunk cache.
8560 pub fn plain_session_kv_bytes_per_token(&self) -> usize {
8561 crate::cache::cache_bytes_per_token_for_plan(
8562 &self.cfg,
8563 &self.plan,
8564 0,
8565 self.plan.layers.len(),
8566 )
8567 }
8568
8569 /// `(logical bytes/token, ring-capped bytes/token, ring row cap)` for exact admission.
8570 pub fn plain_session_kv_shape(&self) -> (usize, usize, usize) {
8571 (
8572 self.plain_session_kv_bytes_per_token(),
8573 crate::cache::cache_ring_bytes_per_token_for_plan(
8574 &self.cfg,
8575 &self.plan,
8576 0,
8577 self.plan.layers.len(),
8578 ),
8579 crate::cache::cache_ring_row_cap_for_plan(&self.plan),
8580 )
8581 }
8582
8583 /// Context-linear bytes for a speculative serving session: trunk cache plus persistent MTP
8584 /// scratch. With no MTP head this equals the plain coefficient.
8585 pub fn spec_session_kv_bytes_per_token(&self) -> usize {
8586 let scratch = self
8587 .mtp
8588 .iter()
8589 .chain(self.mtp_extra.iter())
8590 .map(|mtp| {
8591 let (_, _, k, v) = mtp_scratch_layout(&self.cfg, mtp.geom.as_ref());
8592 k + v
8593 })
8594 .sum::<usize>();
8595 self.plain_session_kv_bytes_per_token()
8596 .saturating_add(scratch)
8597 }
8598
8599 /// Spec twin of [`HybridModel::plain_session_kv_shape`]; Step35's persistent MTP scratch is
8600 /// capped by the same SWA ring rows as the trunk.
8601 pub fn spec_session_kv_shape(&self) -> (usize, usize, usize) {
8602 let total = self.spec_session_kv_bytes_per_token();
8603 let (_, mut ring, rows) = self.plain_session_kv_shape();
8604 if rows > 0 {
8605 ring = ring.saturating_add(
8606 self.mtp
8607 .iter()
8608 .chain(self.mtp_extra.iter())
8609 .map(|mtp| {
8610 let (_, _, k, v) = mtp_scratch_layout(&self.cfg, mtp.geom.as_ref());
8611 k + v
8612 })
8613 .sum::<usize>(),
8614 );
8615 }
8616 (total, ring, rows)
8617 }
8618
8619 /// Greedy MTP speculative decode (§B). Token-identical to `generate(prompt, max_new)` but uses
8620 /// the NextN head to draft K tokens then verifies them in one batched target forward.
8621 /// Returns (generated tokens, total_drafted, total_accepted) so the caller can report
8622 /// acceptance rate. `k` = draft length per round.
8623 ///
8624 /// GRAPH DRAFT (stage 2 of graph-grade spec): when the model is all-Dense and the MTP head is
8625 /// Dense (no MoE host readbacks), the fixed-shape T=1 MTP forward is CUDA-graph-captured ONCE
8626 /// and replayed per draft step — the ~40 eager launches per drafted token collapse into one
8627 /// graph dispatch; only the 4-byte token id (and 4-byte p-min confidence) round-trip per step.
8628 /// Event tracking is disabled for the whole call (generate_graph pattern) so every buffer the
8629 /// captured graph references is event-free; the spec loop is strictly single-stream.
8630 /// MEMRA_SPEC_NOGRAPH=1 forces the eager draft chain.
8631 /// SAMPLED mode (MEMRA_SPEC_TEMP>0) has its OWN capture (gumbel-perturbed in-graph argmax,
8632 /// device Philox event counter, persistent q retention) — graph-vs-eager sampled streams are
8633 /// bit-identical for the same (seed, prompt, K, temp); see the sampled-graph setup in
8634 /// generate_spec_inner2.
8635 /// Multi-turn session: trunk cache + MTP draft scratch persist across generate calls, so
8636 /// turn N+1 primes ONLY its new suffix (the 124k-conversation daily pattern — re-priming a
8637 /// 32k history costs ~54s; a suffix prime costs seconds). APPEND-ONLY by construction: the
8638 /// hybrid linear-attn states are in-place (no position index), so a session can extend but
8639 /// never rewind — `committed` is the exact token list whose state the caches hold (includes
8640 /// any overshoot tokens past max_new; the caller renders from `committed`, not its own echo).
8641 pub fn new_session(
8642 &self,
8643 e: &Engine,
8644 max_ctx: usize,
8645 ) -> Result<SpecSession, Box<dyn std::error::Error>> {
8646 Ok(SpecSession {
8647 // STAGE-OWNED KV (lane/pp2-spec 2026-08-06): `pp::new_cache`, not `Cache::new`. This
8648 // is the SERVING spec-session path, and with the ppN door open across two cards a
8649 // primary-homed cache makes every remote stage peer-read its OWN KV on every verify
8650 // round — the wrong-card class already fixed on the two batched serving paths
8651 // (worker.rs 2483 / 2837). With the door shut `new_cache` IS `Cache::new` (same
8652 // branch, same allocations), so single-device behavior is byte-unchanged.
8653 cache: crate::pp::new_cache_planned(e, &self.cfg, &self.plan, max_ctx)?,
8654 scratch: self.new_mtp_scratch(e, max_ctx)?,
8655 committed: Vec::new(),
8656 last_h: None,
8657 next_pred: None,
8658 sctr: 0,
8659 uctr: 0,
8660 draft_ctx: None,
8661 pending_tok: None,
8662 turn_ckpt: None,
8663 telem: SpecTelemetryCounters::default(),
8664 capture_at: None,
8665 boundary_captures: Vec::new(),
8666 ckpt_at: None,
8667 })
8668 }
8669
8670 /// SPEC-ON-CACHE-HIT restore (lane/spec-on-cache-hit, 2026-08-18 — PORT-PLAN item 3,
8671 /// research/cache-spec-design-20260814, scoped to WHOLE-ENTRY restores only): build a
8672 /// SpecSession around a trunk cache the worker already restored from a prefix-cache
8673 /// entry, re-installing the entry's published draft plane as the MTP scratch rows
8674 /// `[0..prefix.len())` and the entry's boundary hidden as `last_h`, then feeding the
8675 /// prompt SUFFIX here — through EXACTLY the plain path's program selection — so the
8676 /// worker always receives a fully-warm continuation session (committed = whole
8677 /// prompt, `next_pred` + `last_h` set; caller sets `next_pred` from the entry's
8678 /// boundary logits on the empty-suffix shape).
8679 ///
8680 /// PROGRAM LAW (the splitiso two-programs class, learned AGAIN in this lane's own
8681 /// gate): the identity target for a converted hit is the PLAIN hit serving the same
8682 /// request, and plain feeds a carried suffix via eager `decode_step` below
8683 /// PRIME_MIN_T and via `prime_cache` at/above it (prefill_tick's arms). The generate
8684 /// path's tokenwise arm routes qwen35-class through the BATCHED T=1 program
8685 /// (`spec_target_step_h`) instead — ULP-different suffix rows, and the gate measured
8686 /// the near-tie flip at generated token ~8 (research/spec-cache-20260818, qwen r3).
8687 /// So the suffix is fed HERE, mirroring prefill_tick arm-for-arm, not handed to the
8688 /// burst prime.
8689 ///
8690 /// SEED RULE (both sampling regimes; lane/sampled-hit-spec 2026-08-19, sampled draw
8691 /// added by lane/sampled-spec-quality 2026-08-19). The boundary token is produced by
8692 /// EXACTLY the rule the cold burst entry applies to its own first token from the same
8693 /// logits row: `argmax` when greedy, and a `sample_boundary_token` draw at Philox
8694 /// counter 0 when sampled. Both shapes are covered — the entry's boundary logits on a
8695 /// full-cover (empty-suffix) hit, this feed's own boundary logits on a suffix hit.
8696 /// That is what keeps a restored session seed-identical to a cold one PER SEED: the
8697 /// cold session draws from the identical row at counter 0 and then runs its rounds from
8698 /// counter 1, so the restored session admits with `sctr = 1` after its own draw.
8699 /// The WORKER owns the one refusal this constructor cannot see — a constrained request.
8700 /// (The penalized-sampled refusal was LIFTED once the burst's penalty window learned to
8701 /// span the session: `committed` here is the WHOLE prompt, so the restored session's
8702 /// window is the cold session's window. It comes back if `MEMRA_SPEC_PEN_SESSION=0`.)
8703 ///
8704 /// NOT the rolled-back partial-restore hazard: the caller restores at exactly the
8705 /// entry's captured endpoint (`e.pos`) through the shipping whole-entry path;
8706 /// mid-entry (`at < e.pos`) trunk restores stay behind MEMRA_PREFIX_PARTIAL_RESTORE
8707 /// and are never routed here.
8708 ///
8709 /// Failure contract: `Err((Some(cache), why))` before any trunk mutation — the
8710 /// worker rebuilds the plain carrier and the hit serves plain, byte-unchanged.
8711 /// `Err((None, why))` after the suffix feed began — the carrier is part-fed and
8712 /// UNUSABLE; the worker serves the request cold-plain (correct, slower) and the
8713 /// entry stays published for the next request.
8714 #[allow(clippy::too_many_arguments)]
8715 pub fn spec_session_from_restored(
8716 &self,
8717 e: &Engine,
8718 mut cache: Cache,
8719 prefix: Vec<u32>,
8720 suffix: &[u32],
8721 draft_k: &CudaSlice<u8>,
8722 draft_v: &CudaSlice<u8>,
8723 draft_k_tok_bytes: usize,
8724 draft_v_tok_bytes: usize,
8725 draft_len: usize,
8726 last_h: &[f32],
8727 // The ENTRY's boundary logits row (the full-cover shape's seed source). May be empty
8728 // when a suffix follows — the feed's own logits are the boundary then.
8729 boundary_logits: &[f32],
8730 // The request's sampler, or None for greedy. Owned here so the seed rule lives in
8731 // ONE place instead of being half-applied by the worker.
8732 sampling: Option<SpecSampling>,
8733 require_anchor: bool,
8734 max_ctx: usize,
8735 // STABLE-BOUNDARY REPUBLICATION (lane/frspec-multiturn-cache, 2026-08-21): ABSOLUTE
8736 // prompt position to split the suffix feed at and capture the extended-entry
8737 // publication + this session's `turn_ckpt` — the worker's stable pre-generation
8738 // boundary (`plain_checkpoint_boundary`). None = legacy prompt-end republication.
8739 // WHY: the prompt-end capture below includes the template's live generation header
8740 // (`<|im_start|>assistant\n<think>\n`), which the next turn's re-render replaces, so
8741 // for a hybrid (whole-entry restores only) every extended entry's last ~2 tokens
8742 // diverged from every future prompt and the hit boundary FROZE at the first
8743 // lcp-split entry forever (measured: cached 6811 of 38228 by turn 8, B4).
8744 republish_at: Option<usize>,
8745 ) -> Result<SpecSession, (Option<Cache>, String)> {
8746 let pos = prefix.len();
8747 let fail = |cache: Cache, msg: String| -> Result<SpecSession, (Option<Cache>, String)> {
8748 Err((Some(cache), msg))
8749 };
8750 if self.mtp.is_none() {
8751 return fail(cache, "no MTP head attached (nothing to draft with)".into());
8752 }
8753 if pos == 0 {
8754 return fail(cache, "empty committed prefix".into());
8755 }
8756 if cache.pos != pos {
8757 let msg = format!(
8758 "restored cache pos {} != restored prefix len {pos}",
8759 cache.pos
8760 );
8761 return fail(cache, msg);
8762 }
8763 if draft_len != pos {
8764 return fail(
8765 cache,
8766 format!("draft plane len {draft_len} != restored prefix len {pos}"),
8767 );
8768 }
8769 if pos + suffix.len() >= max_ctx {
8770 return fail(
8771 cache,
8772 format!(
8773 "prompt {} + suffix would not leave generation room in ctx {max_ctx}",
8774 pos + suffix.len(),
8775 ),
8776 );
8777 }
8778 let mut scratch = match MtpScratch::new(
8779 e,
8780 &self.cfg,
8781 &self.plan,
8782 max_ctx,
8783 self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
8784 ) {
8785 Ok(s) => s,
8786 Err(err) => return fail(cache, format!("draft scratch alloc failed: {err}")),
8787 };
8788 if scratch.kv.ring.is_some() {
8789 return fail(
8790 cache,
8791 "ring-backed draft scratch (Step35 SWA) cannot take a flat prefix restore".into(),
8792 );
8793 }
8794 if scratch.kv.k_tok_bytes != draft_k_tok_bytes
8795 || scratch.kv.v_tok_bytes != draft_v_tok_bytes
8796 {
8797 return fail(
8798 cache,
8799 format!(
8800 "draft plane layout {draft_k_tok_bytes}/{draft_v_tok_bytes} != scratch \
8801 {}/{} bytes/token (stale entry across a format change)",
8802 scratch.kv.k_tok_bytes, scratch.kv.v_tok_bytes,
8803 ),
8804 );
8805 }
8806 if pos > scratch.cap {
8807 return fail(
8808 cache,
8809 format!(
8810 "draft plane rows {pos} exceed scratch capacity {}",
8811 scratch.cap
8812 ),
8813 );
8814 }
8815 let kb = pos * draft_k_tok_bytes;
8816 let vb = pos * draft_v_tok_bytes;
8817 if draft_k.len() < kb || draft_v.len() < vb {
8818 return fail(
8819 cache,
8820 format!(
8821 "truncated draft plane: K {} < {kb} or V {} < {vb} bytes",
8822 draft_k.len(),
8823 draft_v.len(),
8824 ),
8825 );
8826 }
8827 if kb > 0 {
8828 if let Err(err) = e.copy_u8_into(&mut scratch.kv.k, 0, draft_k, kb) {
8829 return fail(cache, format!("draft K restore copy failed: {err}"));
8830 }
8831 }
8832 if vb > 0 {
8833 if let Err(err) = e.copy_u8_into(&mut scratch.kv.v, 0, draft_v, vb) {
8834 return fail(cache, format!("draft V restore copy failed: {err}"));
8835 }
8836 }
8837 if let Err(err) = scratch.set_len(e, pos) {
8838 return fail(cache, format!("draft scratch len set failed: {err}"));
8839 }
8840 let mut last_h_dev = if last_h.len() == self.cfg.n_embd as usize {
8841 // anchor upload failure is acceptance-only when a suffix feed follows (fill
8842 // row-0 falls back to zeros) but FATAL for an empty-suffix continuation (the
8843 // burst entry asserts committed + last_h + next_pred) — the caller says which.
8844 e.htod(last_h).ok()
8845 } else {
8846 None
8847 };
8848 if require_anchor && last_h_dev.is_none() {
8849 return fail(
8850 cache,
8851 "empty-suffix continuation requires the entry's boundary hidden anchor".into(),
8852 );
8853 }
8854 let mut committed = prefix;
8855 // Set on BOTH shapes below (suffix-fed and full-cover) — never left None, which is
8856 // what the empty-suffix continuation assert in the burst entry requires.
8857 let next_pred;
8858 // Philox: (0,0) at admit exactly like a fresh session; a sampled boundary draw below
8859 // consumes counter 0 and leaves 1, which is the state a cold session reaches after
8860 // drawing its own first token from the same row.
8861 let mut sctr = 0u32;
8862 let sampled = sampling.is_some_and(|s| s.temp > 0.0) && spec_sampled_boundary_on();
8863 // Penalty window for the boundary draw: the last `penalty_last_n` tokens of the WHOLE
8864 // prompt, which is what the cold session's own burst sees (Item 2's window). Built
8865 // after the suffix joins `committed` below.
8866 let mut boundary_captures: Vec<SpecBoundaryCapture> = Vec::new();
8867 let mut restored_turn_ckpt: Option<SpecCheckpoint> = None;
8868 if !suffix.is_empty() {
8869 // ---- SUFFIX FEED, mirroring prefill_tick's program selection exactly ----
8870 // From here on the trunk cache mutates: failures return Err((None, _)) and
8871 // the worker serves the request cold-plain instead of reusing the carrier.
8872 let dirty =
8873 |msg: String| -> Result<SpecSession, (Option<Cache>, String)> { Err((None, msg)) };
8874 let n_embd = self.cfg.n_embd as usize;
8875 let t = suffix.len();
8876 let mut h_rows = match e.uninit(t * n_embd) {
8877 Ok(b) => b,
8878 Err(err) => return fail(cache, format!("suffix hidden buffer alloc: {err}")),
8879 };
8880 // STABLE-BOUNDARY split (see `republish_at`): feed stops at the boundary so the
8881 // in-place GDN conv/ssm state can be snapshotted there — the only moment it
8882 // exists (the cold prime-split law). suffix-relative; None = one-segment legacy.
8883 let b_rel = republish_at
8884 .and_then(|abs| abs.checked_sub(pos))
8885 .filter(|&r| r > 0 && r < t);
8886 let mut feed_logits = Vec::new();
8887 let tokenwise_env = std::env::var("MEMRA_PRIME_TOKENWISE").is_ok()
8888 || e.frozen_cpu_experts_prefer_tokenwise_prime();
8889 let mut fed = 0usize;
8890 for seg_end in [b_rel, Some(t)].into_iter().flatten() {
8891 if seg_end <= fed {
8892 continue;
8893 }
8894 let seg = &suffix[fed..seg_end];
8895 let batched = seg.len() >= crate::hybrid_forward::PRIME_MIN_T && !tokenwise_env;
8896 if batched {
8897 // prefill_tick's prime arm: request-level prime_cache call; tokens still
8898 // queued after this segment ride `queued_after` so Step35 arm selection
8899 // stays keyed to the request's end (tick-seg law).
8900 match self.prime_cache(e, seg, &mut cache, t - seg_end) {
8901 Ok((l, _h_seed, hiddens)) => {
8902 if let Err(err) =
8903 e.copy_into(&mut h_rows, fed * n_embd, &hiddens, seg.len() * n_embd)
8904 {
8905 return dirty(format!("suffix hidden copy: {err}"));
8906 }
8907 feed_logits = l;
8908 }
8909 Err(err) => return dirty(format!("suffix prime failed: {err}")),
8910 }
8911 } else {
8912 // prefill_tick's tokenwise arm: eager decode_step, one token at a time.
8913 for (i, &tok) in seg.iter().enumerate() {
8914 match self.decode_step_h(e, tok, &mut cache) {
8915 Ok((l, h)) => {
8916 if let Err(err) =
8917 e.copy_into(&mut h_rows, (fed + i) * n_embd, &h, n_embd)
8918 {
8919 return dirty(format!("suffix hidden copy: {err}"));
8920 }
8921 feed_logits = l;
8922 }
8923 Err(err) => return dirty(format!("suffix decode_step failed: {err}")),
8924 }
8925 }
8926 }
8927 fed = seg_end;
8928 if Some(seg_end) == b_rel {
8929 // The stable pre-generation boundary: capture the extended-entry
8930 // publication AND this session's own turn checkpoint here instead of at
8931 // prompt-end (both would otherwise carry the volatile live-header tail
8932 // the next re-render replaces). Failure silent, turn_ckpt convention.
8933 debug_assert_eq!(
8934 cache.pos,
8935 pos + seg_end,
8936 "stable-boundary capture off the feed split"
8937 );
8938 if spec_restore_republish_on() {
8939 if let Ok(snap) = cache.snapshot(e) {
8940 boundary_captures.push(SpecBoundaryCapture {
8941 snap,
8942 pos: pos + seg_end,
8943 logits: feed_logits.clone(),
8944 last_h: capture_boundary_hidden(e, &h_rows, seg_end, n_embd),
8945 });
8946 }
8947 }
8948 let anchor: Result<CudaSlice<f32>, Box<dyn std::error::Error>> =
8949 e.uninit(n_embd).and_then(|mut a| {
8950 e.copy_view_into(
8951 &mut a,
8952 0,
8953 &h_rows.slice((seg_end - 1) * n_embd..seg_end * n_embd),
8954 n_embd,
8955 )?;
8956 Ok(a)
8957 });
8958 if let (Ok(snap), Ok(last_h)) = (cache.snapshot(e), anchor) {
8959 restored_turn_ckpt = Some(SpecCheckpoint {
8960 snap,
8961 pos: pos + seg_end,
8962 last_h,
8963 });
8964 }
8965 }
8966 }
8967 // Draft-scratch fill for the suffix rows, predecessor-paired: row `pos` reads
8968 // the entry's boundary anchor (zeros fallback — acceptance-only), row `pos+i`
8969 // reads h_rows[i-1]. Chunked like the generate path's fill (transients scale
8970 // with T). Fill failures are acceptance-only — truncate to the restored rows
8971 // and continue; the burst's own set_len keeps the invariant.
8972 let mtp = self.mtp.as_ref().expect("mtp checked above");
8973 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
8974 let embd_gpu = if spec_host_embd() {
8975 None
8976 } else {
8977 Some(
8978 self.embd_gpu
8979 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
8980 )
8981 };
8982 let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
8983 let fill_chunk = 4096usize;
8984 let mut filled = true;
8985 let mut start = 0usize;
8986 'fill: while start < t {
8987 let end = (start + fill_chunk).min(t);
8988 let tc = end - start;
8989 let Ok(mut phs) = e.zeros(tc * n_embd) else {
8990 filled = false;
8991 break 'fill;
8992 };
8993 let (src_lo, dst_off, n_copy) = if start == 0 {
8994 (0, n_embd, (tc - 1) * n_embd)
8995 } else {
8996 ((start - 1) * n_embd, 0, tc * n_embd)
8997 };
8998 if start == 0 {
8999 if let Some(lh) = last_h_dev.as_ref() {
9000 if e.copy_into(&mut phs, 0, lh, n_embd).is_err() {
9001 filled = false;
9002 break 'fill;
9003 }
9004 }
9005 }
9006 if n_copy > 0
9007 && e.copy_view_into(
9008 &mut phs,
9009 dst_off,
9010 &h_rows.slice(src_lo..src_lo + n_copy),
9011 n_copy,
9012 )
9013 .is_err()
9014 {
9015 filled = false;
9016 break 'fill;
9017 }
9018 if self
9019 .mtp_kv_fill_all(
9020 e,
9021 &suffix[start..end],
9022 &phs,
9023 pos + start,
9024 &mut scratch,
9025 embd_dev,
9026 )
9027 .is_err()
9028 {
9029 filled = false;
9030 break 'fill;
9031 }
9032 start = end;
9033 }
9034 if !filled {
9035 // acceptance-only: drafts over missing suffix rows are cheap and wrong,
9036 // so keep only the restored rows resident and let verify arbitrate.
9037 if let Err(err) = scratch.set_len(e, pos) {
9038 return dirty(format!("scratch truncation after failed fill: {err}"));
9039 }
9040 }
9041 // EXTENDED-ENTRY PUBLICATION (lane/sampled-spec-quality, Item 3 — the fix for
9042 // "a restored spec session never publishes an extended entry", SAMPLED-HIT.md
9043 // finding (d)). Pre-lane, publication was armed only for COLD sessions
9044 // (`spec_resumed == 0` in the worker) and both engine capture sites require a
9045 // non-continuation burst — but a converted hit's first burst IS a continuation,
9046 // so a growing conversation learned exactly ONE boundary and turn 3 could never
9047 // hit a longer prefix than turn 2 did.
9048 //
9049 // WHERE, and why it is safe here: `cache.pos == prefix + suffix` at this exact
9050 // line — the trunk is primed over the whole prompt, nothing is generated, and the
9051 // draft plane rows [0..prompt) are filled just above. That is a complete
9052 // whole-entry boundary (`pos == fed_len`), the same shape the cold seed capture
9053 // publishes; the worker's existing publication sweep picks it up because it is
9054 // keyed on non-empty `boundary_captures` and is sampler- and resume-independent.
9055 // NOT the partial-restore hazard: the boundary is this session's own prompt END,
9056 // never mid-entry, so `entry_pos != fed_len` still refuses on the way back in.
9057 // Failure is SILENT by design (the turn_ckpt / boundary-capture convention):
9058 // publication is an optimization, never a correctness dependency.
9059 //
9060 // SUPERSEDED WHEN `republish_at` FIRED (lane/frspec-multiturn-cache): a prompt-end
9061 // entry's tail is the live generation header the next re-render replaces, so on a
9062 // hybrid (whole-entry restores) it can never serve the conversation's next turn —
9063 // the stable-boundary capture above IS this publication, minus the poisoned tail.
9064 if spec_restore_republish_on() && boundary_captures.is_empty() {
9065 debug_assert_eq!(
9066 cache.pos,
9067 pos + t,
9068 "extended-entry capture must sit at the restored session's prompt end",
9069 );
9070 if let Ok(snap) = cache.snapshot(e) {
9071 boundary_captures.push(SpecBoundaryCapture {
9072 snap,
9073 pos: pos + t,
9074 logits: feed_logits.clone(),
9075 last_h: capture_boundary_hidden(e, &h_rows, t, n_embd),
9076 });
9077 }
9078 }
9079 // continuation seed: the feed's boundary logits ARE the plain path's boundary
9080 // logits (same program), so greedy's argmax here is plain's first emitted token,
9081 // and the sampled draw is the cold sampled session's own first token.
9082 next_pred = Some(if sampled {
9083 let sp = sampling.expect("sampled implies a sampler");
9084 // `committed` is still the restored prefix here; the suffix joins it below —
9085 // so this is the last-N window over the WHOLE prompt, exactly the cold
9086 // session's own window at its first token.
9087 let hist = pen_window_seed(&committed, suffix, sp.penalty_last_n);
9088 match sample_boundary_token(
9089 e,
9090 &feed_logits,
9091 &sp,
9092 &hist,
9093 &mut sctr,
9094 "restore-suffix-feed",
9095 ) {
9096 Ok(t) => t,
9097 // the trunk is already fed: hand nothing back, the worker serves the
9098 // request cold-plain. Never fall back to an argmax — that would put a
9099 // greedy token in a sampled stream to save a slow path.
9100 Err(err) => {
9101 return dirty(format!("boundary token draw failed: {err}"));
9102 }
9103 }
9104 } else {
9105 argmax(&feed_logits) as u32
9106 });
9107 let mut lh = match e.uninit(n_embd) {
9108 Ok(b) => b,
9109 Err(err) => return dirty(format!("boundary hidden alloc: {err}")),
9110 };
9111 if let Err(err) = e.copy_view_into(
9112 &mut lh,
9113 0,
9114 &h_rows.slice((t - 1) * n_embd..t * n_embd),
9115 n_embd,
9116 ) {
9117 return dirty(format!("boundary hidden copy: {err}"));
9118 }
9119 last_h_dev = Some(lh);
9120 committed.extend_from_slice(suffix);
9121 } else {
9122 // FULL-COVER shape (empty suffix — the identical-repeat / agent-loop shape): the
9123 // ENTRY's boundary logits are the boundary row, and this is the token the cold
9124 // session emits from that same row. Owned here rather than in the worker so the
9125 // sampled draw cannot be half-applied on one shape (the worker used to argmax it).
9126 if boundary_logits.is_empty() {
9127 return fail(
9128 cache,
9129 "full-cover restore without the entry's boundary logits".into(),
9130 );
9131 }
9132 next_pred = Some(if sampled {
9133 let sp = sampling.expect("sampled implies a sampler");
9134 let hist = pen_window_seed(&committed, &[], sp.penalty_last_n);
9135 match sample_boundary_token(
9136 e,
9137 boundary_logits,
9138 &sp,
9139 &hist,
9140 &mut sctr,
9141 "restore-full-cover",
9142 ) {
9143 Ok(t) => t,
9144 // nothing has been mutated on this shape — hand the carrier back and let
9145 // the hit serve PLAIN (the banked pre-lane path).
9146 Err(err) => {
9147 return fail(cache, format!("boundary token draw failed: {err}"));
9148 }
9149 }
9150 } else {
9151 argmax(boundary_logits) as u32
9152 });
9153 }
9154 Ok(SpecSession {
9155 cache,
9156 scratch,
9157 committed,
9158 last_h: last_h_dev,
9159 next_pred,
9160 sctr,
9161 uctr: 0,
9162 draft_ctx: None,
9163 pending_tok: None,
9164 // Stable-boundary capture from the split feed above (None on the legacy shape):
9165 // a restored session previously parked WITHOUT a checkpoint, so the next turn's
9166 // affinity probe declined ("no turn checkpoint retained") and the conversation
9167 // fell back to the frozen prefix entry forever.
9168 turn_ckpt: restored_turn_ckpt,
9169 telem: SpecTelemetryCounters::default(),
9170 capture_at: None,
9171 boundary_captures,
9172 ckpt_at: None,
9173 })
9174 }
9175
9176 /// Forced-gate exact state comparison. This intentionally reads the real live prefixes from
9177 /// their owning PP devices: matching emitted ids alone would miss a stale `len_d`, recurrent
9178 /// snapshot, or draft-KV row that only corrupts the following round.
9179 pub fn optipipe_compare_session_state(
9180 &self,
9181 e: &Engine,
9182 reference: &SpecSession,
9183 candidate: &SpecSession,
9184 ) -> Result<OptiForkStateIdentity, Box<dyn std::error::Error>> {
9185 fn fail(what: &str) -> Box<dyn std::error::Error> {
9186 format!("optipipe state mismatch: {what}").into()
9187 }
9188 fn same_f32(a: &[f32], b: &[f32]) -> bool {
9189 a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.to_bits() == y.to_bits())
9190 }
9191 fn compare_layers(
9192 es: &Engine,
9193 range: std::ops::Range<usize>,
9194 reference: &SpecSession,
9195 candidate: &SpecSession,
9196 report: &mut OptiForkStateIdentity,
9197 ) -> Result<(), Box<dyn std::error::Error>> {
9198 for il in range {
9199 match (&reference.cache.kv[il], &candidate.cache.kv[il]) {
9200 (Some(a), Some(b)) => {
9201 if a.len != b.len {
9202 return Err(fail(&format!(
9203 "layer {il} host KV len {} != {}",
9204 a.len, b.len
9205 )));
9206 }
9207 let ad = es.dtoh_i32(&a.len_d)?;
9208 let bd = es.dtoh_i32(&b.len_d)?;
9209 if ad != bd || ad.first().copied() != Some(a.len as i32) {
9210 return Err(fail(&format!(
9211 "layer {il} device KV len {ad:?} != {bd:?} (host={})",
9212 a.len,
9213 )));
9214 }
9215 let kb = a.len * a.k_tok_bytes;
9216 let vb = a.len * a.v_tok_bytes;
9217 if kb > 0 {
9218 let ak = es.dtoh_u8_view(&a.k.slice(0..kb))?;
9219 let bk = es.dtoh_u8_view(&b.k.slice(0..kb))?;
9220 if ak != bk {
9221 let at = ak.iter().zip(&bk).position(|(x, y)| x != y).unwrap();
9222 return Err(fail(&format!(
9223 "layer {il} K bytes at byte {at} row {} offset {}: {} != {}",
9224 at / a.k_tok_bytes,
9225 at % a.k_tok_bytes,
9226 ak[at],
9227 bk[at],
9228 )));
9229 }
9230 }
9231 if vb > 0 {
9232 let av = es.dtoh_u8_view(&a.v.slice(0..vb))?;
9233 let bv = es.dtoh_u8_view(&b.v.slice(0..vb))?;
9234 if av != bv {
9235 let at = av.iter().zip(&bv).position(|(x, y)| x != y).unwrap();
9236 return Err(fail(&format!(
9237 "layer {il} V bytes at byte {at} row {} offset {}: {} != {}",
9238 at / a.v_tok_bytes,
9239 at % a.v_tok_bytes,
9240 av[at],
9241 bv[at],
9242 )));
9243 }
9244 }
9245 report.trunk_kv_bytes += kb + vb;
9246 }
9247 (None, None) => {}
9248 _ => return Err(fail(&format!("layer {il} KV presence"))),
9249 }
9250 match (&reference.cache.recur[il], &candidate.cache.recur[il]) {
9251 (Some(a), Some(b)) => {
9252 let ac = es.dtoh(&a.conv_state)?;
9253 let bc = es.dtoh(&b.conv_state)?;
9254 if !same_f32(&ac, &bc) {
9255 return Err(fail(&format!("layer {il} conv state")));
9256 }
9257 let as_ = es.dtoh(&a.ssm_state)?;
9258 let bs = es.dtoh(&b.ssm_state)?;
9259 if !same_f32(&as_, &bs) {
9260 return Err(fail(&format!("layer {il} SSM state")));
9261 }
9262 report.recurrent_bytes += (ac.len() + as_.len()) * 4;
9263 }
9264 (None, None) => {}
9265 _ => return Err(fail(&format!("layer {il} recurrent presence"))),
9266 }
9267 }
9268 Ok(())
9269 }
9270
9271 if reference.committed != candidate.committed {
9272 return Err(fail("committed token ids"));
9273 }
9274 if reference.cache.pos != candidate.cache.pos
9275 || reference.cache.max_ctx != candidate.cache.max_ctx
9276 {
9277 return Err(fail("cache pos/capacity"));
9278 }
9279 if reference.pending_tok != candidate.pending_tok
9280 || reference.next_pred != candidate.next_pred
9281 || reference.sctr != candidate.sctr
9282 || reference.uctr != candidate.uctr
9283 {
9284 return Err(fail("pending/prediction/counter tail"));
9285 }
9286
9287 let mut report = OptiForkStateIdentity::default();
9288 if let Some(fence) = crate::pp::pp_cuts(self.layers.len()) {
9289 let rt = crate::pp::PpNRt::get(e)?;
9290 for stage in 0..rt.n_stages() {
9291 let _scope = rt.enter(stage);
9292 compare_layers(
9293 rt.engine(stage, e),
9294 fence[stage]..fence[stage + 1],
9295 reference,
9296 candidate,
9297 &mut report,
9298 )?;
9299 }
9300 } else {
9301 compare_layers(e, 0..self.layers.len(), reference, candidate, &mut report)?;
9302 }
9303
9304 if reference.scratch.plane_count() != candidate.scratch.plane_count() {
9305 return Err(fail("draft scratch plane count"));
9306 }
9307 for index in 0..reference.scratch.plane_count() {
9308 let (a, _) = reference.scratch.plane(index);
9309 let (b, _) = candidate.scratch.plane(index);
9310 if a.len != b.len
9311 || a.kv_dim_k != b.kv_dim_k
9312 || a.kv_dim_v != b.kv_dim_v
9313 || a.k_tok_bytes != b.k_tok_bytes
9314 || a.v_tok_bytes != b.v_tok_bytes
9315 || e.dtoh_i32(&a.len_d)? != e.dtoh_i32(&b.len_d)?
9316 {
9317 return Err(fail(&format!("draft scratch plane {index} length/layout")));
9318 }
9319 let kb = a.len * a.k_tok_bytes;
9320 let vb = a.len * a.v_tok_bytes;
9321 if kb > 0 && e.dtoh_u8_view(&a.k.slice(0..kb))? != e.dtoh_u8_view(&b.k.slice(0..kb))? {
9322 return Err(fail(&format!("draft scratch plane {index} K bytes")));
9323 }
9324 if vb > 0 && e.dtoh_u8_view(&a.v.slice(0..vb))? != e.dtoh_u8_view(&b.v.slice(0..vb))? {
9325 return Err(fail(&format!("draft scratch plane {index} V bytes")));
9326 }
9327 report.scratch_kv_bytes += kb + vb;
9328 }
9329
9330 match (&reference.last_h, &candidate.last_h) {
9331 (Some(a), Some(b)) => {
9332 let ah = e.dtoh(a)?;
9333 let bh = e.dtoh(b)?;
9334 if !same_f32(&ah, &bh) {
9335 return Err(fail("last hidden/seed bytes"));
9336 }
9337 report.hidden_bytes = ah.len() * 4;
9338 }
9339 (None, None) => {}
9340 _ => return Err(fail("last hidden/seed presence")),
9341 }
9342 Ok(report)
9343 }
9344
9345 /// SESSION-AFFINITY REWIND (lane/session-affinity, 2026-08-05): roll `sess` back to its
9346 /// retained prompt-end checkpoint, so a request whose prompt matches
9347 /// `committed[..rewind_pos()]` exactly can resume there and prime only its own delta.
9348 ///
9349 /// EXACTNESS. After this returns, the session is byte-for-byte the state it was in AT that
9350 /// boundary: full-attn KV truncated to it (append-only, position-addressed), GDN conv/ssm
9351 /// restored from the device copy taken there, draft scratch length reset, `committed`
9352 /// truncated, `last_h` = the boundary's predecessor anchor. That is precisely the state a
9353 /// fresh prime of `committed[..pos]` would have produced, so the following suffix prime and
9354 /// every burst after it are identical to a cold run of the same token stream — the
9355 /// committed-tokens-authoritative contract.
9356 ///
9357 /// `next_pred` and `pending_tok` are CLEARED: both describe generation past the boundary,
9358 /// which the rewind discards. The caller therefore must supply a non-empty suffix (a
9359 /// rewound session cannot serve an empty-suffix continuation burst — there is nothing to
9360 /// continue). The persistent draft graph survives: it bakes only session-stable pointers
9361 /// (the scratch KV, the resident embedding), none of which the rewind moves.
9362 ///
9363 /// The checkpoint is CONSUMED (`turn_ckpt` taken): its snapshot buffers are freed here, and
9364 /// this turn's own prime installs a fresh one at the new prompt end. Returns the position
9365 /// rewound to, or `None` when the session holds no checkpoint (caller: full re-prime).
9366 pub fn spec_rewind_to_checkpoint(
9367 &self,
9368 e: &Engine,
9369 sess: &mut SpecSession,
9370 ) -> Result<Option<usize>, Box<dyn std::error::Error>> {
9371 if sess.turn_ckpt.as_ref().is_some_and(|ckpt| {
9372 !sess.cache.can_rollback(&ckpt.snap, 0) || !sess.scratch.can_rewind_to(ckpt.pos)
9373 }) {
9374 return Err(
9375 "SWA ring rewind checkpoint has been lapped; full re-prime required".into(),
9376 );
9377 }
9378 let Some(ckpt) = sess.turn_ckpt.take() else {
9379 return Ok(None);
9380 };
9381 assert!(
9382 ckpt.pos <= sess.committed.len(),
9383 "checkpoint past committed ({} > {})",
9384 ckpt.pos,
9385 sess.committed.len()
9386 );
9387 // Restore through each layer's owning engine. A single primary-engine rollback is not
9388 // sufficient when the serving cache is stage-owned under cross-device PP.
9389 crate::pp::restore_cache_checkpoint(e, self, None, &mut sess.cache, &ckpt.snap)?;
9390 debug_assert_eq!(
9391 sess.cache.pos, ckpt.pos,
9392 "rollback landed off the checkpoint"
9393 );
9394 sess.scratch.set_len(e, ckpt.pos)?;
9395 sess.committed.truncate(ckpt.pos);
9396 sess.last_h = Some(ckpt.last_h);
9397 sess.next_pred = None;
9398 sess.pending_tok = None;
9399 Ok(Some(ckpt.pos))
9400 }
9401
9402 /// Grow a parked speculative session to `target_cap` and rewind it to its retained turn
9403 /// checkpoint without re-priming the checkpoint prefix.
9404 ///
9405 /// The trunk cache is restored exactly like a plain grown cache: append-only full-attention
9406 /// KV rows come from the parked cache, while recurrent state comes from the checkpoint's
9407 /// owned snapshot. The MTP scratch is also context-linear and its rows below the checkpoint
9408 /// remain authoritative, so they are copied into a fresh larger scratch before its length is
9409 /// truncated. Pointer-baking draft graphs are dropped and recaptured on the next burst.
9410 ///
9411 /// All fallible work completes before `sess` is mutated. A failed allocation or copy leaves
9412 /// the parked session intact, allowing the caller one reclaim-and-retry attempt.
9413 pub fn spec_grow_and_rewind_to_checkpoint(
9414 &self,
9415 e: &Engine,
9416 sess: &mut SpecSession,
9417 target_cap: usize,
9418 ) -> Result<Option<usize>, Box<dyn std::error::Error>> {
9419 if target_cap <= sess.cache.max_ctx {
9420 return self.spec_rewind_to_checkpoint(e, sess);
9421 }
9422 let Some(ckpt) = sess.turn_ckpt.as_ref() else {
9423 return Ok(None);
9424 };
9425 if ckpt.pos == 0 || ckpt.pos > sess.committed.len() {
9426 return Err(format!(
9427 "checkpoint pos {} outside committed length {}",
9428 ckpt.pos,
9429 sess.committed.len(),
9430 )
9431 .into());
9432 }
9433 if ckpt.pos > target_cap {
9434 return Err(format!(
9435 "checkpoint pos {} exceeds grown capacity {target_cap}",
9436 ckpt.pos,
9437 )
9438 .into());
9439 }
9440
9441 let mut grown_cache = crate::pp::new_cache_planned(e, &self.cfg, &self.plan, target_cap)?;
9442 let mut grown_scratch = self.new_mtp_scratch(e, target_cap)?;
9443 crate::pp::restore_cache_checkpoint(
9444 e,
9445 self,
9446 Some(&sess.cache),
9447 &mut grown_cache,
9448 &ckpt.snap,
9449 )?;
9450
9451 if sess.scratch.plane_count() != grown_scratch.plane_count() {
9452 return Err("checkpoint draft plane count mismatch".into());
9453 }
9454 for index in 0..sess.scratch.plane_count() {
9455 let (src, _) = sess.scratch.plane(index);
9456 let (dst, _) = grown_scratch.plane_mut(index);
9457 if ckpt.pos > src.len
9458 || src.kv_dim_k != dst.kv_dim_k
9459 || src.kv_dim_v != dst.kv_dim_v
9460 || src.k_tok_bytes != dst.k_tok_bytes
9461 || src.v_tok_bytes != dst.v_tok_bytes
9462 {
9463 return Err(format!(
9464 "checkpoint draft plane {index} layout mismatch (pos {}, source len {})",
9465 ckpt.pos, src.len,
9466 )
9467 .into());
9468 }
9469 let kb = ckpt.pos * src.k_tok_bytes;
9470 let vb = ckpt.pos * src.v_tok_bytes;
9471 if kb > 0 {
9472 e.copy_u8_into(&mut dst.k, 0, &src.k, kb)?;
9473 }
9474 if vb > 0 {
9475 e.copy_u8_into(&mut dst.v, 0, &src.v, vb)?;
9476 }
9477 }
9478 grown_scratch.set_len(e, ckpt.pos)?;
9479 // The old scratch is dropped immediately after publication below. Bound its D2D reads
9480 // first; growth happens once per rewritten turn, outside the decode hot loop.
9481 e.stream().synchronize()?;
9482
9483 let ckpt = sess
9484 .turn_ckpt
9485 .take()
9486 .expect("checkpoint remained present through transactional grow");
9487 let pos = ckpt.pos;
9488 sess.cache = grown_cache;
9489 sess.scratch = grown_scratch;
9490 sess.committed.truncate(pos);
9491 sess.last_h = Some(ckpt.last_h);
9492 sess.next_pred = None;
9493 sess.pending_tok = None;
9494 sess.draft_ctx = None;
9495 debug_assert_eq!(sess.cache.pos, pos, "grown rewind landed off checkpoint");
9496 debug_assert!(
9497 (0..sess.scratch.plane_count()).all(|index| sess.scratch.plane(index).0.len == pos),
9498 "grown draft rewind landed off checkpoint"
9499 );
9500 Ok(Some(pos))
9501 }
9502
9503 /// Commit a carried pending bonus (see SpecSession::pending_tok): one T=1 trunk pass
9504 /// (its logits' argmax becomes next_pred) + the draft-KV fill at the carried anchor —
9505 /// byte-identical to the pre-carry session tail. Required before a non-empty-suffix
9506 /// prime, a sampled turn, or parking a session for pool reuse. No-op without a pending.
9507 /// `sampling` is the sampler of the request that will CONSUME the resulting `next_pred`
9508 /// (lane/sampled-spec-quality): this is a boundary site like any other, so a sampled
9509 /// consumer must get a DRAWN token, not an argmax. Pass `None` from the park/demote
9510 /// callers — a pending only ever exists on the GREEDY tail, and the consumer of a
9511 /// park-time flush is a future request whose sampler is not knowable here (residual
9512 /// named at the pool-resume probe in worker.rs and in SAMPLED-QUALITY.md).
9513 pub fn spec_flush_pending(
9514 &self,
9515 e: &Engine,
9516 sess: &mut SpecSession,
9517 sampling: Option<SpecSampling>,
9518 ) -> Result<(), Box<dyn std::error::Error>> {
9519 let Some(b) = sess.pending_tok.take() else {
9520 return Ok(());
9521 };
9522 if self.mtp.is_none() {
9523 return Err("pending carry requires an MTP head".into());
9524 }
9525 let n_embd = self.cfg.n_embd as usize;
9526 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
9527 let embd_gpu = if spec_host_embd() {
9528 None
9529 } else {
9530 Some(
9531 self.embd_gpu
9532 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
9533 )
9534 };
9535 let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
9536 let pos_b = sess.cache.pos;
9537 sess.scratch.set_len(e, pos_b)?;
9538 let (lg_b, hb) = self.spec_target_step_h(e, b, &mut sess.cache)?;
9539 sess.next_pred = Some(match sampling {
9540 Some(sp) if sp.temp > 0.0 && spec_sampled_boundary_on() => {
9541 // window includes `b` itself: it is committed by this pass, and the pre-lane
9542 // code never counted a boundary token in the penalty history at all.
9543 let hist = pen_window_seed(&sess.committed, &[b], sp.penalty_last_n);
9544 sample_boundary_token(e, &lg_b, &sp, &hist, &mut sess.sctr, "flush-pending")?
9545 }
9546 _ => argmax(&lg_b) as u32,
9547 });
9548 let anchor = sess
9549 .last_h
9550 .as_ref()
9551 .expect("pending carry requires last_h (the predecessor-row anchor)");
9552 self.mtp_kv_fill_all(e, &[b], anchor, pos_b, &mut sess.scratch, embd_dev)?;
9553 sess.last_h = Some(hb);
9554 sess.committed.push(b);
9555 Ok(())
9556 }
9557
9558 /// Solo target feed used only at speculative round boundaries. Step35 serving made its
9559 /// staged batched B=1 graph authoritative, so a speculative session must enter and leave
9560 /// rounds through that same graph. Other model families keep their eager T=1 contract.
9561 fn spec_target_step_h(
9562 &self,
9563 e: &Engine,
9564 token: u32,
9565 cache: &mut Cache,
9566 ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
9567 if !self.sliding_gated_moe_batch_program() && !self.batched_serving_numeric_class() {
9568 return self.decode_step_h(e, token, cache);
9569 }
9570 let pos0 = cache.pos;
9571 let (logits, hidden) = self.decode_step_t_core(e, &[token], pos0, cache, None, None)?;
9572 Ok((e.dtoh(&logits)?, hidden))
9573 }
9574
9575 /// The archs whose LIVE B=1 serving runs the generic BATCHED numeric class (decode_step_batch
9576 /// walk + batched head), so their spec verify must run the SAME class. MoE learned this
9577 /// 2026-08-14 AM (4b777ccc5); the dense hybrid reproduced the identical near-tie flip class
9578 /// the same day on Qwen3.8-27B — eager-class verify logits drift from batched-class serving
9579 /// logits ("1 ULP at layer 2 → 2.3e-1 logit maxdiff at the head"), and the GDN recurrence
9580 /// carries the drift until a near-tie flips deep in generation. One predicate so the five
9581 /// dispatch sites cannot drift apart again.
9582 /// Draft-graph head admissibility (lane/draftcost-moe, 2026-08-20): the capture body
9583 /// (`mtp_head_forward_cap`) supports Dense heads AND resident-MoE heads
9584 /// (`Ffn::Moe(m) if m.dev_exps.is_some()`); non-resident MoE still refuses inside the
9585 /// capture and the caller falls back to the eager chain by design. Trunk FFN class is
9586 /// irrelevant — the graph body is the HEAD forward only. One predicate for all three
9587 /// eligibility sites so they cannot drift (the serving numeric-class lesson).
9588 fn mtp_graph_capturable(&self) -> bool {
9589 self.mtp
9590 .as_ref()
9591 .map(|m| match &m.ffn {
9592 crate::hybrid::Ffn::Dense { .. } => true,
9593 crate::hybrid::Ffn::Moe(mo) => mo.dev_exps.is_some(),
9594 })
9595 .unwrap_or(false)
9596 }
9597
9598 fn batched_serving_numeric_class(&self) -> bool {
9599 self.plan
9600 .trunk_operations()
9601 .contains(&memra_gguf::model_plan::OperationKind::GatedDeltaNet)
9602 }
9603
9604 /// The family the MTP verify-graph default was measured on: GatedDeltaNet state layers
9605 /// (a `recur` mixer) together with a routed-MoE FFN — Ornith-1.5-35B-A3B and its kin. The
9606 /// server-side twin of this test is `model_forces_spec_replay` (GatedDeltaNet + MoeMlp);
9607 /// keeping the engine's own version structural rather than name-based means a new
9608 /// checkpoint of the same shape inherits the default, and a different shape does not.
9609 fn vgraph_family_default(&self) -> bool {
9610 let has_linear = self
9611 .layers
9612 .iter()
9613 .any(|l| matches!(l.mixer, Mixer::Linear(_)));
9614 let has_moe = self
9615 .layers
9616 .iter()
9617 .any(|l| matches!(l.ffn, crate::hybrid::Ffn::Moe(_)));
9618 has_linear && has_moe
9619 }
9620
9621 fn sliding_gated_moe_batch_program(&self) -> bool {
9622 self.uses_sliding_gated_moe_program()
9623 }
9624
9625 fn gemma_batch_program(&self) -> bool {
9626 self.uses_gemma_program()
9627 }
9628
9629 /// Reduced-matrix admission for increment 1. This deliberately does not change the PP-2
9630 /// serving policy: the worker calls it only after `MEMRA_SPEC_PIPE=1` and an explicit spec
9631 /// session already exist.
9632 pub fn spec_pipe_available(&self, e: &Engine) -> bool {
9633 if std::env::var("MEMRA_SPEC_PIPE").as_deref() != Ok("1")
9634 || !spec_devacc()
9635 || spec_replay_env_enabled()
9636 || spec_stream()
9637 || std::env::var("MEMRA_SPEC_ADAPT").as_deref() == Ok("1")
9638 || std::env::var("MEMRA_SPEC_PMIN0").as_deref() == Ok("1")
9639 || std::env::var("MEMRA_SPEC_PP_ANATOMY").as_deref() == Ok("1")
9640 || std::env::var("MEMRA_SPEC_PMIN")
9641 .ok()
9642 .and_then(|v| v.parse::<f32>().ok())
9643 .unwrap_or(0.0)
9644 > 0.0
9645 || self.is_gemma4_e4b()
9646 || self.gemma_batch_program()
9647 || self.mtp.is_none()
9648 || !self.mtp_extra.is_empty()
9649 {
9650 return false;
9651 }
9652 let Some(cuts) = crate::pp::pp_cuts(self.layers.len()) else {
9653 return false;
9654 };
9655 if cuts.len() != 3 || crate::pp::pp2_streams_off() || !crate::pp::spec_pp_on() {
9656 return false;
9657 }
9658 crate::pp::PpNRt::get(e)
9659 .map(|rt| rt.n_stages() == 2 && rt.cross_device())
9660 .unwrap_or(false)
9661 }
9662
9663 /// Two warm greedy continuation bursts over one PP-2 interval coordinator. The two existing
9664 /// `generate_spec_inner2` call stacks own all per-session round locals; only phase issue order
9665 /// changes. No callback is accepted in increment 1 — the worker publishes each completed burst.
9666 #[allow(clippy::too_many_arguments)]
9667 pub fn generate_spec_session_pair(
9668 &self,
9669 e: &Engine,
9670 sess_a: &mut SpecSession,
9671 max_new_a: usize,
9672 k_a: usize,
9673 sess_b: &mut SpecSession,
9674 max_new_b: usize,
9675 k_b: usize,
9676 ) -> Result<((Vec<u32>, usize, usize), (Vec<u32>, usize, usize)), Box<dyn std::error::Error>>
9677 {
9678 if !self.spec_pipe_available(e) {
9679 return Err("two-session speculative pipeline is outside its reduced matrix".into());
9680 }
9681 if max_new_a == 0 || max_new_b == 0 || k_a == 0 || k_b == 0 {
9682 return Err(
9683 "two-session speculative pipeline requires non-empty positive-K bursts".into(),
9684 );
9685 }
9686 for sess in [&*sess_a, &*sess_b] {
9687 if sess.committed.is_empty()
9688 || sess.last_h.is_none()
9689 || (sess.next_pred.is_none() && sess.pending_tok.is_none())
9690 {
9691 return Err("two-session speculative pipeline requires warm continuations".into());
9692 }
9693 }
9694
9695 let graph_ok = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
9696 && !spec_host_embd()
9697 && self.mtp_graph_capturable()
9698 && self.mtp_extra.is_empty()
9699 && !crate::model::full_prec_enabled();
9700 let graph_a = graph_ok && k_a + 2 < 96;
9701 let graph_b = graph_ok && k_b + 2 < 96;
9702 let was_tracking = e.ctx().is_event_tracking();
9703 if (graph_a || graph_b) && was_tracking {
9704 unsafe {
9705 e.ctx().disable_event_tracking();
9706 }
9707 }
9708
9709 static LOGGED: std::sync::Once = std::sync::Once::new();
9710 LOGGED.call_once(|| {
9711 eprintln!("[spec-pipe] two-session PP-2 continuation pipeline engaged");
9712 });
9713 let sync = std::sync::Arc::new(SpecPipeSync::new());
9714 let lane_a = SpecPipeLane {
9715 sync: sync.clone(),
9716 lane: 0,
9717 };
9718 let lane_b = SpecPipeLane { sync, lane: 1 };
9719 let mut sess_b_ptr = SpecPipeSessionPtr(sess_b as *mut SpecSession);
9720 let (result_a, result_b) = std::thread::scope(|scope| {
9721 let b = scope.spawn(move || {
9722 let mut finish = SpecPipeFinish::new(&lane_b);
9723 let sess_b = unsafe { sess_b_ptr.get_mut() };
9724 let result = e
9725 .ctx()
9726 .bind_to_thread()
9727 .map_err(|err| err.to_string())
9728 .and_then(|_| {
9729 self.generate_spec_inner2(
9730 e,
9731 &[],
9732 max_new_b,
9733 k_b,
9734 graph_b,
9735 Some(sess_b),
9736 None,
9737 None,
9738 None,
9739 None,
9740 Some(&lane_b),
9741 )
9742 .map_err(|err| err.to_string())
9743 });
9744 finish.close(result.is_err());
9745 result
9746 });
9747 let mut finish = SpecPipeFinish::new(&lane_a);
9748 let result_a = self.generate_spec_inner2(
9749 e,
9750 &[],
9751 max_new_a,
9752 k_a,
9753 graph_a,
9754 Some(sess_a),
9755 None,
9756 None,
9757 None,
9758 None,
9759 Some(&lane_a),
9760 );
9761 finish.close(result_a.is_err());
9762 let result_b = b
9763 .join()
9764 .map_err(|_| "paired speculative session B panicked".to_string())
9765 .and_then(|r| r);
9766 (result_a, result_b)
9767 });
9768
9769 if (graph_a || graph_b) && was_tracking {
9770 unsafe {
9771 e.ctx().enable_event_tracking();
9772 }
9773 }
9774 let result_a = result_a?;
9775 let result_b = result_b.map_err(|err| -> Box<dyn std::error::Error> { err.into() })?;
9776 Ok((result_a, result_b))
9777 }
9778
9779 /// One spec-decode turn on a live session. `suffix` = the NEW tokens only (turn N+1's user
9780 /// message rendered through the chat template continuation). Returns (new tokens emitted,
9781 /// drafted, accepted); session.committed grows by suffix + emitted.
9782 pub fn generate_spec_session(
9783 &self,
9784 e: &Engine,
9785 sess: &mut SpecSession,
9786 suffix: &[u32],
9787 max_new: usize,
9788 k: usize,
9789 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
9790 self.generate_spec_session_sampled(e, sess, suffix, max_new, k, None, None)
9791 }
9792
9793 /// Serve-path sampled spec: routes the burst through the rejection-sampling verify with
9794 /// per-SESSION Philox continuity (sess.sctr/uctr). None = env-driven (CLI) or greedy.
9795 /// Filters (top-k/p/min-p) apply SYMMETRICALLY to draft q and verify p — distribution-exact
9796 /// for the filtered target (feat/filtered-spec).
9797 ///
9798 /// `on_commit` (sse-cadence, 2026-08-05): called with each newly-emitted slice of the
9799 /// output — once right after the prime's first token, then once per round commit — so a
9800 /// streaming caller can flush text at round cadence instead of once per burst. The slices
9801 /// are disjoint, in order, and concatenate to exactly the returned token vec. Emission-
9802 /// timing only: token bytes, session state, and exactness are untouched.
9803 ///
9804 /// The returned bool is a CONTINUE-VERDICT (admission yield, 2026-08-06): `false` ends
9805 /// the burst at the current round boundary, exactly as if `max_new` had been reached —
9806 /// the caller's scheduler regains control without waiting the burst out. Burst size is
9807 /// content-neutral (spec-levers battery), so an early exit moves WHEN the burst returns,
9808 /// never what tokens say. The slice may be EMPTY (a poll-only boundary — round-stream
9809 /// drains and the defensive tail flush can land with nothing new committed).
9810 #[allow(clippy::too_many_arguments)]
9811 pub fn generate_spec_session_sampled(
9812 &self,
9813 e: &Engine,
9814 sess: &mut SpecSession,
9815 suffix: &[u32],
9816 max_new: usize,
9817 k: usize,
9818 sampling: Option<SpecSampling>,
9819 on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
9820 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
9821 self.generate_spec_session_sampled_prime_split(
9822 e, sess, suffix, max_new, k, sampling, None, on_commit,
9823 )
9824 }
9825
9826 /// Serve-only cold-prime segmentation twin. `prime_split` is the same stable boundary the
9827 /// plain worker would honor before entering its sub-floor tokenwise tail; warm continuations
9828 /// pass `None` and stay on the existing zero-prime path.
9829 #[allow(clippy::too_many_arguments)]
9830 pub fn generate_spec_session_sampled_prime_split(
9831 &self,
9832 e: &Engine,
9833 sess: &mut SpecSession,
9834 suffix: &[u32],
9835 max_new: usize,
9836 k: usize,
9837 sampling: Option<SpecSampling>,
9838 prime_split: Option<usize>,
9839 on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
9840 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
9841 self.generate_spec_session_constrained_prime_split(
9842 e,
9843 sess,
9844 suffix,
9845 max_new,
9846 k,
9847 sampling,
9848 None,
9849 prime_split,
9850 on_commit,
9851 )
9852 }
9853
9854 /// `generate_spec_session_sampled` + GRAMMAR (constrained decoding, 2026-08-03): the
9855 /// hook truncates acceptance at the first grammar-illegal token AFTER the exactness
9856 /// verify (grammar is an extra rejection rule, ordering like the batched-verify twins)
9857 /// and replaces an illegal bonus with the MASKED argmax of the target's own verify
9858 /// column — token-identical to constrained plain greedy decode. GREEDY only (the
9859 /// worker routes sampled constrained to plain decode). Acceptance under tight grammars
9860 /// may drop (drafter is unconstrained); that is measured, not hidden.
9861 #[allow(clippy::too_many_arguments)]
9862 pub fn generate_spec_session_constrained(
9863 &self,
9864 e: &Engine,
9865 sess: &mut SpecSession,
9866 suffix: &[u32],
9867 max_new: usize,
9868 k: usize,
9869 sampling: Option<SpecSampling>,
9870 constraint: Option<&mut dyn SpecConstraint>,
9871 on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
9872 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
9873 self.generate_spec_session_constrained_prime_split(
9874 e, sess, suffix, max_new, k, sampling, constraint, None, on_commit,
9875 )
9876 }
9877
9878 #[allow(clippy::too_many_arguments)]
9879 pub fn generate_spec_session_constrained_prime_split(
9880 &self,
9881 e: &Engine,
9882 sess: &mut SpecSession,
9883 suffix: &[u32],
9884 max_new: usize,
9885 k: usize,
9886 sampling: Option<SpecSampling>,
9887 constraint: Option<&mut dyn SpecConstraint>,
9888 prime_split: Option<usize>,
9889 on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
9890 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
9891 if constraint.is_some() && sampling.is_some_and(|s| s.temp > 0.0) {
9892 return Err(
9893 "constrained spec decode is greedy-only (worker routes sampled \
9894 constrained to plain decode)"
9895 .into(),
9896 );
9897 }
9898 // PENDING-CARRY entry flush: a carried bonus precedes any new suffix in the sequence,
9899 // so it must commit BEFORE the suffix primes; the sampled path doesn't carry (its
9900 // round-0 accept needs the commit pass's logits). Empty-suffix greedy bursts — the
9901 // serve continuation case — consume the carry in-loop with zero solo passes.
9902 if sess.pending_tok.is_some()
9903 && (!suffix.is_empty() || sampling.map_or(false, |s| s.temp > 0.0))
9904 {
9905 self.spec_flush_pending(e, sess, sampling)?;
9906 }
9907
9908 // FULL_PREC forces the EAGER draft: the graph capture would enclose cuBLASLt f32 GEMV
9909 // (the FloatBf16 else-branches) and a bf16_to_f32 dequant alloc — neither is stream-capture
9910 // safe. Eager rides matmul/matmul_decode_exact, which dequant FloatBf16 on use. (§item 2.)
9911 let graph_draft = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
9912 && !spec_host_embd()
9913 && self.mtp_graph_capturable()
9914 && self.mtp_extra.is_empty()
9915 && k + 2 < 96
9916 && !crate::model::full_prec_enabled();
9917 let was_tracking = e.ctx().is_event_tracking();
9918 if graph_draft && was_tracking {
9919 unsafe {
9920 e.ctx().disable_event_tracking();
9921 }
9922 }
9923 let r = self.generate_spec_inner2(
9924 e,
9925 suffix,
9926 max_new,
9927 k,
9928 graph_draft,
9929 Some(sess),
9930 sampling,
9931 constraint,
9932 on_commit,
9933 prime_split,
9934 None,
9935 );
9936 if graph_draft && was_tracking {
9937 unsafe {
9938 e.ctx().enable_event_tracking();
9939 }
9940 }
9941 let (out, d, a) = r?;
9942 Ok((out, d, a))
9943 }
9944
9945 pub fn generate_spec(
9946 &self,
9947 e: &Engine,
9948 prompt: &[u32],
9949 max_new: usize,
9950 k: usize,
9951 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
9952 if crate::pp::pp_cuts(self.layers.len()).is_some()
9953 && !self.rewrite_allowed(memra_gguf::execution_manifest::RewriteSurface::Pipeline)
9954 {
9955 return Err("pipeline rewrite is not qualified for speculative decode".into());
9956 }
9957 if !self.rewrite_allowed(memra_gguf::execution_manifest::RewriteSurface::MtpSpec) {
9958 return Err("speculative rewrite is not qualified for this ModelPlan".into());
9959 }
9960 // FULL_PREC forces eager (see generate_spec_session note): CUDA graph capture cannot
9961 // enclose cuBLASLt f32 GEMV or the bf16_to_f32 dequant alloc the FloatBf16 path needs.
9962 let graph_draft = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
9963 && !spec_host_embd()
9964 && self.mtp_graph_capturable()
9965 && self.mtp_extra.is_empty()
9966 && k + 2 < 96
9967 && !crate::model::full_prec_enabled();
9968 if !graph_draft {
9969 return self.generate_spec_inner2(
9970 e, prompt, max_new, k, false, None, None, None, None, None, None,
9971 );
9972 }
9973 let was_tracking = e.ctx().is_event_tracking();
9974 if was_tracking {
9975 unsafe {
9976 e.ctx().disable_event_tracking();
9977 }
9978 }
9979 let r = self.generate_spec_inner2(
9980 e, prompt, max_new, k, true, None, None, None, None, None, None,
9981 );
9982 if was_tracking {
9983 unsafe {
9984 e.ctx().enable_event_tracking();
9985 }
9986 }
9987 r
9988 }
9989
9990 fn generate_spec_inner2(
9991 &self,
9992 e: &Engine,
9993 prompt: &[u32],
9994 max_new: usize,
9995 k: usize,
9996 graph_draft: bool,
9997 mut sess: Option<&mut SpecSession>,
9998 sampling: Option<SpecSampling>,
9999 mut constraint: Option<&mut dyn SpecConstraint>,
10000 mut on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
10001 prime_split: Option<usize>,
10002 pipe: Option<&SpecPipeLane>,
10003 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
10004 assert!(k >= 1, "k must be >= 1");
10005 if let Some(p) = pipe {
10006 p.setup_begin()?;
10007 }
10008 // sse-cadence flush cursor: everything in out[..flushed] has been handed to on_commit.
10009 let mut flushed = 0usize;
10010 // admission yield (2026-08-06): on_commit's continue-verdict; false = end the burst
10011 // at the next round boundary (same exit as max_new reached — the session tail runs).
10012 // Initialized by the unconditional post-prime flush below.
10013 let mut keep_going;
10014 let mtp = self
10015 .mtp
10016 .as_ref()
10017 .expect("generate_spec requires an MTP head (nextn_predict_layers>0)");
10018 let n_vocab = self.output.out_features();
10019 // FR-Spec: the draft head may be TRIMMED (fewer rows than n_vocab); the draft argmax runs
10020 // over the draft vocab and the winning index maps through d2t to a TARGET token id.
10021 // Everything downstream (verify/accept/commit) sees target ids only — exactness unchanged.
10022 let d_vocab = mtp
10023 .shared_head_head
10024 .as_ref()
10025 .unwrap_or(&self.output)
10026 .out_features();
10027 if !self.mtp_extra.is_empty() {
10028 if self.plan.draft_source != memra_gguf::model_plan::DraftSourcePlan::Embedded
10029 || self.plan.mtp_blocks.len() != self.mtp_head_count()
10030 || mtp.d2t.is_some()
10031 {
10032 return Err(
10033 "multi-head MTP requires one embedded canonical block per loaded head".into(),
10034 );
10035 }
10036 for (offset, head) in self.mtp_extra.iter().enumerate() {
10037 if head.d2t.is_some()
10038 || head
10039 .shared_head_head
10040 .as_ref()
10041 .unwrap_or(&self.output)
10042 .out_features()
10043 != d_vocab
10044 {
10045 return Err(format!(
10046 "embedded MTP head {} has incompatible draft vocabulary",
10047 offset + 1
10048 )
10049 .into());
10050 }
10051 }
10052 eprintln!(
10053 "[mtp-chain] heads={} policy=step-modulo prefix-replay kv=per-head",
10054 self.mtp_head_count()
10055 );
10056 }
10057 let n_embd = self.cfg.n_embd as usize;
10058 // SESSION MODE: reuse the live cache/scratch, prime only the suffix. `base` = tokens
10059 // already committed (their state is in the caches); 0 = fresh single-shot call.
10060 let session_mode = sess.is_some();
10061 let max_ctx = match sess.as_ref() {
10062 Some(s) => s.cache.max_ctx,
10063 None => prompt.len() + max_new + k + 8,
10064 };
10065 let mut own_cache;
10066 let mut own_scratch;
10067 // PREFIX-CACHE capture request threaded out of the session (lane/spec-prefix-cache):
10068 // (requested split, destination list). Single-shot per burst; fresh calls have none.
10069 let mut sess_capture: Option<(Option<usize>, &mut Vec<SpecBoundaryCapture>)> = None;
10070 // STABLE-BOUNDARY turn-checkpoint request (lane/frspec-multiturn-cache): ABSOLUTE
10071 // committed-length position; consumed one-shot like `capture_at`. None = legacy
10072 // prompt-end capture below.
10073 let mut ckpt_req: Option<usize> = None;
10074 let (
10075 cache,
10076 scratch,
10077 mut sess_tail,
10078 mut sess_draft_slot,
10079 mut sess_pending_slot,
10080 sess_ckpt_slot,
10081 sess_telem,
10082 ): (
10083 &mut Cache,
10084 &mut MtpScratch,
10085 Option<(
10086 &mut Vec<u32>,
10087 &mut Option<CudaSlice<f32>>,
10088 &mut Option<u32>,
10089 &mut u32,
10090 &mut u32,
10091 )>,
10092 Option<&mut Option<DraftGraphCtx>>,
10093 Option<&mut Option<u32>>,
10094 Option<&mut Option<SpecCheckpoint>>,
10095 Option<&SpecTelemetryCounters>,
10096 ) = match sess.take() {
10097 Some(sr) => {
10098 let SpecSession {
10099 cache,
10100 scratch,
10101 committed,
10102 last_h,
10103 next_pred,
10104 sctr: s_sctr,
10105 uctr: s_uctr,
10106 draft_ctx,
10107 pending_tok,
10108 turn_ckpt,
10109 telem,
10110 capture_at,
10111 boundary_captures,
10112 ckpt_at,
10113 } = sr;
10114 sess_capture = Some((capture_at.take(), boundary_captures));
10115 ckpt_req = ckpt_at.take();
10116 (
10117 cache,
10118 scratch,
10119 Some((committed, last_h, next_pred, s_sctr, s_uctr)),
10120 Some(draft_ctx),
10121 Some(pending_tok),
10122 Some(turn_ckpt),
10123 Some(telem),
10124 )
10125 }
10126 None => {
10127 // STAGE-OWNED KV (lane/pp2-spec 2026-08-06) — see `new_session`. Door shut =
10128 // `Cache::new` verbatim.
10129 own_cache = crate::pp::new_cache_planned(e, &self.cfg, &self.plan, max_ctx)?;
10130 // Persistent scratch = max_ctx rows (~2KB/token quantized).
10131 own_scratch = self.new_mtp_scratch(e, max_ctx)?;
10132 (
10133 &mut own_cache,
10134 &mut own_scratch,
10135 None,
10136 None,
10137 None,
10138 None,
10139 None,
10140 )
10141 }
10142 };
10143 if scratch.plane_count() != self.mtp_head_count() {
10144 return Err(format!(
10145 "MTP scratch/head count mismatch ({}/{})",
10146 scratch.plane_count(),
10147 self.mtp_head_count()
10148 )
10149 .into());
10150 }
10151 let base = cache.pos;
10152 // PENDING-CARRY consume (2026-08-01): a carried bonus reaches here only on the
10153 // empty-suffix GREEDY continuation path (generate_spec_session_sampled flushed every
10154 // other case). It enters the round loop as round-0's pending — verify col 0 — exactly
10155 // like a mid-burst full-accept boundary: no init feed, no tail commit pass.
10156 let carried_pending: Option<u32> = sess_pending_slot.as_mut().and_then(|s| s.take());
10157 // PERSISTENT DRAFT KV (the only mode since 2026-07-08 — the legacy round-local scratch,
10158 // MEMRA_SPEC_KVLOCAL, measured -35 acceptance pts on the 27B p3 sweep and was removed;
10159 // acceptance-only — exactness is verify's job either way).
10160 // HIDDEN-PAIRING CONVENTION (DEFAULT = predecessor-row, 2026-07-04 — the 27B acceptance
10161 // unlock, +16pts): the MTP head is TRAINED on rows pairing token x_p with the trunk
10162 // hidden of its PREDECESSOR h_{p-1} (the reference engine's mtp_update shifts the target
10163 // hiddens right by one; its draft step 0 feeds (id_last, TRUE hidden of the row id_last
10164 // was sampled from)). memra's historical convention paired SAME-ROW (x_p, h_p) in the fill
10165 // and seeded chain step 0 through an extra MTP pass on a duplicated token (the
10166 // pseudo-seed) — measured 27B p2 K=3 acceptance 0.569 vs 0.731, p3 0.445 vs 0.63+, and
10167 // the chain steps j>=1 were already predecessor-shaped, so ONLY the fill + step-0 seed
10168 // move. The fill shifts by one and the chain seeds from the predecessor's true hidden
10169 // DIRECTLY (vh_seed / vx[j-1]) — the pseudo pass disappears (one MTP-block pass saved
10170 // per round on top of the acceptance win). Draft-quality-only: exactness stays the
10171 // verify's job either way. (The legacy same-row pairing seam, MEMRA_SPEC_HSAME, and its
10172 // pseudo-seed passes were removed 2026-07-08 — predecessor pairing won by +16 acc pts;
10173 // the legacy round-local scratch, MEMRA_SPEC_KVLOCAL, went with it.)
10174 // REPLAY-FREE PARTIAL ACCEPT (default, 2026-07-03): partial rounds keep the verify's own
10175 // bit-identical committed-prefix state (KV truncate + recur rebuild from the VerifyCkpt)
10176 // and leave the bonus PENDING — no duplicate trunk pass (profiled ~0.54 extra full weight
10177 // reads/round at long ctx). MEMRA_SPEC_REPLAY=1 restores the legacy rollback+replay (A/B
10178 // + fallback seam).
10179 // Qwen35-MoE replay pin LIFTED (lane/draftcost-moe, 2026-08-20). The pin's stated
10180 // bar — the retained verify-state commit proven equivalent to sequential serving —
10181 // was waiting on this arch running the serving batched verify class, which the
10182 // t-parallel admission (this lane, increment 1) provided: the VerifyCkpt the
10183 // replay-free commit consumes is now produced by the SAME serving-class verify that
10184 // qualified dense qwen35 on 2026-08-15 (where the per-round duplicate replay
10185 // measured 69 -> 30 tok/s). Qualification receipts (run-spec K=1..8 both arms,
10186 // 8-prompt replay-vs-replay-free canary, long-prompt cell):
10187 // research/draftcost-moe-20260820/RECEIPTS.md. MEMRA_SPEC_REPLAY=1 stays the
10188 // rollback + A/B seam.
10189 let spec_replay = spec_replay_env_enabled();
10190 if constraint.is_some() && spec_replay {
10191 return Err(
10192 "constrained spec decode does not support MEMRA_SPEC_REPLAY=1 \
10193 (legacy replay commits an unmasked bonus)"
10194 .into(),
10195 );
10196 }
10197 // TRUE-HIDDEN REFRESH (default in persistent-draft-KV mode): every round overwrites the
10198 // committed positions' scratch entries from the verify's exact hiddens (mtp_kv_fill batch)
10199 // instead of keeping chain-approximate entries. MEMRA_SPEC_NOREFRESH=1 = legacy (A/B seam).
10200 let refresh = std::env::var("MEMRA_SPEC_NOREFRESH").is_err();
10201 if !refresh && !self.mtp_extra.is_empty() {
10202 return Err("multi-head MTP requires exact accepted-prefix refresh".into());
10203 }
10204
10205 // prime: BATCHED cache prime (prime_cache — the measured #1 e2e gap: tokenwise primed at
10206 // ~102/38 tok/s vs the engine's ~2000-5900 tok/s batched prefill). prime_cache returns the
10207 // full pre-output_norm hidden stack [T, n_embd], which IS prompt_h (the persistent-draft-KV
10208 // mtp_kv_fill input) — no per-token collection needed. Prompts below PRIME_MIN_T, and
10209 // MEMRA_PRIME_TOKENWISE=1, and frozen Hy3 CPU/GPU expert splits take the tokenwise
10210 // decode_step_h loop. The latter avoids transient GPU staging of the spilled expert bank.
10211 // EMPTY-SUFFIX CONTINUATION (serve bursts): a session turn with NO new tokens resumes
10212 // generation exactly where the last turn stopped — no prime at all. The stashed
10213 // `next_pred` plays prime_logits' role: it is the token produced from the logits after
10214 // committed.last() by the same rule this entry applies to a cold prime's last row —
10215 // an argmax when greedy, a `sample_boundary_token` draw when sampled (the burst tail,
10216 // or `spec_session_from_restored` for a converted prefix-cache hit, did the drawing
10217 // where the sampler and the session's Philox counters were live). `last_h` seeds the
10218 // predecessor pairing below. Fresh calls and non-empty suffixes take the normal path.
10219 let continuation = prompt.is_empty();
10220 if continuation {
10221 assert!(session_mode, "empty prompt requires a session");
10222 assert!(
10223 sess_tail
10224 .as_ref()
10225 .map_or(false, |(c, lh, np, _, _)| !c.is_empty()
10226 && lh.is_some()
10227 && (np.is_some() || carried_pending.is_some())),
10228 "empty-suffix continuation needs a primed session (committed + last_h + next_pred|pending)"
10229 );
10230 }
10231 let mut prime_logits;
10232 let mut prompt_h: Option<CudaSlice<f32>> = None;
10233 let t_prime = std::time::Instant::now();
10234 let batched_prime = !continuation
10235 && prompt.len() >= crate::hybrid_forward::PRIME_MIN_T
10236 && std::env::var("MEMRA_PRIME_TOKENWISE").is_err()
10237 && !e.frozen_cpu_experts_prefer_tokenwise_prime();
10238 let prime_split = prime_split.filter(|&split| split > 0 && split < prompt.len());
10239 if prime_split.is_some() && continuation {
10240 return Err("spec prime split requires a non-empty prime".into());
10241 }
10242 // STABLE-BOUNDARY TURN CHECKPOINT stop (lane/frspec-multiturn-cache, 2026-08-21):
10243 // the worker's `ckpt_at` request, ABSOLUTE -> prompt-relative. On WARM bursts
10244 // (base != 0, an affinity-rewound or pool-resumed session priming its own delta)
10245 // this is the only stop; on COLD bursts it usually coincides with `prime_split`
10246 // (both are the plain tier's stable pre-generation boundary). A boundary the prime
10247 // cannot honor (outside this prime's range) silently drops the capture — the
10248 // turn_ckpt convention: the next turn re-primes in full, never a wrong resume.
10249 let ckpt_rel = if continuation {
10250 None
10251 } else {
10252 ckpt_req
10253 .and_then(|abs| abs.checked_sub(base))
10254 .filter(|&r| r > 0 && r < prompt.len())
10255 };
10256 // Prime stops, ordered: each is a boundary the prime halts at so the in-place GDN
10257 // conv/ssm state can be snapshotted there (the only moment it exists). One stop =
10258 // the legacy single-split program, byte-for-byte.
10259 let mut stops: Vec<usize> = Vec::new();
10260 for b in [prime_split, ckpt_rel].into_iter().flatten() {
10261 if !stops.contains(&b) {
10262 stops.push(b);
10263 }
10264 }
10265 stops.sort_unstable();
10266 // Captured at the ckpt stop, installed into the session slot post-prime (replacing
10267 // the legacy prompt-end capture). Some(None) = capture attempted and failed -> the
10268 // slot is cleared (a stale checkpoint would rewind to the WRONG boundary).
10269 let mut ckpt_early: Option<Option<SpecCheckpoint>> = None;
10270 if continuation {
10271 prime_logits = Vec::new();
10272 } else if !stops.is_empty() {
10273 if let Some(&first) = stops.first() {
10274 if prime_split == Some(first) && first < crate::hybrid_forward::PRIME_MIN_T {
10275 return Err(format!(
10276 "spec prime split {first} is below PRIME_MIN_T {}",
10277 crate::hybrid_forward::PRIME_MIN_T,
10278 )
10279 .into());
10280 }
10281 }
10282 // Mirror the plain worker's boundary stops exactly. Each segment is a
10283 // request-level prime (`queued_after` keeps Step35 arm selection independent of
10284 // the stops — tick-seg law); a segment below PRIME_MIN_T (and the final tail
10285 // under MEMRA_PRIME_TOKENWISE) takes the same eager tokenwise continuation as
10286 // prefill_tick. Retain every hidden row so the draft scratch fill remains one
10287 // coherent prompt.
10288 let mut h_all = e.uninit(prompt.len() * n_embd)?;
10289 prime_logits = Vec::new();
10290 let mut prev = 0usize;
10291 for seg_end in stops.iter().copied().chain(std::iter::once(prompt.len())) {
10292 if seg_end <= prev {
10293 continue;
10294 }
10295 let seg = &prompt[prev..seg_end];
10296 let is_final = seg_end == prompt.len();
10297 let batched_seg = seg.len() >= crate::hybrid_forward::PRIME_MIN_T
10298 && (!is_final
10299 || (std::env::var("MEMRA_PRIME_TOKENWISE").is_err()
10300 && !e.frozen_cpu_experts_prefer_tokenwise_prime()));
10301 if batched_seg {
10302 let (l, _, h_seg) =
10303 self.prime_cache(e, seg, &mut *cache, prompt.len() - seg_end)?;
10304 e.copy_into(&mut h_all, prev * n_embd, &h_seg, seg.len() * n_embd)?;
10305 prime_logits = l;
10306 } else {
10307 for (i, &tok) in seg.iter().enumerate() {
10308 let (l, h) = self.decode_step_h(e, tok, &mut *cache)?;
10309 e.copy_into(&mut h_all, (prev + i) * n_embd, &h, n_embd)?;
10310 prime_logits = l;
10311 }
10312 }
10313 prev = seg_end;
10314 if is_final {
10315 break;
10316 }
10317 debug_assert_eq!(cache.pos, base + seg_end, "prime stop landed off boundary");
10318 // PREFIX-CACHE BOUNDARY CAPTURE (lane/spec-prefix-cache): the GDN conv/ssm
10319 // states are about to be advanced in place by the next segment, so this is
10320 // the ONLY moment the boundary's recurrent state exists. Capture iff the
10321 // worker requested exactly this stop (cold sessions only — `capture_at` is
10322 // never armed warm). A failed snapshot is silent (turn_ckpt convention) —
10323 // publication is an optimization, never a correctness dependency.
10324 if base == 0 {
10325 if let Some((requested, slot)) = sess_capture.as_mut() {
10326 // Publish at the requested miss-LCP stop (the shared-prefix class)
10327 // AND at the stable-boundary stop (the next-turn re-render class,
10328 // lane/frspec-multiturn-cache) — the same boundary set the plain
10329 // prefill tick learns. Without the second entry, the turn after a
10330 // cold re-park could only hit the OLDER lcp entry (the measured
10331 // one-turn transient: t3 restored 607 of 24122 while the plain arm
10332 // rewound to 15222). Dedupe is the worker sweep's has_key.
10333 if *requested == Some(seg_end) || ckpt_rel == Some(seg_end) {
10334 if let Ok(snap) = cache.snapshot(e) {
10335 slot.push(SpecBoundaryCapture {
10336 snap,
10337 pos: seg_end,
10338 logits: prime_logits.clone(),
10339 // rows [0..seg_end) of h_all are primed — the following
10340 // segments append, never overwrite.
10341 last_h: capture_boundary_hidden(e, &h_all, seg_end, n_embd),
10342 });
10343 }
10344 }
10345 }
10346 }
10347 // SESSION-AFFINITY TURN CHECKPOINT at the STABLE boundary (see `ckpt_at`):
10348 // same snapshot mechanics, installed post-prime in place of the prompt-end
10349 // capture the re-render class always diverged below.
10350 if ckpt_rel == Some(seg_end) {
10351 let anchor: Result<CudaSlice<f32>, Box<dyn std::error::Error>> =
10352 e.uninit(n_embd).and_then(|mut a| {
10353 e.copy_view_into(
10354 &mut a,
10355 0,
10356 &h_all.slice((seg_end - 1) * n_embd..seg_end * n_embd),
10357 n_embd,
10358 )?;
10359 Ok(a)
10360 });
10361 ckpt_early = Some(match (cache.snapshot(e), anchor) {
10362 (Ok(snap), Ok(last_h)) => Some(SpecCheckpoint {
10363 snap,
10364 pos: base + seg_end,
10365 last_h,
10366 }),
10367 _ => None,
10368 });
10369 }
10370 }
10371 if std::env::var("MEMRA_SPEC_STATS").as_deref() == Ok("1") {
10372 eprintln!(
10373 "[spec-prime] stops={stops:?} tail={}",
10374 prompt.len() - stops.last().copied().unwrap_or(0)
10375 );
10376 }
10377 prompt_h = Some(h_all);
10378 } else if batched_prime {
10379 let (l, _h_seed, hiddens) = self.prime_cache(e, prompt, &mut *cache, 0)?;
10380 prime_logits = l;
10381 prompt_h = Some(hiddens);
10382 } else {
10383 prime_logits = Vec::new();
10384 prompt_h = Some(e.uninit(prompt.len() * n_embd)?);
10385 for (i, &tok) in prompt.iter().enumerate() {
10386 let (l, h) = self.spec_target_step_h(e, tok, &mut *cache)?;
10387 if let Some(ph) = prompt_h.as_mut() {
10388 e.copy_into(ph, i * n_embd, &h, n_embd)?;
10389 }
10390 prime_logits = l;
10391 }
10392 }
10393 e.stream().synchronize()?;
10394 // PREFIX-CACHE SEED CAPTURE (lane/spec-prefix-cache): boundary == prompt end (the seed
10395 // case — no shared-prefix split, publish the whole prompt). The prime just finished, so
10396 // cache.pos == base + prompt.len() and the recurrent state IS the boundary state;
10397 // prime_logits are the boundary logits. Cold sessions only (base == 0) — same law as
10398 // prime_split. The mid-prompt capture above already consumed the request if it matched.
10399 if !continuation && base == 0 {
10400 if let Some((requested, slot)) = sess_capture.as_mut() {
10401 if *requested == Some(prompt.len()) && slot.is_empty() {
10402 debug_assert_eq!(cache.pos, prompt.len(), "seed capture off prompt end");
10403 if let Ok(snap) = cache.snapshot(e) {
10404 slot.push(SpecBoundaryCapture {
10405 snap,
10406 pos: prompt.len(),
10407 logits: prime_logits.clone(),
10408 last_h: prompt_h
10409 .as_ref()
10410 .map(|ph| capture_boundary_hidden(e, ph, prompt.len(), n_embd))
10411 .unwrap_or_default(),
10412 });
10413 }
10414 }
10415 }
10416 }
10417 // Harness timing contract (see crate::PRIME_NANOS): gen-only throughput without the
10418 // prime-subtraction hack.
10419 crate::PRIME_NANOS.store(
10420 t_prime.elapsed().as_nanos() as u64,
10421 std::sync::atomic::Ordering::Relaxed,
10422 );
10423
10424 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
10425 // Resident table is fastest when it fits. Large spill deployments can preserve that HBM
10426 // for expert-cache slots and gather only the exact rows needed by MTP/verify from host.
10427 let host_embd = spec_host_embd();
10428 let embd_gpu = if host_embd {
10429 None
10430 } else {
10431 Some(
10432 self.embd_gpu
10433 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
10434 )
10435 };
10436 let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
10437 if host_embd {
10438 eprintln!(
10439 "[spec] host-row embedding: {} bytes kept off HBM",
10440 self.embd.raw.len()
10441 );
10442 }
10443 let mut out: Vec<u32> = Vec::with_capacity(max_new);
10444 let mut total_drafted = 0usize;
10445 let mut total_accepted = 0usize;
10446
10447 // --- SAMPLER FIRST (lane/sampled-spec-quality, 2026-08-19) ---
10448 // The sampler config, the session's Philox counters and the penalty window are parsed
10449 // HERE, above the boundary-token selection, because the boundary token must be drawn
10450 // from the sampler the request asked for. Pre-lane this block sat ~50 lines BELOW the
10451 // selection, which is the whole mechanical reason the boundary token was an argmax:
10452 // the sampler state was not in scope yet. Nothing here depends on the round loop, so
10453 // moving it up is a pure reordering for greedy (`sampled == false` ⇒ every branch
10454 // below takes the argmax path it always took).
10455 // --- SAMPLED SPEC (MEMRA_SPEC_TEMP>0, research/sampled-spec-impl-map.md): rejection-
10456 // sampling verify (Leviathan/Chen) — accept draft x at u < p(x)/q(x), resample from
10457 // norm(max(0,p-q)) on reject, bonus sampled from p on full accept. Counter-based Philox
10458 // everywhere (seed, event) -> reproducible. temp==0/unset = the greedy path, untouched.
10459 let sp = sampling.unwrap_or_else(|| SpecSampling {
10460 temp: std::env::var("MEMRA_SPEC_TEMP")
10461 .ok()
10462 .and_then(|v| v.parse().ok())
10463 .unwrap_or(0.0),
10464 seed: std::env::var("MEMRA_SEED")
10465 .ok()
10466 .and_then(|v| v.parse().ok())
10467 .unwrap_or(42),
10468 top_k: std::env::var("MEMRA_TOP_K")
10469 .ok()
10470 .and_then(|v| v.parse().ok())
10471 .unwrap_or(0),
10472 top_p: std::env::var("MEMRA_TOP_P")
10473 .ok()
10474 .and_then(|v| v.parse().ok())
10475 .unwrap_or(1.0),
10476 min_p: std::env::var("MEMRA_MIN_P")
10477 .ok()
10478 .and_then(|v| v.parse().ok())
10479 .unwrap_or(0.0),
10480 penalty_last_n: std::env::var("MEMRA_PENALTY_LAST_N")
10481 .ok()
10482 .and_then(|v| v.parse().ok())
10483 .unwrap_or(0),
10484 penalty_repeat: std::env::var("MEMRA_PENALTY_REPEAT")
10485 .ok()
10486 .and_then(|v| v.parse().ok())
10487 .unwrap_or(1.0),
10488 penalty_freq: std::env::var("MEMRA_PENALTY_FREQ")
10489 .ok()
10490 .and_then(|v| v.parse().ok())
10491 .unwrap_or(0.0),
10492 penalty_present: std::env::var("MEMRA_PENALTY_PRESENT")
10493 .ok()
10494 .and_then(|v| v.parse().ok())
10495 .unwrap_or(0.0),
10496 });
10497 let (sp_temp, sp_seed) = (sp.temp, sp.seed);
10498 let sampled = sp_temp > 0.0;
10499 // Counters resume from the session (burst continuity: randomness must never repeat
10500 // across generate_spec_session calls); one-shot callers start at (0,0). Read through
10501 // sess_tail — `sess` was take()n into it above, so sess.as_ref() here is always None.
10502 let mut sctr: u32 = sess_tail.as_ref().map(|(_, _, _, s, _)| **s).unwrap_or(0);
10503 let mut uctr: u32 = sess_tail.as_ref().map(|(_, _, _, _, u)| **u).unwrap_or(0);
10504 // Penalties (v2.1): applied to COPIES of q rows and p columns symmetrically (exactness
10505 // for the penalized+filtered target). History = generated tokens, host-tracked window.
10506 let pen_on = sampled
10507 && sp.penalty_last_n > 0
10508 && (sp.penalty_repeat != 1.0 || sp.penalty_freq != 0.0 || sp.penalty_present != 0.0);
10509 // SESSION-SPANNING PENALTY WINDOW (Item 2). Pre-lane this was
10510 // `prompt.iter().rev().take(64).rev()` — the BURST's suffix slice — so a continuation
10511 // burst (the majority of a stream's tokens, and ALL of a converted cache hit's) started
10512 // with an EMPTY penalty history and the client's repetition/frequency/presence penalties
10513 // silently reset at every burst boundary. The window now spans `committed ++ prompt`,
10514 // which is what the API contract says and what the plain sampler's own `history` does.
10515 // Byte-identical to the pre-lane seed for a cold turn-1 burst at the default window.
10516 let mut pen_hist: Vec<u32> = if pen_on {
10517 let sess_hist: &[u32] = if spec_pen_session_on() {
10518 sess_tail
10519 .as_ref()
10520 .map(|(c, ..)| c.as_slice())
10521 .unwrap_or(&[])
10522 } else {
10523 &[] // MEMRA_SPEC_PEN_SESSION=0: pre-lane burst-local window
10524 };
10525 pen_window_seed(sess_hist, prompt, sp.penalty_last_n)
10526 } else {
10527 Vec::new()
10528 };
10529 // First generated token = the BOUNDARY token: greedy takes the argmax of the prompt's
10530 // last logits (== greedy's first token, byte-contract); SAMPLED draws it from the
10531 // request's own filtered/penalized target through the session's Philox stream
10532 // (`sample_boundary_token`, lane/sampled-spec-quality Item 1 — pre-lane this was an
10533 // argmax in both regimes, so ~1 token per burst of a sampled stream was greedy).
10534 // Emit it, then FEED it to establish the loop invariant below.
10535 // PENDING-CARRY: the carried bonus was already emitted by the LAST burst — it becomes
10536 // last_token WITHOUT re-emission, and round 0 consumes it as pending (no init feed).
10537 // CONSTRAINED entry rules: the first emitted token is the MASKED argmax of the
10538 // prompt's last logits (plain constrained-greedy identity); a continuation without
10539 // a carried pending would emit an UNMASKED stashed next_pred — refused loudly (the
10540 // worker never resumes constrained sessions from the pool, so this cannot fire).
10541 if let Some(c) = constraint.as_deref_mut() {
10542 if continuation && carried_pending.is_none() {
10543 return Err("constrained spec continuation requires a carried pending \
10544 (pool resume is unconstrained-only)"
10545 .into());
10546 }
10547 if !continuation {
10548 c.mask_logits(&mut prime_logits)
10549 .map_err(|e2| format!("constraint: {e2}"))?;
10550 }
10551 }
10552 let mut last_token = if let Some(b) = carried_pending {
10553 b
10554 } else if continuation {
10555 // A continuation's boundary token was DRAWN by the burst that stashed it (the
10556 // session tail below), or by `spec_session_from_restored` for a converted
10557 // prefix-cache hit — in both cases from the correct logits row with this same
10558 // session's Philox stream, which is why it can be consumed here as-is.
10559 sess_tail.as_ref().unwrap().2.unwrap()
10560 } else if sampled && constraint.is_none() && spec_sampled_boundary_on() {
10561 sample_boundary_token(e, &prime_logits, &sp, &pen_hist, &mut sctr, "cold-prime")?
10562 } else {
10563 // greedy (byte contract), the rollback door, or constrained (masked-argmax
10564 // identity — the worker routes sampled+constrained to the plain path, and this
10565 // function refuses the combination outright above).
10566 argmax(&prime_logits) as u32
10567 };
10568 if pen_on {
10569 // The boundary token is a GENERATED token: the plain sampler `accept()`s every
10570 // emitted token into its penalty history, and pre-lane the burst's first token
10571 // was invisible to penalties forever (never pushed, and never in `committed`
10572 // until this burst's tail). Covers the carry/continuation seeds too — neither is
10573 // in `committed` yet.
10574 pen_hist.push(last_token);
10575 }
10576 if carried_pending.is_none() {
10577 out.push(last_token);
10578 // grammar advances with every emitted token (carried pendings were consumed
10579 // by the burst that emitted them).
10580 if let Some(c) = constraint.as_deref_mut() {
10581 c.consume(last_token)
10582 .map_err(|e2| format!("constraint: {e2}"))?;
10583 }
10584 }
10585 if continuation {
10586 // draft-KV invariant: entries [0..base) are the session's exact fills; truncate any
10587 // overhang so the chain's first append lands at slot base (== committed.len()).
10588 scratch.set_len(e, base)?;
10589 }
10590 // sse-cadence: hand the caller every not-yet-flushed token (disjoint in-order slices
10591 // concatenating to the full `out`). Called after the prime's first token and after each
10592 // round commit — emission timing only, token bytes untouched. The slice may be EMPTY
10593 // (poll-only boundary: zero-round folds commit nothing new); returns the caller's
10594 // continue-verdict (admission yield, 2026-08-06) — false ends the burst at this round.
10595 fn flush_commit(
10596 cb: &mut Option<&mut dyn FnMut(&[u32]) -> bool>,
10597 out: &[u32],
10598 flushed: &mut usize,
10599 ) -> bool {
10600 if let Some(f) = cb.as_mut() {
10601 let keep = f(&out[*flushed..]);
10602 *flushed = out.len();
10603 keep
10604 } else {
10605 true
10606 }
10607 }
10608 keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
10609 // INVARIANT at loop top: `last_token` is the most-recently-committed/emitted token, its
10610 // KV+recur state IS in `cache` (cache.pos = position right AFTER last_token), `last_pred`
10611 // is the greedy ARGMAX of the logits that predict the token FOLLOWING last_token, and
10612 // `h_seed` = last_token's pre-output_norm hidden. Establish it by feeding last_token once
10613 // (mirrors plain greedy). DEVICE-ARGMAX lever: the accept walk only ever consumes the
10614 // argmax of those logits — never the full vector — so a host u32 replaces the Vec<f32>.
10615 // Trimmed heads: q lives on the trimmed vocab; accept gathers use the TRIMMED index and
10616 // the residual scatters q into target-id space (q=-inf off-trim — the head cannot propose
10617 // those, so their residual mass is p(x), correct by construction).
10618 let d2t_dev: Option<CudaSlice<u32>> = if sampled || crate::spec::spec_stream() {
10619 match &mtp.d2t {
10620 Some(map) => Some(e.htod_u32_v(map)?),
10621 None => None,
10622 }
10623 } else {
10624 None
10625 };
10626 let mut q_full_buf: Option<CudaSlice<f32>> = None;
10627 // host Philox4x32-10 accept-test uniforms: module fn `host_u01` (shared with the
10628 // dspark sampled-admission walk); byte-identical to the closure it replaces.
10629 let mut draft_logits: Vec<CudaSlice<f32>> = Vec::new(); // retained head logits (q), per slot
10630 let mut draft_stats: Vec<(f32, f32, f32)> = Vec::new(); // (row_max, th_e, z_e) per slot
10631 let mut perturb_buf: Option<CudaSlice<f32>> = None; // gumbel scratch (max(n_vocab,d_vocab))
10632 let mut sample_tok = e.alloc_u32_zeroed(1)?; // residual/bonus sample out
10633 let mut col_buf: Option<CudaSlice<f32>> = None; // materialized verify column
10634 let mut pen_hist_d: Option<CudaSlice<u32>> = None;
10635 let mut pcol_buf: Option<CudaSlice<f32>> = None; // penalized p-column scratch
10636 // MEMRA_SPEC_SETUP_TRACE=1 (diagnostics): per-call wall decomposition of the burst
10637 // SETUP + TAIL segments (the round loop's internals are MEMRA_SPEC_PHASE's job) —
10638 // built to pin the serve per-burst fixed cost (research/spec-serving-20260801).
10639 let setup_trace = std::env::var("MEMRA_SPEC_SETUP_TRACE").as_deref() == Ok("1");
10640 let t_ent = std::time::Instant::now();
10641
10642 // SESSION-AFFINITY TURN CHECKPOINT (lane/session-affinity, 2026-08-05): capture the
10643 // PROMPT-END boundary state so a LATER turn can rewind here and re-prime only its own
10644 // delta instead of the whole conversation. See `SpecCheckpoint` for why this boundary is
10645 // the one that matters (a history-rewriting client mutates what the session GENERATED,
10646 // so the next turn's prompt agrees with this one up to exactly here).
10647 //
10648 // WHERE — AND WHY THIS EXACT LINE. Right after the trunk prime, BEFORE the init feed
10649 // (`decode_step_h(last_token)`) and before round 0: the last instant at which the caches
10650 // hold exactly `base + prompt.len()` rows and nothing generated.
10651 //
10652 // This was WRONG in the first cut of this lane: the capture sat after the draft-KV fill,
10653 // which is also after the init feed, so `cache.pos` was `base + prompt.len() + 1` — the
10654 // boundary included the FIRST GENERATED TOKEN. That token is the first thing inside the
10655 // `<think>` block the client strips, so every later turn's diff diverged exactly one
10656 // token below the checkpoint and affinity declined 100% of the time. Measured on the
10657 // owner regime: "history diverged at 12233 of checkpoint 12234". The off-by-one made the
10658 // whole mechanism inert while looking, from the outside, like a working
10659 // correctness-declines-safely path — hence the decline log carries the offsets.
10660 //
10661 // The full-attn planes are `len`-truncatable so the snapshot copies only the GDN conv/ssm
10662 // state (the reason a spec session could not rewind before). The draft scratch needs no
10663 // copy: rows below the boundary are rewritten by the next turn's own fill.
10664 //
10665 // WHEN: non-empty prime only. An empty-suffix continuation burst adds no prompt boundary
10666 // (its "prompt end" IS the previous checkpoint's, already held), so it keeps the existing
10667 // checkpoint rather than replacing it with a strictly worse one.
10668 //
10669 // FAILURE IS SILENT BY DESIGN: on a VRAM-tight rig the snapshot alloc can fail. That
10670 // costs the NEXT turn its rewind (it re-primes fully, today's behavior) and must never
10671 // fail the burst that is already running — so the error is swallowed, loud only under
10672 // MEMRA_DEBUG_SPEC.
10673 //
10674 // STABLE-BOUNDARY OVERRIDE (lane/frspec-multiturn-cache, 2026-08-21): the prompt-end
10675 // posture above was DISPROVED for the think-posture template class — the prompt's own
10676 // tail is the live generation header (`<|im_start|>assistant\n<think>\n`) that the
10677 // next turn's re-render replaces, so the diff diverged a couple tokens BELOW the
10678 // checkpoint and affinity declined 100% of multi-turn agent traffic (the same class
10679 // the plain tier fixed on 2026-08-09 via `plain_checkpoint_boundary`; the port to the
10680 // spec tier is this lane). When the worker armed `ckpt_at`, the capture happened at
10681 // that stop inside the prime above (`ckpt_early`) and is installed here instead;
10682 // capture-attempted-but-failed clears the slot exactly like the legacy arm.
10683 if let Some(slot) = sess_ckpt_slot {
10684 if let Some(early) = ckpt_early {
10685 if early.is_none() && std::env::var("MEMRA_DEBUG_SPEC").is_ok() {
10686 eprintln!(
10687 "[spec] stable-boundary turn checkpoint skipped; \
10688 next turn re-primes in full"
10689 );
10690 }
10691 *slot = early;
10692 } else if !continuation {
10693 let pos = cache.pos;
10694 debug_assert_eq!(
10695 pos,
10696 base + prompt.len(),
10697 "turn checkpoint must sit at the prompt end, before the init feed"
10698 );
10699 let anchor: Result<CudaSlice<f32>, Box<dyn std::error::Error>> =
10700 if let Some(ph) = &prompt_h {
10701 // hidden of the LAST primed row = the predecessor anchor at this
10702 // boundary (exactly what a fresh prime of committed[..pos] leaves in
10703 // last_h, and what the next prime's fill reads for its first row).
10704 let np = prompt.len();
10705 e.uninit(n_embd).and_then(|mut a| {
10706 e.copy_view_into(
10707 &mut a,
10708 0,
10709 &ph.slice((np - 1) * n_embd..np * n_embd),
10710 n_embd,
10711 )?;
10712 Ok(a)
10713 })
10714 } else {
10715 Err("no prompt hiddens".into())
10716 };
10717 match (cache.snapshot(e), anchor) {
10718 (Ok(snap), Ok(last_h)) => {
10719 *slot = Some(SpecCheckpoint { snap, pos, last_h });
10720 }
10721 (s, a) => {
10722 *slot = None; // a stale checkpoint would rewind to the WRONG boundary
10723 if std::env::var("MEMRA_DEBUG_SPEC").is_ok() {
10724 let err = s
10725 .err()
10726 .map(|e| e.to_string())
10727 .or_else(|| a.err().map(|e| e.to_string()))
10728 .unwrap_or_default();
10729 eprintln!(
10730 "[spec] turn checkpoint skipped ({err}); \
10731 next turn re-primes in full"
10732 );
10733 }
10734 }
10735 }
10736 }
10737 }
10738 // INIT FEED — skipped on a pending carry: last_token (the carried bonus) is NOT in the
10739 // caches and must NOT be fed solo; round 0's batched verify commits it as col 0. Its
10740 // seed/anchor hidden is the carried last_h (copied below); last_pred is dead in the
10741 // pending path (t_pred reads verify col 0 — the accept walk overwrites it).
10742 let mut last_pred = 0u32;
10743 let mut last_col_logits: Option<CudaSlice<f32>> = None;
10744 // CONSTRAINED: the init feed's logits back the (n_acc==0, base==0) masked-argmax
10745 // recompute in the grammar-truncation walk — retained host-side, round 0 only.
10746 let mut init_logits_host: Option<Vec<f32>> = None;
10747 let h_seed0: CudaSlice<f32> = if carried_pending.is_none() {
10748 let (init_logits, h) = self.spec_target_step_h(e, last_token, &mut *cache)?;
10749 last_pred = argmax(&init_logits) as u32;
10750 if constraint.is_some() {
10751 init_logits_host = Some(init_logits.clone());
10752 }
10753 // sampled mode: p-distribution after last_token, for the j==0/base==0 accept test.
10754 if sampled {
10755 last_col_logits = Some(e.htod(&init_logits)?);
10756 }
10757 h
10758 } else {
10759 // predecessor-row anchor: hidden of the last COMMITTED row (the carry contract).
10760 let lh = sess_tail
10761 .as_ref()
10762 .unwrap()
10763 .1
10764 .as_ref()
10765 .expect("pending carry requires last_h");
10766 e.clone_dtod(lh)?
10767 };
10768 let t_init = t_ent.elapsed();
10769 let mut last_col_stats: Option<(f32, f32, f32)> = None;
10770 // PERSISTENT h_seed buffer (allocated BEFORE any graph capture so no captured scratch can
10771 // alias it): every path that updates the round seed copies INTO it — no per-round allocs,
10772 // stable pointer for the graph-draft round-start copy.
10773 let mut h_seed_buf = e.clone_dtod(&h_seed0)?;
10774 // Predecessor-pairing trackers: `fill_prev` = trunk hidden AT the last COMMITTED row (the
10775 // predecessor of the next verify's col 0 — the reference's carried pending-h analogue;
10776 // also the predecessor-row hidden for the round-0 legacy-replay seed). At round 0 that
10777 // row is last_token's own (h_seed0). The chain step-0 seed under the pairing default =
10778 // hidden of the row BEFORE last_token = the prompt's last row at round 0 (h_seed_buf
10779 // overwritten below).
10780 let mut fill_prev = e.clone_dtod(&h_seed0)?;
10781 {
10782 if let Some(ph) = &prompt_h {
10783 let np = prompt.len();
10784 e.copy_view_into(
10785 &mut h_seed_buf,
10786 0,
10787 &ph.slice((np - 1) * n_embd..np * n_embd),
10788 n_embd,
10789 )?;
10790 } else if continuation {
10791 if let Some((_, lh, _, _, _)) = sess_tail.as_ref() {
10792 if let Some(lh) = lh.as_ref() {
10793 e.copy_into(&mut h_seed_buf, 0, lh, n_embd)?;
10794 }
10795 }
10796 }
10797 }
10798 // Persistent device prediction slots for the accept walk (max k+1 verify columns).
10799 let mut preds_d = e.alloc_u32_zeroed(k + 2)?;
10800
10801 let debug_spec = std::env::var("MEMRA_DEBUG_SPEC").is_ok();
10802 let fork_mode = OptiForkGateMode::configured();
10803 // MEMRA_SPEC_STATS=1: per-slot accept histogram + draft-length histogram, printed once at
10804 // the end. Metric normalization vs the reference engine: BOTH engines count
10805 // accepted/drafted where the chain stopped at p-min and the sub-threshold token is
10806 // discarded uncounted — per-slot decay + chain-length mix are the extra dimensions.
10807 let spec_stats = std::env::var("MEMRA_SPEC_STATS").is_ok();
10808 let mut st_drafted = vec![0usize; k];
10809 let mut st_accepted = vec![0usize; k];
10810 let mut st_len_hist = vec![0usize; k + 1];
10811 let mut st_full = 0usize;
10812 // P-MIN CONFIDENCE GATE (MEMRA_SPEC_PMIN, the serve script's --spec-draft-p-min mechanism):
10813 // stop the draft chain early when the head's softmax confidence in its own pick drops
10814 // below p_min. Hoisted above the loop: the graph capture bakes the prob kernels iff on.
10815 static PMIN: std::sync::OnceLock<f32> = std::sync::OnceLock::new();
10816 let p_min = *PMIN.get_or_init(|| {
10817 std::env::var("MEMRA_SPEC_PMIN")
10818 .ok()
10819 .and_then(|v| v.parse().ok())
10820 .unwrap_or(0.0)
10821 });
10822 // ZERO-DRAFT ROUNDS (MEMRA_SPEC_PMIN0=1, vendored from llama.cpp's draft gating): let the
10823 // p-min gate apply at j==0 too, so a low-confidence round drafts NOTHING and the verify
10824 // batch is just the pending bonus (m=1 = a plain decode step). llama's 35B win rides
10825 // exactly this — draft acceptance 76% at mean len 2.5 because unpredictable stretches
10826 // never pay draft+verify overhead. Only legal when a pending bonus exists (an empty
10827 // verify batch is not); the j==0 exemption stays for pending-less rounds.
10828 let pmin0 = std::env::var("MEMRA_SPEC_PMIN0")
10829 .map(|v| v == "1")
10830 .unwrap_or(false);
10831
10832 // --- GRAPH DRAFT setup: persistent I/O buffers + ONE capture (2 warmups inside). The
10833 // warmups mutate scratch len_d / pos / tok / seed — all reset at every round start, so the
10834 // only restore needed is the scratch counter. Capture failure (e.g. a non-capturable
10835 // cuBLAS path in an exotic head) falls back to the eager draft chain.
10836 // PER-SESSION PERSISTENCE (2026-08-01): session calls reuse the DraftGraphCtx parked on
10837 // the SpecSession — the capture (2 warmup head forwards + instantiate) ran ONCE at the
10838 // session's first burst, not per burst (measured ~16ms/burst fixed cost on H100 q27,
10839 // research/spec-serving-20260801). Reuse is pointer-exact: the graph bakes the session's
10840 // own scratch KV (never realloc'd), the model's resident embedding, the OnceLock p_min,
10841 // and the g_* buffers carried in the ctx — replay dispatch is identical to a fresh
10842 // capture, so draft tokens are bit-identical (drafts never decide exactness anyway; the
10843 // verify arbitrates). Single-shot calls (sess=None) build a fresh ctx and drop it.
10844 let mut dctx: DraftGraphCtx = match sess_draft_slot.as_mut().and_then(|s| s.take()) {
10845 Some(c) => c,
10846 None => DraftGraphCtx::new(e, n_embd, if sampled { d_vocab } else { 1 })?,
10847 };
10848 // A session that ran greedy bursts first sized g_q/g_perturb at 1; a sampled resume
10849 // needs d_vocab. Realloc is legal exactly while graph_s is None (nothing baked them).
10850 if sampled && dctx.g_q.len() < d_vocab {
10851 dctx.g_q = e.zeros(d_vocab)?;
10852 dctx.g_perturb = e.zeros(d_vocab)?;
10853 }
10854 // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask, 2026-08-04): the drafter samples the
10855 // grammar's legal set, so proposals are legal BY CONSTRUCTION and the verify-side
10856 // truncation (the correctness backstop) stops cutting every tight-schema round.
10857 // The mask is one node inside the captured draft chain — presence is a CAPTURE-TIME
10858 // shape, so a parked graph of the other shape is dropped and recaptured.
10859 let dmask_on = constraint
10860 .as_deref()
10861 .is_some_and(|c| c.draft_mask_enabled());
10862 let dmask_words = if dmask_on { d_vocab.div_ceil(32) } else { 0 };
10863 if dmask_on && dctx.g_dmask.len() < dmask_words {
10864 dctx.g_dmask = e.alloc_u32_zeroed(dmask_words)?;
10865 dctx.graph = None; // the old capture baked the old (or no) mask pointer
10866 dctx.failed.clear_greedy();
10867 dctx.keeper.clear();
10868 }
10869 if dctx.graph.is_some() && dctx.graph_masked != dmask_on {
10870 dctx.graph = None;
10871 dctx.failed.clear_greedy();
10872 dctx.keeper.clear();
10873 }
10874 if graph_draft && !sampled && dctx.graph.is_none() && !dctx.failed.greedy_failed() {
10875 let DraftGraphCtx {
10876 g_tok,
10877 g_pos,
10878 g_seed,
10879 g_p,
10880 g_dmask,
10881 ..
10882 } = &mut dctx;
10883 // capture-time contents: ALL-ONES (ban nothing). A replay only ever runs after the
10884 // host uploads the position's real words, so the warmups stay grammar-free.
10885 if dmask_on {
10886 e.htod_u32_into(g_dmask, &vec![u32::MAX; dmask_words])?;
10887 }
10888 let g_dmask_ro: &CudaSlice<u32> = &*g_dmask;
10889 // CAPTURE-RETAIN (#68 fix): the warmup transients' pool addresses are baked into the
10890 // captured graph; the keeper pins them for the graph's lifetime. capture_graph (non-
10891 // retained) freed them at exit — safe for one-shot generate_spec (nothing else touches
10892 // the pool between replays) but WRONG for sessions: burst-boundary prime/fill/commit
10893 // passes (and, in serve, other sessions) recycle those addresses and the replay then
10894 // clobbers live buffers — the ST serve-spec corruption (research/serve-st-20260803).
10895 let cap_res = e.capture_graph_retained(|e| {
10896 self.mtp_head_forward_cap(
10897 e,
10898 mtp,
10899 g_tok,
10900 g_pos,
10901 g_seed,
10902 g_p,
10903 &mut *scratch,
10904 p_min > 0.0 || fork_mode == OptiForkGateMode::Controller,
10905 true,
10906 embd_gpu.expect("graph draft requires resident embedding"),
10907 embd_qt,
10908 embd_rb,
10909 d_vocab,
10910 None,
10911 None,
10912 if dmask_on {
10913 Some((g_dmask_ro, dmask_words))
10914 } else {
10915 None
10916 },
10917 )
10918 });
10919 match cap_res {
10920 Ok((g, keep)) => {
10921 scratch.set_len(e, base)?;
10922 dctx.graph = Some(g);
10923 dctx.graph_masked = dmask_on;
10924 dctx.keeper = keep;
10925 }
10926 Err(err) => {
10927 scratch.set_len(e, base)?;
10928 // LOUD flip (audit Q2): a dropped draft graph is a coverage loss, never
10929 // silent. Once per flip — mark returns None on an already-failed ctx.
10930 if let Some(line) = dctx.failed.mark_greedy(&err.to_string()) {
10931 eprintln!("{line}");
10932 }
10933 }
10934 }
10935 }
10936 // --- SAMPLED GRAPH DRAFT setup (step 3 of the sampled-spec arc): a SECOND capture, own
10937 // graph object, built only when sampled && graph-eligible — the greedy capture above is
10938 // untouched (and skipped when sampled: its graph would never be launched). Same head
10939 // forward, but the in-graph argmax reads GUMBEL-PERTURBED logits; the Philox event
10940 // counter lives in the persistent device g_ctr (bumped in-graph, host-seeded from sctr
10941 // once per round); the raw head logits land in the persistent g_q for the host's
10942 // per-replay async D2D into the round's q slot (q_slots, K x d_vocab, allocated once).
10943 // seed/temp are capture-time constants — baked into graph_s, so a pool-resumed request
10944 // with a different (seed, temp, k) drops the parked sampled graph and recaptures.
10945 // COST OF THE FRESH-SEED SERVE DEFAULT (dogfood F4, 2026-08-04): omitting `seed` on a
10946 // serve request now draws fresh per-request entropy (it used to default to a pinned 0),
10947 // so a seed-omitting request that RESUMES a parked spec session finds an s_key baked
10948 // with the PREVIOUS request's seed and pays one recapture. Bounded, and it does not
10949 // reopen the ~16ms/burst regression the persistent ctx exists to fix: a session's seed
10950 // is fixed for its whole lifetime (worker.rs reads s.sampler.seed() per burst), so
10951 // this compare misses at most ONCE per resumed request — the first burst recaptures
10952 // and every later burst in that request replays. A client that wants the parked graph
10953 // AND reproducibility supplies an explicit `seed`, honored exactly, which keeps s_key
10954 // stable across its whole conversation.
10955 // COMPOSITION RULE (fspec x gsd merge): the in-graph chain samples from the RAW
10956 // softmax — it can hold neither per-row filter stats nor the varying penalty history.
10957 // The sampled graph therefore engages only in the PURE-TEMP regime; filters/penalties
10958 // force the eager draft (which computes stats/penalties per row).
10959 // KEY THE WHOLE REGIME, not just the baked constants (lane/graph-s-key-exactness-
10960 // 20260819). `s_key` used to be `(seed, temp, k)`; the filters and penalties were left
10961 // out, so a filtered request resuming a session that parked a PURE-TEMP graph kept it —
10962 // and the launch site never re-asked `pure_temp`. See [`SampledGraphKey`] for what that
10963 // costs (an unconditional accept of out-of-head draft tokens, i.e. an exactness bug on
10964 // the request shape the vendor-default flip makes the majority).
10965 let s_key = SampledGraphKey::new(sp_seed, sp_temp, k, sp.top_k, sp.top_p, sp.min_p, pen_on);
10966 let pure_temp = s_key.pure_temp();
10967 if sampled && dctx.s_key.is_some_and(|old| old != s_key) {
10968 dctx.graph_s = None;
10969 dctx.failed.clear_sampled();
10970 dctx.s_key = None;
10971 dctx.q_slots.clear();
10972 dctx.keeper_s.clear();
10973 }
10974 if graph_draft
10975 && sampled
10976 && pure_temp
10977 && dctx.graph_s.is_none()
10978 && !dctx.failed.sampled_failed()
10979 {
10980 let DraftGraphCtx {
10981 g_tok,
10982 g_pos,
10983 g_seed,
10984 g_p,
10985 g_ctr,
10986 g_perturb,
10987 g_q,
10988 ..
10989 } = &mut dctx;
10990 // CAPTURE-RETAIN (#68 fix): same keeper contract as the greedy capture above.
10991 let cap_res = e.capture_graph_retained(|e| {
10992 self.mtp_head_forward_cap(
10993 e,
10994 mtp,
10995 g_tok,
10996 g_pos,
10997 g_seed,
10998 g_p,
10999 &mut *scratch,
11000 p_min > 0.0,
11001 true,
11002 embd_gpu.expect("graph draft requires resident embedding"),
11003 embd_qt,
11004 embd_rb,
11005 d_vocab,
11006 Some((g_ctr, g_perturb, g_q, sp_seed, sp_temp)),
11007 None,
11008 None, // constrained spec is greedy-only — sampled never carries a hook
11009 )
11010 });
11011 match cap_res {
11012 Ok((g, keep)) => {
11013 scratch.set_len(e, base)?;
11014 for _ in 0..k {
11015 dctx.q_slots.push(e.zeros(d_vocab)?);
11016 }
11017 dctx.graph_s = Some(g);
11018 dctx.s_key = Some(s_key);
11019 dctx.keeper_s = keep;
11020 }
11021 Err(err) => {
11022 scratch.set_len(e, base)?;
11023 // LOUD flip (audit Q2): same contract as the greedy capture above.
11024 if let Some(line) = dctx.failed.mark_sampled(&err.to_string()) {
11025 eprintln!("{line}");
11026 }
11027 }
11028 }
11029 }
11030 // ---- EXACTNESS GUARD, the enforceable half (lane/graph-s-key-exactness-20260819) ----
11031 // With the filters and penalties in `s_key`, a graph that SURVIVED the drop above was
11032 // captured under this request's exact regime, and capture requires `pure_temp` — so a
11033 // parked graph implies `pure_temp`. That implication is the whole exactness argument for
11034 // the graph arm, so it is asserted here rather than assumed: a future change that widens
11035 // the capture condition, narrows the key, or copies a `DraftGraphCtx` across regimes
11036 // fails LOUDLY at this line instead of silently drafting from the raw softmax while the
11037 // verify applies filter stats. Release builds refuse the graph (drop it, draft eager)
11038 // rather than launching it; the launch site re-tests `pure_temp` independently.
11039 if sampled && !pure_temp && dctx.graph_s.is_some() {
11040 debug_assert!(
11041 false,
11042 "sampled draft graph parked under {:?} survived into a FILTERED request \
11043 (top_k={} top_p={} min_p={} pen_on={}): the in-graph chain draws from the RAW \
11044 softmax, so the verify's filtered q would test a distribution the draft was \
11045 never sampled from",
11046 dctx.s_key, sp.top_k, sp.top_p, sp.min_p, pen_on,
11047 );
11048 eprintln!(
11049 "[spec] BUG: dropping a parked sampled draft graph that outlived its capture \
11050 regime (s_key={:?}, request top_k={} top_p={} min_p={} pen_on={}); drafting \
11051 EAGER — the key must carry every field that shapes q",
11052 dctx.s_key, sp.top_k, sp.top_p, sp.min_p, pen_on,
11053 );
11054 dctx.graph_s = None;
11055 dctx.s_key = None;
11056 dctx.q_slots.clear();
11057 dctx.keeper_s.clear();
11058 }
11059 // SKEY PROBE (MEMRA_SKEY_PROBE=1): the burst-entry facts the reachability question turns
11060 // on — is this request sampled, is it in the pure-temp regime the sampled graph is only
11061 // legal in, and is a graph PARKED from an earlier request of the same session? The launch
11062 // arms below print which chain actually ran, so the probe never restates the condition.
11063 if skey_probe() {
11064 eprintln!(
11065 "[skey] burst sampled={} pure_temp={} temp={} top_k={} top_p={} min_p={} \
11066 pen_on={} k={} graph_draft={} graph_s_parked={} s_key_parked={:?}",
11067 sampled as u8,
11068 pure_temp as u8,
11069 sp_temp,
11070 sp.top_k,
11071 sp.top_p,
11072 sp.min_p,
11073 pen_on as u8,
11074 k,
11075 graph_draft as u8,
11076 dctx.graph_s.is_some() as u8,
11077 dctx.s_key,
11078 );
11079 }
11080 let t_cap = t_ent.elapsed();
11081 // PERSISTENT DRAFT KV: fill the MTP block's K/V for every prompt position from the exact
11082 // trunk hiddens collected during prime — ONE batched K/V-only pass (overwrites any
11083 // capture-warmup garbage; capture left len at 0). last_token (the init feed) needs no
11084 // fill: the first chain step processes it and appends its entry at slot prompt.len().
11085 if let Some(ph) = &prompt_h {
11086 // SESSION: rows [0..base) are the previous turns' exact fills (refresh overwrote them
11087 // with true verify hiddens) — truncate any draft overhang, fill ONLY the suffix at
11088 // global positions [base..base+tp). Fresh call: base==0, identical to before.
11089 scratch.set_len(e, base)?;
11090 // CHUNKED FILL (long-ctx OOM fix, 2026-07-05): mtp_kv_fill's transients scale with its
11091 // T (concat = T*2*n_embd*4B — 1.5GB at 40k) and its concat loop is 2*T launches. The
11092 // fill is a pure sequential append, so chunking is exact: each chunk appends its rows
11093 // at pos0=base+start with the identical per-row math. Same knob as the trunk prime.
11094 let tp = prompt.len();
11095 let fill_chunk: usize = if crate::cache::swa_ring_on() {
11096 crate::hybrid_forward::prime_chunk_tokens(tp, self.layers.len())
11097 } else {
11098 // Preserve the flag-OFF schedule byte-for-byte, including the legacy zero value
11099 // meaning one monolithic fill.
11100 std::env::var("MEMRA_PRIME_CHUNK")
11101 .ok()
11102 .and_then(|v| v.parse().ok())
11103 .unwrap_or(4096)
11104 };
11105 let fill_chunk = if fill_chunk == 0 { tp } else { fill_chunk };
11106 let mut start = 0usize;
11107 while start < tp {
11108 let end = (start + fill_chunk).min(tp);
11109 let tc = end - start;
11110 {
11111 // PREDECESSOR pairing: row i gets h[i-1]; global row 0 a zeros row (the
11112 // reference engine's initial pending-h is zeroed too); a session turn's row 0
11113 // gets the PREVIOUS turn's last committed hidden (sess.last_h). Per chunk:
11114 // rows start..end read h[start-1..end-1] — one dtod into a chunk buffer.
11115 let mut phs = e.zeros(tc * n_embd)?;
11116 let (src_lo, dst_off) = if start == 0 {
11117 (0, n_embd)
11118 } else {
11119 ((start - 1) * n_embd, 0)
11120 };
11121 let n_copy = if start == 0 {
11122 (tc - 1) * n_embd
11123 } else {
11124 tc * n_embd
11125 };
11126 if start == 0 {
11127 if let Some((_, lh, _, _, _)) = sess_tail.as_ref() {
11128 if let Some(lh) = lh.as_ref() {
11129 e.copy_into(&mut phs, 0, lh, n_embd)?;
11130 }
11131 }
11132 }
11133 if n_copy > 0 {
11134 e.copy_view_into(
11135 &mut phs,
11136 dst_off,
11137 &ph.slice(src_lo..src_lo + n_copy),
11138 n_copy,
11139 )?;
11140 }
11141 self.mtp_kv_fill_all(
11142 e,
11143 &prompt[start..end],
11144 &phs,
11145 base + start,
11146 &mut *scratch,
11147 embd_dev,
11148 )?;
11149 }
11150 start = end;
11151 }
11152 }
11153 // MEMRA_PROFILE_SPEC=2: profiler capture starts HERE — after the prime, so an
11154 // `nsys -c cudaProfilerApi` capture contains ONLY the round loop (draft/verify/commit).
11155 // (=1 brackets the whole call in run_spec.rs, prime included.)
11156 if std::env::var("MEMRA_PROFILE_SPEC").as_deref() == Ok("2") {
11157 unsafe extern "C" {
11158 fn cudaProfilerStart() -> i32;
11159 }
11160 unsafe {
11161 cudaProfilerStart();
11162 }
11163 }
11164 // ROUND-STREAM stage (c) 4 (MEMRA_SPEC_STREAM=1, experimental): pre-issued M-round
11165 // bursts with ZERO per-round host readbacks — the accept/seed/rollback/ring kernels
11166 // consume each other's device outputs; the host drains the ring every M rounds. v1
11167 // constraints: greedy, !spec_replay, single-shot, batched-linear layers, no refresh
11168 // fills (acceptance effect A/B-arbitrated), enters from round 1 (pending guaranteed).
11169 // NOTE: not gated on the caller's graph_draft (its trunk_dense conjunct turns the 35B
11170 // MoE off) — the stream capture encloses ONLY the dense MTP head; the head-dense /
11171 // full-prec / k gates are re-derived here and a failed capture degrades to stream-off.
11172 let stream_on = crate::spec::spec_stream()
11173 && !sampled
11174 && !spec_replay
11175 && self.mtp_extra.is_empty()
11176 && constraint.is_none()
11177 && !session_mode
11178 && embd_gpu.is_some()
11179 && !crate::model::full_prec_enabled()
11180 && k + 2 < 96;
11181 let mut stream_graph: Option<cudarc::driver::CudaGraph> = None;
11182 let mut g_tokp2k = e.alloc_u32_zeroed(2 * k.max(1))?;
11183 if stream_on {
11184 let cap = e.capture_graph(|e| {
11185 for j in 0..k.max(1) {
11186 self.mtp_head_forward_cap(
11187 e,
11188 mtp,
11189 &mut dctx.g_tok,
11190 &mut dctx.g_pos,
11191 &mut dctx.g_seed,
11192 &mut dctx.g_p,
11193 &mut *scratch,
11194 true,
11195 true,
11196 embd_gpu.expect("round stream requires resident embedding"),
11197 embd_qt,
11198 embd_rb,
11199 d_vocab,
11200 None,
11201 Some((&mut g_tokp2k, j, d2t_dev.as_ref())),
11202 None, // round-stream requires constraint.is_none() (see stream_on)
11203 )?;
11204 }
11205 Ok(())
11206 });
11207 match cap {
11208 Ok(g) => {
11209 scratch.set_len(e, 0)?;
11210 stream_graph = Some(g);
11211 }
11212 Err(err) => {
11213 scratch.set_len(e, 0)?;
11214 if debug_spec {
11215 eprintln!("[spec] stream-graph capture failed ({err}); stream off");
11216 }
11217 }
11218 }
11219 }
11220 let stream_active = stream_on && stream_graph.is_some();
11221 if debug_spec {
11222 eprintln!(
11223 "[spec] stream_on={stream_on} env={} samp={sampled} dg={} captured={} active={stream_active} session={session_mode} replay={spec_replay}",
11224 crate::spec::spec_stream(),
11225 dctx.graph.is_some(),
11226 stream_graph.is_some()
11227 );
11228 }
11229 let t_v_s = k + 1;
11230 // ROUND-STREAM buffers + ptr tables now live in the model-generic round_stream
11231 // module (extracted 2026-07-12; the gemma burst reuses them).
11232 let sb = crate::round_stream::StreamBufs::new(e, k, crate::spec::spec_stream_m())?;
11233 let crate::round_stream::StreamBufs {
11234 mut vtok_d,
11235 mut brk_d,
11236 mut pend_d,
11237 last_pred_d,
11238 mut pos_ctr,
11239 mut pos_start_d,
11240 mut ring_d,
11241 acc_d: mut stream_acc,
11242 m_rounds,
11243 k: _,
11244 } = sb;
11245 let stream_ptrs: Option<CudaSlice<u64>> = if stream_active {
11246 Some(crate::round_stream::kv_len_ptr_table(
11247 e,
11248 cache,
11249 Some(&pos_ctr),
11250 )?)
11251 } else {
11252 None
11253 };
11254
11255 let t_fill = t_ent.elapsed();
11256 let mut round = 0usize;
11257 // ADAPTIVE DRAFT LENGTH (MEMRA_SPEC_ADAPT=1, opt-in — the gemma_spec accepted-run law,
11258 // ported 2026-08-01): next round's draft depth = last round's accepted run + 1, clamped
11259 // to [floor(pos), k_cap] — a miss shrinks the next draft to the miss point + 1,
11260 // full-accept streaks re-deepen one step per round. NOT the 2026-07-07 acceptance-EMA
11261 // (that arm measured an HONEST LOSS to static per-class optima — 115.0/85.8/73.4 vs
11262 // 121.6/92.7/75.6, EMA lag — and was removed 2026-07-08; rig5090.jsonl has the record).
11263 // The gemma law has no lag class: it reacts within one round, and was worth +7-20% on
11264 // the gemma cells at unchanged exactness (2026-07-10 flip; floor sweep 2026-07-25;
11265 // position key 2026-07-26). Signal = n_acc from the round's EXISTING accept readback —
11266 // zero new syncs; the draft graph is a SINGLE-STEP capture replayed per drafted token,
11267 // so a per-round depth needs no re-capture (unlike gemma's whole-chain graphs). qwen's
11268 // in-round p-min cut already shortens chains mid-round, so gemma's one-round-late p-min
11269 // fold into kc is unnecessary here — the accepted-run law sees the cut via n_acc.
11270 // Exactness is the verify's job at ANY depth (same contract as p-min variable rounds).
11271 // DEFAULT OFF on the qwen path until its cells gate a flip (gemma's is default-on).
11272 // MEASURED 2026-08-01 (H100 GPU-3, interleaved x3, NGEN=256, same-invocation plain
11273 // denominators; research/qwen-adaptive-k-20260801/): REFUTED on the tuned qwen configs.
11274 // q27 K=3+HPOST+PMIN=0.3: short +0.8% (noise; law ~idles, len_hist identical), board
11275 // -1.9%, agentic -0.5%; board PMIN=0 -2.1% (not p-min shadowing — the law itself);
11276 // floor=1 -2.8% (gemma's floor-collapse, reproduced). q35 K=2 board: -6.4% (52/136
11277 // rounds shrink to depth 1; no depth to reclaim at K=2). The gemma direction DOES
11278 // appear at untuned depth-K — q27 K=6 floor=4 +1.5% over fixed K=6 — but stays -3.7%
11279 // below fixed K=3: same verdict class as the retired EMA arm (honest loss to static
11280 // per-class optima). Acceptance-rate rises under the law while tokens/round falls —
11281 // it buys accept-% by adding rounds, and a round's fixed draft+verify cost wins.
11282 // K=1..8 self-consistency PASS both models with the law ON (exactness held).
11283 let adapt = std::env::var("MEMRA_SPEC_ADAPT").as_deref() == Ok("1");
11284 // floor: per-model default keyed on n_embd (gemma's tiering — models with an expensive
11285 // verify keep deep drafts after a miss); MEMRA_SPEC_ADAPT_FLOOR pins it everywhere.
11286 let adapt_floor_env: Option<usize> = std::env::var("MEMRA_SPEC_ADAPT_FLOOR")
11287 .ok()
11288 .and_then(|v| v.parse().ok());
11289 let adapt_floor_default: usize = if self.cfg.n_embd as usize >= 3500 {
11290 4
11291 } else if self.cfg.n_embd as usize >= 2500 {
11292 2
11293 } else {
11294 1
11295 };
11296 let adapt_floor: usize = adapt_floor_env.unwrap_or(adapt_floor_default);
11297 // position key: past floor_ctx a HIGH floor (>=4) relaxes to 1 — forced-deep drafts
11298 // turn net-negative at depth (gemma 31B d1736 evidence); MEMRA_SPEC_FLOOR_CTX moves
11299 // the boundary, an explicit MEMRA_SPEC_ADAPT_FLOOR pins the floor everywhere.
11300 let floor_ctx: usize = std::env::var("MEMRA_SPEC_FLOOR_CTX")
11301 .ok()
11302 .and_then(|v| v.parse().ok())
11303 .unwrap_or(1024);
11304 let floor_at = |pos: usize| -> usize {
11305 if adapt_floor_env.is_some() || pos < floor_ctx {
11306 adapt_floor
11307 } else if adapt_floor >= 4 {
11308 1
11309 } else {
11310 adapt_floor
11311 }
11312 };
11313 // cap: MEMRA_SPEC_CAPMAX (gemma semantics, default 7). Binds only under adapt — the
11314 // fixed-K default path is untouched by this whole block.
11315 let cap_max: usize = std::env::var("MEMRA_SPEC_CAPMAX")
11316 .ok()
11317 .and_then(|v| v.parse().ok())
11318 .unwrap_or(7);
11319 let k_cap = k.min(cap_max).max(1);
11320 let mut kc = k_cap;
11321 let mut opti_fork: Option<OptiForkState> = None;
11322 let mut fork_snapshot: Option<crate::cache::CacheSnapshot> = None;
11323 if fork_mode != OptiForkGateMode::Disabled {
11324 let fence = crate::pp::pp_cuts(self.layers.len());
11325 let refusal = if !session_mode {
11326 Some("not-session")
11327 } else if k != 1 || adapt {
11328 Some("requires-fixed-k1")
11329 } else if sampled || constraint.is_some() || spec_replay {
11330 Some("sampled-constrained-or-replay")
11331 } else if pipe.is_some() {
11332 Some("two-session-pipeline")
11333 } else if !spec_devacc() {
11334 Some("requires-device-accept")
11335 } else if stream_active || crate::spec::spec_stream() {
11336 Some("round-stream")
11337 } else if !self.mtp_extra.is_empty() {
11338 Some("multi-head-mtp")
11339 } else if crate::cache::swa_ring_on() || cache.has_swa_ring() {
11340 Some("swa-ring")
11341 } else if crate::pp::pp_host_bounce_active() {
11342 Some("host-bounce")
11343 } else if fork_mode == OptiForkGateMode::Controller
11344 && cache.recur.iter().any(Option::is_some)
11345 {
11346 Some("controller-requires-zero-recurrent-state")
11347 } else if fence.as_ref().is_none_or(|f| f.len() != 3) {
11348 Some("requires-pp2")
11349 } else {
11350 None
11351 };
11352 if let Some(reason) = refusal {
11353 OPTI_FORK_REFUSALS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
11354 eprintln!("[opti-fork] refused reason={reason}");
11355 } else {
11356 let fence = fence.expect("validated PP-2 fence");
11357 let rt = crate::pp::PpNRt::get(e)?;
11358 let primary_stage0 = rt.engine(0, e).ctx().ordinal() == e.ctx().ordinal();
11359 let primary_stage1 = rt.engine(1, e).ctx().ordinal() == e.ctx().ordinal();
11360 let primary_supported =
11361 primary_stage0 || (fork_mode == OptiForkGateMode::Controller && primary_stage1);
11362 if !rt.cross_device() || !primary_supported {
11363 OPTI_FORK_REFUSALS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
11364 eprintln!("[opti-fork] refused reason=requires-supported-primary-cross-device");
11365 } else {
11366 // Both recurrent snapshots and both seed generations are allocated before
11367 // the first fork, each through its owning PP stage. Allocation failure
11368 // therefore happens before any optimistic state mutation can occur.
11369 let current_snapshot = opti_snapshot_stage_owned(e, cache, rt, &fence)?;
11370 let alternate_snapshot = opti_snapshot_stage_owned(e, cache, rt, &fence)?;
11371 let fork = OptiForkState::new(
11372 e,
11373 cache,
11374 fork_mode,
11375 alternate_snapshot,
11376 &h_seed_buf,
11377 &fill_prev,
11378 rt,
11379 fence[1],
11380 self.layers.len(),
11381 )?;
11382 eprintln!(
11383 "[opti-fork] armed mode={fork_mode:?} snapshots=2 seeds=2 split={} \
11384 payload_dev0={} payload_dev1={} q_threshold={:.3}",
11385 fence[1],
11386 fork.logical_payload_bytes[0],
11387 fork.logical_payload_bytes[1],
11388 fork.controller.map_or(0.0, |policy| policy.threshold),
11389 );
11390 fork_snapshot = Some(current_snapshot);
11391 opti_fork = Some(fork);
11392 }
11393 }
11394 }
11395 // Persistent snapshot buffers are allocated once and refreshed in place. The fork arm
11396 // uses stage-owned snapshots; refused/disabled arms retain the existing generic helper.
11397 let mut snap = match fork_snapshot {
11398 Some(snapshot) => snapshot,
11399 None => cache.snapshot(e)?,
11400 };
11401 let mut carried_opti: Option<OptiControllerTicket> = None;
11402 // ROUND-STREAM stage (b) 3a: device table of per-layer kvl.len_d pointers (stable — the
11403 // cache never reallocates len_d; see cache.rs "stable pointer" note). 0 = no KV layer.
11404 let kv_len_ptrs: Option<CudaSlice<u64>> = if spec_devacc() && !spec_replay {
11405 Some(crate::round_stream::kv_len_ptr_table(e, cache, None)?)
11406 } else {
11407 None
11408 };
11409 // BONUS FOLD (2026-07-04): after a FULL accept the bonus token is NOT committed with a
11410 // separate T=1 trunk pass (a full weight read per round). It stays PENDING and rides as
11411 // column 0 of the NEXT round's verify batch. Under predecessor pairing the next chain
11412 // seeds from the bonus's predecessor's TRUE verify hidden (free — no extra
11413 // pass of any kind). Verify still
11414 // checks every emitted token against the target -> exactness holds by construction; only
11415 // DRAFT QUALITY can shift, which the acceptance numbers arbitrate.
11416 // bonus emitted but not yet committed to cache. A carried pending (see SpecSession::
11417 // pending_tok) enters round 0 directly — the burst boundary becomes a plain round edge.
11418 let mut pending: Option<u32> = carried_pending;
11419 // MEMRA_SPEC_PHASE=1: per-round wall decomposition (draft / verify / accept+commit) —
11420 // no tracing, no extra syncs (each phase is naturally sync-bounded: draft readbacks,
11421 // the verify accept readback). Printed once at loop end via spec-stats.
11422 let anatomy_on = std::env::var("MEMRA_SPEC_PP_ANATOMY").as_deref() == Ok("1");
11423 let phase_on = anatomy_on || std::env::var("MEMRA_SPEC_PHASE").as_deref() == Ok("1");
11424 // DRAFT-MASK receipt (lane/draft-mask): speculative-clone wall + rounds, printed with
11425 // spec-stats. The clone is the one cost the design adds per round — measured, not assumed.
11426 let (mut dm_clone_ns, mut dm_rounds) = (0u128, 0usize);
11427 // grammar-truncation counters: how many rounds the verify-side cut fired and how many
11428 // already-verified tokens it threw away. THIS is the quantity draft masking targets.
11429 let (mut dm_cuts, mut dm_cut_tokens) = (0usize, 0usize);
11430 let (mut ph_draft, mut ph_verify, mut ph_rest) = (0f64, 0f64, 0f64);
11431 let mut ph_wait = 0f64;
11432 let mut ph_commit = 0f64;
11433 let mut ph_t = std::time::Instant::now();
11434 let mut ph_mark = |acc: &mut f64, on: bool| {
11435 if on {
11436 let now = std::time::Instant::now();
11437 *acc += (now - ph_t).as_secs_f64();
11438 ph_t = now;
11439 }
11440 };
11441 // MTP-ROUTE VERIFY GRAPHS (`MEMRA_SPEC_VERIFY_GRAPH`, see the flag doc): the
11442 // model-owned capture pool, locked for the whole burst exactly as the dspark serve
11443 // arm holds it — the slab stash is live verify -> commit inside a round, and the
11444 // worker drives rounds from one scheduler thread. PERSISTENT across generations on
11445 // the model (rebuilding per call re-captures the pool per prompt, which is the
11446 // measured way to lose more than the launches cost); the captured bodies are
11447 // cache-independent, every state read going through per-round refreshed pointer
11448 // tables. None = the eager walk, byte-identical.
11449 //
11450 // Never armed together with ROUND-STREAM: the tparallel verify refuses that pair
11451 // loudly, and `stream_active` owns the burst arm above, so the door stays shut
11452 // whenever the stream is live rather than relying on that refusal.
11453 // The lock is taken ONLY when the door is armed: with the flag off this whole block
11454 // is inert, so the default path cannot serialize two spec generations behind a mutex
11455 // it never reads.
11456 let vg_armed =
11457 crate::spec::spec_verify_graph_env().unwrap_or_else(|| self.vgraph_family_default());
11458 let mut vg_guard = if vg_armed && !stream_active {
11459 let mut g = self.dspark_vgraphs.lock().unwrap();
11460 if g.is_none() {
11461 // Size by the WIDEST verify this run can present, which is k+1 and NOT
11462 // k_cap+1: the sampled arm's own window is `t_v_s = k + 1`, so a pool built
11463 // from a smaller adaptive cap gets sliced past its stash rows (a `slice_mut`
11464 // panic in the sampled ON arm, measured before this line said k+1).
11465 let vt_cap = (k.max(k_cap) + 1).max(2);
11466 *g = DsparkVerifyGraphs::new(e, cache, vt_cap, n_embd)?;
11467 if g.is_some() {
11468 // Engagement receipt (the dead-arm lesson): prove the door is LIVE rather
11469 // than trusting that a flag set means a pool built.
11470 eprintln!("[spec-vg] MTP verify-graph pool ENGAGED (vt_cap={vt_cap})");
11471 } else {
11472 eprintln!(
11473 "[spec-vg] MTP verify-graph pool declined (no linear layers, \
11474 non-uniform state, or vt_cap < 2) — eager walk"
11475 );
11476 }
11477 }
11478 Some(g)
11479 } else {
11480 None
11481 };
11482 // Capacity fail-safe: a round wider than the pool was built for must take the eager
11483 // walk, not slice the stash past its rows. The sizing above already covers every
11484 // round this run can present; this keeps a future caller (or a k that grows behind
11485 // the pool's back) on the byte-identical fallback instead of a panic.
11486 let vg_t_cap = vg_guard
11487 .as_ref()
11488 .and_then(|g| g.as_ref())
11489 .map(|g| g.t_capacity())
11490 .unwrap_or(0);
11491 if let Some(p) = pipe {
11492 p.setup_end();
11493 }
11494 while keep_going && out.len() < max_new {
11495 // ROUND-STREAM BURST: from round 1 (pending guaranteed by every non-replay arm),
11496 // issue M rounds with zero readbacks, then drain the ring + reconcile mirrors.
11497 if let (true, Some(sg), Some(ptrs)) = (
11498 stream_active && round >= 1 && pending.is_some(),
11499 &stream_graph,
11500 &stream_ptrs,
11501 ) {
11502 if debug_spec {
11503 static ONCE: std::sync::Once = std::sync::Once::new();
11504 ONCE.call_once(|| {
11505 eprintln!("[memra] ROUND-STREAM burst engaged (M={m_rounds} k={k})")
11506 });
11507 }
11508 e.set_i32_one(&mut pos_ctr, cache.pos as i32)?;
11509 e.set_u32_one(&mut pend_d, pending.unwrap())?;
11510 e.set_u32_one(&mut ring_d, 0)?; // ring count = 0 (writes element 0)
11511 for _mi in 0..m_rounds {
11512 e.i32_copy_add(&pos_ctr, &mut pos_start_d, 0)?;
11513 cache.snapshot_into(e, &mut snap)?; // device D2Ds, stream-ordered
11514 e.i32_copy_add(&pos_ctr, &mut scratch.kv.len_d, 0)?; // draft-KV rollback
11515 e.i32_copy_add(&pos_ctr, &mut dctx.g_pos, 1)?; // rope pos = pos + base
11516 e.u32_copy(&pend_d, &mut dctx.g_tok)?;
11517 e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
11518 sg.launch()?;
11519 e.spec_assemble_verify(
11520 &g_tokp2k,
11521 &pend_d,
11522 d2t_dev.as_ref(),
11523 &mut vtok_d,
11524 &mut brk_d,
11525 p_min,
11526 k,
11527 pmin0,
11528 )?;
11529 let mut ck = VerifyCkpt::new(self.layers.len());
11530 let dummy = vec![0u32; t_v_s];
11531 let (tl_d, vx) = self.decode_step_t_core_stream(
11532 e,
11533 &dummy,
11534 0,
11535 &mut *cache,
11536 embd_dev,
11537 Some(&mut ck),
11538 Some((&vtok_d, &pos_ctr)),
11539 None,
11540 None,
11541 None,
11542 )?;
11543 for j in 0..t_v_s {
11544 e.argmax_token_device_col(&tl_d, j, n_vocab, &mut preds_d, j)?;
11545 }
11546 e.spec_accept_greedy_dc(
11547 &preds_d,
11548 &vtok_d,
11549 &last_pred_d,
11550 &brk_d,
11551 &mut stream_acc,
11552 )?;
11553 e.spec_seed_gather(&vx, &fill_prev, &stream_acc, &mut h_seed_buf, 1, n_embd)?;
11554 e.copy_into(&mut fill_prev, 0, &h_seed_buf, n_embd)?;
11555 self.commit_verified_prefix_stream(
11556 e,
11557 &mut *cache,
11558 &snap,
11559 &ck,
11560 &stream_acc,
11561 1,
11562 t_v_s,
11563 )?;
11564 e.spec_rollback_stream(
11565 ptrs,
11566 &pos_start_d,
11567 &stream_acc,
11568 1,
11569 self.layers.len() + 1,
11570 )?;
11571 e.spec_ring_commit(&vtok_d, &stream_acc, &brk_d, &mut ring_d, &mut pend_d)?;
11572 }
11573 e.stream().synchronize()?;
11574 let ring_h = e.dtoh_u32(&ring_d)?;
11575 let cnt = ring_h[0] as usize;
11576 for i in 0..cnt {
11577 if out.len() < max_new {
11578 out.push(ring_h[1 + i]);
11579 }
11580 }
11581 let pos_h = e.dtoh_i32(&pos_ctr)?[0] as usize;
11582 for il in 0..self.layers.len() {
11583 if let Some(kvl) = cache.kv[il].as_mut() {
11584 kvl.len = pos_h;
11585 }
11586 }
11587 cache.pos = pos_h;
11588 scratch.kv.len = pos_h;
11589 pending = Some(ring_h[cnt]); // last drained token = the live bonus
11590 last_token = ring_h[cnt];
11591 total_drafted += k * m_rounds; // upper bound (p-min breaks uncounted)
11592 total_accepted += cnt.saturating_sub(m_rounds);
11593 if let Some(t) = sess_telem {
11594 // totals only — the burst's per-round accept counts stayed on device
11595 // (that is the point of the round-stream arm). pos_* untouched.
11596 t.record_totals(m_rounds, k * m_rounds, cnt.saturating_sub(m_rounds));
11597 }
11598 round += m_rounds;
11599 // sse-cadence: the drained ring is committed — flush it at burst-drain cadence.
11600 keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
11601 continue;
11602 }
11603 let pipe_draft = match pipe {
11604 Some(p) => Some(p.draft_begin(round)?),
11605 None => None,
11606 };
11607 let pos = cache.pos; // #tokens committed (EXCLUDES a pending bonus)
11608 let mut current_opti = carried_opti.take();
11609 let mut fork_generation = if current_opti.is_none() && pending.is_some() {
11610 match opti_fork.as_mut() {
11611 Some(fork) if fork.mode.is_forced() => Some(fork.reserve(&mut snap)?),
11612 None => None,
11613 Some(_) => None,
11614 }
11615 } else {
11616 None
11617 };
11618 if current_opti.is_none() {
11619 if let Some(fork) = opti_fork.as_ref() {
11620 opti_snapshot_stage_owned_into(e, cache, fork.rt, &fork.fence, &mut snap)?;
11621 } else {
11622 cache.snapshot_into(e, &mut snap)?;
11623 }
11624 } else if snap.pos != pos {
11625 return Err(format!(
11626 "optipipe carried snapshot pos {} != current pos {pos}",
11627 snap.pos
11628 )
11629 .into());
11630 } // §C: snapshot BEFORE draft+verify (already retained for a carried successor)
11631 ph_mark(&mut ph_rest, phase_on);
11632
11633 // --- 1. DRAFT k tokens with the NextN head (autoregressive, T=1 each) ---
11634 // p-min semantics (both paths): stop the chain early when the head's confidence in
11635 // its own pick drops below p_min — the just-drafted token is DISCARDED, but its
11636 // scratch append stands (identical to the eager chain's ordering). j==0 always drafts.
11637 let base0 = if pending.is_some() { 1usize } else { 0usize };
11638 // fixed draft length by default; MEMRA_SPEC_ADAPT=1 drafts at last round's
11639 // accepted run + 1 (the gemma law — see the setup block above the loop).
11640 let k_this = if adapt { kc } else { k };
11641 let mut draft: Vec<u32> = Vec::with_capacity(k);
11642 let mut draft_idx: Vec<u32> = Vec::with_capacity(k); // trimmed-vocab ids (== draft when untrimmed)
11643 let mut controller_draft_prob: Option<f32> = None;
11644 let mut controller_eager_state: Option<(u32, CudaSlice<f32>)> = None;
11645 if let Some(ticket) = current_opti.as_mut() {
11646 let carried_pending = pending.ok_or("optipipe carried successor lost pending")?;
11647 if ticket.verify_tokens[0] != carried_pending {
11648 return Err(format!(
11649 "optipipe carried pending mismatch: ticket={} live={carried_pending}",
11650 ticket.verify_tokens[0],
11651 )
11652 .into());
11653 }
11654 draft.push(ticket.verify_tokens[1]);
11655 controller_draft_prob = Some(ticket.draft_prob);
11656 controller_eager_state = ticket
11657 .take_eager_seed()
11658 .map(|seed| (ticket.verify_tokens[1], seed));
11659 } else {
11660 // Round-start draft-KV sync (BOTH paths). Persistent: truncate/align to the committed
11661 // history — slots 0..P hold entries for the tokens before last_token@P (P = pos +
11662 // base0 - 1); this single set_len IS the draft-side rollback (drops last round's
11663 // rejected drafts and p-min extras via the len mechanism).
11664 scratch.set_len(e, pos + base0 - 1)?;
11665 if pen_on {
11666 // PEN_WINDOW_MAX also bounds the per-round upload and the O(n_hist^2)
11667 // device dedup: the serve window is already PEN_WINDOW_MAX, and this
11668 // defensive min also bounds non-server callers.
11669 let win = sp.penalty_last_n.min(PEN_WINDOW_MAX);
11670 let w0 = pen_hist.len().saturating_sub(win);
11671 pen_hist_d = Some(e.htod_u32_v(&pen_hist[w0..])?);
11672 }
11673 if sampled {
11674 draft_logits.clear();
11675 draft_stats.clear();
11676 }
11677 // DRAFT-SIDE GRAMMAR MASK: clone the committed grammar state ONCE per round; each
11678 // position's mask is computed on that clone and advanced by the PROPOSED token. The
11679 // real state moves only on emission (verify's job), so the emitted stream is
11680 // unchanged — the mask only removes tokens the verify would have truncated anyway.
11681 let mut dmask_live = dmask_on;
11682 if dmask_live {
11683 let t_c = std::time::Instant::now();
11684 constraint
11685 .as_deref_mut()
11686 .unwrap()
11687 .draft_begin()
11688 .map_err(|e2| format!("constraint: {e2}"))?;
11689 dm_clone_ns += t_c.elapsed().as_nanos();
11690 dm_rounds += 1;
11691 }
11692 if let (false, Some(gr)) = (sampled || pen_on, &dctx.graph) {
11693 // GRAPH DRAFT: one dispatch per drafted token. The chain feeds itself on-device
11694 // (in-graph argmax -> tok_d -> next replay's embed; h_nextn -> h_seed_d; pos_d
11695 // inc'd in-graph); the host only reads 4B token (+4B p) and decides the break.
11696 e.set_i32_one(&mut dctx.g_pos, (pos + base0) as i32)?;
11697 e.set_u32_one(&mut dctx.g_tok, last_token)?;
11698 e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
11699 for j in 0..k_this {
11700 // per-position mask upload (contents only — the graph's baked pointer is
11701 // dctx.g_dmask). All-ones once masking goes dead mid-chain, so the captured
11702 // mask node degrades to a no-op ban instead of needing a second graph.
11703 if dmask_live
11704 && !upload_draft_mask(
11705 e,
11706 constraint.as_deref_mut().unwrap(),
11707 &mut dctx.g_dmask,
11708 mtp.d2t.as_ref(),
11709 d_vocab,
11710 dmask_words,
11711 )?
11712 {
11713 // no draft-vocab row is grammar-legal here (a trimmed FR-Spec head can
11714 // genuinely miss the legal set): neutralize the captured mask node and
11715 // finish the chain UNMASKED — exactly pre-lane behaviour, never worse.
11716 e.htod_u32_into(&mut dctx.g_dmask, &vec![u32::MAX; dmask_words])?;
11717 dmask_live = false;
11718 }
11719 gr.launch()?;
11720 scratch.kv.len += 1; // host mirror (len_d advanced in-graph)
11721 let idx = e.dtoh_u32_one(&dctx.g_tok)?;
11722 // #87 SENTINEL TRAP: an all-NaN head-logits row leaves the device argmax's
11723 // init sentinel (0x7FFFFFFF) in g_tok — feeding it onward dereferences
11724 // embed_row(sentinel) = table + ~4.6TB (never mapped) inside the NEXT graph
11725 // replay's embed node, and the MMU fault kills the CUDA context for the
11726 // whole process (research/pp2spec-crash-20260807: 3 coredumps, byte-exact
11727 // VA arithmetic). Refuse loudly instead; the diagnostics name the first-NaN
11728 // buffer (g_seed = the verify-side handoff vs head-side compute).
11729 if (idx as usize) >= d_vocab {
11730 // g_seed is SELF-FED (the replay writes h_nextn back into it), so it
11731 // reads as the head's OUTPUT at j; h_seed_buf is the round's INPUT
11732 // seed, untouched since the round-start copy — the pair discriminates
11733 // "seed arrived poisoned" from "head forward produced NaN".
11734 let seed_h = e.dtoh(&dctx.g_seed)?;
11735 let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
11736 let in_h = e.dtoh(&h_seed_buf)?;
11737 let in_nan = in_h.iter().filter(|v| v.is_nan()).count();
11738 return Err(format!(
11739 "draft(graph) argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab} at \
11740 round {round} j={j} pos={pos}: head-out NaN {seed_nan}/{n_embd}, \
11741 round-input-seed NaN {in_nan}/{n_embd} — refusing to dereference \
11742 the embed row (#87 trap)"
11743 )
11744 .into());
11745 }
11746 // trimmed draft vocab -> target token id (identity when no d2t map)
11747 let d = match &mtp.d2t {
11748 Some(map) => map[idx as usize],
11749 None => idx,
11750 };
11751 let draft_p = if p_min > 0.0
11752 || opti_fork
11753 .as_ref()
11754 .is_some_and(|fork| fork.controller.is_some())
11755 {
11756 Some(e.dtoh(&dctx.g_p)?[0])
11757 } else {
11758 None
11759 };
11760 if j == 0 {
11761 controller_draft_prob = draft_p;
11762 }
11763 if let Some(p) = draft_p.filter(|_| p_min > 0.0) {
11764 if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
11765 break;
11766 }
11767 }
11768 draft.push(d);
11769 // with a trimmed head the NEXT embed must read the TARGET id, not the draft
11770 // index the argmax wrote — patch the persistent token buffer (4B htod).
11771 if d != idx {
11772 e.set_u32_one(&mut dctx.g_tok, d)?;
11773 }
11774 // advance the SPECULATIVE state with the proposal; a dead chain drops to
11775 // unmasked drafting for the remaining positions (verify still arbitrates).
11776 // speculative advance; a chain the grammar can no longer follow (EOS
11777 // proposed) ends here. The captured mask node always runs, so a dead chain
11778 // leaves the buffer NEUTRAL (all-ones = ban nothing) before it exits.
11779 if dmask_live
11780 && !constraint
11781 .as_deref_mut()
11782 .unwrap()
11783 .draft_advance(d)
11784 .map_err(|e2| format!("constraint: {e2}"))?
11785 {
11786 e.htod_u32_into(&mut dctx.g_dmask, &vec![u32::MAX; dmask_words])?;
11787 break;
11788 }
11789 }
11790 // PURE-TEMP RE-TEST (lane/graph-s-key-exactness-20260819): the sampled graph is
11791 // legal ONLY in the regime it was captured in. The condition used to read
11792 // `(sampled, &dctx.graph_s)` and trusted `s_key` to have dropped anything else —
11793 // which it could not, because the key omitted the filters. Both halves are now
11794 // enforced: the key drops a stale graph, and this site refuses to launch one.
11795 } else if let (true, Some(gr)) = (sampled && pure_temp, &dctx.graph_s) {
11796 if skey_probe() {
11797 eprintln!(
11798 "[skey] chain=graph_s round={round} pure_temp={} top_k={} \
11799 top_p={} min_p={} s_key_parked={:?}",
11800 pure_temp as u8, sp.top_k, sp.top_p, sp.min_p, dctx.s_key,
11801 );
11802 }
11803 // SAMPLED GRAPH DRAFT: one replay per drafted token — head forward + gumbel +
11804 // argmax in ONE dispatch; the host reads 4B token (+4B p), D2Ds q into slot j,
11805 // and decides the break. Event-counter continuity: g_ctr is host-seeded to
11806 // sctr-1 ONCE per round (outside the graph); the in-graph bump runs BEFORE the
11807 // perturb, so replay j consumes counter sctr+j — exactly the eager arm's Philox
11808 // stream. Host sctr advances in lockstep (computed, no readback needed).
11809 e.set_i32_one(&mut dctx.g_pos, (pos + base0) as i32)?;
11810 e.set_u32_one(&mut dctx.g_tok, last_token)?;
11811 e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
11812 e.set_u32_one(&mut dctx.g_ctr, sctr.wrapping_sub(1))?;
11813 for j in 0..k_this {
11814 gr.launch()?;
11815 scratch.kv.len += 1; // host mirror (len_d advanced in-graph)
11816 sctr += 1; // mirrors the in-graph g_ctr bump (eager parity:
11817 // counts the p-min-discarded token too)
11818 // q retention: ONE async D2D of the persistent head-logits buffer into this
11819 // round's slot j (stream-ordered after the replay, before the next one).
11820 e.copy_into(&mut dctx.q_slots[j], 0, &dctx.g_q, d_vocab)?;
11821 let idx = e.dtoh_u32_one(&dctx.g_tok)?;
11822 // #87 SENTINEL TRAP (see the greedy graph arm above).
11823 if (idx as usize) >= d_vocab {
11824 let seed_h = e.dtoh(&dctx.g_seed)?;
11825 let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
11826 return Err(format!(
11827 "draft(graph-sampled) argmax sentinel 0x{idx:08x} >= d_vocab \
11828 {d_vocab} at round {round} j={j} pos={pos}: round-seed NaN \
11829 {seed_nan}/{n_embd} — refusing to dereference the embed row \
11830 (#87 trap)"
11831 )
11832 .into());
11833 }
11834 let d = match &mtp.d2t {
11835 Some(map) => map[idx as usize],
11836 None => idx,
11837 };
11838 draft_idx.push(idx);
11839 if p_min > 0.0 {
11840 let p = e.dtoh(&dctx.g_p)?[0];
11841 if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
11842 break;
11843 }
11844 }
11845 draft.push(d);
11846 // trimmed head: the NEXT embed must read the TARGET id (see the greedy arm).
11847 if d != idx {
11848 e.set_u32_one(&mut dctx.g_tok, d)?;
11849 }
11850 }
11851 // uniform accept path: fill draft_stats per used slot (pure-temp regime — the
11852 // stats degenerate to th=0 / full-Z; one filter_stats launch per slot, tiny).
11853 for j in 0..draft.len().max(draft_idx.len()) {
11854 let rows0 = e.htod_i32(&[0])?;
11855 let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
11856 e.filter_stats(
11857 &dctx.q_slots[j],
11858 d_vocab,
11859 &rows0,
11860 &mut th_d,
11861 &mut z_d,
11862 &mut mx_d,
11863 d_vocab,
11864 1,
11865 sp_temp,
11866 sp.top_k,
11867 sp.top_p,
11868 sp.min_p,
11869 )?;
11870 draft_stats.push((e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0]));
11871 }
11872 } else {
11873 if skey_probe() && sampled {
11874 eprintln!(
11875 "[skey] chain=eager round={round} pure_temp={} top_k={} \
11876 top_p={} min_p={} s_key_parked={:?}",
11877 pure_temp as u8, sp.top_k, sp.top_p, sp.min_p, dctx.s_key,
11878 );
11879 }
11880 // EAGER DRAFT (fallback: MoE head/trunk, huge k, MEMRA_SPEC_NOGRAPH, capture fail).
11881 let chain_heads = !self.mtp_extra.is_empty();
11882 let mut e_tok = last_token;
11883 let mut d_seed = e.clone_dtod(&h_seed_buf)?;
11884 let mut chain_tokens = if chain_heads {
11885 vec![last_token]
11886 } else {
11887 Vec::new()
11888 };
11889 let mut chain_seeds = if chain_heads {
11890 vec![e.clone_dtod(&h_seed_buf)?]
11891 } else {
11892 Vec::new()
11893 };
11894 for j in 0..k_this {
11895 // GPU-ARGMAX DRAFT (2026-07-03): device logits + device argmax + 4-byte token
11896 // read instead of the ~600KB full-vocab dtoh + host argmax per draft token.
11897 let mtp_pos = pos + base0 + j;
11898 // draft-side grammar mask (eager twin of the graph arm's in-graph node).
11899 // A position with no legal draft-vocab row drops to unmasked drafting for
11900 // the rest of the chain (pre-lane behaviour; verify still arbitrates).
11901 if dmask_live {
11902 dmask_live = upload_draft_mask(
11903 e,
11904 constraint.as_deref_mut().unwrap(),
11905 &mut dctx.g_dmask,
11906 mtp.d2t.as_ref(),
11907 d_vocab,
11908 dmask_words,
11909 )?;
11910 }
11911 let mask = if dmask_live {
11912 Some((&dctx.g_dmask, dmask_words))
11913 } else {
11914 None
11915 };
11916 let (dl_d, h_nextn) = if chain_heads {
11917 if debug_spec {
11918 eprintln!(
11919 "[mtp-chain-step] round={round} j={j} head={} replay_rows={}",
11920 mtp_chain_head_index(j, self.mtp_head_count()),
11921 chain_tokens.len(),
11922 );
11923 }
11924 self.mtp_chain_forward_dev(
11925 e,
11926 &chain_tokens,
11927 &chain_seeds,
11928 &mut *scratch,
11929 pos + base0 - 1,
11930 embd_dev,
11931 mask,
11932 )?
11933 } else {
11934 self.mtp_head_forward_dev(
11935 e,
11936 mtp,
11937 e_tok,
11938 &d_seed,
11939 &mut *scratch,
11940 mtp_pos,
11941 embd_dev,
11942 mask,
11943 )?
11944 };
11945 let tok_d = if sampled {
11946 // FILTERED Gumbel-max: stats -> masked perturb -> argmax = one draw from
11947 // the filtered softmax (filters off => th=0, exact v1 semantics).
11948 if perturb_buf.is_none() {
11949 perturb_buf = Some(e.zeros(d_vocab.max(n_vocab))?);
11950 }
11951 let mut q_row = e.clone_dtod(&dl_d)?; // retained q (penalized when on)
11952 if pen_on {
11953 let h = pen_hist_d.as_ref().unwrap();
11954 let nh = h.len();
11955 e.penalize_logits(
11956 &mut q_row,
11957 h,
11958 nh,
11959 sp.penalty_repeat,
11960 sp.penalty_freq,
11961 sp.penalty_present,
11962 d_vocab,
11963 )?;
11964 }
11965 let rows0 = e.htod_i32(&[0])?;
11966 let (mut th_d, mut z_d, mut mx_d) =
11967 (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
11968 e.filter_stats(
11969 &q_row, d_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, d_vocab,
11970 1, sp_temp, sp.top_k, sp.top_p, sp.min_p,
11971 )?;
11972 let (th, z, mx) =
11973 (e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0], e.dtoh(&mx_d)?[0]);
11974 let pb = perturb_buf.as_mut().unwrap();
11975 e.gumbel_perturb_filtered(
11976 &q_row, pb, d_vocab, sp_seed, sctr, sp_temp, mx, th,
11977 )?;
11978 sctr += 1;
11979 draft_logits.push(q_row);
11980 draft_stats.push((mx, th, z));
11981 e.argmax_token_device(pb, d_vocab)?
11982 } else {
11983 e.argmax_token_device(&dl_d, d_vocab)?
11984 };
11985 let idx = e.dtoh_u32_one(&tok_d)?;
11986 // #87 SENTINEL TRAP (eager twin — see the graph arm). Extra diagnostics
11987 // here because the eager chain's operands are all readable: dl_d (the head
11988 // logits row) and d_seed (this step's h_seed) name the first-NaN buffer.
11989 if (idx as usize) >= d_vocab {
11990 let dl_h = e.dtoh(&dl_d)?;
11991 let dl_nan = dl_h.iter().filter(|v| v.is_nan()).count();
11992 let seed_h = if chain_heads {
11993 e.dtoh(chain_seeds.last().unwrap())?
11994 } else {
11995 e.dtoh(&d_seed)?
11996 };
11997 let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
11998 return Err(format!(
11999 "draft(eager) argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab} at \
12000 round {round} j={j} pos={pos}: head-logits NaN {dl_nan}/{d_vocab}, \
12001 step-seed NaN {seed_nan}/{n_embd} — refusing to dereference the \
12002 embed row (#87 trap)"
12003 )
12004 .into());
12005 }
12006 let d = match &mtp.d2t {
12007 Some(map) => map[idx as usize],
12008 None => idx,
12009 };
12010 if sampled {
12011 draft_idx.push(idx);
12012 }
12013 let draft_p = if p_min > 0.0
12014 || opti_fork
12015 .as_ref()
12016 .is_some_and(|fork| fork.controller.is_some())
12017 {
12018 let p_d = e.prob_of_token_device(&dl_d, &tok_d, d_vocab)?;
12019 Some(e.dtoh(&p_d)?[0])
12020 } else {
12021 None
12022 };
12023 if j == 0 {
12024 controller_draft_prob = draft_p;
12025 }
12026 if let Some(p) = draft_p.filter(|_| p_min > 0.0) {
12027 if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
12028 break;
12029 }
12030 }
12031 draft.push(d);
12032 if chain_heads {
12033 chain_tokens.push(d);
12034 chain_seeds.push(h_nextn);
12035 } else {
12036 e_tok = d;
12037 d_seed = h_nextn;
12038 }
12039 // speculative advance; a chain the grammar can no longer follow (EOS
12040 // proposed) ends here — the prefix already proposed still rides verify.
12041 if dmask_live
12042 && !constraint
12043 .as_deref_mut()
12044 .unwrap()
12045 .draft_advance(d)
12046 .map_err(|e2| format!("constraint: {e2}"))?
12047 {
12048 break;
12049 }
12050 }
12051 if !chain_heads
12052 && opti_fork
12053 .as_ref()
12054 .is_some_and(|fork| fork.controller.is_some())
12055 {
12056 controller_eager_state = Some((e_tok, d_seed));
12057 }
12058 }
12059 }
12060 let k_round = draft.len();
12061 if let Some(p) = pipe {
12062 p.draft_end(round);
12063 }
12064 drop(pipe_draft);
12065
12066 ph_mark(&mut ph_draft, phase_on);
12067 // --- 2. VERIFY: one batched target forward. With a pending bonus, it rides as col 0
12068 // (committing its KV/recur inside the SAME weight read); drafts follow. ---
12069 let verify_tokens: Vec<u32> = match pending {
12070 Some(b) => {
12071 let mut v = Vec::with_capacity(k_round + 1);
12072 v.push(b);
12073 v.extend_from_slice(&draft);
12074 v
12075 }
12076 None => draft.clone(),
12077 };
12078 let base = if pending.is_some() { 1 } else { 0 };
12079 // ckpt (REPLAY-FREE partial accept): retain per-layer state-rebuild inputs alongside
12080 // the verify. Pure buffer keep-alives + dtod clones — kernel work is unchanged.
12081 let mut ckpt = if let Some(ticket) = current_opti.as_mut() {
12082 Some(ticket.take_ckpt())
12083 } else if spec_replay {
12084 None
12085 } else {
12086 Some(VerifyCkpt::new(self.layers.len()))
12087 };
12088 let controller_can_probe = base == 1
12089 && k_round == 1
12090 && out.len().saturating_add(2) < max_new
12091 && controller_draft_prob.is_some()
12092 && opti_fork
12093 .as_ref()
12094 .and_then(|fork| fork.controller.as_ref())
12095 .is_some_and(|policy| !policy.breaker_tripped);
12096 let mut successor_attempt: Option<OptiControllerTicket> = None;
12097 let mut rejected_probe: Option<(f32, u32)> = None;
12098 let mut controller_prepared: Option<OptiControllerPrepared> = None;
12099 if controller_can_probe {
12100 // Prepare d2/q and, on admission, d3 before either current verify half is
12101 // issued. N stage 0 can then be followed immediately by N+1 stage 0; once N's
12102 // boundary fires, those dev0 launches overlap N stage 1 on dev1. Preparing on
12103 // the primary stream after N stage 1 would serialize the supposed pipeline.
12104 let eager_pos = scratch.kv.len + 1;
12105 let (optimistic_pending, pending_probability) = self.opti_controller_draft_step(
12106 e,
12107 mtp,
12108 &mut dctx,
12109 &mut *scratch,
12110 d_vocab,
12111 &mut controller_eager_state,
12112 eager_pos,
12113 embd_dev,
12114 )?;
12115 let first_probability = controller_draft_prob
12116 .ok_or("optipipe controller probe lost first-token probability")?;
12117 let q_proxy = first_probability * pending_probability;
12118 OPTI_GATE_CHECKS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
12119 OPTI_SHADOW_DRAFT_TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
12120 let admitted = opti_fork
12121 .as_ref()
12122 .and_then(|fork| fork.controller.as_ref())
12123 .ok_or("optipipe controller policy disappeared")?
12124 .admit(q_proxy);
12125 if admitted {
12126 OPTI_GATE_ADMITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
12127 let eager_pos = scratch.kv.len + 1;
12128 let (optimistic_draft, optimistic_draft_probability) = self
12129 .opti_controller_draft_step(
12130 e,
12131 mtp,
12132 &mut dctx,
12133 &mut *scratch,
12134 d_vocab,
12135 &mut controller_eager_state,
12136 eager_pos,
12137 embd_dev,
12138 )?;
12139 OPTI_SHADOW_DRAFT_TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
12140 let eager_seed = controller_eager_state.take().map(|(token, seed)| {
12141 debug_assert_eq!(token, optimistic_draft);
12142 seed
12143 });
12144 controller_prepared = Some(OptiControllerPrepared {
12145 verify_tokens: [optimistic_pending, optimistic_draft],
12146 draft_prob: optimistic_draft_probability,
12147 eager_seed,
12148 q_proxy,
12149 scratch_len: scratch.kv.len,
12150 });
12151 } else {
12152 OPTI_GATE_REJECTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
12153 OPTI_WASTED_DRAFT_TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
12154 rejected_probe = Some((q_proxy, optimistic_pending));
12155 eprintln!(
12156 "[opti-controller] reject q={q_proxy:.6} threshold={:.3}",
12157 opti_fork
12158 .as_ref()
12159 .and_then(|fork| fork.controller.as_ref())
12160 .expect("controller policy")
12161 .threshold,
12162 );
12163 }
12164 }
12165 let fork_attempt = match fork_generation.take() {
12166 Some(generation) if base == 1 && k_round == 1 => Some(generation),
12167 Some(generation) => {
12168 opti_fork
12169 .as_mut()
12170 .expect("fork generation without fork state")
12171 .retire(generation)?;
12172 None
12173 }
12174 None => None,
12175 };
12176 let (tlogits_d, vx) = if let Some(p) = pipe {
12177 self.decode_step_t_core_pipelined(
12178 e,
12179 &verify_tokens,
12180 pos,
12181 &mut *cache,
12182 embd_dev,
12183 ckpt.as_mut(),
12184 p,
12185 round,
12186 )?
12187 } else if controller_can_probe {
12188 let fence = opti_fork
12189 .as_ref()
12190 .ok_or("optipipe controller probe lost fork state")?
12191 .fence;
12192 let boundary = match current_opti.as_mut() {
12193 Some(ticket) => ticket.take_boundary(),
12194 None => self.verify_stage0_issue(
12195 e,
12196 &verify_tokens,
12197 pos,
12198 &mut *cache,
12199 embd_dev,
12200 ckpt.as_mut(),
12201 None,
12202 &fence,
12203 Some(true),
12204 None,
12205 )?,
12206 };
12207 if let Some(prepared) = controller_prepared.take() {
12208 let generation = {
12209 let fork = opti_fork
12210 .as_mut()
12211 .ok_or("optipipe controller admission lost fork state")?;
12212 let generation = fork.reserve_successor()?;
12213 let rt = fork.rt;
12214 let snapshot_fence = fork.fence;
12215 opti_snapshot_one_stage_owned_into(
12216 e,
12217 cache,
12218 rt,
12219 &snapshot_fence,
12220 0,
12221 fork.successor_snapshot_mut(),
12222 )?;
12223 generation
12224 };
12225 let mut successor_ckpt = VerifyCkpt::new(self.layers.len());
12226 let successor_boundary = self.verify_stage0_issue(
12227 e,
12228 &prepared.verify_tokens,
12229 pos + verify_tokens.len(),
12230 &mut *cache,
12231 embd_dev,
12232 Some(&mut successor_ckpt),
12233 None,
12234 &fence,
12235 Some(false),
12236 None,
12237 )?;
12238 OPTI_FORK_ATTEMPTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
12239 let fork = opti_fork
12240 .as_ref()
12241 .ok_or("optipipe controller ticket lost fork state")?;
12242 successor_attempt = Some(fork.controller_ticket(
12243 generation,
12244 successor_boundary,
12245 successor_ckpt,
12246 prepared.verify_tokens,
12247 prepared.draft_prob,
12248 prepared.eager_seed,
12249 prepared.q_proxy,
12250 prepared.scratch_len,
12251 ));
12252 eprintln!(
12253 "[opti-controller] issue generation={} q={:.6} threshold={:.3} \
12254 verify={:?}",
12255 generation.id,
12256 prepared.q_proxy,
12257 fork.controller.expect("controller policy").threshold,
12258 prepared.verify_tokens,
12259 );
12260 }
12261 let result = self.verify_stage1_finish(
12262 e,
12263 boundary,
12264 &mut *cache,
12265 ckpt.as_mut(),
12266 None,
12267 &fence,
12268 successor_attempt.is_none(),
12269 )?;
12270 if let Some(ticket) = current_opti.as_mut() {
12271 ticket.settle();
12272 }
12273 if successor_attempt.is_some() {
12274 let fork = opti_fork
12275 .as_mut()
12276 .ok_or("optipipe successor snapshot lost fork state")?;
12277 let rt = fork.rt;
12278 let snapshot_fence = fork.fence;
12279 opti_snapshot_one_stage_owned_into(
12280 e,
12281 cache,
12282 rt,
12283 &snapshot_fence,
12284 1,
12285 fork.successor_snapshot_mut(),
12286 )?;
12287 // Publish N only after both independent successor-state queues are complete.
12288 fork.rt.publish_to(1, &e.stream())?;
12289 }
12290 result
12291 } else if let Some(ticket) = current_opti.as_mut() {
12292 let fork = opti_fork
12293 .as_mut()
12294 .ok_or("optipipe carried controller ticket lost fork state")?;
12295 let boundary = ticket.take_boundary();
12296 let result = self.verify_stage1_finish(
12297 e,
12298 boundary,
12299 &mut *cache,
12300 ckpt.as_mut(),
12301 None,
12302 &fork.fence,
12303 true,
12304 )?;
12305 ticket.settle();
12306 result
12307 } else if let Some(generation) = fork_attempt {
12308 let fork = opti_fork
12309 .as_mut()
12310 .expect("fork generation without fork state");
12311 fork.capture_seed(e, generation, &h_seed_buf, &fill_prev, scratch.kv.len)?;
12312 let action = fork.mode.action(generation.id);
12313 let boundary = self.verify_stage0_issue(
12314 e,
12315 &verify_tokens,
12316 pos,
12317 &mut *cache,
12318 embd_dev,
12319 ckpt.as_mut(),
12320 None,
12321 &fork.fence,
12322 Some(true),
12323 None,
12324 )?;
12325 OPTI_FORK_ATTEMPTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
12326 let mut ticket = fork.ticket(generation, boundary);
12327 if action == OptiForkAction::Abort {
12328 return Err(format!(
12329 "optipipe forced abort with generation {} stage0 in flight",
12330 generation.id,
12331 )
12332 .into());
12333 }
12334 fork.reconcile(
12335 e,
12336 &mut *cache,
12337 &mut *scratch,
12338 &snap,
12339 &mut h_seed_buf,
12340 &mut fill_prev,
12341 generation,
12342 action,
12343 verify_tokens[0],
12344 )?;
12345 let result = if action == OptiForkAction::Hit {
12346 let boundary = ticket.take_boundary();
12347 self.verify_stage1_finish(
12348 e,
12349 boundary,
12350 &mut *cache,
12351 ckpt.as_mut(),
12352 None,
12353 &fork.fence,
12354 true,
12355 )?
12356 } else {
12357 // The optimistic boundary slot has no reader. Re-run the unchanged serial
12358 // verify only after E_restart published the restored stage-0 state.
12359 self.decode_step_t_core(
12360 e,
12361 &verify_tokens,
12362 pos,
12363 &mut *cache,
12364 embd_dev,
12365 ckpt.as_mut(),
12366 )?
12367 };
12368 ticket.settle();
12369 debug_assert_eq!(ticket.generation, generation);
12370 fork.retire(generation)?;
12371 result
12372 } else {
12373 // The serial verify every non-fork round takes — the MTP route's
12374 // verify-graph door. The pool is None unless MEMRA_SPEC_VERIFY_GRAPH armed
12375 // a pool above, and then the walk replays the captured trunk instead of
12376 // re-issuing it launch by launch.
12377 let vg_round = if verify_tokens.len() <= vg_t_cap {
12378 vg_guard.as_mut().and_then(|g| g.as_mut())
12379 } else {
12380 if let Some(g) = vg_guard.as_mut().and_then(|g| g.as_mut()) {
12381 // The commit reads this flag to pick its arm; a round that declines
12382 // the pool must not inherit a stale `true` from the round before it.
12383 g.round_slab = false;
12384 }
12385 None
12386 };
12387 self.decode_step_t_core_vg(
12388 e,
12389 &verify_tokens,
12390 pos,
12391 &mut *cache,
12392 embd_dev,
12393 ckpt.as_mut(),
12394 vg_round,
12395 )?
12396 };
12397 let pipe_accept = match pipe {
12398 Some(p) => Some(p.accept_begin(round)?),
12399 None => None,
12400 };
12401
12402 ph_mark(&mut ph_verify, phase_on);
12403 // --- 3. GREEDY ACCEPT (walk prefix, stop at first mismatch) ---
12404 // DEVICE-ARGMAX ACCEPT: argmax every verify column ON DEVICE (same 2-pass kernels +
12405 // smallest-index tie-break as host argmax, argmax_gate-validated) and read back ONE
12406 // [T] u32 — replaces the T x n_vocab f32 dtoh + T host argmaxes per round.
12407 // t_pred[j] = target's greedy prediction for the slot after draft[j-1] (j>=1) or after
12408 // last_token (j==0). With a pending bonus, col 0 IS the prediction after last_token
12409 // (== the bonus), so every index shifts by `base` and last_pred is unused.
12410 let t_v = verify_tokens.len();
12411 let mut preds: Vec<u32> = Vec::new();
12412 if !sampled {
12413 for j in 0..t_v {
12414 e.argmax_token_device_col(&tlogits_d, j, n_vocab, &mut preds_d, j)?;
12415 }
12416 preds = e.dtoh_u32(&preds_d)?; // <- the verify-GPU wait lands here
12417 // #87 SENTINEL TRAP, verify side: a sentinel pred becomes the round's bonus =
12418 // next round's last_token = the next chain's embed lookup. Catch it at the
12419 // source with the column named — an all-NaN VERIFY column implicates the
12420 // stage-split trunk (decode_step_t_core_ppn), not the draft head.
12421 if let Some(bad) = preds[..t_v].iter().position(|&p| (p as usize) >= n_vocab) {
12422 let col = &tlogits_d.slice(bad * n_vocab..(bad + 1) * n_vocab);
12423 let mut probe = e.zeros(n_vocab)?;
12424 e.copy_view_into(&mut probe, 0, col, n_vocab)?;
12425 let col_h = e.dtoh(&probe)?;
12426 let col_nan = col_h.iter().filter(|v| v.is_nan()).count();
12427 return Err(format!(
12428 "verify argmax sentinel 0x{:08x} >= n_vocab {n_vocab} at round {round} \
12429 col {bad}/{t_v} pos={pos}: verify-logits col NaN {col_nan}/{n_vocab} \
12430 — the stage-split verify produced a poisoned column (#87 trap)",
12431 preds[bad]
12432 )
12433 .into());
12434 }
12435 }
12436 ph_mark(&mut ph_wait, phase_on);
12437 let t_pred = |j: usize| -> u32 {
12438 if j == 0 && base == 0 {
12439 last_pred
12440 } else {
12441 // GREEDY-ONLY: `preds` is filled under `if !sampled` above. The debug print
12442 // used to call this from the sampled arm and panicked the worker; it now goes
12443 // through `debug_t_pred0`. Keep the strict index here — in the greedy walk an
12444 // out-of-range pred is a real bug, not something to paper over.
12445 debug_assert!(
12446 !sampled,
12447 "t_pred is greedy-only: `preds` is empty in the sampled arm"
12448 );
12449 preds[base + j - 1]
12450 }
12451 };
12452 let mut devacc_seeded = false;
12453 let mut devacc_acc: Option<CudaSlice<u32>> = None;
12454 let (n_acc, bonus) = if !sampled {
12455 // ROUND-STREAM stage (a) (MEMRA_SPEC_DEVACC=1 opt-in): the walk runs ON DEVICE
12456 // (spec_accept_greedy, verbatim rule) and the host reads back 8B (n_acc, bonus)
12457 // instead of the [T] preds. Same sync count — machinery for stages (b)/(c),
12458 // gated on token identity vs the host walk (the arms below are bit-equal rules).
12459 if crate::spec::spec_devacc() && k_round > 0 && !spec_replay && constraint.is_none()
12460 {
12461 let draft_d = e.htod_u32_v(&draft)?;
12462 let mut acc_out = e.alloc_u32_zeroed(2)?;
12463 e.spec_accept_greedy(
12464 &preds_d,
12465 &draft_d,
12466 last_pred,
12467 base,
12468 k_round,
12469 &mut acc_out,
12470 )?;
12471 devacc_acc = Some(acc_out.clone());
12472 // stage (b): next-round seed gathered ON DEVICE from acc_out before the host
12473 // ever reads n_acc (j=base+n_acc -> vx col j-1; j==0 -> fill_prev). The three
12474 // non-replay commit arms skip their host-offset seed copies (guarded below);
12475 // the legacy spec_replay arm keeps its own rx-based seeding (excluded here).
12476 // NOTE: fill_prev is NOT updated here — the commit arms' TRUE-HIDDEN
12477 // REFRESH reads the OLD fill_prev (predecessor of this round's verify batch);
12478 // the update lands after the arms (devacc_seeded guard below).
12479 e.spec_seed_gather(&vx, &fill_prev, &acc_out, &mut h_seed_buf, base, n_embd)?;
12480 // 3a: KV lens roll back on device (len = saved + base + n_acc, all arms'
12481 // unified rule; full accept rewrites the verify-left value). Host mirrors
12482 // update after the readback; commit_verified_prefix skips its len_d writes.
12483 if let Some(successor) = successor_attempt.as_ref() {
12484 opti_fork
12485 .as_mut()
12486 .ok_or("optipipe successor reconcile lost fork state")?
12487 .queue_actual_reconcile(
12488 e,
12489 &snap,
12490 &acc_out,
12491 successor.verify_tokens[0],
12492 base,
12493 )?;
12494 } else if let Some(ptrs) = &kv_len_ptrs {
12495 let saved: Vec<i32> = (0..self.layers.len())
12496 .map(|il| snap.kv_len[il].map(|v| v as i32).unwrap_or(0))
12497 .collect();
12498 let saved_d = e.htod_i32(&saved)?;
12499 e.spec_rollback_kv(ptrs, &saved_d, &acc_out, base, self.layers.len())?;
12500 }
12501 devacc_seeded = true;
12502 let ab = e.dtoh_u32(&acc_out)?;
12503 (ab[0] as usize, ab[1])
12504 } else {
12505 let mut n_acc = 0usize;
12506 for j in 0..k_round {
12507 if t_pred(j) == draft[j] {
12508 n_acc += 1;
12509 } else {
12510 break;
12511 }
12512 }
12513 // bonus = target's own token at the first non-accepted slot. n_acc in 0..=k; t_pred
12514 // is defined for j in 0..=k (j==0 -> last_logits, j>=1 -> col j-1, last col = k-1).
12515 (n_acc, t_pred(n_acc))
12516 }
12517 } else {
12518 // --- SAMPLED ACCEPT (rejection sampling): u_j < p_j(x_j)/q_j(x_j) walk ---
12519 if col_buf.is_none() {
12520 col_buf = Some(e.zeros(n_vocab)?);
12521 }
12522 // FILTERED p_j: per-verify-col stats (one batched filter_stats call), then the
12523 // filtered gather. j==0&&base==0 reads last_col (its own stats row appended).
12524 let mut pj = vec![0f32; k_round.max(1)];
12525 let mut col_stats: Vec<(f32, f32, f32)> = Vec::new(); // (max, th, z) per verify col used
12526 if k_round > 0 {
12527 let mut ids: Vec<u32> = Vec::new();
12528 let mut rows: Vec<i32> = Vec::new();
12529 for j in 0..k_round {
12530 if j > 0 || base == 1 {
12531 ids.push(draft[j]);
12532 rows.push((base + j) as i32 - 1);
12533 }
12534 }
12535 if !ids.is_empty() {
12536 let nr = rows.len();
12537 // penalties: materialize the used columns into one contiguous penalized
12538 // buffer (rows remapped 0..nr) so stats+gathers see the penalized p.
12539 // penalties: materialize used columns contiguously, penalize all rows in
12540 // one launch, and point stats+gathers at the penalized buffer (rows 0..nr).
12541 let p_rows: Vec<i32> = if pen_on {
12542 (0..nr as i32).collect()
12543 } else {
12544 rows.clone()
12545 };
12546 if pen_on {
12547 if pcol_buf.as_ref().map(|b| b.len()).unwrap_or(0) < nr * n_vocab {
12548 pcol_buf = Some(e.zeros(nr * n_vocab)?);
12549 }
12550 let pc = pcol_buf.as_mut().unwrap();
12551 for (i2, &r) in rows.iter().enumerate() {
12552 let c = r as usize;
12553 e.copy_view_into(
12554 pc,
12555 i2 * n_vocab,
12556 &tlogits_d.slice(c * n_vocab..(c + 1) * n_vocab),
12557 n_vocab,
12558 )?;
12559 }
12560 let h = pen_hist_d.as_ref().unwrap();
12561 let nh = h.len();
12562 e.penalize_logits_rows(
12563 pc,
12564 h,
12565 nh,
12566 sp.penalty_repeat,
12567 sp.penalty_freq,
12568 sp.penalty_present,
12569 n_vocab,
12570 nr,
12571 )?;
12572 }
12573 let p_src: &CudaSlice<f32> = if pen_on {
12574 pcol_buf.as_ref().unwrap()
12575 } else {
12576 &tlogits_d
12577 };
12578 let rowsd = e.htod_i32(&p_rows)?;
12579 let (mut th_d, mut z_d, mut mx_d) =
12580 (e.zeros(nr)?, e.zeros(nr)?, e.zeros(nr)?);
12581 e.filter_stats(
12582 p_src, n_vocab, &rowsd, &mut th_d, &mut z_d, &mut mx_d, n_vocab, nr,
12583 sp_temp, sp.top_k, sp.top_p, sp.min_p,
12584 )?;
12585 let idsd = e.htod_u32_v(&ids)?;
12586 let mut outd = e.zeros(nr)?;
12587 e.softmax_gather_filtered(
12588 p_src, n_vocab, &idsd, &rowsd, &th_d, &z_d, &mut outd, n_vocab, nr,
12589 sp_temp,
12590 )?;
12591 let outv = e.dtoh(&outd)?;
12592 let (thv, zv, mxv) = (e.dtoh(&th_d)?, e.dtoh(&z_d)?, e.dtoh(&mx_d)?);
12593 let mut oi = 0usize;
12594 for j in 0..k_round {
12595 if j > 0 || base == 1 {
12596 pj[j] = outv[oi];
12597 oi += 1;
12598 }
12599 }
12600 col_stats = (0..nr).map(|i| (mxv[i], thv[i], zv[i])).collect();
12601 }
12602 if base == 0 {
12603 let lc: &CudaSlice<f32> = if pen_on {
12604 if col_buf.is_none() {
12605 col_buf = Some(e.zeros(n_vocab)?);
12606 }
12607 let cb = col_buf.as_mut().unwrap();
12608 e.copy_into(
12609 cb,
12610 0,
12611 last_col_logits
12612 .as_ref()
12613 .expect("sampled: last_col_logits unset"),
12614 n_vocab,
12615 )?;
12616 let h = pen_hist_d.as_ref().unwrap();
12617 let nh = h.len();
12618 e.penalize_logits(
12619 cb,
12620 h,
12621 nh,
12622 sp.penalty_repeat,
12623 sp.penalty_freq,
12624 sp.penalty_present,
12625 n_vocab,
12626 )?;
12627 col_buf.as_ref().unwrap()
12628 } else {
12629 last_col_logits
12630 .as_ref()
12631 .expect("sampled: last_col_logits unset")
12632 };
12633 let rows0 = e.htod_i32(&[0])?;
12634 let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
12635 e.filter_stats(
12636 lc, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1,
12637 sp_temp, sp.top_k, sp.top_p, sp.min_p,
12638 )?;
12639 let idsd = e.htod_u32_v(&[draft[0]])?;
12640 let mut outd = e.zeros(1)?;
12641 e.softmax_gather_filtered(
12642 lc, n_vocab, &idsd, &rows0, &th_d, &z_d, &mut outd, n_vocab, 1, sp_temp,
12643 )?;
12644 pj[0] = e.dtoh(&outd)?[0];
12645 last_col_stats =
12646 Some((e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0]));
12647 }
12648 }
12649 // q source: the graph arm retained the head logits in the persistent q_slots;
12650 // the eager arm in per-round draft_logits clones. Same raw-logit values either way.
12651 // FILTERED q_j: stats from draft_stats (eager pushes in-chain; the graph arm
12652 // computes them post-replay — graph engages only filter/penalty-free, so the
12653 // stats degenerate to th=0/full-Z there, keeping ONE accept path).
12654 let q_bufs: &[CudaSlice<f32>] = if dctx.graph_s.is_some() {
12655 &dctx.q_slots
12656 } else {
12657 &draft_logits
12658 };
12659 let mut n_acc = 0usize;
12660 for j in 0..k_round {
12661 let (qmx, qth, qz) = draft_stats[j];
12662 let idsd = e.htod_u32_v(&[draft_idx[j]])?;
12663 let rowsd = e.htod_i32(&[0])?;
12664 let thd = e.htod(&[qth])?;
12665 let zd = e.htod(&[qz])?;
12666 let _ = qmx;
12667 let mut outd = e.zeros(1)?;
12668 e.softmax_gather_filtered(
12669 &q_bufs[j], d_vocab, &idsd, &rowsd, &thd, &zd, &mut outd, d_vocab, 1,
12670 sp_temp,
12671 )?;
12672 let qj = e.dtoh(&outd)?[0];
12673 let u = host_u01(sp_seed, uctr);
12674 uctr += 1;
12675 let accept = (u as f64) * (qj as f64) < pj[j] as f64;
12676 // SKEY PROBE: q == 0 for the token the draft actually proposed is the
12677 // exactness signature (see `skey_probe`). Impossible when the draft was
12678 // drawn from the same filtered distribution the verify reconstructs here;
12679 // `u * 0 < p` makes it an UNCONDITIONAL accept whenever p > 0.
12680 if skey_probe() && qj == 0.0 {
12681 eprintln!(
12682 "[skey] EXACTNESS q=0 round={round} j={j} draft_tok={} \
12683 draft_idx={} p={:e} u={u} accepted={} th_z={:?}",
12684 draft[j], draft_idx[j], pj[j], accept as u8, draft_stats[j],
12685 );
12686 }
12687 if accept {
12688 n_acc += 1;
12689 } else {
12690 break;
12691 }
12692 }
12693 let bonus = if n_acc == k_round {
12694 // FULL ACCEPT: bonus ~ FILTERED softmax at the last verify column.
12695 let col = base + k_round - 1;
12696 let cb = col_buf.as_mut().unwrap();
12697 e.copy_view_into(
12698 cb,
12699 0,
12700 &tlogits_d.slice(col * n_vocab..(col + 1) * n_vocab),
12701 n_vocab,
12702 )?;
12703 if pen_on {
12704 let h = pen_hist_d.as_ref().unwrap();
12705 let nh = h.len();
12706 e.penalize_logits(
12707 cb,
12708 h,
12709 nh,
12710 sp.penalty_repeat,
12711 sp.penalty_freq,
12712 sp.penalty_present,
12713 n_vocab,
12714 )?;
12715 }
12716 if perturb_buf.is_none() {
12717 perturb_buf = Some(e.zeros(d_vocab.max(n_vocab))?);
12718 }
12719 // STATS MUST COME FROM THIS COLUMN (bug fix 2026-08-05, lane/sampler-
12720 // truncation-fix; receipts research/sampfix-20260805/). The old code reused
12721 // `col_stats.last()` here, which is ALWAYS the wrong row: the gathered set
12722 // covers verify columns 0..=(base+k_round-2) (rows pushed as base+j-1), while
12723 // the full-accept bonus samples column base+k_round-1 — exactly ONE PAST the
12724 // last gathered column, in both base arms. `th` is a threshold in e-units of
12725 // its OWN row's max, so feeding a neighbour's (row_max, th) into
12726 // gumbel_perturb_filtered mis-scales every e0 = exp((x-row_max)/T). When the
12727 // donor column's peak is higher by more than T*ln(1/th), EVERY id fails
12728 // `e0 >= th`, the whole perturbed row becomes -3.4e38, and the 2-pass argmax
12729 // falls through to its smallest-index tie-break => token id 0 ("!") spliced
12730 // mid-word. Fragility is ordered by how large th is: min_p pins th = min_p
12731 // (0.05 => trigger at delta > 2.4 at T=0.8, fires constantly), top_p's
12732 // mass-boundary th is smaller, top_k's k-th-largest th smaller still — which
12733 // is why the head-to-head matrix saw min_p and top_p corrupt while top_k-only
12734 // stayed clean. The pure-temp default regime is immune (th == 0 masks nothing,
12735 // and row_max is unused once nothing is masked), so this fix is a byte-level
12736 // no-op for the untruncated serve default. One extra one-block filter_stats
12737 // per full-accept round is the whole cost.
12738 let (mx, th) = {
12739 let rows0 = e.htod_i32(&[0])?;
12740 let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
12741 let cb0 = col_buf.as_ref().unwrap();
12742 e.filter_stats(
12743 cb0, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1,
12744 sp_temp, sp.top_k, sp.top_p, sp.min_p,
12745 )?;
12746 (e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0])
12747 };
12748 let pb = perturb_buf.as_mut().unwrap();
12749 let cb2 = col_buf.as_ref().unwrap();
12750 e.gumbel_perturb_filtered(cb2, pb, n_vocab, sp_seed, sctr, sp_temp, mx, th)?;
12751 sctr += 1;
12752 let td = e.argmax_token_device(pb, n_vocab)?;
12753 e.dtoh_u32_one(&td)?
12754 } else {
12755 // REJECT at n_acc: bonus ~ norm(max(0, softmax_T(p) - softmax_T(q))).
12756 let cb = col_buf.as_mut().unwrap();
12757 if n_acc > 0 || base == 1 {
12758 let col = base + n_acc - 1;
12759 e.copy_view_into(
12760 cb,
12761 0,
12762 &tlogits_d.slice(col * n_vocab..(col + 1) * n_vocab),
12763 n_vocab,
12764 )?;
12765 } else {
12766 let lc = last_col_logits.as_ref().unwrap();
12767 e.copy_into(cb, 0, lc, n_vocab)?;
12768 }
12769 if pen_on {
12770 let h = pen_hist_d.as_ref().unwrap();
12771 let nh = h.len();
12772 e.penalize_logits(
12773 cb,
12774 h,
12775 nh,
12776 sp.penalty_repeat,
12777 sp.penalty_freq,
12778 sp.penalty_present,
12779 n_vocab,
12780 )?;
12781 }
12782 let cb2 = col_buf.as_ref().unwrap();
12783 let sc = sctr;
12784 sctr += 1;
12785 // p-stats for the reject column: from col_stats when the col was gathered,
12786 // else (j==0&&base==0) from last_col_stats.
12787 let p_stats = if n_acc > 0 || base == 1 {
12788 // col index within the gathered set == number of gathered cols before n_acc
12789 let gi = if base == 1 { n_acc } else { n_acc - 1 };
12790 col_stats.get(gi).copied().unwrap_or_else(|| {
12791 (0.0, 0.0, 1.0) // unreachable: gathered cols always cover the reject slot
12792 })
12793 } else {
12794 last_col_stats.expect("sampled: last_col_stats unset at reject")
12795 };
12796 let q_stats = draft_stats[n_acc];
12797 if let Some(map) = &d2t_dev {
12798 if q_full_buf.is_none() {
12799 q_full_buf = Some(e.zeros(n_vocab)?);
12800 }
12801 let qf = q_full_buf.as_mut().unwrap();
12802 e.scatter_trim_logits(&q_bufs[n_acc], map, qf, d_vocab, n_vocab)?;
12803 let qf2 = q_full_buf.as_ref().unwrap();
12804 e.residual_sample_filtered(
12805 cb2,
12806 Some(qf2),
12807 n_vocab,
12808 sp_temp,
12809 sp_seed,
12810 sc,
12811 p_stats,
12812 q_stats,
12813 &mut sample_tok,
12814 )?;
12815 } else {
12816 e.residual_sample_filtered(
12817 cb2,
12818 Some(&q_bufs[n_acc]),
12819 n_vocab,
12820 sp_temp,
12821 sp_seed,
12822 sc,
12823 p_stats,
12824 q_stats,
12825 &mut sample_tok,
12826 )?;
12827 }
12828 e.dtoh_u32(&sample_tok)?[0]
12829 };
12830 (n_acc, bonus)
12831 };
12832 // --- 3b. GRAMMAR TRUNCATION (constrained spec, 2026-08-03): the grammar is
12833 // an extra rejection rule AFTER the exactness verify (the batched-verify-twins
12834 // ordering). Walk the accepted drafts through the grammar in commit order; the
12835 // first illegal token truncates acceptance at its slot, and that slot's emission
12836 // is recomputed as the MASKED argmax of the target's own verify column — token-
12837 // identical to constrained plain greedy decode (an unmasked argmax that is
12838 // grammar-legal IS the masked argmax: masking only removes competitors). The
12839 // column D2H (~1MB) is paid only when a cut fires — the tight-grammar cost,
12840 // measured in acceptance numbers, never hidden.
12841 let (n_acc, bonus) = match constraint.as_deref_mut() {
12842 None => (n_acc, bonus),
12843 Some(c) => {
12844 fn ce(e2: String) -> Box<dyn std::error::Error> {
12845 format!("constraint: {e2}").into()
12846 }
12847 let mut na = n_acc;
12848 let mut cut = false;
12849 for (j, &d) in draft.iter().enumerate().take(n_acc) {
12850 if c.is_allowed(d).map_err(ce)? {
12851 c.consume(d).map_err(ce)?;
12852 } else {
12853 na = j;
12854 cut = true;
12855 dm_cut_tokens += n_acc - j;
12856 break;
12857 }
12858 }
12859 if cut {
12860 dm_cuts += 1;
12861 }
12862 let mut bo = bonus;
12863 if cut || !c.is_allowed(bo).map_err(ce)? {
12864 let mut row = if na == 0 && base == 0 {
12865 init_logits_host
12866 .clone()
12867 .ok_or("constraint: init logits missing (round-0 cut)")?
12868 } else {
12869 e.dtoh_view(
12870 &tlogits_d.slice((base + na - 1) * n_vocab..(base + na) * n_vocab),
12871 )?
12872 };
12873 c.mask_logits(&mut row).map_err(ce)?;
12874 bo = argmax(&row) as u32;
12875 }
12876 c.consume(bo).map_err(ce)?;
12877 (na, bo)
12878 }
12879 };
12880 let mut successor_valid = false;
12881 if let Some((q_proxy, expected_d2)) = rejected_probe {
12882 let v_n = n_acc == 1 && bonus == expected_d2;
12883 eprintln!(
12884 "[opti-controller] shadow q={q_proxy:.6} admitted=false v_n={v_n} \
12885 expected_d2={expected_d2} n_acc={n_acc} bonus={bonus}",
12886 );
12887 }
12888 if let Some(successor) = successor_attempt.as_ref() {
12889 successor_valid = n_acc == 1 && bonus == successor.verify_tokens[0];
12890 let generation = successor.generation;
12891 let q_proxy = successor.q_proxy;
12892 let expected_pending = successor.verify_tokens[0];
12893 let resolution_ms = successor.issued_at.elapsed().as_secs_f64() * 1e3;
12894 let fork = opti_fork
12895 .as_mut()
12896 .ok_or("optipipe successor resolution lost fork state")?;
12897 fork.finish_actual_reconcile(e, &mut *cache, &snap, n_acc, base, successor_valid)?;
12898 if successor_valid {
12899 OPTI_FORK_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
12900 } else {
12901 OPTI_FORK_MISSES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
12902 OPTI_RECONCILES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
12903 OPTI_WASTED_DRAFT_TOKENS.fetch_add(2, std::sync::atomic::Ordering::Relaxed);
12904 }
12905 let breaker_tripped = fork
12906 .controller
12907 .as_mut()
12908 .expect("controller policy")
12909 .resolve(successor_valid);
12910 if breaker_tripped {
12911 OPTI_BREAKER_TRIPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
12912 }
12913 eprintln!(
12914 "[opti-controller] resolve generation={} hit={} q={q_proxy:.6} \
12915 expected_pending={expected_pending} n_acc={n_acc} bonus={bonus} \
12916 resolution_ms={resolution_ms:.3} reconcile={} breaker={}",
12917 generation.id, successor_valid, !successor_valid, breaker_tripped,
12918 );
12919 if !successor_valid {
12920 let mut successor = successor_attempt
12921 .take()
12922 .expect("controller successor disappeared on miss");
12923 successor.settle();
12924 fork.retire(generation)?;
12925 }
12926 }
12927 total_drafted += k_round;
12928 total_accepted += n_acc;
12929 if let Some(t) = sess_telem {
12930 // Greedy, rejection-sampling, and grammar truncation all converge here after
12931 // the accept decision is already on host. Fixed-size relaxed atomics only.
12932 t.record_round(k_round, n_acc);
12933 }
12934 if spec_stats {
12935 st_len_hist[k_round] += 1;
12936 for j in 0..k_round {
12937 st_drafted[j] += 1;
12938 }
12939 for j in 0..n_acc {
12940 st_accepted[j] += 1;
12941 }
12942 if n_acc == k_round {
12943 st_full += 1;
12944 }
12945 }
12946
12947 if debug_spec {
12948 eprintln!(
12949 "[R{round}] pos={pos} out_len={} last_tok={last_token} draft={draft:?} n_acc={n_acc} bonus={bonus} t_pred0={}",
12950 out.len(),
12951 // NOT `t_pred(0)`: `preds` is filled only under `if !sampled` above, so on a
12952 // sampled request round >= 1 (base == 1) indexed an EMPTY vector and PANICKED
12953 // the GPU worker thread — a debug flag that killed the exact regime you would
12954 // set it to investigate. See `debug_t_pred0`.
12955 debug_t_pred0(sampled, base, last_pred, &preds)
12956 );
12957 }
12958
12959 // --- 4. COMMIT: draft[0..n_acc] then bonus (n_acc + 1 tokens) ---
12960 let commit_started = std::time::Instant::now();
12961 // SESSION MODE: every accepted column is already in the CACHE — `out` must carry all
12962 // of them (overshoot past max_new included) or `committed` under-counts the cache rows
12963 // and the next turn's continuation seeds one token off (gate-caught 2026-07-05). The
12964 // single-shot path keeps the cap (its caller truncates + drops the cache anyway).
12965 for j in 0..n_acc {
12966 if !session_mode && out.len() >= max_new {
12967 break;
12968 }
12969 out.push(draft[j]);
12970 }
12971 if pen_on {
12972 pen_hist.extend_from_slice(&draft[0..n_acc]);
12973 pen_hist.push(bonus);
12974 }
12975 let bonus_emitted = session_mode || out.len() < max_new;
12976 if bonus_emitted {
12977 out.push(bonus);
12978 }
12979 last_token = bonus;
12980
12981 // --- 5. ROLLBACK + advance (§C) ---
12982 if n_acc == k_round && !spec_replay {
12983 // FULL ACCEPT, BONUS FOLD: all verify columns (pending? + drafts) are committed in
12984 // cache; the NEW bonus stays PENDING for the next round's verify batch — NO extra
12985 // T=1 trunk pass. The next draft chain seeds from the MTP block's h_nextn at the
12986 // bonus position: one MTP-block pass (~1/33 trunk cost) replaces the trunk read.
12987 // last_pred is dead in the pending path (t_pred reads verify col 0).
12988 //
12989 // PERSISTENT DRAFT KV, full-accept fill: the chain covered last_token +
12990 // draft[0..k_round-2] as INPUTS (slots P..P'-2); draft[k_round-1] (slot P'-1) was
12991 // only ever an output, so its entry is MISSING. Fill it from vh_seed — its EXACT
12992 // trunk hidden (the last verify column). set_len first: a p-min break may have
12993 // left one extra chain append at that slot. Partial accepts need NO fill (the
12994 // chain already covered every accepted position; round-start set_len truncates).
12995 let mut vh_seed = e.zeros(n_embd)?;
12996 e.copy_view_into(
12997 &mut vh_seed,
12998 0,
12999 &vx.slice((t_v - 1) * n_embd..t_v * n_embd),
13000 n_embd,
13001 )?;
13002 if refresh {
13003 // TRUE-HIDDEN REFRESH (2026-07-03, the HANDOVER-listed acceptance lever):
13004 // overwrite ALL committed positions' scratch entries with K/V from their EXACT
13005 // verify hiddens — the reference engine's mtp_update fills from true hiddens;
13006 // the full stack (vx) is already resident from the verify. Replaces both the
13007 // chain-approximate entries AND the old last-token-only fill. Acceptance-only
13008 // (draft attention quality); exactness stays the verify's job.
13009 scratch.set_len(e, pos)?;
13010 // PREDECESSOR pairing: row i gets vx[i-1]; row 0 the carried fill_prev
13011 // (hidden of the last committed row before this verify batch).
13012 let mut vxs = e.zeros(t_v * n_embd)?;
13013 e.copy_into(&mut vxs, 0, &fill_prev, n_embd)?;
13014 if t_v > 1 {
13015 e.copy_view_into(
13016 &mut vxs,
13017 n_embd,
13018 &vx.slice(0..(t_v - 1) * n_embd),
13019 (t_v - 1) * n_embd,
13020 )?;
13021 }
13022 self.mtp_kv_fill_all(e, &verify_tokens, &vxs, pos, &mut *scratch, embd_dev)?;
13023 } else {
13024 scratch.set_len(e, pos + base + k_round - 1)?;
13025 // predecessor of the last draft = verify col t_v-2 (or fill_prev at t_v==1)
13026 let mut hp = e.zeros(n_embd)?;
13027 if t_v >= 2 {
13028 e.copy_view_into(
13029 &mut hp,
13030 0,
13031 &vx.slice((t_v - 2) * n_embd..(t_v - 1) * n_embd),
13032 n_embd,
13033 )?;
13034 } else {
13035 e.copy_into(&mut hp, 0, &fill_prev, n_embd)?;
13036 }
13037 self.mtp_kv_fill_all(
13038 e,
13039 &[draft[k_round - 1]],
13040 &hp,
13041 pos + base + k_round - 1,
13042 &mut *scratch,
13043 embd_dev,
13044 )?;
13045 }
13046 // REFERENCE SEEDING: no pseudo pass — the next chain's step 0 IS the
13047 // reference's (id_last, h_prev) draft row; it appends the bonus's scratch
13048 // entry itself. Seed = TRUE hidden of the bonus's predecessor (last verify
13049 // col). Saves one MTP-block pass per round on top of the pairing fix.
13050 if !devacc_seeded {
13051 e.copy_into(&mut h_seed_buf, 0, &vh_seed, n_embd)?;
13052 e.copy_into(&mut fill_prev, 0, &vh_seed, n_embd)?;
13053 }
13054 pending = Some(bonus);
13055 if debug_spec {
13056 eprintln!(" -> FULL ACCEPT (bonus pending, prev-h seed)");
13057 }
13058 } else if !spec_replay && base + n_acc >= 1 {
13059 // PARTIAL ACCEPT, REPLAY-FREE (2026-07-03 — the profiled #1 long-ctx spec cost):
13060 // the verify's first j = base+n_acc columns ARE the committed sequence, computed
13061 // bit-identically to eager (decode-exact contract) — so KEEP them: KV truncates to
13062 // pos+j, recurrent state rebuilds from the VerifyCkpt (same-kernel gdn prefix
13063 // re-run / pure state-clone restore), and the bonus stays PENDING exactly like the
13064 // full-accept path — the legacy duplicate trunk replay is gone. The next chain
13065 // seeds from the MTP pseudo-hidden of the bonus, whose seed = the TRUE verify
13066 // hidden of its predecessor (col j-1) — same one-hop pseudo structure as full
13067 // accept (never compounds: the next verify recomputes true hiddens for all
13068 // committed columns).
13069 let j = base + n_acc;
13070 // VERIFY-GRAPH SLAB COMMIT: when the captured trunk ran, the linear layers'
13071 // column stash was written into the graphs ctx's persistent slabs as in-graph
13072 // memcpy nodes, NOT into the per-column VerifyCkpt the cols arm reads — so the
13073 // commit must take the slab twin (same semantics, slab-addressed sources). The
13074 // ctx states which of the two this round produced via `round_slab`; trusting the
13075 // flag rather than the env keeps a round that fell back to the eager walk (a
13076 // capture that declined, a t the pool never captured) on the cols arm.
13077 let slab_commit = vg_guard
13078 .as_ref()
13079 .and_then(|g| g.as_ref())
13080 .map(|g| g.round_slab)
13081 .unwrap_or(false);
13082 if slab_commit {
13083 self.dspark_commit_prefix_slab(
13084 e,
13085 &mut *cache,
13086 &snap,
13087 vg_guard
13088 .as_ref()
13089 .and_then(|g| g.as_ref())
13090 .expect("slab_commit implies a graphs ctx"),
13091 j,
13092 )?;
13093 } else {
13094 self.commit_verified_prefix(
13095 e,
13096 &mut *cache,
13097 &snap,
13098 ckpt.as_ref().unwrap(),
13099 j,
13100 devacc_seeded,
13101 if devacc_seeded {
13102 devacc_acc.as_ref().map(|a| (a, base, t_v))
13103 } else {
13104 None
13105 },
13106 )?;
13107 }
13108 let mut seed = e.zeros(n_embd)?;
13109 e.copy_view_into(
13110 &mut seed,
13111 0,
13112 &vx.slice((j - 1) * n_embd..j * n_embd),
13113 n_embd,
13114 )?;
13115 // Draft scratch: TRUE-HIDDEN REFRESH of the committed prefix (see the full-accept
13116 // branch); without it the chain entries stand and only the tail truncates. Either
13117 // way len ends at pos+j so the pseudo append lands at the bonus's slot pos+j
13118 // (persistent mode), rope pos+j+1 (chain convention).
13119 if refresh {
13120 scratch.set_len(e, pos)?;
13121 let mut vxs = e.zeros(j * n_embd)?;
13122 e.copy_into(&mut vxs, 0, &fill_prev, n_embd)?;
13123 if j > 1 {
13124 e.copy_view_into(
13125 &mut vxs,
13126 n_embd,
13127 &vx.slice(0..(j - 1) * n_embd),
13128 (j - 1) * n_embd,
13129 )?;
13130 }
13131 self.mtp_kv_fill_all(
13132 e,
13133 &verify_tokens[0..j],
13134 &vxs,
13135 pos,
13136 &mut *scratch,
13137 embd_dev,
13138 )?;
13139 } else {
13140 scratch.set_len(e, pos + j)?;
13141 }
13142 // REFERENCE SEEDING (see the full-accept branch): seed = TRUE hidden of the
13143 // bonus's predecessor (verify col j-1); no pseudo pass.
13144 if !devacc_seeded {
13145 e.copy_into(&mut h_seed_buf, 0, &seed, n_embd)?;
13146 e.copy_into(&mut fill_prev, 0, &seed, n_embd)?;
13147 }
13148 pending = Some(bonus);
13149 if debug_spec {
13150 eprintln!(" -> PARTIAL(replay-free j={j}, bonus pending, prev-h seed)");
13151 }
13152 } else if !spec_replay {
13153 // ZERO ROUND FOLD (2026-07-10, verify-cost target #3): base+n_acc == 0 — a
13154 // pending-less round where nothing was accepted (PMIN0 zero-draft chains after a
13155 // replay/commit, or plain 0-accept rounds at round 0). The old path replayed
13156 // [bonus] through a FULL m=1 trunk+head forward (the 489us full-vocab head pass
13157 // measured at ~0.75/round on PMIN0 configs). Instead: restore the pre-round
13158 // snapshot and let the bonus ride the NEXT round's verify as col 0 — the existing
13159 // base=1 pending machinery, bit-identical by the decode-exact verify contract.
13160 // Seed: the bonus's predecessor is the last COMMITTED token, whose hidden
13161 // fill_prev already carries (same seeding as the 1-token-replay case it replaces).
13162 cache.rollback(e, &snap, 0)?;
13163 scratch.set_len(e, pos)?;
13164 e.copy_into(&mut h_seed_buf, 0, &fill_prev, n_embd)?;
13165 pending = Some(bonus);
13166 if debug_spec {
13167 eprintln!(" -> ZERO-ROUND FOLD (bonus pending, fill_prev seed)");
13168 }
13169 } else {
13170 // PARTIAL ACCEPT, LEGACY REPLAY (seam MEMRA_SPEC_REPLAY=1 — or j==0: nothing of
13171 // this round survives, only possible before the first pending exists, ~round 0):
13172 // restore EVERYTHING to the pre-round snapshot (KV truncate to pos + recur
13173 // restore), then replay the committed prefix pending? ++ draft[0..n_acc] ++
13174 // [bonus] as ONE batched T forward — single weight read, bit-identical to greedy
13175 // (the verify-all-columns path is the same math). Commits the bonus with a TRUE
13176 // trunk hidden.
13177 cache.rollback(e, &snap, 0)?; // accept_len=0: KV len = pos, recur = snapshot
13178 let mut replay: Vec<u32> = Vec::with_capacity(base + n_acc + 1);
13179 if let Some(b) = pending.take() {
13180 replay.push(b);
13181 }
13182 replay.extend_from_slice(&draft[0..n_acc]);
13183 replay.push(bonus);
13184 // Full-stack forward (decode_step_t_core = decode_step_t_h_emb_dev's body):
13185 // Predecessor pairing seeds from the PREDECESSOR row (col len-2) — the same-row path takes the
13186 // last col exactly as before (byte-identical to the old _h_emb_dev call).
13187 let (rl_d, rx) = if self.batched_serving_numeric_class() {
13188 let mut logits = Vec::with_capacity(replay.len() * n_vocab);
13189 let mut hidden = e.uninit(replay.len() * n_embd)?;
13190 for (row, &token) in replay.iter().enumerate() {
13191 let (row_logits, row_hidden) =
13192 self.spec_target_step_h(e, token, &mut *cache)?;
13193 logits.extend_from_slice(&row_logits);
13194 e.dtod_copy_into(&row_hidden, &mut hidden, row * n_embd)?;
13195 }
13196 (e.htod(&logits)?, hidden)
13197 } else {
13198 self.decode_step_t_core(e, &replay, pos, &mut *cache, embd_dev, None)?
13199 };
13200 // last_pred = argmax of the LAST column's logits (predicts the token after `bonus`)
13201 // — device argmax + one 4-byte read instead of the full-vocab column dtoh.
13202 e.argmax_token_device_col(&rl_d, replay.len() - 1, n_vocab, &mut preds_d, 0)?;
13203 last_pred = e.dtoh_u32(&preds_d)?[0];
13204 if sampled {
13205 let lr0 = replay.len();
13206 let lc = last_col_logits
13207 .as_mut()
13208 .expect("sampled: last_col_logits unset");
13209 e.copy_view_into(
13210 lc,
13211 0,
13212 &rl_d.slice((lr0 - 1) * n_vocab..lr0 * n_vocab),
13213 n_vocab,
13214 )?;
13215 }
13216 let lr = replay.len();
13217 if lr >= 2 {
13218 e.copy_view_into(
13219 &mut h_seed_buf,
13220 0,
13221 &rx.slice((lr - 2) * n_embd..(lr - 1) * n_embd),
13222 n_embd,
13223 )?;
13224 } else {
13225 // 1-token replay (round-0 miss): the bonus's predecessor is the OLD
13226 // last_token, whose own-row hidden fill_prev still holds.
13227 e.copy_into(&mut h_seed_buf, 0, &fill_prev, n_embd)?;
13228 }
13229 // the bonus is COMMITTED here — it becomes the last committed row.
13230 let mut rh_last = e.zeros(n_embd)?;
13231 e.copy_view_into(
13232 &mut rh_last,
13233 0,
13234 &rx.slice((lr - 1) * n_embd..lr * n_embd),
13235 n_embd,
13236 )?;
13237 e.copy_into(&mut fill_prev, 0, &rh_last, n_embd)?;
13238 if debug_spec {
13239 eprintln!(" -> PARTIAL(replay={replay:?}), next_pred={last_pred}");
13240 }
13241 }
13242 if devacc_seeded {
13243 // stage (b) epilogue: fill_prev takes the gathered seed AFTER the refresh fills
13244 // consumed the old value (both slots carry the same value in every non-replay arm).
13245 e.copy_into(&mut fill_prev, 0, &h_seed_buf, n_embd)?;
13246 }
13247 if successor_valid {
13248 let optimistic_scratch_len = successor_attempt
13249 .as_ref()
13250 .expect("valid controller successor disappeared")
13251 .scratch_len;
13252 // The normal current-round commit refreshed/truncated the logical scratch tail.
13253 // Its optimistic successor row was already written physically, so restoring only
13254 // the retained logical length makes that row live for the carried round.
13255 scratch.set_len(e, optimistic_scratch_len)?;
13256 }
13257 if let Some(current) = current_opti.take() {
13258 opti_fork
13259 .as_mut()
13260 .ok_or("optipipe current retirement lost fork state")?
13261 .retire(current.generation)?;
13262 }
13263 if successor_valid {
13264 let successor = successor_attempt
13265 .take()
13266 .expect("valid controller successor disappeared before promotion");
13267 let generation = successor.generation;
13268 opti_fork
13269 .as_mut()
13270 .ok_or("optipipe successor promotion lost fork state")?
13271 .promote_successor_snapshot(&mut snap, generation);
13272 carried_opti = Some(successor);
13273 }
13274 if anatomy_on {
13275 // Commit/rollback is normally asynchronous on the primary/head stream. Bound it
13276 // only for this diagnostic so it does not disappear into the following draft's
13277 // first token readback.
13278 e.stream().synchronize()?;
13279 ph_commit += commit_started.elapsed().as_secs_f64();
13280 }
13281 // adaptive-K update (host math, zero syncs): next round drafts accepted-run + 1,
13282 // clamped to [floor(pos), k_cap]. cache.pos is post-rollback here (the round's
13283 // final position — the floor's position key reads the committed depth). Burst
13284 // rounds (`continue` above) draft the captured fixed depth and skip this, exactly
13285 // like gemma's burst arm.
13286 if adapt {
13287 let fl_now = floor_at(cache.pos);
13288 kc = (n_acc + 1).clamp(fl_now.min(k_cap), k_cap);
13289 }
13290 ph_mark(&mut ph_rest, phase_on);
13291 if let Some(p) = pipe {
13292 p.accept_end(round);
13293 }
13294 drop(pipe_accept);
13295 round += 1;
13296 // sse-cadence: this round's accepted drafts + bonus are committed (out is
13297 // append-only past step 4) — flush at round cadence.
13298 keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
13299 }
13300 if let Some(mut ticket) = carried_opti.take() {
13301 opti_fork
13302 .as_mut()
13303 .ok_or("optipipe tail drain lost fork state")?
13304 .cancel_controller_ticket(e, &mut *cache, &mut *scratch, &snap, &mut ticket)?;
13305 }
13306 // sse-cadence: nothing below appends to `out`; flush any remainder (defensive).
13307 // (verdict ignored — the burst is over either way; the session tail runs unchanged.)
13308 let _ = flush_commit(&mut on_commit, &out, &mut flushed);
13309
13310 if spec_stats {
13311 let per_slot: Vec<String> = (0..k)
13312 .map(|j| {
13313 if st_drafted[j] > 0 {
13314 format!(
13315 "{}/{}={:.3}",
13316 st_accepted[j],
13317 st_drafted[j],
13318 st_accepted[j] as f64 / st_drafted[j] as f64
13319 )
13320 } else {
13321 "0/0".into()
13322 }
13323 })
13324 .collect();
13325 let acc = if total_drafted > 0 {
13326 total_accepted as f64 / total_drafted as f64
13327 } else {
13328 0.0
13329 };
13330 eprintln!(
13331 "[spec-stats] rounds={round} full_accept={st_full} len_hist={st_len_hist:?} \
13332 per_slot=[{}] total={total_accepted}/{total_drafted}={acc:.3} \
13333 tok_per_round={:.3}",
13334 per_slot.join(" "),
13335 (total_accepted + round) as f64 / round.max(1) as f64
13336 );
13337 }
13338 if constraint.is_some() {
13339 eprintln!(
13340 "[draft-mask] mask_rounds={dm_rounds} clone_total={:.3}ms \
13341 clone_per_round={:.4}ms gram_cuts={dm_cuts}/{round} cut_tokens={dm_cut_tokens}",
13342 dm_clone_ns as f64 / 1e6,
13343 dm_clone_ns as f64 / 1e6 / dm_rounds.max(1) as f64
13344 );
13345 }
13346 if phase_on {
13347 let tot = ph_draft + ph_verify + ph_wait + ph_rest;
13348 eprintln!(
13349 "[spec-phase] draft={:.1}ms ({:.1}%) verify-issue={:.1}ms ({:.1}%) verify-wait={:.1}ms ({:.1}%) commit-host={:.1}ms ({:.1}%) rounds={round}",
13350 ph_draft * 1e3,
13351 ph_draft / tot * 100.0,
13352 ph_verify * 1e3,
13353 ph_verify / tot * 100.0,
13354 ph_wait * 1e3,
13355 ph_wait / tot * 100.0,
13356 ph_rest * 1e3,
13357 ph_rest / tot * 100.0
13358 );
13359 }
13360 if anatomy_on {
13361 let rounds_f = round.max(1) as f64;
13362 let other = (ph_rest - ph_commit).max(0.0);
13363 eprintln!(
13364 "[spec-anatomy] per-round draft={:.3}ms pp-verify={:.3}ms \
13365 verify-accept={:.3}ms commit-rollback={:.3}ms other={:.3}ms rounds={round}",
13366 ph_draft * 1e3 / rounds_f,
13367 ph_verify * 1e3 / rounds_f,
13368 ph_wait * 1e3 / rounds_f,
13369 ph_commit * 1e3 / rounds_f,
13370 other * 1e3 / rounds_f,
13371 );
13372 }
13373 let _pipe_tail = pipe.map(|p| p.primary());
13374 // SESSION TAIL: leave the session in the exact invariant the next turn's suffix prime
13375 // expects — every row in `committed` has trunk KV/recur state AND an exact draft-KV row.
13376 // Park the draft-graph ctx back on the session (the serve-burst fixed-cost fix): the next
13377 // burst replays instead of recapturing. Error paths (`?` above) drop it — recaptured then.
13378 if let Some(slot) = sess_draft_slot.take() {
13379 *slot = Some(dctx);
13380 }
13381 let t_rounds = t_ent.elapsed();
13382 if let Some((committed, last_h, next_pred_slot, sctr_slot, uctr_slot)) = sess_tail.take() {
13383 // NEXT BURST'S BOUNDARY TOKEN (lane/sampled-spec-quality, Item 1). Greedy stashes
13384 // the argmax `last_pred` exactly as before (byte contract). SAMPLED draws the token
13385 // HERE, where the sampler, the session Philox counters and the penalty window are
13386 // all live and the boundary logits row still exists — that is the "make the state
13387 // available" half of the fix; the consuming burst then just emits it. `sctr` is
13388 // written to the session BELOW the draws so the advance is never lost.
13389 *next_pred_slot = Some(last_pred);
13390 let sample_boundary = sampled && constraint.is_none() && spec_sampled_boundary_on();
13391 let mut stashed_pending = false;
13392 if let Some(b) = pending.take() {
13393 if !sampled {
13394 // PENDING-CARRY (2026-08-01): stash the bonus on the session instead of
13395 // committing it with a solo T=1 pass — the next empty-suffix greedy burst
13396 // consumes it as round-0 verify col 0 (a plain round edge; the old tail
13397 // commit + next burst's init feed were 11.6+11.5ms solo trunk passes per
13398 // burst on H100 q27, [spec-setup] trace). b stays in `out` (emitted) but
13399 // OUT of `committed` (cache rows == committed); the consuming call
13400 // prepends it once its verify commits the row. next_pred is unknowable
13401 // without the commit pass — None; callers gate on pending_tok too.
13402 debug_assert_eq!(out.last(), Some(&b), "pending must be the last emitted");
13403 if let Some(slot) = sess_pending_slot.take() {
13404 *slot = Some(b);
13405 }
13406 *next_pred_slot = None;
13407 // fill_prev = hidden of the last COMMITTED row (b's predecessor) — the
13408 // exact chain-seed/fill anchor the consuming burst (or a flush) needs.
13409 *last_h = Some(e.clone_dtod(&fill_prev)?);
13410 stashed_pending = true;
13411 } else {
13412 // SAMPLED tail (unchanged): commit the bonus (one T=1 pass) + draft fill —
13413 // the sampled round-0 accept needs this pass's logits (last_col_logits).
13414 let pos_b = cache.pos;
13415 scratch.set_len(e, pos_b)?;
13416 let (lg_b, hb) = self.spec_target_step_h(e, b, &mut *cache)?;
13417 // after a FULL-accept exit `last_pred` is STALE (it predicted the bonus
13418 // itself — the prediction AFTER the bonus never materialized; it would have
13419 // been the next round's verify col 0). The commit's logits ARE that
13420 // prediction — so they are also the row the next burst's boundary token
13421 // comes off, and (lane/sampled-spec-quality) it is DRAWN from them here.
13422 *next_pred_slot = Some(if sample_boundary {
13423 sample_boundary_token(
13424 e,
13425 &lg_b,
13426 &sp,
13427 &pen_hist,
13428 &mut sctr,
13429 "burst-tail-commit",
13430 )?
13431 } else {
13432 argmax(&lg_b) as u32
13433 });
13434 self.mtp_kv_fill_all(e, &[b], &fill_prev, pos_b, &mut *scratch, embd_dev)?;
13435 *last_h = Some(hb);
13436 }
13437 } else {
13438 // fill_prev tracks the hidden of the last COMMITTED row throughout the loop.
13439 *last_h = Some(e.clone_dtod(&fill_prev)?);
13440 if sample_boundary {
13441 // No pending to commit, so the boundary row is the one `last_pred` was
13442 // argmaxed from and the sampled path keeps it on device: the init feed's
13443 // logits when the burst ran zero rounds, else the legacy-replay path's
13444 // last verify column (both predict the token AFTER the last committed
13445 // row). It is retained precisely because round 0's accept test needs it,
13446 // so the draw costs no extra D2H of the [n_vocab] row.
13447 match last_col_logits.as_ref() {
13448 Some(lc) => {
13449 *next_pred_slot = Some(sample_boundary_token_dev(
13450 e,
13451 lc,
13452 n_vocab,
13453 &sp,
13454 &pen_hist,
13455 &mut sctr,
13456 "burst-tail-nopending",
13457 )?);
13458 }
13459 // NAME THE FALLBACK (house standard): unreachable today — a sampled
13460 // burst always feeds or replays, so the row exists — but if it ever
13461 // is, the stream takes a greedy token and SAYS so rather than
13462 // silently regressing to the pre-lane behaviour.
13463 None => eprintln!(
13464 "[spec-boundary] sampled tail kept the ARGMAX boundary token \
13465 (reason: no retained boundary logits row)"
13466 ),
13467 }
13468 }
13469 }
13470 *sctr_slot = sctr;
13471 *uctr_slot = uctr;
13472 committed.extend_from_slice(prompt);
13473 if let Some(cb) = carried_pending {
13474 // the consumed carry's cache row landed in round 0's verify (every pending
13475 // round commits col 0) — it joins `committed` here, in sequence order.
13476 committed.push(cb);
13477 }
13478 if stashed_pending {
13479 // ZERO-EMIT BURST (2026-08-06 c=8 serve panic, pre-existing since b4aea184):
13480 // `out.len() - 1` underflowed on an EMPTY `out` — "range end index
13481 // 18446744073709551615 out of range for slice of length 0", killing the
13482 // memra-gpu-worker and failing 31 of 32 concurrent requests with "worker closed
13483 // stream". Reachable because `pending` starts as `carried_pending` (a bonus
13484 // stashed by the PREVIOUS burst) while `out` starts empty, and the carry is
13485 // deliberately NOT pushed to `out` (line ~3239: the burst that emitted it already
13486 // did). So a burst that stashes a pending without emitting anything of its own —
13487 // the round loop exits before a push, e.g. the ring drain's `out.len() < max_new`
13488 // guard skipping every token under a tight budget — arrives here with
13489 // out.len() == 0 and stashed_pending == true.
13490 //
13491 // The invariant is unchanged: `committed` gets every emitted token EXCEPT the
13492 // stashed bonus. With nothing emitted, that is nothing — and the carry pushed
13493 // just above is already accounted. Saturating, not a min/assert: an empty `out`
13494 // here is a legitimate burst shape, not a corrupt state.
13495 let emitted = out.len().saturating_sub(1);
13496 committed.extend_from_slice(&out[..emitted]);
13497 } else {
13498 committed.extend_from_slice(&out); // FULL out incl. overshoot — all committed
13499 }
13500 debug_assert_eq!(
13501 cache.pos,
13502 committed.len(),
13503 "session invariant: cache rows == committed tokens"
13504 );
13505 if setup_trace {
13506 e.stream().synchronize()?; // bound the async tail fill in the trace
13507 let t_tail = t_ent.elapsed();
13508 eprintln!(
13509 "[spec-setup] init={:.2}ms cap={:.2}ms fill={:.2}ms rounds={:.2}ms tail={:.2}ms total={:.2}ms out={} cont={}",
13510 t_init.as_secs_f64() * 1e3,
13511 (t_cap - t_init).as_secs_f64() * 1e3,
13512 (t_fill - t_cap).as_secs_f64() * 1e3,
13513 (t_rounds - t_fill).as_secs_f64() * 1e3,
13514 (t_tail - t_rounds).as_secs_f64() * 1e3,
13515 t_tail.as_secs_f64() * 1e3,
13516 out.len(),
13517 continuation
13518 );
13519 }
13520 return Ok((out, total_drafted, total_accepted));
13521 }
13522 out.truncate(max_new);
13523 Ok((out, total_drafted, total_accepted))
13524 }
13525
13526 /// Anchor-bounded DSpark target extraction. The trunk sees the exact generated token tape;
13527 /// only requested hidden rows and target-logit rows cross PCIe. An anchor token at p pairs
13528 /// with the pre-output-norm h[p-1] carrier, exactly as the existing replay/NextN path does.
13529 pub fn extract_dspark_anchors(
13530 &self,
13531 e: &Engine,
13532 tokens: &[u32],
13533 anchor_positions: &[usize],
13534 gamma: usize,
13535 top_k: usize,
13536 chunk: usize,
13537 temperature: f32,
13538 ) -> Result<Vec<DsparkAnchorRecord>, Box<dyn std::error::Error>> {
13539 if tokens.len() < gamma + 2 || gamma == 0 || chunk < 2 {
13540 return Err("DSpark extraction token tape/gamma/chunk is invalid".into());
13541 }
13542 if anchor_positions.windows(2).any(|pair| pair[0] >= pair[1]) {
13543 return Err("DSpark anchor positions must be sorted and unique".into());
13544 }
13545 for &position in anchor_positions {
13546 if position == 0 || position + gamma >= tokens.len() {
13547 return Err(format!(
13548 "DSpark anchor {position} has no predecessor or cannot cover gamma={gamma} in {} tokens",
13549 tokens.len()
13550 )
13551 .into());
13552 }
13553 }
13554
13555 let n_vocab = self.output.out_features();
13556 let n_embd = self.cfg.n_embd as usize;
13557 let mut cache =
13558 crate::pp::new_cache_planned(e, &self.cfg, &self.plan, tokens.len() + gamma + 8)?;
13559 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
13560 let embd_gpu = if spec_host_embd() {
13561 None
13562 } else {
13563 Some(
13564 self.embd_gpu
13565 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
13566 )
13567 };
13568 let embd_dev = embd_gpu.map(|gpu| (gpu, embd_qt, embd_rb));
13569
13570 struct PendingRecord {
13571 position: usize,
13572 hidden: Option<Vec<f32>>,
13573 tokens: Vec<u32>,
13574 target_top_ids: Vec<Option<Vec<u32>>>,
13575 target_top_logits: Vec<Option<Vec<f32>>>,
13576 target_top_probs: Vec<Option<Vec<f32>>>,
13577 target_tail_probs: Vec<Option<f32>>,
13578 }
13579
13580 let mut pending: Vec<PendingRecord> = anchor_positions
13581 .iter()
13582 .map(|&position| PendingRecord {
13583 position,
13584 hidden: None,
13585 tokens: tokens[position..=position + gamma].to_vec(),
13586 target_top_ids: vec![None; gamma],
13587 target_top_logits: vec![None; gamma],
13588 target_top_probs: vec![None; gamma],
13589 target_tail_probs: vec![None; gamma],
13590 })
13591 .collect();
13592
13593 let mut start = 0usize;
13594 while start < tokens.len() {
13595 let end = (start + chunk).min(tokens.len());
13596 let chunk_tokens = &tokens[start..end];
13597 let (target_logits, hidden_rows) =
13598 self.decode_step_t_core(e, chunk_tokens, start, &mut cache, embd_dev, None)?;
13599 for record in &mut pending {
13600 let hidden_position = record.position - 1;
13601 if hidden_position >= start && hidden_position < end {
13602 let local = hidden_position - start;
13603 record.hidden = Some(
13604 e.dtoh_view(&hidden_rows.slice(local * n_embd..(local + 1) * n_embd))?,
13605 );
13606 }
13607 for slot in 0..gamma {
13608 let target_row = record.position + slot;
13609 if target_row < start || target_row >= end {
13610 continue;
13611 }
13612 let local = target_row - start;
13613 let logits =
13614 e.dtoh_view(&target_logits.slice(local * n_vocab..(local + 1) * n_vocab))?;
13615 let (ids, top_logits, probs, tail) =
13616 dspark_sparse_softmax_topk(&logits, top_k, temperature)?;
13617 record.target_top_ids[slot] = Some(ids);
13618 record.target_top_logits[slot] = Some(top_logits);
13619 record.target_top_probs[slot] = Some(probs);
13620 record.target_tail_probs[slot] = Some(tail);
13621 }
13622 }
13623 start = end;
13624 }
13625
13626 pending
13627 .into_iter()
13628 .map(|record| {
13629 let hidden = record
13630 .hidden
13631 .ok_or_else(|| format!("missing DSpark hidden at {}", record.position))?;
13632 let target_top_ids =
13633 flatten_dspark_rows(record.target_top_ids, record.position, "target ids")?;
13634 let target_top_logits = flatten_dspark_rows(
13635 record.target_top_logits,
13636 record.position,
13637 "target logits",
13638 )?;
13639 let target_top_probs =
13640 flatten_dspark_rows(record.target_top_probs, record.position, "target probs")?;
13641 let target_tail_probs = record
13642 .target_tail_probs
13643 .into_iter()
13644 .enumerate()
13645 .map(|(slot, value)| {
13646 value.ok_or_else(|| {
13647 format!("missing DSpark tail at {} slot {slot}", record.position)
13648 })
13649 })
13650 .collect::<Result<Vec<_>, _>>()?;
13651 Ok(DsparkAnchorRecord {
13652 position: record.position,
13653 hidden,
13654 tokens: record.tokens,
13655 target_top_ids,
13656 target_top_logits,
13657 target_top_probs,
13658 target_tail_probs,
13659 })
13660 })
13661 .collect()
13662 }
13663
13664 /// TEACHER-FORCED REPLAY ACCEPTANCE (hqmtp MTP-heal protocol): walk a FIXED token
13665 /// sequence and, at sampled positions, compare the MTP head's K-token draft chain against
13666 /// the trunk's own teacher-forced greedy predictions. Nothing is generated — the context is
13667 /// the corpus text itself, so (a) degenerate self-generated loops cannot inflate acceptance
13668 /// and (b) two arms (bf16 ceiling vs NVFP4) score on IDENTICAL contexts, isolating the
13669 /// quant-induced head/hidden-state mismatch from text drift.
13670 ///
13671 /// Per eval position p (context = tokens[0..=p], predecessor pairing as in spec decode):
13672 /// draft_j = chain token j from (tokens[p], h_{p-1}), then its own drafts — the exact
13673 /// eager spec-decode chain (same mtp_head_forward_dev, same rope positions).
13674 /// target_j = teacher-forced greedy pick for position p+1+j (argmax of the trunk logits
13675 /// at forced context tokens[0..p+j]). For j==0 this equals live spec
13676 /// acceptance; for j>=1 live verify would condition on the drafts, here it
13677 /// conditions on the corpus — deterministic and arm-comparable by design.
13678 ///
13679 /// Returns (rows, bg): one (p, drafts[k], targets[k]) row per eval position (ascending p),
13680 /// plus the full teacher-forced greedy track bg (bg[i] = greedy pick for position i, i>=1)
13681 /// so harnesses can cross-check runs (e.g. different chunk sizes must give identical bg).
13682 ///
13683 /// `hdump`: when Some, every position's pre-output_norm trunk hidden (the exact rows the
13684 /// draft-KV fill pairs from) streams to the file as little-endian f32 [t_total, n_embd] —
13685 /// the head-distillation extraction (hqmtp): the ENGINE is the source of truth for trunk
13686 /// hiddens (HF torch reproductions of the hybrid trunk measured only ~0.5 greedy
13687 /// agreement vs this path — not usable as a training-data source).
13688 pub fn replay_acceptance(
13689 &self,
13690 e: &Engine,
13691 tokens: &[u32],
13692 k: usize,
13693 stride: usize,
13694 chunk: usize,
13695 mut hdump: Option<&mut std::fs::File>,
13696 ) -> Result<(Vec<(usize, Vec<u32>, Vec<u32>)>, Vec<u32>), Box<dyn std::error::Error>> {
13697 assert!(k >= 1 && stride >= 1 && chunk >= 2);
13698 let mtp = self
13699 .mtp
13700 .as_ref()
13701 .expect("replay_acceptance requires an MTP head");
13702 let n_vocab = self.output.out_features();
13703 let d_vocab = mtp
13704 .shared_head_head
13705 .as_ref()
13706 .unwrap_or(&self.output)
13707 .out_features();
13708 let n_embd = self.cfg.n_embd as usize;
13709 let t_total = tokens.len();
13710 assert!(t_total >= 8, "corpus too short ({t_total} tokens)");
13711 // STAGE-OWNED KV (lane/pp2-spec 2026-08-06) — see `new_session`. Door shut = `Cache::new`.
13712 let mut cache = crate::pp::new_cache_planned(e, &self.cfg, &self.plan, t_total + k + 8)?;
13713 let mut scratch = self.new_mtp_scratch(e, t_total + k + 8)?;
13714 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
13715 let embd_gpu = if spec_host_embd() {
13716 None
13717 } else {
13718 Some(
13719 self.embd_gpu
13720 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
13721 )
13722 };
13723 let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
13724
13725 // bg[i] = the trunk's greedy pick for position i under the forced context (i >= 1).
13726 let mut bg: Vec<u32> = vec![0; t_total + 1];
13727 let mut rows: Vec<(usize, Vec<u32>, Vec<u32>)> = Vec::new();
13728 let mut prev_last_h = e.zeros(n_embd)?; // predecessor hidden entering the chunk
13729 let mut seed_buf = e.zeros(n_embd)?;
13730 let mut preds_d = e.alloc_u32_zeroed(chunk)?;
13731 let nll_on = std::env::var("MEMRA_REPLAY_NLL").as_deref() == Ok("1");
13732 let (mut nll_sum, mut nll_cnt) = (0f64, 0u64);
13733 let mut s = 0usize;
13734 while s < t_total {
13735 let cend = (s + chunk).min(t_total);
13736 let tc = cend - s;
13737 let ch = &tokens[s..cend];
13738 // 1. forced trunk pass — verify path (decode-exact contract): all-column logits +
13739 // the chunk's true hiddens.
13740 let (tl_d, vx) = self.decode_step_t_core(e, ch, s, &mut cache, embd_dev, None)?;
13741 for j in 0..tc {
13742 e.argmax_token_device_col(&tl_d, j, n_vocab, &mut preds_d, j)?;
13743 }
13744 let preds = e.dtoh_u32(&preds_d)?;
13745 for j in 0..tc {
13746 bg[s + j + 1] = preds[j];
13747 }
13748 // MEMRA_REPLAY_NLL=1: teacher-forced NLL/perplexity over the same forced pass — the
13749 // checkpoint-quality metric (position j's logits score the GOLD next token).
13750 if nll_on {
13751 let jmax = if cend < t_total { tc } else { tc - 1 }; // last pos has no gold next
13752 if jmax > 0 {
13753 let ids: Vec<u32> = (0..jmax).map(|j| tokens[s + j + 1]).collect();
13754 let rows: Vec<i32> = (0..jmax as i32).collect();
13755 let idsd = e.htod_u32_v(&ids)?;
13756 let rowsd = e.htod_i32(&rows)?;
13757 let mut outd = e.zeros(jmax)?;
13758 e.softmax_gather(&tl_d, n_vocab, &idsd, &rowsd, &mut outd, n_vocab, jmax, 1.0)?;
13759 for pr in e.dtoh(&outd)? {
13760 nll_sum += -((pr.max(1e-30)) as f64).ln();
13761 nll_cnt += 1;
13762 }
13763 }
13764 }
13765 if let Some(f) = hdump.as_deref_mut() {
13766 use std::io::Write;
13767 let host: Vec<f32> = e.dtoh(&vx)?;
13768 // bf16 round-to-nearest-even — f32 doubled the disk bill at bulk
13769 // extraction scale (20M tokens x 4096 = 320GB f32 vs 160GB bf16).
13770 let mut bytes = Vec::with_capacity(tc * n_embd * 2);
13771 for v in &host[..tc * n_embd] {
13772 let b = v.to_bits();
13773 let r = b.wrapping_add(0x7FFF + ((b >> 16) & 1));
13774 bytes.extend_from_slice(&((r >> 16) as u16).to_le_bytes());
13775 }
13776 f.write_all(&bytes)?;
13777 }
13778 // CHAINLESS extraction (stride > corpus, the bulk-hdump mode): no chunk ever
13779 // drafts, so the draft-KV fills are pure waste — skip them (2 MTP-block passes
13780 // per token saved; the forced trunk pass + hdump is all the mode needs).
13781 let chainless = stride > t_total;
13782 if chainless {
13783 e.copy_view_into(
13784 &mut prev_last_h,
13785 0,
13786 &vx.slice((tc - 1) * n_embd..tc * n_embd),
13787 n_embd,
13788 )?;
13789 s = cend;
13790 continue;
13791 }
13792 // 2. TRUE predecessor-paired draft-KV fill for the chunk (row i carries h_{i-1};
13793 // row s reads the previous chunk's last true hidden, zeros at corpus start).
13794 let mut vxs = e.zeros(tc * n_embd)?;
13795 e.copy_into(&mut vxs, 0, &prev_last_h, n_embd)?;
13796 if tc > 1 {
13797 e.copy_view_into(
13798 &mut vxs,
13799 n_embd,
13800 &vx.slice(0..(tc - 1) * n_embd),
13801 (tc - 1) * n_embd,
13802 )?;
13803 }
13804 scratch.set_len(e, s)?;
13805 self.mtp_kv_fill_all(e, ch, &vxs, s, &mut scratch, embd_dev)?;
13806 // 3. draft chains at sampled positions, DESCENDING: a chain reads only slots
13807 // [0..p) (true fills) and appends at >= p; the next (smaller-p) chain's set_len
13808 // truncates those approximate appends before they can ever be read.
13809 let ps: Vec<usize> = (s..cend)
13810 .filter(|p| *p >= 1 && *p % stride == 0 && *p + k <= t_total)
13811 .collect();
13812 for &p in ps.iter().rev() {
13813 scratch.set_len(e, p)?;
13814 if p == s {
13815 e.copy_into(&mut seed_buf, 0, &prev_last_h, n_embd)?;
13816 } else {
13817 e.copy_view_into(
13818 &mut seed_buf,
13819 0,
13820 &vx.slice((p - 1 - s) * n_embd..(p - s) * n_embd),
13821 n_embd,
13822 )?;
13823 }
13824 let mut e_tok = tokens[p];
13825 let mut d_seed = e.clone_dtod(&seed_buf)?;
13826 let chain_heads = !self.mtp_extra.is_empty();
13827 let mut chain_tokens = if chain_heads {
13828 vec![tokens[p]]
13829 } else {
13830 Vec::new()
13831 };
13832 let mut chain_seeds = if chain_heads {
13833 vec![e.clone_dtod(&seed_buf)?]
13834 } else {
13835 Vec::new()
13836 };
13837 let mut drafts: Vec<u32> = Vec::with_capacity(k);
13838 for j in 0..k {
13839 let (dl_d, h_nextn) = if chain_heads {
13840 self.mtp_chain_forward_dev(
13841 e,
13842 &chain_tokens,
13843 &chain_seeds,
13844 &mut scratch,
13845 p,
13846 embd_dev,
13847 None,
13848 )?
13849 } else {
13850 self.mtp_head_forward_dev(
13851 e,
13852 mtp,
13853 e_tok,
13854 &d_seed,
13855 &mut scratch,
13856 p + 1 + j,
13857 embd_dev,
13858 None,
13859 )?
13860 };
13861 let tok_d = e.argmax_token_device(&dl_d, d_vocab)?;
13862 let idx = e.dtoh_u32_one(&tok_d)?;
13863 let d = match &mtp.d2t {
13864 Some(map) => map[idx as usize],
13865 None => idx,
13866 };
13867 drafts.push(d);
13868 if chain_heads {
13869 chain_tokens.push(d);
13870 chain_seeds.push(h_nextn);
13871 } else {
13872 e_tok = d;
13873 d_seed = h_nextn;
13874 }
13875 }
13876 // targets may live in a LATER chunk's bg — resolved after the walk.
13877 rows.push((p, drafts, Vec::new()));
13878 }
13879 // 4. restore TRUE entries for the whole chunk (the next chunk's chains and fills
13880 // expect scratch.len == cend with exact rows).
13881 scratch.set_len(e, s)?;
13882 self.mtp_kv_fill_all(e, ch, &vxs, s, &mut scratch, embd_dev)?;
13883 e.copy_view_into(
13884 &mut prev_last_h,
13885 0,
13886 &vx.slice((tc - 1) * n_embd..tc * n_embd),
13887 n_embd,
13888 )?;
13889 s = cend;
13890 }
13891 for (p, drafts, targets) in rows.iter_mut() {
13892 for j in 0..drafts.len() {
13893 targets.push(bg[*p + 1 + j]);
13894 }
13895 }
13896 rows.sort_by_key(|r| r.0);
13897 if nll_cnt > 0 {
13898 let mean = nll_sum / nll_cnt as f64;
13899 println!(
13900 "[replay-nll] tokens={nll_cnt} nll/token={mean:.5} ppl={:.4}",
13901 mean.exp()
13902 );
13903 }
13904 Ok((rows, bg))
13905 }
13906}
13907
13908#[cfg(test)]
13909mod vg_debt_tests {
13910 use super::dspark_vg_debt_projection;
13911
13912 /// TOOTH for the verify-graph admission accounting: the pool's projected remaining
13913 /// growth must be charged (pre-fix, admission charged 0 for a pool measured at
13914 /// 8,852 MiB), the projection must price the MARGINAL cost of one more key rather than
13915 /// extrapolating the pool's one-time shared allocation, and the doors that make growth
13916 /// impossible must zero the debt.
13917 #[test]
13918 fn vg_debt_projects_remaining_growth_and_respects_the_freeze_valves() {
13919 const MIB: usize = 1 << 20;
13920 let d = dspark_vg_debt_projection;
13921 // cold pool: nothing observed, one capture fits inside SPEC_SHRINK_RESERVE.
13922 assert_eq!(d(0, 256, 0, None), 0);
13923 // freeze valve MEMRA_DSPARK_VG_MAX=0: the pool cannot grow.
13924 assert_eq!(d(10, 0, 500 * MIB, None), 0);
13925 // saturated pool: at/past the cap the pool FREEZES, nothing left to reserve.
13926 assert_eq!(d(256, 256, 8852 * MIB, None), 0);
13927 assert_eq!(d(300, 256, 8852 * MIB, None), 0);
13928
13929 // BOOTSTRAP (one observation, growth unmeasurable): at most one more pool's worth.
13930 // The pre-fix mean rule extrapolated 255x here — the measured 8.5 GB phantom.
13931 assert_eq!(d(1, 256, 33 * MIB, None), 33 * MIB);
13932
13933 // MARGINAL, flat pool (the box9 receipt: reserved stayed ~33.6 MiB across captures
13934 // 1..3, so an additional key costs ~nothing and the debt must collapse to ~0 —
13935 // NOT the 8,556/4,261/2,830 MB the mean rule printed).
13936 assert_eq!(d(3, 256, 33 * MIB, Some((1, 33 * MIB))), 0);
13937
13938 // MARGINAL, genuinely growing pool: 40 MiB per new key over 2 keys, 250 slots left.
13939 let debt = d(6, 256, 273 * MIB, Some((4, 193 * MIB)));
13940 assert_eq!(debt, 250 * (40 * MIB));
13941 assert!(
13942 debt > 3 * (1536 * MIB),
13943 "real growth must dwarf SPEC_SHRINK_RESERVE"
13944 );
13945
13946 // a shrinking/recycled reading never becomes a negative charge.
13947 assert_eq!(d(6, 256, 10 * MIB, Some((4, 99 * MIB))), 0);
13948 // a stale observation at the same capture count falls back to bootstrap.
13949 assert_eq!(d(4, 256, 80 * MIB, Some((4, 80 * MIB))), 80 * MIB);
13950 }
13951}
13952
13953#[cfg(test)]
13954mod mtp_chain_tests {
13955 use super::mtp_chain_head_index;
13956
13957 #[test]
13958 fn embedded_step_heads_cycle_in_declared_order() {
13959 let actual: Vec<usize> = (0..8).map(|step| mtp_chain_head_index(step, 3)).collect();
13960 assert_eq!(actual, [0, 1, 2, 0, 1, 2, 0, 1]);
13961 }
13962
13963 #[test]
13964 fn standalone_draft_remains_single_head() {
13965 assert!((0..8).all(|step| mtp_chain_head_index(step, 1) == 0));
13966 }
13967}
13968
13969#[cfg(test)]
13970mod tp_verified_prefix_tests {
13971 use super::rewind_tp_kv_verified_prefix;
13972 use crate::tp::ResidentTpKvCache;
13973
13974 fn cache_with_committed_len(committed: usize) -> ResidentTpKvCache {
13975 let mut cache = ResidentTpKvCache::new(Vec::new(), 1, 1, 1, 1, 8);
13976 let transaction = cache.begin_transaction().unwrap();
13977 let target = cache.append_target(transaction, committed).unwrap();
13978 cache.publish_append(transaction, target).unwrap();
13979 let target = cache.commit_target(transaction, committed).unwrap();
13980 cache.publish_finalize(transaction, target).unwrap();
13981 cache
13982 }
13983
13984 #[test]
13985 fn replay_free_prefix_rewinds_tp_visibility_to_snapshot_plus_accepts() {
13986 let mut layers = vec![Some(cache_with_committed_len(5)), None];
13987 rewind_tp_kv_verified_prefix(&mut layers, &[Some(2), None], 1).unwrap();
13988 let cache = layers[0].as_ref().unwrap();
13989 assert_eq!(cache.committed_len(), 3);
13990 assert_eq!(cache.staged_len(), 3);
13991 }
13992
13993 #[test]
13994 fn replay_free_prefix_rejects_a_changed_tp_cache_shape() {
13995 let mut layers = vec![Some(cache_with_committed_len(1))];
13996 let error = rewind_tp_kv_verified_prefix(&mut layers, &[None], 1)
13997 .unwrap_err()
13998 .to_string();
13999 assert!(error.contains("changed shape"), "unexpected error: {error}");
14000 }
14001}
14002
14003#[cfg(test)]
14004mod dspark_sparse_tests {
14005 use super::dspark_sparse_softmax_topk;
14006
14007 #[test]
14008 fn topk_keeps_full_softmax_mass_and_stable_ties() {
14009 let logits = [1.0f32, 3.0, 3.0, -2.0];
14010 let (ids, top_logits, probs, tail) = dspark_sparse_softmax_topk(&logits, 2, 1.0).unwrap();
14011 assert_eq!(ids, vec![1, 2]);
14012 assert_eq!(top_logits, vec![3.0, 3.0]);
14013 let denominator = logits.iter().map(|value| (value - 3.0).exp()).sum::<f32>();
14014 let expected = 1.0 / denominator;
14015 assert!((probs[0] - expected).abs() < 1.0e-6);
14016 assert!((probs[1] - expected).abs() < 1.0e-6);
14017 assert!((tail - (1.0 - 2.0 * expected)).abs() < 1.0e-6);
14018 assert!((probs.iter().sum::<f32>() + tail - 1.0).abs() < 1.0e-6);
14019 }
14020}
14021
14022#[cfg(test)]
14023mod spec_replay_env_tests {
14024 use super::spec_replay_env_on;
14025
14026 #[test]
14027 fn replay_requires_literal_one() {
14028 assert!(!spec_replay_env_on(None));
14029 assert!(!spec_replay_env_on(Some("")));
14030 assert!(!spec_replay_env_on(Some("0")));
14031 assert!(!spec_replay_env_on(Some("true")));
14032 assert!(!spec_replay_env_on(Some("2")));
14033 assert!(spec_replay_env_on(Some("1")));
14034 }
14035}
14036
14037#[cfg(test)]
14038mod telem_tests {
14039 use super::{SPEC_TELEM_POS, SpecTelemetry, SpecTelemetryCounters};
14040
14041 #[test]
14042 fn synthetic_accept_masks_produce_tau_and_position_histogram() {
14043 let counters = SpecTelemetryCounters::default();
14044 for mask in [
14045 [true, true, true],
14046 [true, true, false],
14047 [true, false, false],
14048 [false, false, false],
14049 ] {
14050 let accepted = mask.iter().take_while(|&&value| value).count();
14051 counters.record_round(mask.len(), accepted);
14052 }
14053
14054 let snapshot = counters.snapshot();
14055 assert_eq!(
14056 (snapshot.rounds, snapshot.drafted, snapshot.accepted),
14057 (4, 12, 6)
14058 );
14059 assert_eq!(&snapshot.pos_drafted[..3], &[4, 4, 4]);
14060 assert_eq!(&snapshot.pos_accepted[..3], &[3, 2, 1]);
14061 assert_eq!(snapshot.tau(), 1.5);
14062 assert_eq!(snapshot.pos_drafted[3..], [0; SPEC_TELEM_POS - 3]);
14063 assert_eq!(snapshot.pos_accepted[3..], [0; SPEC_TELEM_POS - 3]);
14064 }
14065
14066 /// The worker's per-burst pattern: stash, accumulate, diff — the delta must isolate
14067 /// exactly the burst's contribution (pool-resumed sessions carry prior requests' counts).
14068 #[test]
14069 fn delta_isolates_burst_contribution() {
14070 let mut t = SpecTelemetry::default();
14071 // "previous request": 2 rounds of k=3, accepts 3 then 1.
14072 for (kr, na) in [(3usize, 3usize), (3, 1)] {
14073 t.rounds += 1;
14074 t.drafted += kr as u64;
14075 t.accepted += na as u64;
14076 for j in 0..kr {
14077 t.pos_drafted[j] += 1;
14078 }
14079 for j in 0..na {
14080 t.pos_accepted[j] += 1;
14081 }
14082 }
14083 let before = t;
14084 // "this burst": 1 round k=3, accepts 2.
14085 t.rounds += 1;
14086 t.drafted += 3;
14087 t.accepted += 2;
14088 for j in 0..3 {
14089 t.pos_drafted[j] += 1;
14090 }
14091 for j in 0..2 {
14092 t.pos_accepted[j] += 1;
14093 }
14094 let d = t.delta_since(&before);
14095 assert_eq!((d.rounds, d.drafted, d.accepted), (1, 3, 2));
14096 assert_eq!(&d.pos_drafted[..3], &[1, 1, 1]);
14097 assert_eq!(&d.pos_accepted[..3], &[1, 1, 0]);
14098 assert_eq!(d.pos_drafted[3..], [0; SPEC_TELEM_POS - 3]);
14099 }
14100
14101 /// merge(delta) then merge(delta2) equals accumulating both — the per-model /metrics
14102 /// aggregation invariant.
14103 #[test]
14104 fn merge_accumulates_fieldwise() {
14105 let mut agg = SpecTelemetry::default();
14106 let mut d1 = SpecTelemetry {
14107 rounds: 2,
14108 drafted: 6,
14109 accepted: 4,
14110 ..Default::default()
14111 };
14112 d1.pos_drafted[0] = 2;
14113 d1.pos_accepted[0] = 2;
14114 let mut d2 = SpecTelemetry {
14115 rounds: 1,
14116 drafted: 3,
14117 accepted: 1,
14118 ..Default::default()
14119 };
14120 d2.pos_drafted[0] = 1;
14121 d2.pos_accepted[0] = 1;
14122 d2.pos_drafted[1] = 1;
14123 agg.merge(&d1);
14124 agg.merge(&d2);
14125 assert_eq!((agg.rounds, agg.drafted, agg.accepted), (3, 9, 5));
14126 assert_eq!(agg.pos_drafted[0], 3);
14127 assert_eq!(agg.pos_accepted[0], 3);
14128 assert_eq!(agg.pos_drafted[1], 1);
14129 assert_eq!(agg.pos_accepted[1], 0);
14130 }
14131
14132 /// Wrong-snapshot diff saturates to zero instead of wrapping — the counters feed a
14133 /// public metrics surface and must never publish a u64-wrapped garbage value.
14134 #[test]
14135 fn delta_saturates_never_wraps() {
14136 let small = SpecTelemetry {
14137 rounds: 1,
14138 drafted: 2,
14139 accepted: 1,
14140 ..Default::default()
14141 };
14142 let big = SpecTelemetry {
14143 rounds: 5,
14144 drafted: 15,
14145 accepted: 9,
14146 ..Default::default()
14147 };
14148 let d = small.delta_since(&big);
14149 assert_eq!((d.rounds, d.drafted, d.accepted), (0, 0, 0));
14150 }
14151}
14152
14153#[cfg(test)]
14154mod opti_fork_tests {
14155 use super::{
14156 OptiControllerPolicy, OptiForkAction, OptiForkGateMode, OptiForkGenerationTracker,
14157 };
14158
14159 #[test]
14160 fn controller_threshold_and_three_miss_breaker_are_exact() {
14161 let mut policy = OptiControllerPolicy {
14162 threshold: 0.7,
14163 consecutive_misses: 0,
14164 breaker_tripped: false,
14165 };
14166 assert!(!policy.admit(0.699_999));
14167 assert!(policy.admit(0.7));
14168 assert!(!policy.resolve(false));
14169 assert!(!policy.resolve(false));
14170 assert!(policy.resolve(false));
14171 assert!(policy.breaker_tripped);
14172 assert!(!policy.admit(1.0));
14173 assert!(
14174 !policy.resolve(true),
14175 "a resolved hit cannot re-arm a tripped request"
14176 );
14177 assert!(policy.breaker_tripped);
14178 }
14179
14180 #[test]
14181 fn zero_threshold_is_the_true_unconditional_measurement_arm() {
14182 let mut policy = OptiControllerPolicy {
14183 threshold: 0.0,
14184 consecutive_misses: 0,
14185 breaker_tripped: false,
14186 };
14187 for _ in 0..16 {
14188 assert!(policy.admit(0.0));
14189 assert!(!policy.resolve(false));
14190 }
14191 for invalid in [f32::NAN, f32::INFINITY, -0.01, 1.01] {
14192 assert!(
14193 !policy.admit(invalid),
14194 "invalid q proxy must fail closed: {invalid}"
14195 );
14196 }
14197 assert!(!policy.breaker_tripped);
14198 assert_eq!(policy.consecutive_misses, 0);
14199 }
14200
14201 #[test]
14202 fn alternating_mode_flips_by_generation_not_round_parity() {
14203 assert_eq!(OptiForkGateMode::Alternate.action(0), OptiForkAction::Hit);
14204 assert_eq!(OptiForkGateMode::Alternate.action(1), OptiForkAction::Miss);
14205 assert_eq!(OptiForkGateMode::Alternate.action(8), OptiForkAction::Hit);
14206 assert_eq!(OptiForkGateMode::Alternate.action(9), OptiForkAction::Miss);
14207 }
14208
14209 #[test]
14210 fn live_generation_cannot_be_overwritten() {
14211 let mut tracker = OptiForkGenerationTracker::default();
14212 let g0 = tracker.reserve().unwrap();
14213 let g1 = tracker.reserve().unwrap();
14214 let err = tracker.reserve().unwrap_err().to_string();
14215 assert!(
14216 err.contains("still owns generation 0"),
14217 "unexpected error: {err}"
14218 );
14219 tracker.retire(g0).unwrap();
14220 let g2 = tracker.reserve().unwrap();
14221 assert_eq!((g2.id, g2.slot), (2, 0));
14222 tracker.retire(g1).unwrap();
14223 tracker.retire(g2).unwrap();
14224 }
14225
14226 #[test]
14227 fn teardown_rejects_a_stale_generation_tag() {
14228 let mut tracker = OptiForkGenerationTracker::default();
14229 let g0 = tracker.reserve().unwrap();
14230 tracker.retire(g0).unwrap();
14231 let err = tracker.retire(g0).unwrap_err().to_string();
14232 assert!(err.contains("teardown mismatch"), "unexpected error: {err}");
14233 }
14234}
14235
14236#[cfg(test)]
14237mod draft_graph_fallback_tests {
14238 use super::DraftGraphFallback;
14239
14240 /// The Q2 contract, part (a): a fallback flip is LOUD — exactly once per flip.
14241 #[test]
14242 fn flip_is_loud_once_and_memoized_after() {
14243 let mut f = DraftGraphFallback::default();
14244 let line = f
14245 .mark_greedy("out of memory")
14246 .expect("first flip must return the warn line");
14247 assert!(
14248 line.contains("WARN"),
14249 "flip line must be warn-level: {line}"
14250 );
14251 assert!(
14252 line.contains("out of memory"),
14253 "flip line must carry the reason: {line}"
14254 );
14255 assert!(f.greedy_failed());
14256 // re-marking an already-failed graph is the memoization: quiet, still failed.
14257 assert!(f.mark_greedy("out of memory").is_none());
14258 assert!(f.greedy_failed());
14259 // the two graphs' flags are independent (greedy flip leaves sampled capturable).
14260 assert!(!f.sampled_failed());
14261 let line_s = f
14262 .mark_sampled("capture unsupported")
14263 .expect("sampled flip is its own flip");
14264 assert!(
14265 line_s.contains("sampled"),
14266 "sampled flip names itself: {line_s}"
14267 );
14268 assert!(f.mark_sampled("capture unsupported").is_none());
14269 }
14270
14271 /// The Q2 contract, part (b): resume-from-pool RESETS both flags (fresh capture chance),
14272 /// and says so exactly when there was something to reset.
14273 #[test]
14274 fn reset_on_resume_clears_flags_and_logs_once() {
14275 let mut f = DraftGraphFallback::default();
14276 // clean session: resume is silent, nothing to reset.
14277 assert!(f.reset_on_resume().is_none());
14278 f.mark_greedy("oom").unwrap();
14279 f.mark_sampled("oom").unwrap();
14280 let note = f
14281 .reset_on_resume()
14282 .expect("a set flag must produce the reset note");
14283 assert!(
14284 note.contains("greedy+sampled"),
14285 "note names what was reset: {note}"
14286 );
14287 assert!(
14288 !f.greedy_failed() && !f.sampled_failed(),
14289 "both flags cleared"
14290 );
14291 // and the NEXT failure after a reset is a fresh flip — loud again.
14292 assert!(f.mark_greedy("oom again").is_some());
14293 let note2 = f.reset_on_resume().expect("greedy-only reset");
14294 assert!(note2.contains("(greedy)"), "single-flag note: {note2}");
14295 }
14296
14297 /// Shape-change clears (dmask realloc / mask-shape mismatch / s_key change) stay silent —
14298 /// they precede a fresh capture attempt whose own failure re-flips loudly.
14299 #[test]
14300 fn shape_change_clears_are_silent() {
14301 let mut f = DraftGraphFallback::default();
14302 f.mark_greedy("oom").unwrap();
14303 f.clear_greedy();
14304 assert!(!f.greedy_failed());
14305 f.mark_sampled("oom").unwrap();
14306 f.clear_sampled();
14307 assert!(!f.sampled_failed());
14308 // after a silent clear there is nothing left for resume to report.
14309 assert!(f.reset_on_resume().is_none());
14310 }
14311}
14312
14313/// SAMPLED DRAFT-GRAPH KEY (lane/graph-s-key-exactness-20260819).
14314///
14315/// These are the CPU teeth for an exactness bug whose live reproduction needs a GPU, a trunk, a
14316/// drafter and a two-turn session: the key itself. Every test below fails against the pre-fix key
14317/// `(seed, temp.to_bits(), k)` — `legacy_key` restates it so the collision is explicit rather
14318/// than remembered.
14319#[cfg(test)]
14320mod sampled_graph_key_tests {
14321 use super::{SampledGraphKey, debug_t_pred0};
14322
14323 /// The pre-fix key, verbatim: `let s_key = (sp_seed, sp_temp.to_bits(), k);`
14324 fn legacy_key(k: &SampledGraphKey) -> (u64, u32, usize) {
14325 (k.seed, k.temp_bits, k.k)
14326 }
14327
14328 fn pure_temp_key() -> SampledGraphKey {
14329 // temperature 1.0, filters off — today's serve default, the shape that parks a graph.
14330 SampledGraphKey::new(12345, 1.0, 3, 0, 1.0, 0.0, false)
14331 }
14332
14333 /// THE COLLISION. Two requests that differ ONLY in the truncation filters shared one key, so
14334 /// a parked pure-temp graph survived into a filtered request and the launch site launched it.
14335 #[test]
14336 fn vendor_filters_change_the_key() {
14337 let parked = pure_temp_key();
14338 // qwen3.8 generation_config.json — what the vendor-default flip makes the default shape.
14339 let vendor = SampledGraphKey::new(12345, 1.0, 3, 20, 0.95, 0.0, false);
14340 assert_eq!(
14341 legacy_key(&parked),
14342 legacy_key(&vendor),
14343 "pre-fix key collided: this is the bug, and the reason a test asserts on it",
14344 );
14345 assert_ne!(parked, vendor, "post-fix key must separate the two regimes");
14346 assert!(parked.pure_temp());
14347 assert!(!vendor.pure_temp());
14348 }
14349
14350 /// Each distribution-shaping field alone is enough to drop the parked graph.
14351 #[test]
14352 fn every_filter_field_is_keyed() {
14353 let base = pure_temp_key();
14354 for (what, other) in [
14355 (
14356 "top_k",
14357 SampledGraphKey::new(12345, 1.0, 3, 20, 1.0, 0.0, false),
14358 ),
14359 (
14360 "top_p",
14361 SampledGraphKey::new(12345, 1.0, 3, 0, 0.95, 0.0, false),
14362 ),
14363 (
14364 "min_p",
14365 SampledGraphKey::new(12345, 1.0, 3, 0, 1.0, 0.05, false),
14366 ),
14367 (
14368 "penalties",
14369 SampledGraphKey::new(12345, 1.0, 3, 0, 1.0, 0.0, true),
14370 ),
14371 ] {
14372 assert_ne!(base, other, "{what} must be part of the key");
14373 assert!(!other.pure_temp(), "{what} leaves the pure-temp regime");
14374 assert_eq!(
14375 legacy_key(&base),
14376 legacy_key(&other),
14377 "{what} was invisible to the pre-fix key",
14378 );
14379 }
14380 }
14381
14382 /// The baked constants stay keyed (this half was always right — regression cover for it).
14383 #[test]
14384 fn baked_constants_stay_keyed() {
14385 let base = pure_temp_key();
14386 assert_ne!(
14387 base,
14388 SampledGraphKey::new(999, 1.0, 3, 0, 1.0, 0.0, false),
14389 "seed"
14390 );
14391 assert_ne!(
14392 base,
14393 SampledGraphKey::new(12345, 0.7, 3, 0, 1.0, 0.0, false),
14394 "temp"
14395 );
14396 assert_ne!(
14397 base,
14398 SampledGraphKey::new(12345, 1.0, 4, 0, 1.0, 0.0, false),
14399 "k"
14400 );
14401 // bitwise on temperature: 0.7f32 vs the same value re-derived must NOT differ.
14402 assert_eq!(
14403 SampledGraphKey::new(1, 0.7, 3, 0, 1.0, 0.0, false),
14404 SampledGraphKey::new(1, 7.0 / 10.0, 3, 0, 1.0, 0.0, false),
14405 );
14406 }
14407
14408 /// THE LOAD-BEARING HALF OF THE SEED DECISION (lane/session-resume-sampler-predicate-
14409 /// 20260820). The whole-session resume predicate deliberately does NOT compare `seed`: an
14410 /// omitted serve `seed` draws fresh per-request entropy, so comparing it would refuse every
14411 /// seed-omitting sampled conversation. That is only sound because the one piece of parked state
14412 /// that BAKES the seed — this graph — is re-keyed on it, so a seed change drops and recaptures.
14413 ///
14414 /// This test is the other end of that argument, asserted here rather than remembered in a
14415 /// comment: if a future change dropped `seed` from the key, the resume predicate's exclusion
14416 /// would silently become the unsound thing it is documented not to be.
14417 /// (Paired with `seed_alone_does_not_refuse` in `memra-sampling`.)
14418 #[test]
14419 fn seed_alone_still_rekeys_the_draft_graph() {
14420 let parked = pure_temp_key();
14421 let reseeded = SampledGraphKey::new(999, 1.0, 3, 0, 1.0, 0.0, false);
14422 assert_ne!(
14423 parked, reseeded,
14424 "a seed-only change MUST drop the parked sampled graph — the resume predicate's \
14425 decision not to compare seed rests on exactly this",
14426 );
14427 // Same regime on both sides: the drop is a recapture, not a fall to the eager chain
14428 // because of a filter difference.
14429 assert!(parked.pure_temp() && reseeded.pure_temp());
14430 }
14431
14432 /// `pure_temp()` is the capture guard's predicate, computed from the key so the two cannot
14433 /// drift. The equality below is the invariant the launch-site guard asserts: identical keys
14434 /// agree on the regime, so a graph that survives the drop is legal to launch.
14435 #[test]
14436 fn equal_keys_agree_on_the_regime() {
14437 let a = SampledGraphKey::new(7, 0.8, 3, 20, 0.95, 0.0, false);
14438 let b = SampledGraphKey::new(7, 0.8, 3, 20, 0.95, 0.0, false);
14439 assert_eq!(a, b);
14440 assert_eq!(a.pure_temp(), b.pure_temp());
14441 // top_p slightly above 1.0 (a client sending 1.0 exactly, or an operator default) is
14442 // still the unfiltered regime, matching the original `sp.top_p >= 1.0` test.
14443 assert!(SampledGraphKey::new(7, 0.8, 3, 0, 1.0, 0.0, false).pure_temp());
14444 assert!(SampledGraphKey::new(7, 0.8, 3, 0, 1.5, -1.0, false).pure_temp());
14445 }
14446
14447 /// MEMRA_DEBUG_SPEC on a SAMPLED spec request past round 0: the print must render without
14448 /// indexing the empty greedy `preds` vector (it panicked the GPU worker before this lane).
14449 #[test]
14450 fn debug_print_survives_the_sampled_arm() {
14451 // round >= 1 with a pending bonus == base 1, sampled == `preds` empty.
14452 assert_eq!(debug_t_pred0(true, 1, 4242, &[]), "n/a");
14453 assert_eq!(debug_t_pred0(true, 2, 4242, &[]), "n/a");
14454 // round 0 without a pending bonus still reports last_pred, in both arms.
14455 assert_eq!(debug_t_pred0(true, 0, 4242, &[]), "4242");
14456 assert_eq!(debug_t_pred0(false, 0, 4242, &[7, 8]), "4242");
14457 // greedy keeps the real prediction it always printed.
14458 assert_eq!(debug_t_pred0(false, 1, 4242, &[7, 8]), "7");
14459 assert_eq!(debug_t_pred0(false, 2, 4242, &[7, 8]), "8");
14460 }
14461}