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 memra_gguf::config::SwigluClamp;
17use std::sync::atomic::{AtomicU64, Ordering};
18
19/// Parse the documented `MEMRA_SPEC_REPLAY=1` rollback seam.
20///
21/// Keep this shared with serving admission so `=0` cannot select replay in one
22/// layer while another layer treats it as disabled.
23pub fn spec_replay_env_on(value: Option<&str>) -> bool {
24 value == Some("1")
25}
26
27pub fn spec_replay_env_enabled() -> bool {
28 let value = std::env::var("MEMRA_SPEC_REPLAY").ok();
29 spec_replay_env_on(value.as_deref())
30}
31
32/// step35 dcw draft-chain door (lane/step37-draft-graph-20260829). ON routes the step35 MTP
33/// block's draft attention through the WINDOWED device-counter family
34/// (`append_kv_quantized_dcw` + `fa_decode_dcw`, the step TP graph arc's kernels), which
35/// derives the SWA view entirely from device state (len_d, base_d, window): exactly the view
36/// offset the old capture refusal said `fa_decode_dc` could not express. BOTH draft modes
37/// switch together: eager and captured run the ONE launcher at the ONE bucket
38/// (min(cap, window)), so graph-vs-eager draft parity holds by construction (the
39/// `mtp_full_attn_dc` precedent).
40///
41/// DEFAULT ON since lane/step37-draft-graph-serving-20260830: the 20260829 lane shipped it
42/// OFF because it enabled nothing at the shipping head count (capture was structurally
43/// unreachable at heads=3); with the multi-head chain capture and the in-graph filtered
44/// sampler landed, this door is the kernel prerequisite for the captured chain on the
45/// QUALIFIED serving shape, and the exactness battery (greedy K=1..8 identity, per-K
46/// acceptance identity, seeded sampled twins) banks on the ON arm. Rollback seam:
47/// MEMRA_STEP35_DRAFT_DCW=0 restores the host-len eager arm (`mtp_step35_attn`) plus the
48/// named capture refusal, byte-for-byte the pre-lane serving; no state survives restart.
49fn step35_draft_dcw_on() -> bool {
50 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
51 *ON.get_or_init(|| std::env::var("MEMRA_STEP35_DRAFT_DCW").as_deref() != Ok("0"))
52}
53
54/// Multi-head MTP draft-chain capture door (lane/step37-draft-graph-serving-20260830,
55/// default ON — receipts in the lane RESULTS). ON lets the step-modulo prefix-replay chain
56/// (`mtp_extra` non-empty, the step37 3-head shipping shape) capture per-head single-row
57/// CUDA graphs and replay them in the exact eager launch order; the chain POLICY (head
58/// selection, prefix length, seed history) stays host-side, so graph-vs-eager drafts are
59/// bit-identical by construction. A failed capture degrades LOUDLY to the eager chain (the
60/// draft-graph WARN contract). OFF (=0) keeps the eager chain as the only multi-head path —
61/// the pre-lane serving byte-for-byte. Single-head capture is untouched by this door.
62fn mtp_chain_graph_on() -> bool {
63 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
64 *ON.get_or_init(|| std::env::var("MEMRA_MTP_CHAIN_GRAPH").as_deref() != Ok("0"))
65}
66
67/// In-graph FILTERED sampled draft door (lane/step37-draft-graph-serving-20260830, default
68/// ON — receipts in the lane RESULTS). ON widens the sampled draft-graph capture from the
69/// pure-temp regime to every truncation-filtered regime (top_k / top_p / min_p): the capture
70/// body runs `filter_stats` + `gumbel_perturb_filtered_ctr` IN-GRAPH, so the draft draws
71/// from the SAME filtered distribution the verify's accept test reconstructs (the
72/// graph-s-key exactness law, now satisfied inside the graph instead of by refusing it).
73/// Penalties stay eager either way (the history varies per round and cannot be baked).
74/// The pure-temp capture body is UNTOUCHED by this door (byte-identical to the pre-lane
75/// graph). OFF (=0) restores the pure-temp-only capture guard: filtered requests draft
76/// eager, byte-for-byte the pre-lane behavior.
77fn spec_graph_filtered_on() -> bool {
78 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
79 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_GRAPH_FILTERED").as_deref() != Ok("0"))
80}
81
82fn parse_prime_trows_width(value: Option<&str>) -> Result<usize, String> {
83 let Some(raw) = value else {
84 return Ok(8);
85 };
86 let width = raw
87 .parse::<usize>()
88 .map_err(|_| format!("MEMRA_PRIME_TROWS_T must be an integer in 2..=8, got {raw:?}"))?;
89 if !(2..=8).contains(&width) {
90 return Err(format!("MEMRA_PRIME_TROWS_T must be in 2..=8, got {width}"));
91 }
92 Ok(width)
93}
94
95#[cfg(test)]
96mod prime_trows_width_tests {
97 #[test]
98 fn width_defaults_to_eight_and_refuses_invalid_operator_values() {
99 assert_eq!(super::parse_prime_trows_width(None), Ok(8));
100 assert_eq!(super::parse_prime_trows_width(Some("2")), Ok(2));
101 assert_eq!(super::parse_prime_trows_width(Some("8")), Ok(8));
102 for invalid in ["", "1", "9", "32", "wide"] {
103 let err = super::parse_prime_trows_width(Some(invalid)).unwrap_err();
104 assert!(err.contains("MEMRA_PRIME_TROWS_T"), "{err}");
105 assert!(err.contains("2..=8"), "{err}");
106 }
107 }
108}
109
110/// One compact, anchor-bounded DSpark supervision record. `tokens[0]` is the anchor at p and
111/// `hidden` is its predecessor carrier h[p-1], matching the live NextN/DSpark pairing. Target
112/// rows p..p+gamma-1 score tokens p+1..p+gamma. They are the full-target softmax's top-k
113/// entries; `target_tail_probs[j]` is the probability mass outside those rows. All flattened
114/// target arrays are `[gamma, top_k]` in row-major order.
115pub struct DsparkAnchorRecord {
116 pub position: usize,
117 pub hidden: Vec<f32>,
118 pub tokens: Vec<u32>,
119 pub target_top_ids: Vec<u32>,
120 pub target_top_logits: Vec<f32>,
121 pub target_top_probs: Vec<f32>,
122 pub target_tail_probs: Vec<f32>,
123}
124
125#[allow(clippy::type_complexity)] // allow: one-shot composite type; naming it would hide the shape that matters at the call site
126fn dspark_sparse_softmax_topk(
127 logits: &[f32],
128 top_k: usize,
129 temperature: f32,
130) -> Result<(Vec<u32>, Vec<f32>, Vec<f32>, f32), Box<dyn std::error::Error>> {
131 if logits.is_empty() || top_k == 0 || top_k > logits.len() || temperature <= 0.0 {
132 return Err("invalid DSpark sparse-softmax shape or temperature".into());
133 }
134 if logits.iter().any(|value| !value.is_finite()) {
135 return Err("DSpark target logits contain a non-finite value".into());
136 }
137 let mut ranked: Vec<(u32, f32)> = logits
138 .iter()
139 .copied()
140 .enumerate()
141 .map(|(index, value)| (index as u32, value))
142 .collect();
143 let compare = |left: &(u32, f32), right: &(u32, f32)| {
144 right.1.total_cmp(&left.1).then(left.0.cmp(&right.0))
145 };
146 ranked.select_nth_unstable_by(top_k - 1, compare);
147 ranked[..top_k].sort_unstable_by(compare);
148
149 let max_logit = logits.iter().copied().fold(f32::NEG_INFINITY, f32::max);
150 let inv_temperature = 1.0f64 / temperature as f64;
151 let denominator: f64 = logits
152 .iter()
153 .map(|value| (((*value - max_logit) as f64) * inv_temperature).exp())
154 .sum();
155 let ids: Vec<u32> = ranked[..top_k].iter().map(|(index, _)| *index).collect();
156 let top_logits: Vec<f32> = ranked[..top_k].iter().map(|(_, value)| *value).collect();
157 let top_probs: Vec<f32> = top_logits
158 .iter()
159 .map(|value| ((((value - max_logit) as f64) * inv_temperature).exp() / denominator) as f32)
160 .collect();
161 let top_mass: f64 = top_probs.iter().map(|value| *value as f64).sum();
162 let tail = (1.0f64 - top_mass).clamp(0.0, 1.0) as f32;
163 Ok((ids, top_logits, top_probs, tail))
164}
165
166fn flatten_dspark_rows<T>(
167 rows: Vec<Option<Vec<T>>>,
168 position: usize,
169 label: &str,
170) -> Result<Vec<T>, Box<dyn std::error::Error>> {
171 let mut flattened = Vec::new();
172 for (slot, row) in rows.into_iter().enumerate() {
173 flattened.extend(
174 row.ok_or_else(|| format!("missing DSpark {label} at {position} slot {slot}"))?,
175 );
176 }
177 Ok(flattened)
178}
179
180/// H-SEED CONVENTION (MEMRA_SPEC_HPOST=1): feed the MTP head the POST-norm hidden — trunk rows
181/// hand over `output_norm(x)` and the draft chain recurrence hands over `shared_head_norm(h_nextn)`
182/// (= final_h) — matching the reference engines: llama.cpp #24025 ("qwen35: use post-norm hidden
183/// state for MTP", t_h_nextn is taken AFTER the final norm in both trunk and MTP graphs) and
184/// SGLang's qwen3_5_mtp (spec_info.hidden_states = the target model's post-norm output). memra's
185/// historical convention (default, MTP-PLAN §A) is PRE-norm x. Draft-quality-only: exactness is
186/// the verify's job either way; acceptance arbitrates. OnceLock: read once, hot-loop safe.
187/// `MEMRA_SPEC_HEAD_ROWS=1` — batch the verify tail's LM head over its t columns instead of running
188/// it at m=1 once per column. See the call site in `decode_step_t_core_stream` for why the batched
189/// form is the same per-row arithmetic (the bf16/q8 rows twins, not cuBLASLt) and what it costs
190/// today: the head is re-streamed t times per verify pass. Default off until the byte tape says so.
191pub(crate) fn head_rows_on() -> bool {
192 static ENV: std::sync::OnceLock<Option<bool>> = std::sync::OnceLock::new();
193 crate::step37_door(&ENV, "MEMRA_SPEC_HEAD_ROWS")
194}
195
196/// The serving walk's own doors, tri-stated the same way (owner flip 2026-08-27): env forces,
197/// unset takes the step37 family default. Call sites are the t-row verify walk itself.
198pub(crate) fn spec_verify_eager_on() -> bool {
199 static ENV: std::sync::OnceLock<Option<bool>> = std::sync::OnceLock::new();
200 crate::step37_door(&ENV, "MEMRA_SPEC_VERIFY_EAGER")
201}
202
203pub(crate) fn spec_verify_tcol_on() -> bool {
204 static ENV: std::sync::OnceLock<Option<bool>> = std::sync::OnceLock::new();
205 crate::step37_door(&ENV, "MEMRA_SPEC_VERIFY_TCOL")
206}
207
208/// NOT family-armed (2026-08-27): the walk's prime leaves its sub-32 TAIL chunk out of the
209/// DISTRIBUTED kv, so the server refuses before decode with "cache lengths diverged
210/// local=N distributed=floor(N/32)*32" for every prompt whose token count is not a multiple of
211/// 32 — i.e. nearly all real traffic. Isolated on the server route: defaults ERR (local=445
212/// distributed=416), MEMRA_PRIME_TROWS=0 OK. It was default-OFF before the 2026-08-27 flip and
213/// goes back to opt-in until the tail append is fixed and gated ON THE SERVER ROUTE, not just
214/// run-gen (run-gen calls decode_step_t on the whole prompt and never exercises this path — the
215/// reason a run-gen-only receipt could not see it). The GEMM prime supersedes it on this route.
216pub(crate) fn prime_trows_on() -> bool {
217 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
218 *ON.get_or_init(|| std::env::var("MEMRA_PRIME_TROWS").as_deref() == Ok("1"))
219}
220
221pub(crate) fn tcol_ffn_on() -> bool {
222 static ENV: std::sync::OnceLock<Option<bool>> = std::sync::OnceLock::new();
223 crate::step37_door(&ENV, "MEMRA_TCOL_FFN")
224}
225
226pub(crate) fn spec_hpost() -> bool {
227 static H: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
228 *H.get_or_init(|| {
229 std::env::var("MEMRA_SPEC_HPOST")
230 .map(|v| v != "0")
231 .unwrap_or(false)
232 })
233}
234
235/// LEAN VERIFY (default ON since 2026-07-08; MEMRA_SPEC_LEAN=0 reverts — close35 lane): the verify m-scaling
236/// probe + nsys diff showed the verify t-path pays ~1.0ms/call at m=1 over eager decode on the
237/// 35B, and the kernels are NOT the cause (dev-MoE identical, kernel-time delta only +179us).
238/// The overhead is (a) ~250 extra cuMemsetD8Async/call from `e.zeros()` on buffers every kernel
239/// fully overwrites (~0.9ms host issue + ~0.35ms GPU) and (b) the t=1 FA rows dispatch (rows_v2 +
240/// combine_rows, +50us vs the eager fa_decode pair). This flag switches (a) fully-overwritten
241/// verify buffers to `e.uninit` (identical bytes: every element is written before read) and
242/// (b) t==1 verify FA to the eager `fa_decode` entry (byte-identical: kernel-check pins the
243/// rows-vs-loop identity and the per-row loop at t=1 IS fa_decode on the same q). Gates arbitrate.
244pub(crate) fn spec_lean() -> bool {
245 static L: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
246 // DEFAULT ON since 2026-07-08 (MEMRA_SPEC_LEAN=0 reverts): bit-identical (buffers fully
247 // overwritten; gates green incl maxdiff-identical run-gen) and measured +2.4% e2e p3 /
248 // +1.5% p2 at the daily 35B config. m=1 verify now costs eager-decode parity.
249 *L.get_or_init(|| {
250 std::env::var("MEMRA_SPEC_LEAN")
251 .map(|v| v != "0")
252 .unwrap_or(true)
253 })
254}
255
256/// SMALL-M BATCHED VERIFY (default ON since 2026-07-09; MEMRA_SPEC_M2=0 reverts — lane/spec-m2): extend the
257/// batched linear-attn verify arm down to t=2 and batch the MoE dev token loop over a
258/// grid.z=token axis at every verify t. The close35 m-scaling probe put the m=2 verify tier at
259/// x1.54 of m=1 (llama x1.14); the per-column linear chain (t<3) and the serial MoE dev token
260/// loop are the two launch-structure causes. Both changes are LAUNCH-STRUCTURE ONLY:
261/// (a) the batched conv's t<pad ring update is pure copies (ssm_conv_ring_rebuild from a cloned
262/// ring — the ring stores raw input columns); every arithmetic kernel is the same one the
263/// t>=3 arm already runs (matmul_decode_exact bit-identical at m=2-4, gdn_scan's internal
264/// t-loop == chained T=1 steps);
265/// (b) the MoE dev-rows twins run the serial loop's per-token warp program with tok-offset
266/// pointers (same sel/w/aq/ad bytes, same dot order, same slot-ordered FMA chain).
267/// Gates arbitrate: run-spec K=1..8 self-consistency (35B+9B), kernel-check, run-gen argmax.
268pub(crate) fn spec_m2() -> bool {
269 static M: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
270 // DEFAULT ON since 2026-07-09 (MEMRA_SPEC_M2=0 reverts): launch-structure only — t=2
271 // batched linear arm (ring-roll copies, zero new FP order) + MoE dev-rows kernels
272 // (grid.z=token, 4 launches/layer at any verify t). Acceptance bit-identical at every K;
273 // 35B p2 +3.4% / p3 +3.6%; the profitable-K plateau widens (new optimum K=3 at 223).
274 *M.get_or_init(|| {
275 std::env::var("MEMRA_SPEC_M2")
276 .map(|v| v != "0")
277 .unwrap_or(true)
278 })
279}
280pub(crate) fn spec_stream() -> bool {
281 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
282 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_STREAM").as_deref() == Ok("1"))
283}
284pub(crate) fn spec_stream_m() -> usize {
285 static M: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
286 *M.get_or_init(|| {
287 std::env::var("MEMRA_SPEC_STREAM_M")
288 .ok()
289 .and_then(|v| v.parse().ok())
290 .unwrap_or(4)
291 })
292}
293pub(crate) fn spec_devacc() -> bool {
294 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
295 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_DEVACC").as_deref() == Ok("1"))
296}
297/// Engine-bundle slice 2 (DSF-ROUNDCOST-20260820 §1.1 host/device round trips + §2 rows 2-3),
298/// DEFAULT ON (`MEMRA_DSPARK_DEFER_READBACK=0` reverts): the dspark round's draft-chain DtoH
299/// is DEFERRED past verify dispatch and merged with the verify-argmax readback into ONE host
300/// sync (2 blocking DtoH/round -> 1). Verify embeds DEVICE tokens (`chain_d`) through the
301/// resident embed table — `embed_gather_u32_t`, bit-identical rows to the host gather by its
302/// own pinned contract. The host therefore dispatches snap + the whole verify while the DRAFT
303/// is still executing, instead of blocking ~1.7 ms on the chain and letting the device drain.
304/// Ladder arm only: the confidence policies size vt from a pre-verify head readback (their
305/// chain readback merges into that same sync instead). Exactness unchanged BY CONSTRUCTION —
306/// same tokens, same kernels, same order; E2E + accept-bank gates arbitrate.
307pub(crate) fn dspark_defer_readback_on() -> bool {
308 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
309 *ON.get_or_init(|| {
310 std::env::var("MEMRA_DSPARK_DEFER_READBACK")
311 .map(|v| v != "0")
312 .unwrap_or(true)
313 })
314}
315/// Engine-bundle slice 1 (DSF-ROUNDCOST-20260820 §1.1, lane/dspark-engine-bundle-20260820),
316/// DEFAULT ON (`MEMRA_STATE_COPY_BATCH=0` reverts): batch the dspark round's GDN state
317/// snapshot and partial-accept restore into single `copy_batch_uniform_f32` launches
318/// instead of ~2 memcpy dispatches (+2 alloc_zeros on the snap side) per linear layer per
319/// round — measured 0.67 ms/round snap + 0.25 ms/round commit of pure dispatch on the q38
320/// route. Launch-structure only: bytes, buffers and stream order are unchanged, so
321/// acceptance and streams stay bit-identical (E2E-gated on the B1 packs).
322pub(crate) fn state_copy_batch_on() -> bool {
323 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
324 *ON.get_or_init(|| {
325 std::env::var("MEMRA_STATE_COPY_BATCH")
326 .map(|v| v != "0")
327 .unwrap_or(true)
328 })
329}
330/// Engine-bundle slice 3 + fa-execupdate slice 4c (DSF-ROUNDCOST-20260820 §5 rank 1),
331/// DEFAULT OFF — `MEMRA_DSPARK_VERIFY_GRAPH=1` opts in: per-(segment, vt) CUDA graphs
332/// for the LINEAR-layer runs, plus the full-verify single graph per (vt, rung) when a
333/// round's rows all ride one seqs rung — see [`DsparkVerifyGraphs`]. Requires the
334/// slice-2 deferred path (device tokens); the eager walk is the byte-identical fallback.
335///
336/// MEASURED disposition (box6 card0, agentic pack, 2026-08-20, both slices): exactness
337/// holds everywhere (ALL EXACT, accept lines byte-match the banks, ckpt-gate oracle
338/// green over the graph + slab-commit paths). Slice-3's AUTO_FREE launch-scan limiter
339/// (25.6 us x 16 launches ≈ 0.41 ms/round) is FIXED — the captured bodies' alloc nodes
340/// are balanced by in-graph frees (census 84/84 per segment, 1776/1776 full) so graphs
341/// instantiate USE_NODE_PRIORITY and the scan is gone. What remains at gate scale:
342/// segment graphs +0.1 tok/s over the batched-rows default (114.4 vs 114.3 x5
343/// interleaved — the linear launch overhead was only ~0.1 ms); the FULL-verify graph is
344/// NET NEGATIVE at gate scale (110.6 vs 114.2: ~14-21 (vt, rung) captures/process at
345/// 2 full-walk executions + ~2.9k-node instantiate each eat far more than the ~0.2-0.3
346/// ms/round of remaining launch overhead). The orchestration ceiling of §1.3 is spent —
347/// the fa/append recovery landed DEFAULT-ON as the batched rows arm
348/// (`dspark_fa_rows_on`), not as a graph. The serve-lifetime cell (DSF-ROUNDCOST §9,
349/// nj-ws-solo) measured the amortization: crossover K≈33 requests, steady −0.246
350/// ms/round, −1.25% session wall over 240 requests — and the graphs-serve lane wired
351/// the door into the session arm (`dspark_spec_session_burst`) as a model-owned
352/// capture pool shared across sessions. Stays opt-in pending the owner's default-ON
353/// ratification on the serve-surface battery.
354pub(crate) fn dspark_verify_graph_on() -> bool {
355 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
356 *ON.get_or_init(|| std::env::var("MEMRA_DSPARK_VERIFY_GRAPH").as_deref() == Ok("1"))
357}
358/// MTP-ROUTE verify graphs, DEFAULT ON for the GDN+MoE family since 2026-08-23
359/// (`MEMRA_SPEC_VERIFY_GRAPH=0` is the kill switch, `=1` opts other families in).
360///
361/// The slice-4c capture already lived inside `qwen35_verify_tparallel` and said so in its own
362/// comment — "stream rides the qwen35moe burst, graphs ride the dspark route" — with no caller
363/// on this route. The MTP spec round is that caller.
364///
365/// WHY it is worth a default (receipts: `research/orndecode-20260822/VGRAPH.md`). With
366/// `MEMRA_SPEC_PHASE=1` this route's round reads verify-ISSUE 44-58% and verify-WAIT **0.0%**:
367/// the host is never waiting for the device, it is spending its own time launching the trunk.
368/// Replay collapses that into one graph launch and the phase all but disappears (55-62 ms ->
369/// 8-10 ms per burst).
370///
371/// MEASURED, two host generations, forced ON/OFF, balanced 4+4 boots in both orders:
372/// * current-generation host (9950X, the serving class): OFF 266.0-266.5, ON 318.8-319.5
373/// tok/s — **+19.7%**, no overlap, sub-1% spread per arm; per-round 6.9 -> 5.7 ms.
374/// * Zen 3 host: +3-9% (that rig's own clock drift is wider than the effect, so the ratio
375/// comes from per-round phase totals, which are internal to each boot).
376/// The ON arm lands at ~320 tok/s on BOTH hosts while OFF tracks host speed — the arm moves
377/// the round off the host and onto the device, which is the whole point.
378///
379/// EXACTNESS is structural (same kernels, same order) and gated anyway: a fixed-seed SAMPLED
380/// completion hashes identically ON vs OFF **and across both hosts** (`08941d5bb9762b21`),
381/// greedy seed-pinned likewise, `run-spec` K=1..8 PASS on both arms with identical acceptance
382/// at every K, kernel-check ALL GREEN.
383///
384/// SCOPE, deliberately narrow: default ON only where it was measured — the GatedDeltaNet +
385/// MoE family (`vgraph_family_default`). Qwen3.8-27B is GDN + DENSE mlp and would otherwise
386/// inherit this default unmeasured, which is the family-by-family law this repo keeps; it can
387/// opt in with `=1` once it has its own interleave. Also never armed together with
388/// ROUND-STREAM, and a round wider than the pool declines it for the eager walk.
389pub(crate) fn spec_verify_graph_env() -> Option<bool> {
390 static ON: std::sync::OnceLock<Option<bool>> = std::sync::OnceLock::new();
391 *ON.get_or_init(
392 || match std::env::var("MEMRA_SPEC_VERIFY_GRAPH").as_deref() {
393 Ok("1") => Some(true),
394 Ok("0") => Some(false),
395 _ => None,
396 },
397 )
398}
399/// SERVE-ROUTE twin of [`dspark_verify_graph_on`], DEFAULT ON — owner-ratified
400/// 2026-08-22 on the §10 serve-lifetime battery (DSF-ROUNDCOST-20260820 §10.3:
401/// crossover K=36–43, steady −0.357 ms/round, session wall −1.55..−1.65%, byte-exact
402/// 240/240 ×3 pairs, pool bounded at 8,852 MiB under `MEMRA_DSPARK_VG_MAX`). The env
403/// stays as the kill-switch: `MEMRA_DSPARK_VERIFY_GRAPH=0` restores the eager walk
404/// (byte-identical body); `MEMRA_DSPARK_VG_MAX=0` is the finer freeze valve. The BIN
405/// arm keeps its own opt-in default (`dspark_verify_graph_on`): at gate scale the
406/// capture toll is never repaid (§8 measured disposition — 14–21 captures over a
407/// 256-token run vs the serve session's thousands of rounds), and the two
408/// instruments must keep their own measured dispositions rather than share one flag.
409pub(crate) fn dspark_verify_graph_serve_on() -> bool {
410 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
411 *ON.get_or_init(|| std::env::var("MEMRA_DSPARK_VERIFY_GRAPH").as_deref() != Ok("0"))
412}
413/// Capture-count ceiling for the dspark verify-graph pool (graphs-serve lane) — the
414/// pool's memory policy STATED instead of silently unbounded. The keyspace is
415/// intrinsically finite — segment keys (run_start, vt) ≤ 16 runs x 7 windows, full
416/// keys (vt, rung, hi) ≤ 7 windows x the split-rung ladder (8 rungs at 32k ctx), ~168
417/// on the q38 export — so the default (256) never engages there; the knob is the
418/// safety valve for a future export with a wider ladder. At the ceiling the pool
419/// FREEZES: existing keys keep replaying, rounds needing a new capture run the eager
420/// walk byte-identically (round-atomic — a partial refusal would mix slab- and
421/// cols-stashed layers inside one commit). No eviction by design: destroying a live
422/// exec graph re-opens the stale-address class the indirect tables exist to close,
423/// and the bounded keyspace makes reclaim worthless.
424pub(crate) fn dspark_vg_cap() -> usize {
425 static CAP: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
426 *CAP.get_or_init(|| {
427 std::env::var("MEMRA_DSPARK_VG_MAX")
428 .ok()
429 .and_then(|v| v.parse().ok())
430 .unwrap_or(256)
431 })
432}
433
434/// PROJECTED REMAINING GROWTH of the verify-graph pool, in bytes (lane/hermes-perf-fixes,
435/// 2026-08-23 — the admission accounting the "pool dwarfs spec admission reserve" finding
436/// asks for). The pool was measured at 8,852 MiB at storm-complete on the q38 export while
437/// admission's transient floor (`SPEC_SHRINK_RESERVE`) is 1.5 GiB and never charged for it:
438/// sessions admitted while the pool is cold overcommit VRAM the pool WILL hold, because the
439/// pool grows monotonically (no eviction by design) and is model-owned across sessions.
440///
441/// SELF-MEASURING, no per-model constant (generic-model law — the 8,852 MiB is a q38 number
442/// and proves nothing about another export): the debt is remaining capture slots x the
443/// MARGINAL bytes a capture adds to this device's graph mem pool.
444///
445/// MARGINAL, NOT MEAN — measured correction (box9 on-box receipt, 2026-08-23). The first
446/// version of this used the mean (`reserved / captures`) and the live serve log showed why
447/// that is wrong: with the pool's reservation flat at ~33.6 MiB across captures 1..3, the
448/// mean-based debt printed **8,556 MB, then 4,261, then 2,830** — it extrapolated capture
449/// #1's ONE-TIME shared allocation (staging buffers, stash slabs, pointer tables: sized
450/// once per pool, shared by every key) across all 256 slots. An 8.5 GB phantom reserve at
451/// boot can refuse admissions that would have fit, which is a worse defect than the
452/// under-charge this accounting exists to remove. The marginal reading prices what an
453/// ADDITIONAL key actually costs: two observations `(captures, reserved)` give
454/// `(r1 - r0) / (c1 - c0)`, which is ~0 on an export whose pool does not grow per key and
455/// tracks real growth on one that does.
456///
457/// BOOTSTRAP (only one observation so far, so growth is unmeasurable): reserve one more
458/// pool's worth — `min(remaining x mean, reserved)`. "We have measured `reserved` bytes for
459/// `captures` keys; until growth is measurable, assume at most a doubling" is fail-safe in
460/// the same direction as the old rule without the 255x extrapolation.
461///
462/// Before the FIRST capture the debt is 0 (a single capture lands well inside the existing
463/// 1.5 GiB floor). `cap` is the intrinsic freeze ceiling (`MEMRA_DSPARK_VG_MAX`; =0 freeze
464/// valve => the pool cannot grow => debt 0); at or past the cap the pool FREEZES, so the
465/// debt is 0 there too.
466pub fn dspark_vg_debt_projection(
467 captures: usize,
468 cap: usize,
469 reserved_bytes: usize,
470 prev: Option<(usize, usize)>,
471) -> usize {
472 if captures == 0 || cap == 0 {
473 return 0;
474 }
475 let remaining = cap.saturating_sub(captures);
476 if remaining == 0 {
477 return 0;
478 }
479 match prev {
480 // marginal growth between two observations of the same pool
481 Some((c0, r0)) if captures > c0 => {
482 let marginal = reserved_bytes.saturating_sub(r0) / (captures - c0);
483 remaining.saturating_mul(marginal)
484 }
485 // bootstrap: at most one more pool's worth
486 _ => remaining
487 .saturating_mul(reserved_bytes / captures)
488 .min(reserved_bytes),
489 }
490}
491/// PRE-CAPTURE VRAM RESERVE CHECK door (lane/step37-vram-admission-20260830), DEFAULT ON.
492/// A draft-graph capture attempt on a tight card used to be try-and-fail: the 2 warmup
493/// forwards + instantiate grew the pool to the edge BEFORE the OOM surfaced, and the
494/// "eager fallback" then ran on a card the failed attempt had just exhausted (the owner's
495/// single-session second-prompt OOM: capture WARN followed by 28 step-OOM engine errors,
496/// device at 5 MiB free). With the gate ON, a capture is attempted only when the device's
497/// effective free (driver free + async-pool cached) covers the capture's expected appetite
498/// PLUS a post-capture safety floor — otherwise the session falls back to eager EARLY,
499/// with headroom intact, through the same LOUD once-per-flip WARN. `=0` restores
500/// try-and-fail (diagnostics door; the trim-on-OOM recovery below stays active either way).
501pub fn spec_capture_gate_on() -> bool {
502 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
503 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_CAPTURE_GATE").as_deref() != Ok("0"))
504}
505
506/// Post-capture safety floor the reserve check keeps free ON TOP of the capture's own
507/// appetite: the same measured constant class as the admission transient floor
508/// (capture arenas + verify activations — the admit-oom control fit). A capture that
509/// would leave less than this behind is not worth its eager-coverage risk.
510pub(crate) const CAPTURE_HEADROOM_FLOOR: usize = 1536 << 20;
511
512/// Pure verdict half of the pre-capture reserve check (unit-testable): given the device's
513/// driver-free and pool-cached bytes and the capture's expected `need`, returns
514/// `Some((required, effective))` when the capture must be REFUSED, `None` when it fits.
515pub(crate) fn capture_headroom_verdict(
516 driver_free: usize,
517 pool_cached: usize,
518 need: usize,
519 floor: usize,
520) -> Option<(usize, usize)> {
521 let effective = driver_free.saturating_add(pool_cached);
522 let required = need.saturating_add(floor);
523 (effective < required).then_some((required, effective))
524}
525
526/// Expected device appetite of a draft-graph capture attempt when no measurement exists
527/// yet (bootstrap only — the model-owned high-water gauge takes over after the first
528/// observed capture). Deliberately conservative and shape-derived, never a per-family
529/// constant: per (head, mode) capture the two warmups + capture each walk one head
530/// forward whose dominant transients are a handful of `n_embd` rows and one `d_vocab`
531/// logits row, retained by the keeper; the sampled tail additionally parks
532/// `k` q-slots + perturb/q buffers of `d_vocab` each.
533pub(crate) fn draft_capture_bootstrap_estimate(
534 heads: usize,
535 k: usize,
536 d_vocab: usize,
537 n_embd: usize,
538) -> usize {
539 let per_capture = 3usize // 2 warmups + capture body, each retaining its transients
540 .saturating_mul(d_vocab.saturating_add(8 * n_embd))
541 .saturating_mul(4)
542 .max(32 << 20); // instantiate + driver-side graph backing per capture, floor
543 let captures = heads.max(1).saturating_mul(2); // interior + last per head
544 let sampled_slots = (k.saturating_add(2))
545 .saturating_mul(d_vocab)
546 .saturating_mul(4);
547 captures
548 .saturating_mul(per_capture)
549 .saturating_add(sampled_slots)
550 .max(64 << 20)
551}
552
553/// OOM predicate for capture-failure recovery (engine-side twin of the worker's
554/// `is_cuda_oom` — the same quoted-text contract).
555pub(crate) fn capture_err_is_oom(reason: &str) -> bool {
556 reason.contains("CUDA_ERROR_OUT_OF_MEMORY") || reason.contains("out of memory")
557}
558
559/// Impure half of the pre-capture reserve check: reads the device, trims the async pool
560/// when the driver alone is short but cached blocks would cover it (graph instantiate and
561/// cuBLAS workspaces allocate from the DRIVER, not from our pool — a pool sitting on freed
562/// blocks starves them), and returns the refusal reason line when the capture must not be
563/// attempted. `None` = go ahead.
564pub(crate) fn capture_headroom_refusal(e: &Engine, need: usize) -> Option<String> {
565 let Ok((driver_free, _total)) = e.ctx().mem_get_info() else {
566 return None; // unreadable device: keep the historical try-and-fail behavior
567 };
568 let pool_cached = e.pool_cached_bytes();
569 // A capture may take AT MOST HALF the discretionary headroom: required =
570 // 2x appetite + two floors (owner's contract: "fall back to eager EARLY with headroom
571 // intact"). Measured escalation on the owner-shape cells: one floor of slack let the
572 // capture walk the card to the edge and the burst step-OOM'd immediately; two floors
573 // still allowed a capture whose session then OOM'd on its own admission-charged work,
574 // because the capture had consumed the memory the charge was counting on. Requiring
575 // the appetite TWICE means the card retains a whole capture's worth of room after the
576 // capture lands - enough for the session's charged classes and its peers' bursts. The
577 // capture is an optimization worth ~2-3 ms of TTFT (draft-graph lane receipts); at the
578 // margin it is never worth an OOM incident.
579 let floor = CAPTURE_HEADROOM_FLOOR.saturating_mul(2);
580 let required_need = need.saturating_mul(2);
581 let required = required_need.saturating_add(floor);
582 match capture_headroom_verdict(driver_free, pool_cached, required_need, floor) {
583 Some((required, effective)) => Some(format!(
584 "insufficient VRAM headroom for capture: effective free {}MB (driver {}MB + pool-cached \
585 {}MB) < required {}MB (2x appetite {}MB + floor {}MB); capture skipped pre-attempt",
586 effective / (1 << 20),
587 driver_free / (1 << 20),
588 pool_cached / (1 << 20),
589 required / (1 << 20),
590 need / (1 << 20),
591 floor / (1 << 20),
592 )),
593 None => {
594 if driver_free < required && pool_cached > 0 {
595 let trimmed = e.pool_trim_to_zero();
596 if trimmed > 0 {
597 eprintln!(
598 "[spec] pre-capture pool trim: released {}MB cached back to the driver \
599 (driver free {}MB < required {}MB; instantiate allocates from the driver)",
600 trimmed / (1 << 20),
601 driver_free / (1 << 20),
602 required / (1 << 20),
603 );
604 }
605 }
606 None
607 }
608 }
609}
610
611/// GRAPH-LAUNCH HEADROOM FLOOR (lane/step37-vram-admission-20260830, defect 3 root
612/// cause): `cuGraphLaunch` SEGFAULTS inside libcuda (offset +0x27c87f, a null internal
613/// dereference at address 0x60) when a captured graph is dispatched into a
614/// driver-exhausted card — reproduced on this lane's box with core dumps on BOTH the
615/// pre-lane and lane binaries (multi-active step-OOM squeeze; the crashing thread sits in
616/// `CudaGraph::launch` inside `generate_spec_inner2`). The eager arms fail RECOVERABLY on
617/// the same card (a quoted CUDA OOM the park path handles), so below this driver-free
618/// floor every graph arm yields to eager for the round. A named constant, not a knob: the
619/// winning value is the default and the guard exists to make a driver segfault
620/// unreachable, not to tune anything.
621pub(crate) const GRAPH_LAUNCH_MIN_FREE: usize = 256 << 20;
622
623/// Per-round guard for the floor above. Read failure keeps serving (never a false
624/// refusal from an unreadable device); one `mem_get_info` (~microseconds) per ~25ms round.
625pub(crate) fn graph_launch_headroom_ok(e: &Engine) -> bool {
626 match e.ctx().mem_get_info() {
627 Ok((free, _total)) => free >= GRAPH_LAUNCH_MIN_FREE,
628 Err(_) => true,
629 }
630}
631
632/// One grep-stable suspension line per ROUTE (each call site holds its own
633/// process-lifetime `Once`): every captured-graph launch route below the floor names
634/// itself in the tag while keeping the same `graph replay suspended:` key the step37
635/// admission lane's squeeze cell greps for. The spec-round guard keeps its original
636/// per-generation `[spec]` line; the sweep routes (graph-launch-guard-sweep lane,
637/// 2026-08-31) note once per process — presence is what the gates assert, and a
638/// suspended round is otherwise byte-identical to its eager twin.
639pub(crate) fn graph_replay_suspended_note(route: &str) {
640 eprintln!(
641 "[{route}] graph replay suspended: driver free below the {}MB launch floor \
642 (eager arms serve; cuGraphLaunch segfaults into an exhausted card)",
643 GRAPH_LAUNCH_MIN_FREE / (1 << 20)
644 );
645}
646
647/// Engine-bundle slice 4 (fa-execupdate lane, DSF-ROUNDCOST-20260820 §6 close: "the
648/// residual gap lives in the FULL-ATTENTION per-row section"), DEFAULT ON —
649/// `MEMRA_DSPARK_FA_ROWS=0` reverts to the per-row loop: when every row of a verify
650/// round takes the v4-seqs arm on ONE `fa_split_keys` rung (the straddle law, evaluated
651/// at the round's first and last t_kv — both eligibility gates are intervals in t_kv),
652/// the qwen35 t-parallel verify's per-row KV-append + fa-decode loop collapses into the
653/// z-batched serving twins: ONE `append_quantize_kv_q8_0_q5_1_seqs` + ONE
654/// `fa_decode_vec_q_seqs_v4` + ONE combine per full-attention layer, replacing
655/// T x (4 dtod row copies + append + 3 memsets + main + combine) launches. Bytes are
656/// pinned by the batched-tick increment-2 kernel-check (seqs-vs-per-seq-loop bit
657/// identity: per-row T_kv derives in-kernel from pos_seq[z]; splits >= ns_eff write the
658/// empty partial the combine never reads, so the shared n_splits_max stride changes no
659/// bytes) and re-gated e2e by this lane's battery.
660pub(crate) fn dspark_fa_rows_on() -> bool {
661 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
662 *ON.get_or_init(|| {
663 std::env::var("MEMRA_DSPARK_FA_ROWS")
664 .map(|v| v != "0")
665 .unwrap_or(true)
666 })
667}
668
669/// `t_pred0` for the `MEMRA_DEBUG_SPEC` per-round print, sampled-safe.
670///
671/// `generate_spec_inner2` fills its `preds` vector ONLY on the greedy path (`if !sampled`), and
672/// the per-round debug print was the sole consumer in the sampled arm: `t_pred(0)` survives round
673/// 0 (`base == 0` returns `last_pred`) and from round 1 (`base == 1`, a pending bonus) indexes an
674/// EMPTY vector — `index out of bounds: the len is 0 but the index is 0`, in the GPU worker
675/// thread, which then respawns and reloads weights while the request dies. So any sampled spec
676/// request longer than one round used to kill the worker whenever `MEMRA_DEBUG_SPEC` was set:
677/// the flag crashed precisely the regime it exists to investigate.
678///
679/// Fixed at the print site, not inside the closure, so the greedy accept walk keeps its strict
680/// indexing (an out-of-range pred there is a real bug and must still be loud).
681fn debug_t_pred0(sampled: bool, base: usize, last_pred: u32, preds: &[u32]) -> String {
682 if base == 0 {
683 return last_pred.to_string();
684 }
685 match preds.get(base - 1) {
686 Some(p) => p.to_string(),
687 // sampled: the greedy per-column argmax was never run for this round.
688 None => {
689 debug_assert!(
690 sampled,
691 "greedy spec: preds[{}] missing at base {base}",
692 base - 1
693 );
694 "n/a".to_string()
695 }
696 }
697}
698
699/// `MEMRA_SKEY_PROBE=1` — sampled-draft-graph key probe (lane/graph-s-key-exactness-20260819).
700///
701/// Reports, per burst and per round, which draft chain the sampled arm chose and under which
702/// filter regime, plus the ONE observable that separates a legal filtered draft from a stale
703/// pure-temp graph replayed under filters: an accept test whose gathered `q` is exactly 0.
704/// A draft token sampled from the FILTERED softmax can never gather q=0 (it was drawn from the
705/// kept set), so `q=0` in the verify means the draft came from a distribution the verify does
706/// not believe in — and `u * 0 < p` then accepts it unconditionally.
707///
708/// Its own env var, deliberately NOT `MEMRA_DEBUG_SPEC`: that flag panicked the GPU worker on
709/// any sampled spec request past round 0 until this lane fixed it (§2 of the bank note).
710pub(crate) fn skey_probe() -> bool {
711 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
712 *ON.get_or_init(|| std::env::var("MEMRA_SKEY_PROBE").as_deref() == Ok("1"))
713}
714
715/// GRAMMAR HOOK for constrained spec decode (lane/constrained-full, 2026-08-03). The engine
716/// stays llguidance-agnostic: the server adapts its per-session grammar state behind this
717/// trait. CONTRACT (the verify-side truncation rule — token-identical to constrained plain
718/// greedy decode): the exactness walk runs UNMASKED first; the hook then (a) truncates
719/// acceptance at the first grammar-illegal accepted token, and (b) when the truncation fired
720/// or the bonus is illegal, the engine recomputes that slot as the MASKED argmax of the
721/// target's own verify column (an unmasked argmax that is grammar-legal IS the masked argmax
722/// — masking only removes tokens — so the common case pays nothing). `consume` advances the
723/// state with each EMITTED token in order; EOS handling is the implementor's job (skip).
724pub trait SpecConstraint {
725 /// -inf the current state's banned ids on a HOST logits row (prompt-tail / init-feed
726 /// masked argmax).
727 fn mask_logits(&mut self, logits: &mut [f32]) -> Result<(), String>;
728 /// Packed 32-bit bitset words of the CURRENT state's allowed set (device-mask form).
729 fn mask_words(&mut self) -> Result<Vec<u32>, String>;
730 /// Is `tok` consumable in the CURRENT state?
731 fn is_allowed(&mut self, tok: u32) -> Result<bool, String>;
732 /// Advance the state with an emitted token.
733 fn consume(&mut self, tok: u32) -> Result<(), String>;
734
735 // --- DRAFT-SIDE MASKING (lane/draft-mask, 2026-08-04) ---
736 // The drafter proposed grammar-illegal tokens under tight schemas, so verify-side
737 // truncation cut nearly every round (measured acceptance 0.467-0.513 tight vs 0.62-0.82
738 // loose, research/constrained-full-20260803). These three methods let the engine mask the
739 // DRAFT model's own sampling with the grammar's legal set, so proposals are legal by
740 // construction. The state they walk is a SPECULATIVE CLONE of the session matcher — the
741 // real state is advanced only by `consume` (emitted tokens), so verify-side truncation
742 // stays the correctness backstop and the emitted stream is unchanged by construction
743 // (an accepted draft is the target's unmasked argmax AND grammar-legal, hence the masked
744 // argmax; a cut slot is recomputed as the masked argmax either way).
745 // Default impls = feature OFF (pre-lane behaviour: unmasked drafts).
746
747 /// Is draft-side masking available on this hook? Probed ONCE per burst, before the draft
748 /// graph is captured (the mask is an in-graph node — its presence is a capture-time shape).
749 fn draft_mask_enabled(&self) -> bool {
750 false
751 }
752 /// Start a draft chain: clone the CURRENT (committed) grammar state into the speculative
753 /// slot. Called once per spec round, before the first draft position.
754 fn draft_begin(&mut self) -> Result<(), String> {
755 Ok(())
756 }
757 /// Packed 32-bit bitset words of the SPECULATIVE state's allowed set (target-vocab ids),
758 /// for the draft position about to be sampled. `None` = draft masking off (no-op).
759 fn draft_mask_words(&mut self) -> Result<Option<Vec<u32>>, String> {
760 Ok(None)
761 }
762 /// Advance the SPECULATIVE state with a PROPOSED draft token. `false` = the chain cannot
763 /// continue (EOS proposed, or an unmasked position proposed something illegal) — the
764 /// engine stops drafting; the token already pushed still goes through verify.
765 fn draft_advance(&mut self, _tok: u32) -> Result<bool, String> {
766 Ok(false)
767 }
768}
769
770/// DRAFT-MASK UPLOAD (lane/draft-mask): pull the speculative state's allowed set (TARGET-id
771/// space) from the hook, project it into the DRAFT head's vocab space, and upload it into the
772/// stable device buffer the draft chain reads. Returns false when the chain must stop drafting:
773/// the hook handed out no mask, or NO draft-vocab row is grammar-legal at this position (a
774/// trimmed FR-Spec head genuinely cannot propose a legal token there — masking it would leave
775/// a fully-banned row whose argmax is meaningless, so the round drafts fewer tokens and the
776/// verify emits the masked argmax as usual).
777fn upload_draft_mask(
778 e: &Engine,
779 c: &mut dyn SpecConstraint,
780 dst: &mut CudaSlice<u32>,
781 d2t: Option<&Vec<u32>>,
782 d_vocab: usize,
783 words: usize,
784) -> Result<bool, Box<dyn std::error::Error>> {
785 let Some(tw) = c
786 .draft_mask_words()
787 .map_err(|e2| format!("constraint: {e2}"))?
788 else {
789 return Ok(false);
790 };
791 let bit = |t: usize| -> bool {
792 let w = t >> 5;
793 w < tw.len() && (tw[w] >> (t & 31)) & 1 == 1
794 };
795 let mut buf = vec![0u32; words];
796 match d2t {
797 // TRIMMED draft head: row i proposes target id d2t[i] — permute the mask accordingly.
798 Some(map) => {
799 for (i, &t) in map.iter().enumerate().take(d_vocab) {
800 if bit(t as usize) {
801 buf[i >> 5] |= 1u32 << (i & 31);
802 }
803 }
804 }
805 // UNTRIMMED: draft ids ARE target ids; the packed words transfer verbatim (a short
806 // mask leaves the padded tail zeroed == banned, same rule as constrained::apply_mask).
807 None => {
808 let n = tw.len().min(words);
809 buf[..n].copy_from_slice(&tw[..n]);
810 }
811 }
812 if buf.iter().all(|w| *w == 0) {
813 return Ok(false);
814 }
815 e.htod_u32_into(dst, &buf)?;
816 Ok(true)
817}
818
819/// Keep the full token-embedding table in host memory and upload only the rows needed by each
820/// MTP/verify step. This is an exact memory-capacity seam for very large BF16 vocab tables: host
821/// gather expands the same source bits to f32, and only O(T*n_embd) bytes cross PCIe per step.
822/// CUDA-graph/round-stream draft paths require device token ids and therefore stay disabled.
823pub(crate) fn spec_host_embd() -> bool {
824 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
825 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_HOST_EMBD").as_deref() == Ok("1"))
826}
827
828/// VERIFY-TIER TRUNK LAUNCH-FUSION (default ON since 2026-07-09; MEMRA_SPEC_FUSED_T=0 reverts — lane/close35b): extend
829/// the t=1 fused2/fused3 Q8_0 trunk launches to the batched verify tier (t=2-4, the K=1..3
830/// verify shapes). At t>1 the trunk pairs/triples (35B wqkv+wqkv_gate, wq/wk/wv,
831/// gate_shexp+up_shexp) each run a separate `matmul_decode_exact` — one q8_1 re-quantize of the
832/// SAME activation plus one _b2/_b4 launch per tensor. The fused twins share ONE quantize and
833/// ONE launch per group; per (tensor,token,row) the kernel body is q8_0_mmvq_batched verbatim
834/// with the identical row mapping -> BIT-IDENTICAL by construction (kernel-check pins it,
835/// run-spec K=1..8 + acceptance identity arbitrate e2e).
836pub(crate) fn spec_fused_t() -> bool {
837 static F: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
838 // DEFAULT ON since 2026-07-09 (MEMRA_SPEC_FUSED_T=0 reverts): verify t=2-4 trunk launch-fusion
839 // (fused2/fused3 Q8_0 batched twins, bit-identical by construction — m=1 block-offset split on
840 // the batched body). m=2 marginal token 2117->1762us; 35B daily: p3 +3.7% (crosses llama), p2 +5%.
841 *F.get_or_init(|| {
842 std::env::var("MEMRA_SPEC_FUSED_T")
843 .map(|v| v != "0")
844 .unwrap_or(true)
845 })
846}
847
848/// zeros/uninit switch for verify-path buffers that are FULLY OVERWRITTEN before any read.
849/// Only call this on such buffers — the lean contract is "identical bytes by construction".
850/// TOKEN-ID GUARD for every id that reaches an embed gather (#87 family).
851///
852/// A device argmax seeds its running index with 0x7FFFFFFF and replaces it only through
853/// comparisons, all of which are FALSE against NaN. An all-NaN logits row therefore returns
854/// the sentinel, and the next thing done with a token id is `embed_row(id)` — table +
855/// ~4.6 TB, never mapped, an MMU fault that kills the CUDA context for the whole process
856/// (research/pp2spec-crash-20260807). The draft chain and the GREEDY verify walk already
857/// trap this; the SAMPLED verify bonus, the boundary sampler and the replay arm's last_pred
858/// did not, which is why the recoverable fault on the greedy instrument is a TERMINAL one on
859/// the vendor-default sampled shape we actually serve.
860pub(crate) fn guard_vocab_token(
861 tok: u32,
862 n_vocab: usize,
863 what: &str,
864) -> Result<u32, Box<dyn std::error::Error>> {
865 if (tok as usize) >= n_vocab {
866 return Err(format!(
867 "{what}: token id 0x{tok:08x} >= n_vocab {n_vocab} — an all-NaN logits row left \
868 the device argmax's init sentinel in place; refusing to dereference the embed \
869 row (#87 trap)"
870 )
871 .into());
872 }
873 Ok(tok)
874}
875
876/// SPEC NaN-ORIGIN SCAN (`MEMRA_SPEC_NAN_SCAN=1`, DEFAULT OFF, diagnostic only).
877///
878/// The `#87` trap reports an all-NaN VERIFY logits column, which says the poison reached the
879/// head but not where it entered. With the scan armed the verify walk syncs and reads back
880/// every layer's output, so the FIRST layer whose residual carries a NaN names itself with the
881/// round's row and position. Off by default and never on a serving path: it costs one host
882/// sync + one `t*n_embd` D2H per layer, and the syncs change scheduling (so a run that stops
883/// reproducing under the scan is itself a datum, not an all-clear).
884///
885/// Rollback seam: unset `MEMRA_SPEC_NAN_SCAN` (or set it to 0). Every call site is behind
886/// `spec_nan_scan()`, so the default path keeps the exact launch sequence it had.
887pub(crate) fn spec_nan_scan() -> bool {
888 spec_nan_scan_level() > 0
889}
890
891/// `MEMRA_SPEC_NAN_SCAN` as a LEVEL, not a boolean. `1` scans each layer's residual, which
892/// names the layer. `2` also scans INSIDE the t-column layer body — the per-column attention
893/// output, the deferred-column o-proj/fa2 join, the post-attention norm and the routed-MoE
894/// output — because "layer 20 poisons row 0" does not say whether the attention or the routed
895/// MoE produced it, and those are different bugs with different fixes.
896pub(crate) fn spec_nan_scan_level() -> u8 {
897 static LVL: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
898 *LVL.get_or_init(|| match std::env::var("MEMRA_SPEC_NAN_SCAN").as_deref() {
899 Ok("1") => 1,
900 Ok("2") => 2,
901 _ => 0,
902 })
903}
904
905/// Read back `[rows, cols]` and fail with the first NaN's coordinates. `what` names the
906/// producer (layer index, walk arm) so the error line is the localization.
907/// VERIFY-ARM RECEIPT (rides `MEMRA_SPEC_NAN_SCAN>=1`, bounded to 200 lines).
908///
909/// Names, per trunk layer, WHICH attention arm the t-column walk actually took. This exists
910/// because the level-1 residual scan below sat only on the non-fused tail: the fused
911/// rope+append+fa arm ends in `continue`, so every layer that fused was NEVER SCANNED and
912/// silently read as "clean". A poisoned residual therefore first reported at the next
913/// non-fused layer, which is how "layer 20 creates the poison" could be true of the scan and
914/// false of the engine. Also carries the row-table lookup counter, so "the fused path never
915/// ran" is distinguishable from "it ran and was innocent".
916/// KV-PLANE SCAN (`MEMRA_KV_PLANE_SCAN=1`, DEFAULT OFF, diagnostic only).
917///
918/// Reads back the STAGED rows of a layer's distributed K/V planes and reports the first row
919/// whose quantization scale is not finite. No kernel required: q8_0 blocks are
920/// `[half d][32 x i8]` and q5_1 blocks carry `half d` then `half m`, so the fp16 scale at the
921/// head of each block is host-checkable straight out of the byte plane.
922///
923/// It exists because the level-2 bad-row bitmap says EVERY verify row is non-finite at a
924/// global-attention layer's join, and row r attends a strict superset of row r-1's keys: that
925/// implicates the shared KV history those rows walk, not per-column staging. "The attention
926/// output is NaN" and "the KV history it attends is already NaN" are different bugs with
927/// different owners, and nothing measured so far separates them. A first-corrupt-row index
928/// also dates the corruption against the prime/decode boundary.
929///
930/// Bounded hard: only layers whose geometry has NO window (the global planes), only the first
931/// `MEMRA_KV_PLANE_SCAN_ROUNDS` verify rounds of a process (default 2), and it copies only
932/// `[0, staged_len)`, which is ~1.6 MB at the 1480-token repro rather than the 262144-row
933/// provision. It still syncs per layer, so it is never a serving or a measured-perf arm.
934pub(crate) fn kv_plane_scan_on() -> bool {
935 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
936 *ON.get_or_init(|| std::env::var("MEMRA_KV_PLANE_SCAN").as_deref() == Ok("1"))
937}
938
939fn kv_plane_scan_rounds() -> usize {
940 static R: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
941 *R.get_or_init(|| {
942 std::env::var("MEMRA_KV_PLANE_SCAN_ROUNDS")
943 .ok()
944 .and_then(|v| v.parse().ok())
945 .unwrap_or(2)
946 })
947}
948
949/// First non-finite fp16 block scale in `bytes`, as (block index, raw u16), scanning one
950/// scale every `stride` bytes. Returns None when every block scale is finite.
951fn first_bad_scale(bytes: &[u8], stride: usize) -> Option<(usize, u16)> {
952 if stride == 0 {
953 return None;
954 }
955 for (i, blk) in bytes.chunks_exact(stride).enumerate() {
956 let raw = u16::from_le_bytes([blk[0], blk[1]]);
957 if half_is_non_finite(raw) {
958 return Some((i, raw));
959 }
960 }
961 None
962}
963
964/// IEEE binary16: exponent all ones is Inf or NaN, whatever the mantissa says.
965fn half_is_non_finite(raw: u16) -> bool {
966 (raw & 0x7C00) == 0x7C00
967}
968
969/// Scan one layer's staged K/V planes for a non-finite quantization scale. Returns the
970/// receipt line, or None when the layer is out of scope or every scale is finite.
971pub(crate) fn scan_kv_plane(
972 e: &crate::Engine,
973 distributed: &memra_kv::ResidentTpKvCache,
974 il: usize,
975 pos0: usize,
976) -> Result<(), Box<dyn std::error::Error>> {
977 // One "round" is one pos0, not one layer: the walk visits 45 layers per verify. The
978 // default of 2 rounds is for a fault that shows up immediately; the step37 repro does not
979 // fire until rep 3 or later, i.e. round ~60 of the process, so that arm MUST raise
980 // MEMRA_KV_PLANE_SCAN_ROUNDS or it will scan only the two rounds that were never going to
981 // be poisoned and report a clean history it never looked at.
982 static ROUNDS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
983 static LAST_POS: std::sync::atomic::AtomicUsize =
984 std::sync::atomic::AtomicUsize::new(usize::MAX);
985 if LAST_POS.swap(pos0, std::sync::atomic::Ordering::Relaxed) != pos0 {
986 ROUNDS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
987 }
988 if ROUNDS.load(std::sync::atomic::Ordering::Relaxed) > kv_plane_scan_rounds() {
989 return Ok(());
990 }
991 let staged = distributed.staged_len();
992 if staged == 0 {
993 return Ok(());
994 }
995 // ENGAGEMENT RECEIPT. This scan prints only on corruption, so `kvbad=0` in a cell would
996 // read the same whether the history was clean or the scan never ran once. Bounded so a
997 // 45-layer walk cannot flood the log.
998 static SEEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
999 let seen = SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1000 let (ktb, vtb) = (distributed.k_tok_bytes(), distributed.v_tok_bytes());
1001 if seen < 4 {
1002 eprintln!(
1003 "[kv-plane] engaged #{seen} layer {il} pos0={pos0} staged={staged} \
1004 ktok={ktb} vtok={vtb} (scan armed; a corrupt plane prints its own line)"
1005 );
1006 }
1007 for rank in 0..distributed.ranks().len() {
1008 let Some(rc) = distributed.rank(rank) else {
1009 continue;
1010 };
1011 // q8_0 K blocks are [half d][32 x i8] = 34B; q5_1 V blocks lead with half d then half m.
1012 let kbytes = e.dtoh_u8_view(&rc.k().slice(0..staged * ktb))?;
1013 let vbytes = e.dtoh_u8_view(&rc.v().slice(0..staged * vtb))?;
1014 let kbad = first_bad_scale(&kbytes, 34);
1015 let vbad = first_bad_scale(&vbytes, 24);
1016 if kbad.is_some() || vbad.is_some() {
1017 let row = |b: Option<(usize, u16)>, tok: usize| {
1018 b.map(|(i, raw)| format!("blk {i} (row {}) raw={raw:#06x}", i * 34 / tok.max(1)))
1019 .unwrap_or_else(|| "clean".into())
1020 };
1021 eprintln!(
1022 "[kv-plane] layer {il} rank {rank} pos0={pos0} staged={staged} K={} V={} - the attended KV history is ALREADY non-finite, so a non-finite attention output here is a symptom and not the origin",
1023 row(kbad, ktb),
1024 row(vbad, vtb)
1025 );
1026 return Ok(());
1027 }
1028 }
1029 Ok(())
1030}
1031
1032pub(crate) fn verify_arm_receipt(
1033 arm: &str,
1034 il: usize,
1035 pos0: usize,
1036 t: usize,
1037 staged: Option<usize>,
1038) {
1039 static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1040 if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) >= 200 {
1041 return;
1042 }
1043 eprintln!(
1044 "[verify-arm] layer {il} arm={arm} pos0={pos0} t={t} staged_len={} rows_tab_lookups={}",
1045 staged.map(|v| v as i64).unwrap_or(-1),
1046 crate::tp::ROWS_TAB_ENGAGED.load(std::sync::atomic::Ordering::Relaxed)
1047 );
1048}
1049
1050pub(crate) fn nan_scan_rows(
1051 e: &Engine,
1052 buf: &CudaSlice<f32>,
1053 rows: usize,
1054 cols: usize,
1055 what: &str,
1056) -> Result<(), Box<dyn std::error::Error>> {
1057 // The readback is also the ATTRIBUTION point for an asynchronous fault: a
1058 // CUDA_ERROR_ILLEGAL_ADDRESS raised by any launch since the previous scan surfaces on this
1059 // sync, and the bare DriverError names nothing. Wrapping it with `what` turns "the process
1060 // died somewhere" into "it died at or before this layer, on this row, at this position".
1061 let host = e.dtoh(buf).map_err(|err| -> Box<dyn std::error::Error> {
1062 format!(
1063 "spec nan-scan: sync at {what} FAILED: {err} — the fault is at or before \
1064 this point in the walk"
1065 )
1066 .into()
1067 })?;
1068 if host.len() < rows * cols {
1069 return Err(format!(
1070 "nan-scan {what}: buffer holds {} < {rows}x{cols}",
1071 host.len()
1072 )
1073 .into());
1074 }
1075 // SCAN EVERY ROW BEFORE REPORTING. A first-hit return says "row 0 is bad" and leaves the
1076 // other rows UNEXAMINED, which is exactly the bit that discriminates the two mechanisms: in
1077 // the t-column verify, row 0 attends keys [0..p+1) and row 1 attends [0..p+2), a strict
1078 // superset, so poison in the SHARED KV history must appear in BOTH rows, while poison in
1079 // per-column staging can appear in one. Report the whole map.
1080 let mut per_row: Vec<usize> = Vec::with_capacity(rows);
1081 let mut first_bad: Option<(usize, usize)> = None;
1082 for r in 0..rows {
1083 let row = &host[r * cols..(r + 1) * cols];
1084 let bad = row.iter().filter(|v| !v.is_finite()).count();
1085 per_row.push(bad);
1086 if bad > 0 && first_bad.is_none() {
1087 first_bad = Some((r, row.iter().position(|v| !v.is_finite()).unwrap_or(0)));
1088 }
1089 }
1090 if let Some((r0, c0)) = first_bad {
1091 let map: String = per_row
1092 .iter()
1093 .map(|&b| if b == 0 { '.' } else { 'X' })
1094 .collect();
1095 return Err(format!(
1096 "spec nan-scan: {what} produced non-finite values — rows[{rows}] map={map} \
1097 counts={per_row:?} of {cols} each; first at row {r0} element {c0}. Both rows bad \
1098 implicates shared state (the KV history this layer reads); one row bad implicates \
1099 per-column staging."
1100 )
1101 .into());
1102 }
1103 Ok(())
1104}
1105
1106fn vbuf(e: &Engine, n: usize) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1107 if spec_lean() { e.uninit(n) } else { e.zeros(n) }
1108}
1109
1110/// Scratch KV for the MTP block (one full-attn layer).
1111///
1112/// PERSISTENT MODE (default, 2026-07-03 — the acceptance lever): sized cap = max_ctx and kept in
1113/// sync with the COMMITTED sequence — slot p holds the MTP block's K/V for committed token p
1114/// (roped p+1, the chain's rope convention), so the draft chain's self-attention sees the FULL
1115/// committed history instead of only the current round's 1..K+1 chain tokens (the reference
1116/// engine's "mtp_update" design). Entries come from two sources:
1117/// - chain appends: accepted positions KEEP their chain-computed entries (embedding exact,
1118/// hidden chain-approximate — the reference engine accepts the same);
1119/// - `mtp_kv_fill` batches: prompt positions + the last-draft position on full accept, computed
1120/// from EXACT trunk hiddens (K/V-only MTP-block pass, no attention/FFN/lm_head).
1121/// Rejected drafts / p-min extras / pseudo-seed appends are all discarded by the round-start
1122/// `set_len` truncation (the KvLayer len mechanism — §C rollback for the draft side).
1123/// Multi-turn spec-decode session (2026-07-05): trunk Cache + persistent MTP draft scratch +
1124/// the committed token list, alive across generate_spec_session calls. Turn N+1 primes ONLY its
1125/// suffix (chunked continuation prime over the quantized past) and mtp_kv_fill's its suffix rows,
1126/// then the round loop runs unchanged. `last_h` carries the pre-output_norm hidden of the last
1127/// committed row across turns (the predecessor-pairing seed + fill anchor).
1128/// Per-request sampling config for the sampled-spec serve path.
1129#[derive(Clone, Copy, Debug)]
1130pub struct SpecSampling {
1131 pub temp: f32,
1132 pub seed: u64,
1133 pub top_k: i32, // 0 = off
1134 pub top_p: f32, // 1.0 = off
1135 pub min_p: f32, // 0.0 = off
1136 pub penalty_last_n: usize, // 0 = penalties off
1137 pub penalty_repeat: f32,
1138 pub penalty_freq: f32,
1139 pub penalty_present: f32,
1140}
1141
1142impl SpecSampling {
1143 /// Non-identity penalties requested — THE `pen_on` predicate (one definition; the
1144 /// same group-off rule `SamplerIdentity::of` canonicalizes: a window with neutral
1145 /// coefficients is penalties-absent). Both spec routes and the dspark accept walk
1146 /// key their penalty arms off this.
1147 pub fn pen_on(&self) -> bool {
1148 self.penalty_last_n > 0
1149 && (self.penalty_repeat != 1.0
1150 || self.penalty_freq != 0.0
1151 || self.penalty_present != 0.0)
1152 }
1153}
1154
1155/// Which draft source a spec session is pinned to. The ENGINE-LEVEL half of
1156/// `DraftSourcePlan` (memra-gguf `model_plan.rs`, always general): the plan states what the
1157/// model DECLARES, this states what actually LOADED and therefore what the session runs.
1158/// Pinned at session creation for the session's lifetime.
1159///
1160/// Family-agnostic on purpose (lane/glm5-extract2, the DraftSource seam): glm5 is today's
1161/// consumer with NativeMtp | Dflash2; the hy3/qwen-next spec lanes select through the same
1162/// three-way law instead of re-deriving it. What each family still owns is the per-session
1163/// STATE behind the kind (see `dflash.rs`'s seam note for why that half is not a trait yet).
1164#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1165pub enum DraftSourceKind {
1166 /// The model's own embedded NextN/MTP head.
1167 NativeMtp,
1168 /// A separately loaded DFlash2 block-diffusion drafter
1169 /// ([`crate::dflash::DflashDrafter`]).
1170 Dflash2,
1171}
1172
1173/// The uniform draft-source selection law. Pure — no env, no engine, no family types — so it
1174/// is CPU-gateable and so every spec family answers "which source" the same way.
1175///
1176/// THE LAW, in precedence order:
1177/// 1. A LOADED DFlash2 drafter IS the source. The operator asked for it by name (a set
1178/// drafter flag that cannot load is already a loud boot failure, never a silent
1179/// fallback), and the family's embedded head is deliberately NOT loaded for this source —
1180/// it is a full trunk layer of VRAM.
1181/// 2. Otherwise the embedded head, and only when the PLAN declares an embedded source: a
1182/// loaded head under a plan that does not declare `Embedded` is a load-path bug, not a
1183/// draft source, and it is refused by name rather than drafted from.
1184/// 3. Otherwise there is no draft source and speculative decode must refuse before drafting.
1185pub fn resolve_draft_source_kind(
1186 plan: memra_gguf::model_plan::DraftSourcePlan,
1187 embedded_head_loaded: bool,
1188 dflash_loaded: bool,
1189) -> Result<DraftSourceKind, String> {
1190 use memra_gguf::model_plan::DraftSourcePlan as P;
1191 if dflash_loaded {
1192 return Ok(DraftSourceKind::Dflash2);
1193 }
1194 if embedded_head_loaded {
1195 if plan != P::Embedded {
1196 return Err(format!(
1197 "an embedded draft head is loaded but the ModelPlan declares \
1198 draft_source={plan:?} — refused rather than drafting from a head the plan \
1199 does not claim"
1200 ));
1201 }
1202 return Ok(DraftSourceKind::NativeMtp);
1203 }
1204 Err(format!(
1205 "no draft source loaded (ModelPlan declares draft_source={plan:?}): speculative \
1206 decode has nothing to draft from"
1207 ))
1208}
1209
1210#[cfg(test)]
1211mod draft_source_kind_tests {
1212 use super::{DraftSourceKind, resolve_draft_source_kind};
1213 use memra_gguf::model_plan::DraftSourcePlan as P;
1214
1215 #[test]
1216 fn a_loaded_drafter_wins_over_a_co_loaded_embedded_head() {
1217 // The operator asked for the drafter BY NAME (a set drafter flag that cannot load is
1218 // already a loud boot failure), so it takes precedence under every plan value —
1219 // including ExternalArtifact, which is what a pack declares when the draft weights
1220 // are not in the model file.
1221 for plan in [P::Embedded, P::ExternalArtifact, P::None] {
1222 assert_eq!(
1223 resolve_draft_source_kind(plan, true, true).unwrap(),
1224 DraftSourceKind::Dflash2,
1225 "plan {plan:?}: a loaded drafter must win"
1226 );
1227 assert_eq!(
1228 resolve_draft_source_kind(plan, false, true).unwrap(),
1229 DraftSourceKind::Dflash2
1230 );
1231 }
1232 }
1233
1234 #[test]
1235 fn the_embedded_head_is_the_source_only_under_a_plan_that_claims_it() {
1236 assert_eq!(
1237 resolve_draft_source_kind(P::Embedded, true, false).unwrap(),
1238 DraftSourceKind::NativeMtp
1239 );
1240 // A head loaded under a plan that does not declare Embedded is a LOAD-PATH BUG, not a
1241 // draft source. Unreachable on glm5 today (its pack hardcodes Embedded and the head
1242 // only loads under it) — which is exactly why it is pinned here: an unreachable
1243 // refusal with no arm is an untested refusal, and the next family is the one that
1244 // makes it reachable.
1245 for plan in [P::ExternalArtifact, P::None] {
1246 let err = resolve_draft_source_kind(plan, true, false)
1247 .expect_err("a head under a non-Embedded plan must refuse");
1248 assert!(err.contains("does not claim"), "{err}");
1249 assert!(err.contains(&format!("{plan:?}")), "{err}");
1250 }
1251 }
1252
1253 #[test]
1254 fn nothing_loaded_refuses_before_drafting_and_names_the_plan() {
1255 for plan in [P::Embedded, P::ExternalArtifact, P::None] {
1256 let err =
1257 resolve_draft_source_kind(plan, false, false).expect_err("no source must refuse");
1258 assert!(err.contains("no draft source loaded"), "{err}");
1259 assert!(err.contains(&format!("{plan:?}")), "{err}");
1260 }
1261 }
1262}
1263
1264/// `MEMRA_SPEC_PMIN` break semantics over per-slot draft confidences (the chain break this
1265/// module's drafting loops apply inline: `p < p_min && (j > 0 || pmin0)`): keep the longest
1266/// prefix whose every slot clears `p_min`; slot 0 survives a miss unless PMIN0 arms
1267/// zero-draft rounds. Prefix truncation is forced by the accept rule anyway (a kept slot
1268/// after a dropped one could never commit — the dspark confidence-slot argument). Pure so
1269/// the rule is CPU-gateable; the SHARED K-policy surface every spec family consumes
1270/// (hoisted from the glm5 loop, lane/glm5-extract-general).
1271pub fn spec_conf_keep(q: &[f32], p_min: f32, pmin0: bool) -> usize {
1272 if p_min <= 0.0 {
1273 return q.len();
1274 }
1275 let mut kept = 0usize;
1276 for (j, &qj) in q.iter().enumerate() {
1277 if qj < p_min && (j > 0 || pmin0) {
1278 break;
1279 }
1280 kept += 1;
1281 }
1282 kept
1283}
1284
1285/// Host Philox4x32-10 uniform in (0,1) — mirrors spec_sample.cu's `philox4`/`u01` with the
1286/// ctr_lo tag 0xFFFF_FFFE, so the host accept-test stream never collides with any device
1287/// sampling event (device Gumbel uses (i>>2, stream_pos); device residual uses 0xFFFF_FFFD).
1288/// One value per (seed, ctr) EVENT; callers own the counter discipline. Extracted verbatim
1289/// from generate_spec_inner2's closure for the dspark sampled-admission walk (the two paths
1290/// MUST consume the identical stream construction — two ad-hoc Philox copies drifting apart
1291/// is a distributional bug, not a style problem).
1292pub(crate) fn host_u01(seed: u64, ctr: u32) -> f32 {
1293 let (m0, m1) = (0xD2511F53u32, 0xCD9E8D57u32);
1294 let (mut c0, mut c1, mut c2, mut c3) = (0xFFFF_FFFEu32, ctr, 0u32, 0u32);
1295 let (mut k0, mut k1) = ((seed & 0xFFFF_FFFF) as u32, (seed >> 32) as u32);
1296 for _ in 0..10 {
1297 let (h0, l0) = (((m0 as u64 * c0 as u64) >> 32) as u32, m0.wrapping_mul(c0));
1298 let (h1, l1) = (((m1 as u64 * c2 as u64) >> 32) as u32, m1.wrapping_mul(c2));
1299 let (n0, n1, n2, n3) = (h1 ^ c1 ^ k0, l1, h0 ^ c3 ^ k1, l0);
1300 c0 = n0;
1301 c1 = n1;
1302 c2 = n2;
1303 c3 = n3;
1304 k0 = k0.wrapping_add(0x9E3779B9);
1305 k1 = k1.wrapping_add(0xBB67AE85);
1306 }
1307 (c0 as f32 + 1.0) * (1.0 / 4294967296.0)
1308}
1309
1310/// Tracked draft positions for [`SpecTelemetry`] (serve K defaults to 3; the run-spec gate
1311/// sweeps K=1..8, and MEMRA_SPEC_CAPMAX defaults to 7 — 8 covers every tuned config).
1312pub const SPEC_TELEM_POS: usize = 8;
1313
1314/// Always-on per-draft-position acceptance telemetry (lane/accept-telemetry, 2026-08-05 —
1315/// the llama.cpp #26389 / vLLM spec-decode counter schema, upstream-sweeps 2026-08-05).
1316/// Lives on the [`SpecSession`] and accumulates across bursts; the serve worker diffs a
1317/// stashed copy per burst for its per-model /metrics aggregation and per-request usage.
1318/// Same normalization as the `[spec-stats]` line: p-min-discarded chain tokens are counted
1319/// in NEITHER drafted nor accepted.
1320#[derive(Clone, Copy, Default, Debug)]
1321pub struct SpecTelemetry {
1322 /// verify rounds completed (a round-stream burst counts each of its M rounds).
1323 pub rounds: u64,
1324 /// tokens drafted / accepted across all rounds.
1325 pub drafted: u64,
1326 pub accepted: u64,
1327 /// how often draft position j (0-based within a round's chain) was offered / accepted.
1328 /// Positions >= SPEC_TELEM_POS are untracked (totals still count them). The opt-in
1329 /// round-stream arm (MEMRA_SPEC_STREAM=1) reads back only totals, so under it these
1330 /// arrays cover the standard-path rounds only and their sums may undercount the totals.
1331 pub pos_drafted: [u64; SPEC_TELEM_POS],
1332 pub pos_accepted: [u64; SPEC_TELEM_POS],
1333}
1334
1335impl SpecTelemetry {
1336 /// Fieldwise `self - prev` — the worker's per-burst delta off a copy stashed before the
1337 /// burst call. Saturating: a caller diffing against the wrong snapshot gets zeros, not
1338 /// a wrapped counter.
1339 pub fn delta_since(&self, prev: &SpecTelemetry) -> SpecTelemetry {
1340 let mut d = SpecTelemetry {
1341 rounds: self.rounds.saturating_sub(prev.rounds),
1342 drafted: self.drafted.saturating_sub(prev.drafted),
1343 accepted: self.accepted.saturating_sub(prev.accepted),
1344 ..Default::default()
1345 };
1346 for j in 0..SPEC_TELEM_POS {
1347 d.pos_drafted[j] = self.pos_drafted[j].saturating_sub(prev.pos_drafted[j]);
1348 d.pos_accepted[j] = self.pos_accepted[j].saturating_sub(prev.pos_accepted[j]);
1349 }
1350 d
1351 }
1352 /// Fieldwise `self += d` — the worker's per-model aggregation.
1353 pub fn merge(&mut self, d: &SpecTelemetry) {
1354 self.rounds += d.rounds;
1355 self.drafted += d.drafted;
1356 self.accepted += d.accepted;
1357 for j in 0..SPEC_TELEM_POS {
1358 self.pos_drafted[j] += d.pos_drafted[j];
1359 self.pos_accepted[j] += d.pos_accepted[j];
1360 }
1361 }
1362
1363 /// Mean accepted draft-prefix length per verify round (tau).
1364 pub fn tau(&self) -> f64 {
1365 if self.rounds > 0 {
1366 self.accepted as f64 / self.rounds as f64
1367 } else {
1368 0.0
1369 }
1370 }
1371}
1372
1373/// Session-lifetime atomic acceptance counters. The verifier records only after the greedy or
1374/// rejection-sampling walk has resolved on the host, so these relaxed increments add no GPU
1375/// launch, synchronization, allocation, or ordering dependency to the numeric path.
1376struct SpecTelemetryCounters {
1377 rounds: AtomicU64,
1378 drafted: AtomicU64,
1379 accepted: AtomicU64,
1380 pos_drafted: [AtomicU64; SPEC_TELEM_POS],
1381 pos_accepted: [AtomicU64; SPEC_TELEM_POS],
1382}
1383
1384impl Default for SpecTelemetryCounters {
1385 fn default() -> Self {
1386 Self {
1387 rounds: AtomicU64::new(0),
1388 drafted: AtomicU64::new(0),
1389 accepted: AtomicU64::new(0),
1390 pos_drafted: std::array::from_fn(|_| AtomicU64::new(0)),
1391 pos_accepted: std::array::from_fn(|_| AtomicU64::new(0)),
1392 }
1393 }
1394}
1395
1396impl SpecTelemetryCounters {
1397 fn record_round(&self, drafted: usize, accepted: usize) {
1398 debug_assert!(accepted <= drafted);
1399 self.rounds.fetch_add(1, Ordering::Relaxed);
1400 self.drafted.fetch_add(drafted as u64, Ordering::Relaxed);
1401 self.accepted.fetch_add(accepted as u64, Ordering::Relaxed);
1402 for counter in self.pos_drafted.iter().take(drafted) {
1403 counter.fetch_add(1, Ordering::Relaxed);
1404 }
1405 for counter in self.pos_accepted.iter().take(accepted) {
1406 counter.fetch_add(1, Ordering::Relaxed);
1407 }
1408 }
1409
1410 /// Round-stream keeps each round's accept length on device; retain exact scalar totals while
1411 /// leaving the per-position arrays untouched, matching the pre-existing telemetry contract.
1412 fn record_totals(&self, rounds: usize, drafted: usize, accepted: usize) {
1413 self.rounds.fetch_add(rounds as u64, Ordering::Relaxed);
1414 self.drafted.fetch_add(drafted as u64, Ordering::Relaxed);
1415 self.accepted.fetch_add(accepted as u64, Ordering::Relaxed);
1416 }
1417
1418 fn snapshot(&self) -> SpecTelemetry {
1419 SpecTelemetry {
1420 rounds: self.rounds.load(Ordering::Relaxed),
1421 drafted: self.drafted.load(Ordering::Relaxed),
1422 accepted: self.accepted.load(Ordering::Relaxed),
1423 pos_drafted: std::array::from_fn(|j| self.pos_drafted[j].load(Ordering::Relaxed)),
1424 pos_accepted: std::array::from_fn(|j| self.pos_accepted[j].load(Ordering::Relaxed)),
1425 }
1426 }
1427}
1428
1429pub struct SpecSession {
1430 pub(crate) cache: Cache,
1431 pub(crate) scratch: MtpScratch,
1432 /// Every token whose state the caches hold, in order (prompt turns + generated), INCLUDING
1433 /// overshoot: spec commits accepted drafts past max_new; those rows are in the caches, so the
1434 /// session must count them. Callers render output from this, not from their own echo.
1435 pub committed: Vec<u32>,
1436 /// Pre-output_norm hidden of the LAST committed row (device). None before the first turn.
1437 pub(crate) last_h: Option<CudaSlice<f32>>,
1438 /// Greedy argmax predicting the token AFTER committed.last() (from the last turn's final
1439 /// logits). Fuels empty-suffix continuation bursts (serve): the next turn emits this token
1440 /// first, feeds it, and the round loop resumes without any prime. None before the first turn.
1441 pub next_pred: Option<u32>,
1442 /// SAMPLED-SPEC stream continuity across bursts: Philox event counters persist here so a
1443 /// session's randomness never repeats between generate_spec_session calls. (0,0) at admit.
1444 pub sctr: u32,
1445 pub uctr: u32,
1446 /// PERSISTENT DRAFT-GRAPH CONTEXT (2026-08-01, the serve-burst fixed-cost fix): the captured
1447 /// draft graph(s) + every device I/O buffer they bake, carried ACROSS generate_spec_session
1448 /// calls. Before this, every serve burst re-captured the draft graph (2 warmup forwards +
1449 /// instantiate) — measured ~16ms/burst on H100 q27 (MEMRA_SPEC_BURST sweep,
1450 /// research/spec-serving-20260801). None before the first turn; error paths drop it
1451 /// (next burst recaptures — serve retires errored sessions anyway).
1452 pub(crate) draft_ctx: Option<DraftGraphCtx>,
1453 /// PENDING-CARRY across bursts (2026-08-01, the serve burst-boundary fix): the bonus token
1454 /// emitted by the last round but NOT committed to the caches. The old tail committed it with
1455 /// a solo T=1 trunk pass (+ draft fill), and the next burst's setup fed the stashed next_pred
1456 /// with ANOTHER solo pass — 2x ~11.5ms/burst measured on H100 q27 ([spec-setup] trace).
1457 /// Carrying it lets the next empty-suffix greedy burst consume it as round-0 verify col 0,
1458 /// exactly like a mid-burst full-accept boundary (no solo passes). INVARIANT: when set,
1459 /// `committed` (== cache rows) EXCLUDES this token although it was already emitted in the
1460 /// last burst's output, and `last_h` holds the hidden of the last COMMITTED row (its
1461 /// predecessor — the chain-seed/fill anchor). `next_pred` is None (unknown without the
1462 /// commit pass). Non-empty-suffix or sampled turns must flush first (spec_flush_pending);
1463 /// generate_spec_session_sampled does this at entry, and serve parks only flushed sessions.
1464 pub pending_tok: Option<u32>,
1465 /// SESSION-AFFINITY TURN CHECKPOINT (lane/session-affinity, 2026-08-05): the state at this
1466 /// turn's PROMPT-END boundary, retained so a later turn can REWIND here. See
1467 /// [`SpecCheckpoint`]. Refreshed by every non-empty prime; None until the first one, and on
1468 /// a rig too tight to hold it (a failed capture is silent — resume just isn't available).
1469 pub(crate) turn_ckpt: Option<SpecCheckpoint>,
1470 /// Session-lifetime acceptance telemetry. Relaxed atomics update at the host-side round
1471 /// accounting the loop already does — no syncs, no allocation. NOTE a
1472 /// pool-resumed session carries the PREVIOUS requests' counts; per-request consumers
1473 /// diff with [`SpecTelemetry::delta_since`] around each burst.
1474 telem: SpecTelemetryCounters,
1475 /// PREFIX-CACHE publication request (lane/spec-prefix-cache): worker sets this to the
1476 /// miss-LCP boundary before a cold burst; the prime captures at exactly that split (it must
1477 /// coincide with the burst's `prime_split` or no capture happens). One-shot: consumed by the
1478 /// prime, result lands in `boundary_captures`.
1479 pub capture_at: Option<usize>,
1480 /// The captures the last prime produced (see [`SpecBoundaryCapture`]). Worker drains them
1481 /// post-burst to assemble prefix entries. A failed capture is silent, like `turn_ckpt` —
1482 /// publication just isn't available for that request. Plural since
1483 /// lane/frspec-multiturn-cache (2026-08-21): a cold burst can capture BOTH the miss-LCP
1484 /// split (the shared-prefix class) and the stable pre-generation boundary (the
1485 /// next-turn re-render class) — one entry per stop, exactly the boundary set the plain
1486 /// prefill tick publishes/checkpoints.
1487 pub boundary_captures: Vec<SpecBoundaryCapture>,
1488 /// STABLE-BOUNDARY TURN CHECKPOINT REQUEST (lane/frspec-multiturn-cache, 2026-08-21): the
1489 /// ABSOLUTE committed-length position the next non-empty prime should capture `turn_ckpt`
1490 /// at, instead of prompt-end. The worker sets it to the STABLE PRE-GENERATION boundary
1491 /// (`plain_checkpoint_boundary` — before the live generation header the client rewrites),
1492 /// porting the 2026-08-09 plain-tier fix: a prompt-end spec checkpoint includes the
1493 /// template's live assistant-generation header (`<|im_start|>assistant\n<think>\n`), which
1494 /// the NEXT turn's re-render replaces, so `affinity_match` diverged a couple tokens below
1495 /// the checkpoint and the spec pool declined 100% of multi-turn agent traffic (measured:
1496 /// `spec-affinity: declined (history diverged at 6811 of checkpoint 6813)`,
1497 /// research/multiturn-cache-20260821 B4). One-shot, `capture_at` convention; None = legacy
1498 /// prompt-end capture.
1499 pub ckpt_at: Option<usize>,
1500 /// FAIL-SAFE (lane/step37-vram-admission-20260830, external-review corroboration): set
1501 /// by the worker on a session serving a step-OOM park REPLAY. The burst entry pre-marks
1502 /// the draft-graph fallback so the replay never re-enters the capture path — the capture
1503 /// appetite is part of what drove the card to the OOM, and a replay that recaptures
1504 /// re-runs the incident. If the eager replay still cannot fit, the bounded retry budget
1505 /// exhausts into the honest recoverable Overloaded error instead of looping.
1506 pub capture_disabled: bool,
1507}
1508impl SpecSession {
1509 /// Context capacity of the session's caches (the server's ContextFull guard).
1510 pub fn cache_max_ctx(&self) -> usize {
1511 self.cache.max_ctx
1512 }
1513 /// Read access to the live trunk cache (lane/spec-prefix-cache): the worker slices
1514 /// full-attn KV rows `[0..capture.pos)` out of it when publishing a boundary capture —
1515 /// those rows are append-only for the session's lifetime (rollbacks never truncate below
1516 /// the prime boundary), so no copy was taken at prime time.
1517 pub fn cache_ref(&self) -> &Cache {
1518 &self.cache
1519 }
1520 /// Read access to the persistent draft-scratch plane (lane/spec-on-cache-hit): the
1521 /// worker slices rows `[0..capture.pos)` when publishing a boundary capture, exactly
1522 /// like the trunk KV — draft rows below the prompt end are append-only for the
1523 /// session's lifetime (the prime fill wrote them once; rollbacks reset `len_d` to the
1524 /// committed length, never below the prime boundary, and the true-hidden refresh
1525 /// rewrites generated positions only). Returns `(k, v, k_tok_bytes, v_tok_bytes)`.
1526 /// None when the scratch is ring-backed (Step35 SWA — physical rows are not
1527 /// prefix-addressable; the prefix cache already refuses that class end to end).
1528 pub fn draft_plane_ref(&self) -> Option<(&CudaSlice<u8>, &CudaSlice<u8>, usize, usize)> {
1529 if self.scratch.kv.ring.is_some() {
1530 return None;
1531 }
1532 Some((
1533 &self.scratch.kv.k,
1534 &self.scratch.kv.v,
1535 self.scratch.kv.k_tok_bytes,
1536 self.scratch.kv.v_tok_bytes,
1537 ))
1538 }
1539 /// Snapshot the session's process-local acceptance counters for per-burst diffing.
1540 pub fn telemetry(&self) -> SpecTelemetry {
1541 self.telem.snapshot()
1542 }
1543 /// Committed position this session can REWIND to (its retained prompt-end boundary), if any.
1544 /// A request whose prompt matches `committed[..pos]` exactly can resume from here — see
1545 /// `spec_rewind_to_checkpoint`.
1546 pub fn rewind_pos(&self) -> Option<usize> {
1547 self.turn_ckpt.as_ref().map(|c| c.pos)
1548 }
1549 /// Whether every ring-backed trunk/draft row needed by the retained checkpoint is resident.
1550 pub fn rewind_is_resident(&self) -> bool {
1551 self.turn_ckpt.as_ref().is_some_and(|ckpt| {
1552 self.cache.can_rollback(&ckpt.snap, 0) && self.scratch.can_rewind_to(ckpt.pos)
1553 })
1554 }
1555 /// Is this session in the DEMOTION-READY shape (see [`SpecSession::into_demoted`])?
1556 /// `false` means a carried pending must be flushed first (`spec_flush_pending`), or the
1557 /// session has never run a turn and has no prediction to hand over.
1558 pub fn demote_ready(&self) -> bool {
1559 self.pending_tok.is_none() && self.next_pred.is_some()
1560 }
1561 /// Does this session hold a carried pending bonus (flush required before a handoff/park)?
1562 pub fn has_pending(&self) -> bool {
1563 self.pending_tok.is_some()
1564 }
1565 /// Committed row count == cache rows (the session invariant), for the caller's own
1566 /// `fed`-length cross-check at a handoff boundary.
1567 pub fn committed_len(&self) -> usize {
1568 self.committed.len()
1569 }
1570 /// DEMOTION HANDOFF (lane/spec-gate, 2026-08-07): consume this session and hand its trunk
1571 /// cache + next-token prediction to the plain batched-decode path.
1572 ///
1573 /// WHY THIS IS EXACT (greedy). The invariant at a burst boundary is `cache.pos ==
1574 /// committed.len()`: every committed row has trunk KV + recurrent state, exactly as a plain
1575 /// tokenwise prime of the same `committed` sequence would have left it (that is the
1576 /// session-tail contract, and the same property `spec_rewind_to_checkpoint` and the reuse
1577 /// pool already rely on). `next_pred` is the argmax of the verify's logits for the LAST
1578 /// committed row — and verify-column logits are bit-identical to plain decode's logits at
1579 /// that position, because `matmul_decode_exact` bit-identity IS the basis of the greedy
1580 /// accept walk. So handing (cache, next_pred) to the batched path continues the stream from
1581 /// a state indistinguishable from one the batched path produced itself: the batched tick
1582 /// emits `next_pred`, feeds it into this same cache, and decodes on.
1583 ///
1584 /// `None` when the session is not in the handoff shape — a carried pending (its bonus row is
1585 /// NOT in the cache, so `spec_flush_pending` must commit it first) or no `next_pred` yet
1586 /// (never bursted). Callers must not force it: a half-committed cache handed to the batched
1587 /// path would silently skip a token.
1588 ///
1589 /// The MTP draft scratch, the persistent draft-graph context and the turn checkpoint are
1590 /// DROPPED here (freeing their VRAM): the batched path never drafts, and this handoff is
1591 /// one-way by design — there is no cheap symmetric re-promotion (rebuilding the draft KV
1592 /// would mean an `mtp_kv_fill` over the whole committed history).
1593 pub fn into_demoted(self) -> Option<(Cache, u32)> {
1594 if self.pending_tok.is_some() || self.cache.tainted {
1595 return None;
1596 }
1597 let np = self.next_pred?;
1598 debug_assert_eq!(
1599 self.cache.pos,
1600 self.committed.len(),
1601 "demotion handoff: cache rows != committed tokens"
1602 );
1603 Some((self.cache, np))
1604 }
1605 /// Pool-resume hook (audit Q2): clear the parked draft-graph failure memoization so a
1606 /// NEW request resuming this session gets one fresh capture chance — a transient-pressure
1607 /// capture failure must not persist for the pool's whole lifetime (the TRT #16072 class).
1608 /// Logs once iff a flag was actually set; a no-fallback resume is silent and free.
1609 pub fn reset_graph_fallback_on_resume(&mut self) {
1610 if let Some(line) = self
1611 .draft_ctx
1612 .as_mut()
1613 .and_then(|c| c.failed.reset_on_resume())
1614 {
1615 eprintln!("{line}");
1616 }
1617 }
1618}
1619
1620/// A session's PROMPT-END boundary state, the rewind target for session-affinity resume.
1621///
1622/// WHY THIS BOUNDARY, AND WHY IT IS THE ONLY ONE WORTH KEEPING. The rewrite class this lane
1623/// exists for (a client that strips `<think>` blocks out of prior assistant turns) mutates the
1624/// text the session GENERATED, never the prompt it was given. So turn N's prompt agrees with
1625/// turn N-1's committed tokens up to almost exactly where turn N-1's generation began — the
1626/// prompt-end boundary. Keeping a checkpoint there means the next turn re-primes only its own
1627/// delta (the rewritten answer + the new user turn) instead of the whole conversation.
1628///
1629/// WHAT IT MUST HOLD. Full-attn KV is append-only and position-addressed, so rewinding it is a
1630/// `len` truncation (no data). Linear-attn (GDN) conv/ssm state is mutated IN PLACE with no
1631/// position index, so it must be a real device COPY — that copy is the entire reason a spec
1632/// session could not previously rewind. The MTP draft scratch needs no copy either: its rows
1633/// below the boundary were written by this turn's fill and are never revisited (the per-round
1634/// true-hidden refresh only rewrites the CURRENT burst's committed positions), so rewinding it
1635/// is also just a `len` reset. `last_h` is the hidden of the last row below the boundary — the
1636/// predecessor-pairing anchor the next prime's fill reads for its first row.
1637///
1638/// COST: one `Cache::snapshot` per TURN, on a code path that already takes one per ROUND.
1639pub(crate) struct SpecCheckpoint {
1640 snap: crate::cache::CacheSnapshot,
1641 /// Committed length at the boundary (== cache.pos there, the session invariant).
1642 pos: usize,
1643 /// Pre-output_norm hidden of row `pos - 1`.
1644 last_h: CudaSlice<f32>,
1645}
1646
1647/// PREFIX-CACHE BOUNDARY CAPTURE (lane/spec-prefix-cache, 2026-08-14): the state a spec session
1648/// records at its cold-prime split so the WORKER can publish a cross-request prefix entry —
1649/// the commit-gated-publication port (research/cache-spec-design-20260814/PORT-PLAN.md item 1).
1650/// Only the pieces that are DESTROYED by continuing the prime need copies here: the in-place
1651/// GDN conv/ssm states (via `Cache::snapshot`, same mechanism as [`SpecCheckpoint`]) and the
1652/// boundary logits. Full-attn KV rows `[0..pos)` and draft-scratch rows `[0..pos)` are
1653/// append-only for the session's lifetime (rollbacks never truncate below the prime boundary),
1654/// so the worker slices those from the live caches post-burst instead of copying at prime time.
1655pub struct SpecBoundaryCapture {
1656 pub snap: crate::cache::CacheSnapshot,
1657 /// Token boundary (== cache.pos at capture; == the worker's miss-LCP split).
1658 pub pos: usize,
1659 /// Full-vocab logits after the prefix prime — the entry's boundary logits.
1660 pub logits: Vec<f32>,
1661 /// Pre-output_norm trunk hidden of row `pos - 1` (lane/spec-on-cache-hit): the
1662 /// predecessor-pairing anchor a RESTORED spec session's first suffix-fill row reads
1663 /// (the `SpecSession::last_h` convention). Empty = unavailable (capture stays valid;
1664 /// the fill's zeros row-0 fallback covers it at a bounded acceptance cost).
1665 pub last_h: Vec<f32>,
1666 /// Per-layer latent boundary tails (lane/glm5-prefix-latent2, 2026-09-01): the
1667 /// generation-destroyed slice of each MLA/DSA layer's boundary state, captured eagerly
1668 /// so the worker's DEFERRED publication can slice the append-only planes from the live
1669 /// cache (`LatentKvLayer::snapshot_plane_at`). EMPTY on every two-plane model — the
1670 /// pre-field captures are byte-identical; a latent-bearing cache with an EMPTY vec here
1671 /// keeps the publisher's loud refusal (the fail-closed door stays shut).
1672 pub latent_tails: Vec<Option<crate::cache::LatentTailCapture>>,
1673}
1674
1675/// D2H one hidden row out of a `[T, n_embd]` prime hidden stack — the boundary anchor a
1676/// spec boundary capture carries for later restored-session fills. Failure is silent
1677/// (`turn_ckpt` convention): the capture publishes without an anchor.
1678pub(crate) fn capture_boundary_hidden(
1679 e: &Engine,
1680 h_rows: &CudaSlice<f32>,
1681 pos: usize,
1682 n_embd: usize,
1683) -> Vec<f32> {
1684 if pos == 0 || h_rows.len() < pos * n_embd {
1685 return Vec::new();
1686 }
1687 let Ok(mut row) = e.uninit(n_embd) else {
1688 return Vec::new();
1689 };
1690 if e.copy_view_into(
1691 &mut row,
1692 0,
1693 &h_rows.slice((pos - 1) * n_embd..pos * n_embd),
1694 n_embd,
1695 )
1696 .is_err()
1697 {
1698 return Vec::new();
1699 }
1700 e.dtoh(&row).unwrap_or_default()
1701}
1702
1703/// ROLLBACK DOOR for sampled BOUNDARY tokens (lane/sampled-spec-quality, 2026-08-19).
1704/// Default ON: the token a burst emits at its own boundary is drawn from the request's
1705/// sampler. `MEMRA_SPEC_SAMPLED_BOUNDARY=0` restores the pre-lane posture (an ARGMAX at
1706/// every boundary) without touching greedy, which is byte-unaffected either way.
1707pub fn spec_sampled_boundary_on() -> bool {
1708 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1709 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_SAMPLED_BOUNDARY").as_deref() != Ok("0"))
1710}
1711
1712/// ROLLBACK DOOR for SESSION-SPANNING penalty history (lane/sampled-spec-quality).
1713/// Default ON: `pen_hist` is seeded from the session's committed tail, so repetition /
1714/// frequency / presence penalties see the whole stream. `MEMRA_SPEC_PEN_SESSION=0`
1715/// restores the pre-lane posture (each burst restarts the window from its own prompt
1716/// slice, i.e. from NOTHING on a continuation burst) — and with the door shut the worker
1717/// must keep refusing penalized sampled prefix-cache restores, because the restored
1718/// session's continuation burst is handed no prompt slice at all.
1719pub fn spec_pen_session_on() -> bool {
1720 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1721 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_PEN_SESSION").as_deref() != Ok("0"))
1722}
1723
1724/// ROLLBACK DOOR for extended-entry publication from a RESTORED session
1725/// (lane/sampled-spec-quality, Item 3). Default ON: a converted prefix-cache hit that fed a
1726/// suffix captures its own prompt-end boundary so the NEXT turn can hit a longer prefix.
1727/// `MEMRA_SPEC_RESTORE_REPUBLISH=0` restores the pre-lane posture (a namespace learns exactly
1728/// one boundary and never advances it). Whole-entry semantics only — the boundary is the
1729/// restored session's own prompt end, so `entry_pos != fed_len` still refuses on the way in.
1730pub fn spec_restore_republish_on() -> bool {
1731 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1732 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_RESTORE_REPUBLISH").as_deref() != Ok("0"))
1733}
1734
1735/// Diagnostics: name every boundary token on stderr (`MEMRA_SPEC_BOUNDARY_TRACE=1`), with
1736/// the argmax the pre-lane code would have emitted from the same row. This is how the
1737/// lane MEASURES the boundary rate and the deviation rate instead of estimating them.
1738fn spec_boundary_trace() -> bool {
1739 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1740 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_BOUNDARY_TRACE").as_deref() == Ok("1"))
1741}
1742
1743/// llama-parity floor for the penalty window when the request does not ask for a bigger
1744/// one (`repeat_last_n` default). The serve API arms `penalty_last_n = PEN_WINDOW_MAX` for any
1745/// non-identity penalty, so this floor only matters to explicit small windows and to the
1746/// CLI env path.
1747const PEN_WINDOW_FLOOR: usize = 64;
1748
1749/// CEILING on the penalty window, and it is a COST bound, not a semantic preference.
1750/// `penalize_logits_f32` (cu/spec_sample.cu) dedups on device by having thread `i` scan
1751/// `hist[0..i]`, so a pass is O(n_hist²) and it runs ~3x per verify round (the q rows, the
1752/// p column, the bonus column). The serve API uses this same bound for every non-identity
1753/// penalty so host/plain, sparse-device, and speculative sampling cannot change logits on
1754/// admission demotion. An uncapped 128k-token history would put ~1.7e10
1755/// comparisons per pass, tens of ms per round, i.e. penalties would silently destroy decode
1756/// throughput on exactly the long-context requests that most want them. 8192 keeps a pass
1757/// at ~7e7 comparisons (tens of microseconds) while still being **128x wider than the
1758/// pre-lane effective window** (64 prompt-tail tokens + whatever the current burst had
1759/// generated). A request that genuinely needs a window beyond this wants host-side dedup +
1760/// counts through a new kernel signature — a follow-up lane, named here rather than hidden.
1761/// `pub` since lane/dspark-penalized-sampled-20260821: the dspark route's accept walk and
1762/// the dspark_sample_gate binary trim their uploads with the SAME cap — a second constant
1763/// is a second thing to drift.
1764pub const PEN_WINDOW_MAX: usize = 8192;
1765
1766/// Seed a penalty window over the SESSION, not the burst (lane/sampled-spec-quality,
1767/// Item 2). The window is the last `max(penalty_last_n, 64)` tokens of
1768/// `session_committed ++ burst_prompt` — for a cold turn-1 burst (`session_committed`
1769/// empty, default `penalty_last_n`) that is byte-identically the pre-lane
1770/// `prompt.iter().rev().take(64).rev()`; for a continuation burst it is the stream the
1771/// client actually asked us to penalize, where the pre-lane code had NOTHING.
1772/// `pub` since lane/dspark-penalized-sampled-20260821: the dspark route seeds its session
1773/// window through the SAME function (one definition of "the window" across both spec
1774/// routes and the gate binary's trunk-only reference arm).
1775pub fn pen_window_seed(
1776 session_committed: &[u32],
1777 burst_prompt: &[u32],
1778 penalty_last_n: usize,
1779) -> Vec<u32> {
1780 let win = penalty_last_n.clamp(PEN_WINDOW_FLOOR, PEN_WINDOW_MAX);
1781 let take_prompt = burst_prompt.len().min(win);
1782 let take_sess = (win - take_prompt).min(session_committed.len());
1783 let mut hist = Vec::with_capacity(take_sess + take_prompt);
1784 hist.extend_from_slice(&session_committed[session_committed.len() - take_sess..]);
1785 hist.extend_from_slice(&burst_prompt[burst_prompt.len() - take_prompt..]);
1786 hist
1787}
1788
1789/// Draw a BOUNDARY token from the target distribution the request asked for
1790/// (lane/sampled-spec-quality, Item 1) — the fix for "sampled spec emits an ARGMAX token at
1791/// every burst boundary".
1792///
1793/// WHY THIS EXISTS. A spec burst's first emitted token is not produced by the accept walk:
1794/// it comes off a logits row that already exists (the prime's last row on a cold burst; the
1795/// row after the last committed token on a continuation burst; the prefix-cache entry's
1796/// boundary row on a restored one). Pre-lane that token was `argmax` in BOTH sampling
1797/// regimes, so a sampled stream took a greedy token once per burst — measured, not
1798/// estimated, in research/spec-cache-20260818/SAMPLED-QUALITY.md. At temperature > 0 the
1799/// customer asked for a sampled token, so this draws one.
1800///
1801/// THE PROGRAM IS THE FULL-ACCEPT BONUS'S PROGRAM, deliberately: penalize the row (over the
1802/// session's window), take this row's OWN filter stats (the sampfix-20260805 law — stats
1803/// from a neighbour row mis-scale every `e0` and can wipe the row to token 0), gumbel-perturb
1804/// with the session's Philox stream at `*sctr`, argmax the perturbed row. Reusing the bonus's
1805/// composition means `sample_check`'s distributional oracle covers this draw too, and the
1806/// boundary token is drawn from the same filtered/penalized `p` the accept walk targets.
1807///
1808/// THE STREAM IS THE SESSION'S, NOT A FRESH ONE. `sctr` is the caller's live counter and is
1809/// advanced by exactly one, so a boundary draw consumes the next value in the same Philox
1810/// stream the accept walk uses — never a second, independently seeded stream (which would be
1811/// a new distributional bug: two streams from one seed correlate wherever their counters
1812/// collide). That also makes a restored session's boundary draw at `sctr == 0` bit-identical
1813/// to the cold session's own first draw from the same logits row, which is what preserves the
1814/// sampled-hit lane's per-seed hit==cold byte identity.
1815#[allow(clippy::too_many_arguments)]
1816pub fn sample_boundary_token_dev(
1817 e: &Engine,
1818 logits: &CudaSlice<f32>,
1819 n_vocab: usize,
1820 sp: &SpecSampling,
1821 pen_hist: &[u32],
1822 sctr: &mut u32,
1823 site: &str,
1824) -> Result<u32, Box<dyn std::error::Error>> {
1825 debug_assert!(
1826 sp.temp > 0.0,
1827 "boundary sampling is the sampled regime only"
1828 );
1829 // Own copy: penalize_logits mutates in place and the caller's row is live state
1830 // (prime_logits back the constrained recompute; last_col_logits backs round 0's accept).
1831 let mut col = e.zeros(n_vocab)?;
1832 e.copy_into(&mut col, 0, logits, n_vocab)?;
1833 let pen_on = sp.penalty_last_n > 0
1834 && (sp.penalty_repeat != 1.0 || sp.penalty_freq != 0.0 || sp.penalty_present != 0.0);
1835 if pen_on && !pen_hist.is_empty() {
1836 // window trim mirrors the round loop's own upload (`pen_hist[w0..]`), cap included.
1837 let w0 = pen_hist
1838 .len()
1839 .saturating_sub(sp.penalty_last_n.min(PEN_WINDOW_MAX));
1840 let hist = &pen_hist[w0..];
1841 let hd = e.htod_u32_v(hist)?;
1842 e.penalize_logits(
1843 &mut col,
1844 &hd,
1845 hist.len(),
1846 sp.penalty_repeat,
1847 sp.penalty_freq,
1848 sp.penalty_present,
1849 n_vocab,
1850 )?;
1851 }
1852 let rows0 = e.htod_i32(&[0])?;
1853 let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
1854 e.filter_stats(
1855 &col, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1, sp.temp, sp.top_k,
1856 sp.top_p, sp.min_p,
1857 )?;
1858 let (th, mx) = (e.dtoh(&th_d)?[0], e.dtoh(&mx_d)?[0]);
1859 let mut perturb = e.zeros(n_vocab)?;
1860 e.gumbel_perturb_filtered(&col, &mut perturb, n_vocab, sp.seed, *sctr, sp.temp, mx, th)?;
1861 *sctr = sctr.wrapping_add(1);
1862 let td = e.argmax_token_device(&perturb, n_vocab)?;
1863 let tok = guard_vocab_token(
1864 e.dtoh_u32_one(&td)?,
1865 n_vocab,
1866 &format!("sampled boundary token (site={site})"),
1867 )?;
1868 if spec_boundary_trace() {
1869 // the pre-lane token, from the SAME row, so the deviation rate is measurable.
1870 let raw = e.argmax_token_device(logits, n_vocab)?;
1871 let greedy = e.dtoh_u32_one(&raw)?;
1872 eprintln!(
1873 "[spec-boundary] site={site} sampled={tok} argmax={greedy} \
1874 deviates={} temp={} sctr={}",
1875 (tok != greedy) as u8,
1876 sp.temp,
1877 sctr.wrapping_sub(1),
1878 );
1879 }
1880 Ok(tok)
1881}
1882
1883/// Host-row twin of [`sample_boundary_token_dev`] (the prime / feed / entry rows arrive as
1884/// host `Vec<f32>`).
1885#[allow(clippy::too_many_arguments)]
1886pub fn sample_boundary_token(
1887 e: &Engine,
1888 logits: &[f32],
1889 sp: &SpecSampling,
1890 pen_hist: &[u32],
1891 sctr: &mut u32,
1892 site: &str,
1893) -> Result<u32, Box<dyn std::error::Error>> {
1894 let n_vocab = logits.len();
1895 let d = e.htod(logits)?;
1896 sample_boundary_token_dev(e, &d, n_vocab, sp, pen_hist, sctr, site)
1897}
1898
1899struct SpecPipeTraceClock {
1900 pair: usize,
1901 started: std::time::Instant,
1902}
1903
1904#[derive(Clone)]
1905struct SpecPipeTraceCtx {
1906 clock: std::sync::Arc<SpecPipeTraceClock>,
1907 round: usize,
1908 lane: usize,
1909}
1910
1911struct SpecPipeTraceMarker {
1912 trace: SpecPipeTraceCtx,
1913 phase: &'static str,
1914 edge: &'static str,
1915 slot: Option<usize>,
1916}
1917
1918unsafe extern "C" fn spec_pipe_trace_marker(raw: *mut std::ffi::c_void) {
1919 let marker = unsafe { Box::from_raw(raw.cast::<SpecPipeTraceMarker>()) };
1920 let lane = if marker.trace.lane == 0 { "A" } else { "B" };
1921 let slot = marker
1922 .slot
1923 .map(|v| v.to_string())
1924 .unwrap_or_else(|| "-".into());
1925 let t_ms = marker.trace.clock.started.elapsed().as_secs_f64() * 1e3;
1926 use std::io::Write as _;
1927 let stderr = std::io::stderr();
1928 let mut stderr = stderr.lock();
1929 let _ = writeln!(
1930 stderr,
1931 "[spec-pipe-timeline] pair={} round={} lane={lane} phase={} edge={} \
1932 slot={slot} t_ms={t_ms:.3}",
1933 marker.trace.clock.pair, marker.trace.round, marker.phase, marker.edge,
1934 );
1935}
1936
1937fn enqueue_spec_pipe_trace_marker(
1938 stream: &cudarc::driver::CudaStream,
1939 trace: Option<&SpecPipeTraceCtx>,
1940 phase: &'static str,
1941 edge: &'static str,
1942 slot: Option<usize>,
1943) -> Result<(), Box<dyn std::error::Error>> {
1944 let Some(trace) = trace else {
1945 return Ok(());
1946 };
1947 let marker = Box::new(SpecPipeTraceMarker {
1948 trace: trace.clone(),
1949 phase,
1950 edge,
1951 slot,
1952 });
1953 let raw = Box::into_raw(marker);
1954 let result = unsafe {
1955 cudarc::driver::result::stream::launch_host_function(
1956 stream.cu_stream(),
1957 spec_pipe_trace_marker,
1958 raw.cast(),
1959 )
1960 };
1961 if let Err(err) = result {
1962 unsafe {
1963 drop(Box::from_raw(raw));
1964 }
1965 return Err(err.into());
1966 }
1967 Ok(())
1968}
1969
1970#[derive(Default)]
1971struct SpecPipeProgress {
1972 setup_done: [bool; 2],
1973 draft_done: [usize; 2],
1974 stage0_done: [usize; 2],
1975 verify_done: [usize; 2],
1976 accept_done: [usize; 2],
1977 finished: [bool; 2],
1978 aborted: bool,
1979}
1980
1981/// Host-side issue coordinator for the reduced two-session speculative pipeline. Each session
1982/// keeps its existing call stack and round locals; this object only orders phase entry. The
1983/// primary mutex spans whole draft/accept/tail issue regions so Engine's single-stream scratch
1984/// cannot be interleaved by the two host threads.
1985struct SpecPipeSync {
1986 progress: std::sync::Mutex<SpecPipeProgress>,
1987 changed: std::sync::Condvar,
1988 primary: std::sync::Mutex<()>,
1989 trace: Option<std::sync::Arc<SpecPipeTraceClock>>,
1990}
1991
1992impl SpecPipeSync {
1993 fn new() -> Self {
1994 static TRACE_PAIR: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1995 let trace = (std::env::var("MEMRA_SPEC_PIPE_TRACE").as_deref() == Ok("1")).then(|| {
1996 std::sync::Arc::new(SpecPipeTraceClock {
1997 pair: TRACE_PAIR.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1,
1998 started: std::time::Instant::now(),
1999 })
2000 });
2001 Self {
2002 progress: std::sync::Mutex::new(SpecPipeProgress::default()),
2003 changed: std::sync::Condvar::new(),
2004 primary: std::sync::Mutex::new(()),
2005 trace,
2006 }
2007 }
2008}
2009
2010#[derive(Clone)]
2011struct SpecPipeLane {
2012 sync: std::sync::Arc<SpecPipeSync>,
2013 lane: usize,
2014 rt: &'static crate::pp::PpNRt,
2015 walk_permit: crate::pp::PpWalkPermit,
2016}
2017
2018struct SpecPipePrimaryGuard<'a> {
2019 _primary: std::sync::MutexGuard<'a, ()>,
2020 _walk: crate::pp::PpWalkBorrowGuard,
2021}
2022
2023impl SpecPipeLane {
2024 fn peer(&self) -> usize {
2025 1 - self.lane
2026 }
2027
2028 fn aborted() -> Box<dyn std::error::Error> {
2029 "paired speculative peer aborted".into()
2030 }
2031
2032 fn trace(&self, round: usize) -> Option<SpecPipeTraceCtx> {
2033 self.sync.trace.as_ref().map(|clock| SpecPipeTraceCtx {
2034 clock: clock.clone(),
2035 round,
2036 lane: self.lane,
2037 })
2038 }
2039
2040 fn setup_begin(&self) -> Result<crate::pp::PpWalkBorrowGuard, Box<dyn std::error::Error>> {
2041 let mut p = self.sync.progress.lock().unwrap();
2042 while !p.aborted && self.lane == 1 && !p.setup_done[0] && !p.finished[0] {
2043 p = self.sync.changed.wait(p).unwrap();
2044 }
2045 if p.aborted {
2046 Err(Self::aborted())
2047 } else {
2048 drop(p);
2049 self.rt.borrow_walk(&self.walk_permit, "spec_pipe/setup")
2050 }
2051 }
2052
2053 fn setup_end(&self) {
2054 let mut p = self.sync.progress.lock().unwrap();
2055 p.setup_done[self.lane] = true;
2056 self.sync.changed.notify_all();
2057 }
2058
2059 fn draft_begin(
2060 &self,
2061 round: usize,
2062 ) -> Result<SpecPipePrimaryGuard<'_>, Box<dyn std::error::Error>> {
2063 let peer = self.peer();
2064 let mut p = self.sync.progress.lock().unwrap();
2065 loop {
2066 if p.aborted {
2067 return Err(Self::aborted());
2068 }
2069 let setup_ready =
2070 (p.setup_done[0] || p.finished[0]) && (p.setup_done[1] || p.finished[1]);
2071 let prior_ready = p.accept_done[self.lane] >= round
2072 && (p.accept_done[peer] >= round || p.finished[peer]);
2073 let turn_ready = if self.lane == 0 {
2074 true
2075 } else {
2076 p.draft_done[0] > round || p.finished[0]
2077 };
2078 if setup_ready && prior_ready && turn_ready {
2079 break;
2080 }
2081 p = self.sync.changed.wait(p).unwrap();
2082 }
2083 drop(p);
2084 let primary = self.sync.primary.lock().unwrap();
2085 let walk = self.rt.borrow_walk(&self.walk_permit, "spec_pipe/draft")?;
2086 Ok(SpecPipePrimaryGuard {
2087 _primary: primary,
2088 _walk: walk,
2089 })
2090 }
2091
2092 fn draft_end(&self, round: usize) {
2093 let mut p = self.sync.progress.lock().unwrap();
2094 p.draft_done[self.lane] = round + 1;
2095 self.sync.changed.notify_all();
2096 }
2097
2098 /// Admit stage 0 and return whether this lane owns the interval's one reverse fence.
2099 /// Lane B releases as soon as lane A has issued its boundary TX, not after A's full body.
2100 fn stage0_begin(&self, round: usize) -> Result<bool, Box<dyn std::error::Error>> {
2101 let peer = self.peer();
2102 let mut p = self.sync.progress.lock().unwrap();
2103 loop {
2104 if p.aborted {
2105 return Err(Self::aborted());
2106 }
2107 let ready = if self.lane == 0 {
2108 p.draft_done[0] > round && (p.draft_done[1] > round || p.finished[1])
2109 } else {
2110 p.draft_done[1] > round && (p.stage0_done[0] > round || p.finished[0])
2111 };
2112 if ready {
2113 return Ok(self.lane == 0 || p.finished[peer]);
2114 }
2115 p = self.sync.changed.wait(p).unwrap();
2116 }
2117 }
2118
2119 fn stage0_end(&self, round: usize) {
2120 let mut p = self.sync.progress.lock().unwrap();
2121 p.stage0_done[self.lane] = round + 1;
2122 self.sync.changed.notify_all();
2123 }
2124
2125 /// Stage 1 is single-owner per engine. A proceeds immediately after its own ticket; B waits
2126 /// for A's full stage1/head issue so only A.S1 and B.S0 can overlap.
2127 fn stage1_begin(&self, round: usize) -> Result<(), Box<dyn std::error::Error>> {
2128 let mut p = self.sync.progress.lock().unwrap();
2129 while !p.aborted
2130 && !(p.stage0_done[self.lane] > round
2131 && (self.lane == 0 || p.verify_done[0] > round || p.finished[0]))
2132 {
2133 p = self.sync.changed.wait(p).unwrap();
2134 }
2135 if p.aborted {
2136 Err(Self::aborted())
2137 } else {
2138 Ok(())
2139 }
2140 }
2141
2142 fn verify_end(&self, round: usize) {
2143 let mut p = self.sync.progress.lock().unwrap();
2144 p.verify_done[self.lane] = round + 1;
2145 self.sync.changed.notify_all();
2146 }
2147
2148 fn accept_begin(
2149 &self,
2150 round: usize,
2151 ) -> Result<SpecPipePrimaryGuard<'_>, Box<dyn std::error::Error>> {
2152 let mut p = self.sync.progress.lock().unwrap();
2153 loop {
2154 if p.aborted {
2155 return Err(Self::aborted());
2156 }
2157 let ready = if self.lane == 0 {
2158 p.verify_done[0] > round && (p.verify_done[1] > round || p.finished[1])
2159 } else {
2160 p.verify_done[1] > round && (p.accept_done[0] > round || p.finished[0])
2161 };
2162 if ready {
2163 break;
2164 }
2165 p = self.sync.changed.wait(p).unwrap();
2166 }
2167 drop(p);
2168 let primary = self.sync.primary.lock().unwrap();
2169 let walk = self.rt.borrow_walk(&self.walk_permit, "spec_pipe/accept")?;
2170 Ok(SpecPipePrimaryGuard {
2171 _primary: primary,
2172 _walk: walk,
2173 })
2174 }
2175
2176 fn accept_end(&self, round: usize) {
2177 let mut p = self.sync.progress.lock().unwrap();
2178 p.accept_done[self.lane] = round + 1;
2179 self.sync.changed.notify_all();
2180 }
2181
2182 fn primary(&self) -> Result<SpecPipePrimaryGuard<'_>, Box<dyn std::error::Error>> {
2183 let primary = self.sync.primary.lock().unwrap();
2184 let walk = self.rt.borrow_walk(&self.walk_permit, "spec_pipe/tail")?;
2185 Ok(SpecPipePrimaryGuard {
2186 _primary: primary,
2187 _walk: walk,
2188 })
2189 }
2190
2191 fn coordinated_walk(&self) -> Result<crate::pp::PpWalkBorrowGuard, Box<dyn std::error::Error>> {
2192 self.rt
2193 .borrow_walk(&self.walk_permit, "spec_pipe/coordinated_verify")
2194 }
2195
2196 fn finish(&self, failed: bool) {
2197 let mut p = self.sync.progress.lock().unwrap();
2198 p.finished[self.lane] = true;
2199 p.aborted |= failed;
2200 self.sync.changed.notify_all();
2201 }
2202}
2203
2204struct SpecPipeFinish<'a> {
2205 lane: &'a SpecPipeLane,
2206 closed: bool,
2207}
2208
2209impl<'a> SpecPipeFinish<'a> {
2210 fn new(lane: &'a SpecPipeLane) -> Self {
2211 Self {
2212 lane,
2213 closed: false,
2214 }
2215 }
2216
2217 fn close(&mut self, failed: bool) {
2218 self.lane.finish(failed);
2219 self.closed = true;
2220 }
2221}
2222
2223impl Drop for SpecPipeFinish<'_> {
2224 fn drop(&mut self) {
2225 if !self.closed {
2226 self.lane.finish(true);
2227 }
2228 }
2229}
2230
2231/// Scoped transfer of one exclusively-borrowed session to the second host issue thread.
2232/// `CudaGraph` is not marked Send by cudarc because its raw driver handles carry no automatic
2233/// trait. CUDA driver graph handles are context-scoped rather than OS-thread-affine; the caller
2234/// binds that context before touching the session, joins before returning, and never aliases the
2235/// pointer. Keep this exception local to the experimental pair call instead of marking the public
2236/// session type Send.
2237struct SpecPipeSessionPtr(*mut SpecSession);
2238
2239unsafe impl Send for SpecPipeSessionPtr {}
2240
2241impl SpecPipeSessionPtr {
2242 unsafe fn get_mut(&mut self) -> &mut SpecSession {
2243 unsafe { &mut *self.0 }
2244 }
2245}
2246
2247/// Per-session persistent draft-graph context: the captured CUDA graph(s) plus the device
2248/// buffers whose POINTERS the capture bakes. Reuse legality: the greedy capture bakes only
2249/// session-stable pointers (the session's own MtpScratch KV — allocated once, never realloc'd;
2250/// the model's resident embedding; the process-wide OnceLock p_min) and the g_* buffers held
2251/// HERE — so one capture serves the session's whole lifetime. The sampled capture additionally
2252/// bakes (seed, temp) as capture-time constants and needs k q-slots — keyed by `s_key`, dropped
2253/// and recaptured when a pool-resumed request changes them. `*_failed` memoizes a failed capture
2254/// so the eager fallback doesn't pay a doomed capture attempt every burst.
2255/// Capture identity of the parked SAMPLED draft graph (`DraftGraphCtx::graph_s`).
2256///
2257/// EXACTNESS, not perf (lane/graph-s-key-exactness-20260819; receipts
2258/// `research/spec-cache-20260818/GRAPH-S-KEY.md`). Two classes of field live here, both
2259/// load-bearing:
2260///
2261/// - **Baked constants.** `seed` and `temp` are capture-time constants INSIDE the graph and `k`
2262/// sizes the q slots its replays write. A resumed request changing any of them must recapture.
2263/// This is all the key used to carry.
2264/// - **Regime fields.** `top_k`/`top_p`/`min_p`/`pen_on` are not baked, but they decide whether
2265/// the captured graph is a legal draft chain AT ALL. The in-graph draw is one gumbel-max over
2266/// the RAW softmax (`gumbel_perturb_ctr`, unfiltered by construction), while the verify builds
2267/// the accept test's `q` from `filter_stats(q_slots, top_k, top_p, min_p)`. If those disagree
2268/// the accept test evaluates a distribution the draft was never sampled from: a draft token
2269/// below the filter threshold gathers `q = 0` (`softmax_gather_filtered_f32`,
2270/// `cu/spec_sample.cu`) and `u * 0 < p` accepts it UNCONDITIONALLY.
2271///
2272/// Omitting the regime fields was reachable — not through the prefix-cache spec restore (that
2273/// path is greedy-only, `memra-server` `spec_restore_convertible`), but through WHOLE-SESSION
2274/// spec reuse: a parked `SpecSession` carries this `DraftGraphCtx`, and the pool-resume probe
2275/// applies no sampler predicate at all. Turn 1 pure-temp parks a graph; turn 2 of the same
2276/// conversation, same explicit seed and temperature, adds `top_p`/`top_k` and inherits it.
2277#[derive(Clone, Copy, PartialEq, Eq, Debug)]
2278pub(crate) struct SampledGraphKey {
2279 seed: u64,
2280 temp_bits: u32,
2281 k: usize,
2282 top_k: i32,
2283 top_p_bits: u32,
2284 min_p_bits: u32,
2285 pen_on: bool,
2286}
2287
2288impl SampledGraphKey {
2289 pub(crate) fn new(
2290 seed: u64,
2291 temp: f32,
2292 k: usize,
2293 top_k: i32,
2294 top_p: f32,
2295 min_p: f32,
2296 pen_on: bool,
2297 ) -> Self {
2298 SampledGraphKey {
2299 seed,
2300 temp_bits: temp.to_bits(),
2301 k,
2302 top_k,
2303 top_p_bits: top_p.to_bits(),
2304 min_p_bits: min_p.to_bits(),
2305 pen_on,
2306 }
2307 }
2308
2309 /// The one regime the PURE-TEMP in-graph sampled chain may stand in for the eager one:
2310 /// nothing but temperature shapes `q`. Computed FROM THE KEY so the capture guard, the
2311 /// launch guard and the key can never drift apart (they were three separate expressions
2312 /// before this lane, and the launch site simply forgot to ask).
2313 pub(crate) fn pure_temp(&self) -> bool {
2314 self.top_k == 0
2315 && f32::from_bits(self.top_p_bits) >= 1.0
2316 && f32::from_bits(self.min_p_bits) <= 0.0
2317 && !self.pen_on
2318 }
2319
2320 /// Truncation filters active — the capture body needs the IN-GRAPH filter nodes
2321 /// (`filter_stats` + `gumbel_perturb_filtered_ctr`) so the draft draws from the same
2322 /// filtered distribution the accept test reconstructs. Meaningful only when
2323 /// `graph_capturable`; penalties never reach a capture body.
2324 pub(crate) fn filtered(&self) -> bool {
2325 !self.pure_temp()
2326 }
2327
2328 /// May the sampled draft graph be CAPTURED (and a parked one LAUNCHED) for this regime?
2329 /// Pure-temp always; filtered regimes when the filtered-capture door is on
2330 /// (lane/step37-draft-graph-serving-20260830); penalties never — the per-round history
2331 /// cannot be baked into a graph, and composing a raw-softmax (or stale-history) draw
2332 /// with a penalized accept test is the unconditional-accept exactness bug. Computed FROM
2333 /// THE KEY for the same no-drift reason as `pure_temp`.
2334 pub(crate) fn graph_capturable(&self) -> bool {
2335 !self.pen_on && (self.pure_temp() || spec_graph_filtered_on())
2336 }
2337}
2338
2339/// Per-head captured graphs for the MULTI-HEAD MTP draft chain (step-modulo prefix-replay,
2340/// lane/step37-draft-graph-serving-20260830). The chain POLICY — which head serves step j,
2341/// how long the replayed prefix is, which stored seed feeds row r — stays HOST-SIDE in the
2342/// launch loop, exactly `mtp_chain_forward_dev`'s order; the graphs capture ONE head-row
2343/// forward each, on the head's OWN scratch plane:
2344/// - `interior[i]`: head i, `with_head=false` — KV append + carrier only. Interior rows'
2345/// logits are dead in the eager chain too (`mtp_chain_forward_dev` keeps only the last
2346/// row), so skipping the head matmul changes no consumed byte and removes the eager
2347/// chain's per-replay-row full-vocab matmul.
2348/// - `last[i]`: head i, `with_head=true` + the mode's tail (greedy argmax, or the sampled
2349/// gumbel draw — filtered in-graph when the request carries filters).
2350///
2351/// One `DraftChainGraphs` per MODE (greedy vs sampled), owning its keeper: dropping the
2352/// sampled chain on an s_key change never invalidates the greedy one.
2353struct DraftChainGraphs {
2354 interior: Vec<cudarc::driver::CudaGraph>,
2355 last: Vec<cudarc::driver::CudaGraph>,
2356 /// Never read: exists to OWN the captured graphs' backing buffers for as long as the
2357 /// graphs replay (the capture-retain law; same class as `DsparkSegGraph::_keeper`).
2358 _keeper: Vec<Box<dyn std::any::Any + Send>>,
2359}
2360
2361/// Sampled-tail capture pack for `mtp_head_forward_cap`: the persistent buffers and baked
2362/// constants of the in-graph categorical draw. `filt: None` = the PURE-TEMP body (gumbel
2363/// over the raw softmax), byte-identical to the pre-lane capture; `Some` adds the in-graph
2364/// truncation filter (`filter_stats` + `gumbel_perturb_filtered_ctr`) so the draft draws
2365/// from the same filtered distribution the accept test reconstructs
2366/// (lane/step37-draft-graph-serving-20260830).
2367struct SampledCapArgs<'a> {
2368 ctr: &'a mut CudaSlice<u32>,
2369 perturb: &'a mut CudaSlice<f32>,
2370 q_out: &'a mut CudaSlice<f32>,
2371 seed: u64,
2372 temp: f32,
2373 filt: Option<SampledCapFilter<'a>>,
2374}
2375
2376/// In-graph truncation-filter nodes: the stat slots `filter_stats` fills and the perturb
2377/// reads, plus the filter constants baked into the capture (they live in `s_key`, so a
2378/// request whose filters differ drops the parked graph before this ever goes stale).
2379struct SampledCapFilter<'a> {
2380 rows0: &'a CudaSlice<i32>,
2381 th: &'a mut CudaSlice<f32>,
2382 z: &'a mut CudaSlice<f32>,
2383 mx: &'a mut CudaSlice<f32>,
2384 top_k: i32,
2385 top_p: f32,
2386 min_p: f32,
2387}
2388
2389pub(crate) struct DraftGraphCtx {
2390 g_tok: CudaSlice<u32>,
2391 g_pos: CudaSlice<i32>,
2392 g_seed: CudaSlice<f32>,
2393 g_p: CudaSlice<f32>,
2394 g_ctr: CudaSlice<u32>,
2395 g_q: CudaSlice<f32>,
2396 g_perturb: CudaSlice<f32>,
2397 /// IN-GRAPH filter-stat slots (filtered sampled capture): `filter_stats` writes
2398 /// (th, z, mx) here inside the graph; `gumbel_perturb_filtered_ctr` reads (mx, th) from
2399 /// the same slots. Persistent so the baked pointers survive replays. `g_rows0` is the
2400 /// constant row-index-0 the single-row `filter_stats` launch reads (a captured memcpy
2401 /// source must not be a host temporary).
2402 g_rows0: CudaSlice<i32>,
2403 g_th: CudaSlice<f32>,
2404 g_z: CudaSlice<f32>,
2405 g_mx: CudaSlice<f32>,
2406 q_slots: Vec<CudaSlice<f32>>,
2407 /// DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): packed allowed-set words over the DRAFT
2408 /// head's vocab, at a STABLE address so the captured draft graph's mask node reads the
2409 /// per-position contents the host re-uploads before each replay (the graph-promote
2410 /// pattern from decode.rs). Empty unless the session drafts under a grammar.
2411 g_dmask: CudaSlice<u32>,
2412 /// was `graph` captured WITH the mask node? A parked graph of the wrong shape is dropped.
2413 /// Covers the multi-head `chain` too (single-head and chain are mutually exclusive for a
2414 /// given model, so one flag serves whichever is active).
2415 graph_masked: bool,
2416 graph: Option<cudarc::driver::CudaGraph>,
2417 graph_s: Option<cudarc::driver::CudaGraph>,
2418 /// Multi-head chain graphs (see [`DraftChainGraphs`]): greedy and sampled chains, the
2419 /// chain twins of `graph` / `graph_s`. `chain_s`'s capture identity is `s_key` (shared
2420 /// with `graph_s` — a session is either single-head or chain, never both), and it obeys
2421 /// the same drop rules (key mismatch, penalty regime, mask-shape change).
2422 chain: Option<DraftChainGraphs>,
2423 chain_s: Option<DraftChainGraphs>,
2424 /// Failed-capture memoization for both graphs — LOUD on flip, cleared on pool resume
2425 /// (audit Q2, the TRT #16072 silent-permanent-coverage-loss class).
2426 failed: DraftGraphFallback,
2427 /// Capture identity of `graph_s` — see [`SampledGraphKey`]. `None` iff no sampled graph is
2428 /// parked; a request whose key differs drops the parked graph (and its q slots/keeper).
2429 s_key: Option<SampledGraphKey>,
2430 /// CAPTURE-RETAIN keepers (#68 root cause, 2026-08-04): the warmup-run transients whose
2431 /// pool addresses the captured graph(s) bake. Without these, the transients return to the
2432 /// pool at capture-body exit and later work (burst-boundary prime/fill/commit passes, or a
2433 /// co-served session in the worker) reuses those addresses — the persisted graph's replay
2434 /// then reads/writes live unrelated buffers (exactness corruption, first seen as the ST
2435 /// serve-spec 4B graph-arm corruption; one-shot CLI calls never re-shuffled the pool, which
2436 /// is why run-spec K=1..8 passed on the same checkpoint). Same fix class as
2437 /// capture_graph_retained's gemma/decode.rs sites — hold as long as the graph replays.
2438 keeper: Vec<Box<dyn std::any::Any + Send>>,
2439 keeper_s: Vec<Box<dyn std::any::Any + Send>>,
2440}
2441
2442/// Failed-capture memoization for the two draft graphs (audit Q2, 2026-08-05 — the
2443/// TRT #16072 trap class: pressure-triggered, silent, long-lived coverage loss).
2444///
2445/// Three contracts:
2446/// - LOUD FLIP: `mark_*` returns the warn line exactly on the false→true transition
2447/// (returned, not printed, so the once-per-flip contract is unit-testable); the caller
2448/// `eprintln!`s it UNCONDITIONALLY — a dropped draft graph is never silent. Re-marking
2449/// an already-failed graph returns None (the per-burst memoization that keeps the eager
2450/// fallback from paying a doomed capture attempt every burst).
2451/// - RESET ON RESUME: `reset_on_resume` clears both flags — a parked session resumed by a
2452/// NEW request gets one fresh capture chance instead of carrying a transient-pressure
2453/// failure for the pool's whole lifetime. Returns the note line only when a flag was
2454/// actually set (quiet on the common clean-resume path).
2455/// - Shape-change clears (`clear_*`) stay silent, exactly as before: they precede a fresh
2456/// capture attempt whose own failure would re-flip loudly.
2457#[derive(Default)]
2458pub(crate) struct DraftGraphFallback {
2459 greedy: bool,
2460 sampled: bool,
2461}
2462impl DraftGraphFallback {
2463 fn mark_greedy(&mut self, reason: &str) -> Option<String> {
2464 if self.greedy {
2465 return None;
2466 }
2467 self.greedy = true;
2468 Some(format!(
2469 "[spec] WARN: draft-graph capture failed ({reason}); eager fallback until session resume"
2470 ))
2471 }
2472 fn mark_sampled(&mut self, reason: &str) -> Option<String> {
2473 if self.sampled {
2474 return None;
2475 }
2476 self.sampled = true;
2477 Some(format!(
2478 "[spec] WARN: sampled draft-graph capture failed ({reason}); eager fallback until session resume"
2479 ))
2480 }
2481 fn greedy_failed(&self) -> bool {
2482 self.greedy
2483 }
2484 fn sampled_failed(&self) -> bool {
2485 self.sampled
2486 }
2487 fn clear_greedy(&mut self) {
2488 self.greedy = false;
2489 }
2490 fn clear_sampled(&mut self) {
2491 self.sampled = false;
2492 }
2493 /// Pool-resume reset: both graphs get a fresh capture chance. Some(note) iff any flag
2494 /// was set (so clean resumes stay quiet).
2495 pub(crate) fn reset_on_resume(&mut self) -> Option<String> {
2496 if !self.greedy && !self.sampled {
2497 return None;
2498 }
2499 let which = match (self.greedy, self.sampled) {
2500 (true, true) => "greedy+sampled",
2501 (true, false) => "greedy",
2502 _ => "sampled",
2503 };
2504 self.greedy = false;
2505 self.sampled = false;
2506 Some(format!(
2507 "[spec] draft-graph fallback reset on session resume ({which}); recapture eligible"
2508 ))
2509 }
2510}
2511
2512impl DraftGraphCtx {
2513 fn new(e: &Engine, n_embd: usize, qlen: usize) -> Result<Self, Box<dyn std::error::Error>> {
2514 Ok(DraftGraphCtx {
2515 g_tok: e.alloc_u32_zeroed(1)?,
2516 g_pos: e.htod_i32(&[0])?,
2517 g_seed: e.zeros(n_embd)?,
2518 g_p: e.zeros(1)?,
2519 g_ctr: e.alloc_u32_zeroed(1)?,
2520 g_q: e.zeros(qlen)?,
2521 g_perturb: e.zeros(qlen)?,
2522 g_rows0: e.htod_i32(&[0])?,
2523 g_th: e.zeros(1)?,
2524 g_z: e.zeros(1)?,
2525 g_mx: e.zeros(1)?,
2526 q_slots: Vec::new(),
2527 g_dmask: e.alloc_u32_zeroed(1)?,
2528 graph_masked: false,
2529 graph: None,
2530 graph_s: None,
2531 chain: None,
2532 chain_s: None,
2533 failed: DraftGraphFallback::default(),
2534 s_key: None,
2535 keeper: Vec::new(),
2536 keeper_s: Vec::new(),
2537 })
2538 }
2539}
2540
2541pub(crate) struct MtpScratch {
2542 kv: KvLayer,
2543 /// Logical row capacity. On the graph/DC draft path it also doubles as fa_decode_dc's
2544 /// bucket_max: n_splits is sized from it ONCE, so the graph captured at round 0 stays valid
2545 /// for every later t_kv. Step35 refuses that path and may back this logical extent with the
2546 /// smaller host-indexed SWA ring instead.
2547 cap: usize,
2548 extra: Vec<MtpScratchPlane>,
2549}
2550
2551struct MtpScratchPlane {
2552 kv: KvLayer,
2553 cap: usize,
2554}
2555
2556fn mtp_scratch_layout(
2557 cfg: &memra_gguf::config::ModelConfig,
2558 geom: Option<&crate::hybrid::DraftGeom>,
2559) -> (usize, usize, usize, usize) {
2560 // Student draft heads carry fewer KV heads (head_dim unchanged) -> smaller scratch rows.
2561 let n_head_kv = geom.map(|g| g.n_head_kv).unwrap_or(cfg.n_head_kv as usize);
2562 let head_dim_k = cfg.head_dim_k as usize;
2563 let head_dim_v = cfg.head_dim_v as usize;
2564 assert!(
2565 head_dim_k.is_multiple_of(32) && head_dim_v.is_multiple_of(32),
2566 "KVQUANT requires head_dim%32==0 (MTP scratch)"
2567 );
2568 let kv_dim_k = head_dim_k * n_head_kv;
2569 let kv_dim_v = head_dim_v * n_head_kv;
2570 // The fp8-KV arm deliberately does not reach the draft scratch; keep the exact format
2571 // policy shared with `MtpScratch::new` so admission scales the same allocation.
2572 let (kbb, vbb) = crate::kv_blk_bytes();
2573 let k_tok_bytes = (kv_dim_k / 32) * kbb;
2574 let v_tok_bytes = (kv_dim_v / 32) * vbb;
2575 (kv_dim_k, kv_dim_v, k_tok_bytes, v_tok_bytes)
2576}
2577
2578fn mtp_chain_head_index(step: usize, head_count: usize) -> usize {
2579 assert!(head_count > 0, "MTP chain requires at least one head");
2580 step % head_count
2581}
2582
2583impl MtpScratch {
2584 fn alloc_plane(
2585 e: &Engine,
2586 cfg: &memra_gguf::config::ModelConfig,
2587 plan: &memra_gguf::model_plan::ModelPlan,
2588 cap: usize,
2589 geom: Option<&crate::hybrid::DraftGeom>,
2590 ) -> Result<MtpScratchPlane, Box<dyn std::error::Error>> {
2591 let (kv_dim_k, kv_dim_v, k_tok_bytes, v_tok_bytes) = mtp_scratch_layout(cfg, geom);
2592 let ring = if crate::cache::swa_ring_on()
2593 && crate::plan_backend::decode_batch_program(plan)
2594 == crate::plan_backend::DecodeBatchProgram::SlidingGatedMoe
2595 {
2596 let window = plan
2597 .layers
2598 .iter()
2599 .find_map(|layer| match layer.attention {
2600 memra_gguf::model_plan::AttentionPlan::SlidingWindow { window, .. } => {
2601 Some(window as usize)
2602 }
2603 _ => None,
2604 })
2605 .ok_or("sliding-gated-MoE draft scratch has no sliding-window layer")?;
2606 Some(crate::cache::KvRing::new(
2607 crate::cache::swa_ring_rows(window, cap),
2608 window,
2609 ))
2610 } else {
2611 None
2612 };
2613 let alloc_rows = ring.as_ref().map(crate::cache::KvRing::rows).unwrap_or(cap);
2614 // Ring-backed planes arm the device base mirror for the dcw draft arm (see
2615 // KvLayer::base_d): the captured chain derives its physical rows from
2616 // (len_d, base_d, window) with zero per-token node updates.
2617 let base_d = match ring.as_ref() {
2618 Some(_) => Some(e.htod_i32(&[0])?),
2619 None => None,
2620 };
2621 Ok(MtpScratchPlane {
2622 kv: KvLayer {
2623 k: e.alloc_u8(alloc_rows * k_tok_bytes)?,
2624 v: e.alloc_u8(alloc_rows * v_tok_bytes)?,
2625 kv_dim_k,
2626 kv_dim_v,
2627 k_tok_bytes,
2628 v_tok_bytes,
2629 len: 0,
2630 ring,
2631 len_d: e.htod_i32(&[0])?,
2632 base_d,
2633 },
2634 cap,
2635 })
2636 }
2637
2638 fn new(
2639 e: &Engine,
2640 cfg: &memra_gguf::config::ModelConfig,
2641 plan: &memra_gguf::model_plan::ModelPlan,
2642 cap: usize,
2643 geom: Option<&crate::hybrid::DraftGeom>,
2644 ) -> Result<Self, Box<dyn std::error::Error>> {
2645 // env-selected KV formats (default 34/24). The fp8-KV arm (MEMRA_KV_FP8) deliberately
2646 // does NOT reach the draft scratch: fp8 drafts drifted acceptance 69-88% -> 46%
2647 // (2026-07-12 A/B); the scratch is tiny, so it keeps baseline q8_0/q5_1 numerics
2648 // while the TRUNK cache carries the fp8 depth win. Scratch append/fa pass g=false.
2649 let primary = Self::alloc_plane(e, cfg, plan, cap, geom)?;
2650 Ok(MtpScratch {
2651 kv: primary.kv,
2652 cap: primary.cap,
2653 extra: Vec::new(),
2654 })
2655 }
2656
2657 fn push_plane(
2658 &mut self,
2659 e: &Engine,
2660 cfg: &memra_gguf::config::ModelConfig,
2661 plan: &memra_gguf::model_plan::ModelPlan,
2662 geom: Option<&crate::hybrid::DraftGeom>,
2663 ) -> Result<(), Box<dyn std::error::Error>> {
2664 self.extra
2665 .push(Self::alloc_plane(e, cfg, plan, self.cap, geom)?);
2666 Ok(())
2667 }
2668
2669 fn plane_count(&self) -> usize {
2670 1 + self.extra.len()
2671 }
2672
2673 fn plane(&self, index: usize) -> (&KvLayer, usize) {
2674 if index == 0 {
2675 (&self.kv, self.cap)
2676 } else {
2677 let plane = &self.extra[index - 1];
2678 (&plane.kv, plane.cap)
2679 }
2680 }
2681
2682 fn plane_mut(&mut self, index: usize) -> (&mut KvLayer, usize) {
2683 if index == 0 {
2684 (&mut self.kv, self.cap)
2685 } else {
2686 let plane = &mut self.extra[index - 1];
2687 (&mut plane.kv, plane.cap)
2688 }
2689 }
2690
2691 // #[track_caller]: set_len/set_plane_len have eight call sites (checkpoint restore, spec
2692 // rollback, session grow, seed replay ...) and the lap failure needs to say WHICH one, not
2693 // just that a rewind was refused.
2694 #[track_caller]
2695 fn set_plane_len(
2696 &mut self,
2697 e: &Engine,
2698 index: usize,
2699 n: usize,
2700 ) -> Result<(), Box<dyn std::error::Error>> {
2701 let caller = std::panic::Location::caller();
2702 let (kv, cap) = self.plane_mut(index);
2703 if let Some(ring) = kv.ring.as_ref()
2704 && !ring.can_rewind_to(n)
2705 {
2706 // NAME THE NUMBERS (2026-08-28). This error is a step37 serving blocker on the
2707 // vendor-default shape and it fires from more than one call path with more than
2708 // one trigger: a long generation walks the checkpoint out of the ring, but a
2709 // ~4.5k-token prompt also fails within 5 s of prime, which accumulation cannot
2710 // explain. A bare message forced two rounds of guessing; the operands make each
2711 // trigger name itself.
2712 let raw = n.saturating_sub(ring.window().saturating_sub(1));
2713 return Err(format!(
2714 "SWA ring MTP checkpoint has been lapped; full re-prime required (plane={index} rewind_to={n} window={} base={} rows={} cap={cap} needed_view_start={} < base, called from {caller})",
2715 ring.window(),
2716 ring.base(),
2717 ring.rows(),
2718 raw & !31usize,
2719 )
2720 .into());
2721 }
2722 kv.len = n;
2723 e.set_i32_one(&mut kv.len_d, n as i32)
2724 }
2725
2726 /// Set BOTH length counters: the host mirror AND the device len_d the captured append/fa read
2727 /// (a 4-byte in-place htod — the counter pointer is baked into the graph, never realloc'd).
2728 /// This is the ONLY truncation/rollback mechanism the persistent draft KV needs.
2729 #[track_caller]
2730 fn set_len(&mut self, e: &Engine, n: usize) -> Result<(), Box<dyn std::error::Error>> {
2731 let caller = std::panic::Location::caller();
2732 if !self.can_rewind_to(n) {
2733 // set_plane_len re-checks and reports the operands; call it so the failure carries
2734 // which plane refused and why, instead of this bare aggregate.
2735 for index in 0..self.plane_count() {
2736 self.set_plane_len(e, index, n)?;
2737 }
2738 return Err(format!(
2739 "SWA ring MTP checkpoint has been lapped; full re-prime required (aggregate rewind_to={n}, no single plane reported, called from {caller})"
2740 )
2741 .into());
2742 }
2743 for index in 0..self.plane_count() {
2744 self.set_plane_len(e, index, n)?;
2745 }
2746 Ok(())
2747 }
2748
2749 fn can_rewind_to(&self, n: usize) -> bool {
2750 (0..self.plane_count()).all(|index| {
2751 self.plane(index)
2752 .0
2753 .ring
2754 .as_ref()
2755 .is_none_or(|ring| ring.can_rewind_to(n))
2756 })
2757 }
2758
2759 /// Pre-arm ring headroom for `rows` upcoming DEVICE-COUNTER appends (the dcw draft arm):
2760 /// a captured chain cannot rebase mid-replay, so any rebase the coming appends could need
2761 /// happens HERE, host-side, before the capture warmups or the round's replays (the rebase
2762 /// arm of `prepare_kv_append` also refreshes the plane's `base_d` device mirror). No-op on
2763 /// flat planes and when the ring already has room; `len` is untouched either way.
2764 fn ensure_dcw_headroom(
2765 &mut self,
2766 e: &Engine,
2767 rows: usize,
2768 ) -> Result<(), Box<dyn std::error::Error>> {
2769 for index in 0..self.plane_count() {
2770 let (kv, _) = self.plane_mut(index);
2771 let Some(ring) = kv.ring.as_ref() else {
2772 continue;
2773 };
2774 let retain = memra_kv::swa_retain_from(kv.len, ring.window(), ring.base());
2775 e.prepare_kv_append(kv, retain, rows)?;
2776 }
2777 Ok(())
2778 }
2779}
2780
2781/// Retained verify intermediates for the REPLAY-FREE partial accept (2026-07-03, the profiled
2782/// #1 spec cost at long ctx: the partial-accept replay was a DUPLICATE trunk pass — ~0.54 extra
2783/// full weight reads per round — recomputing columns the verify had already produced
2784/// bit-identically). Holds, per linear layer, everything needed to rebuild its recurrent state
2785/// to "after the first j verify columns" WITHOUT re-running the trunk:
2786/// - BATCHED-path layers (`gdn`): the exact token-major inputs the round's ONE gdn_scan
2787/// consumed. A prefix re-run of the SAME kernel (t=j) from the snapshot state is bit-identical
2788/// to the first j iterations of the verify's scan — the kernel's t-loop carries state in
2789/// registers and iteration t never depends on T. `qkv_mixed` (the conv input) feeds the
2790/// pure-copy ring rebuild.
2791/// - PER-COLUMN-path layers (`cols`): dtod clones of (conv_state, ssm_state) taken after each
2792/// column 0..t-2 — pure copies of the actual chain states (the last column is never a rebuild
2793/// target: j <= t-1).
2794/// Full-attn layers need nothing: their verify KV rows are bit-identical to eager's (the
2795/// decode-exact contract; verify-probe pins it), so rollback = len truncation.
2796struct GdnStash {
2797 qkv_mixed: CudaSlice<f32>, // [t, conv_dim] token-major (conv input)
2798 q_l2: CudaSlice<f32>,
2799 k_l2: CudaSlice<f32>,
2800 v_g: CudaSlice<f32>, // [t, num_v, d_state]
2801 g_log: CudaSlice<f32>,
2802 beta: CudaSlice<f32>, // [t, num_v]
2803}
2804pub(crate) struct VerifyCkpt {
2805 gdn: Vec<Option<GdnStash>>, // [n_layer], Some iff batched linear path ran
2806 #[allow(clippy::type_complexity)]
2807 // allow: one-shot composite type; naming it would hide the shape that matters at the call site
2808 cols: Vec<Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>>>, // [n_layer][col] = (conv, ssm) after col
2809}
2810/// Opaque handle for the dspark round (dflash.rs) — VerifyCkpt stays spec-private.
2811pub(crate) struct DsparkVerifyCkpt(VerifyCkpt);
2812
2813/// Engine-bundle slice 3 (DSF-ROUNDCOST-20260820 §2 row 4 / §5 rank 1): bucketed CUDA
2814/// graphs for the dspark verify's LINEAR-layer segments. The measured verify is ~2,800
2815/// eager launches whose residual cost is DEVICE-side per-launch overhead (slice 2 proved
2816/// host dispatch is not the binder: fully-deferred dispatch bought ~0 wall). The 48 GDN
2817/// layers between full-attention layers are shape-static given vt — no positions, no
2818/// t_kv, state addressed through pointer tables — so runs of them capture per
2819/// (segment, vt) and replay as ONE graph launch each. Full-attention layers stay eager
2820/// (their per-row append/fa arm picks are t_kv-driven — the exec-update extension).
2821///
2822/// Per round out-of-graph: one pointer-table refresh (gdn ping-pong moves the canonical
2823/// handles), one input-staging copy per segment, host parity bookkeeping. Captured via
2824/// `capture_graph_retained` (2 warmups + capture, keeper retains warmup transients so
2825/// pool addresses stay stable); the warmups EXECUTE, so segment conv/ssm state is saved
2826/// before and restored after — the graph's first real launch starts from the exact
2827/// pre-round state. The ckpt column stash rides persistent slabs (written inside the
2828/// graph as memcpy nodes); commit reads them via `dspark_commit_prefix_slab`.
2829/// `MEMRA_DSPARK_VERIFY_GRAPH=0` reverts to the eager walk (byte-identical body).
2830pub(crate) struct DsparkVerifyGraphs {
2831 /// Linear-attention layer indices ascending; `lin_pos[il]` = index into the vecs.
2832 lin: Vec<usize>,
2833 lin_pos: std::collections::HashMap<usize, usize>,
2834 /// [n_lin x 6] pointer table (conv, s0, s1, conv, s1, s0 per layer), refreshed per
2835 /// verify from the live handles; layer il's slice starts at lin_pos[il]*6.
2836 table_all: CudaSlice<u64>,
2837 host_table: Vec<u64>,
2838 /// Persistent per-layer ckpt stash slabs: row r of the verify at slab offset
2839 /// r*words. Shared by every (segment, vt) bucket — one verify runs at a time.
2840 stash_conv: Vec<CudaSlice<f32>>,
2841 stash_ssm: Vec<CudaSlice<f32>>,
2842 conv_words: usize,
2843 ssm_words: usize,
2844 /// Per-vt input/output staging (stable addresses the graphs bake).
2845 stage: std::collections::HashMap<usize, (CudaSlice<f32>, CudaSlice<f32>)>,
2846 /// Per-vt dflash tap-sink buffers — the captured segments bake the tap dst address,
2847 /// so the sink buffer must live (and persist) with the graphs, not with the round.
2848 pub(crate) tap_bufs: std::collections::HashMap<usize, CudaSlice<f32>>,
2849 graphs: std::collections::HashMap<(usize, usize), DsparkSegGraph>,
2850 /// Warmup-corruption guard scratch: pre-capture conv/ssm of every linear layer
2851 /// (sized n_lin — the slice-4c full-verify warmups execute the whole walk).
2852 save_conv: CudaSlice<f32>,
2853 save_ssm: CudaSlice<f32>,
2854 max_run: usize,
2855 n_embd: usize,
2856 /// Set by the verify walk: this round's linear ckpt lives in the slabs (the caller
2857 /// commits through `dspark_commit_prefix_slab` instead of the cols arm).
2858 pub(crate) round_slab: bool,
2859 // ---- slice 4c: full-verify single graph per (vt, rung) ----
2860 /// Full-attention layer indices ascending; `fa_pos[il]` = index into the vec.
2861 fa: Vec<usize>,
2862 fa_pos: std::collections::HashMap<usize, usize>,
2863 /// [n_fa x 2 x t_cap] interleaved (k,v) base-pointer pairs, refreshed per verify;
2864 /// layer il's slice starts at `fa_pos[il] * 2 * t_cap` (the seqs twins read pairs
2865 /// [2z], z < t <= t_cap, so one t_cap-sized table serves every vt).
2866 fa_table: CudaSlice<u64>,
2867 fa_host_table: Vec<u64>,
2868 t_cap: usize,
2869 /// Per-vt position staging for the captured bodies — contents refreshed per round
2870 /// (rope reads row r; the seqs twins derive append slot and T_kv per z from it).
2871 pos_stage: std::collections::HashMap<usize, CudaSlice<i32>>,
2872 /// Full-verify graphs keyed (vt, rung_end, hi).
2873 full: std::collections::HashMap<(usize, usize, usize), DsparkSegGraph>,
2874 /// Largest n with every layer in [0, n) linear or full-attention (walk coverage).
2875 covered: usize,
2876 /// Every layer in [0, n) is linear or full-attention (no MLA/unknown mixers) — the
2877 /// full-verify capture walks all of them.
2878 walk_uniform: bool,
2879 /// Last `(captures, device graph-mem reserved bytes)` reading taken by
2880 /// `HybridModel::dspark_vg_admission_debt` — the two-point base of the MARGINAL debt
2881 /// projection (see `dspark_vg_debt_projection`; a mean-based reading extrapolated the
2882 /// pool's one-time shared allocation and reserved 8.5 GB of phantom VRAM).
2883 debt_obs: Option<(usize, usize)>,
2884}
2885
2886struct DsparkSegGraph {
2887 graph: cudarc::driver::CudaGraph,
2888 _keeper: Vec<Box<dyn std::any::Any + Send>>,
2889}
2890
2891/// Per-call arguments of [`HybridModel::qwen35_tparallel_fa_layer`] — one struct so the
2892/// eager walk and the slice-4c captured full-verify graphs hand the SAME body its two
2893/// modes without a second copy of the math.
2894pub(crate) struct FaLayerArgs<'a> {
2895 /// [T] per-row positions (device): rope reads them row-indexed; the seqs twins read
2896 /// them per-z (append slot = pos, T_kv = pos + 1).
2897 pub pos_d: &'a CudaSlice<i32>,
2898 /// Verify-level lazy per-row 1-element position buffers — only the per-row fallback
2899 /// arm builds/uses them (graph mode refuses that arm).
2900 pub pos_rows: &'a mut Option<Vec<CudaSlice<i32>>>,
2901 pub pos0: usize,
2902 pub seqs_append: bool,
2903 pub batch_fa_on: bool,
2904 /// Some((kv pointer table, offset-in-u64s, rung_end)) = captured-graph mode.
2905 pub graph_cap: Option<(&'a CudaSlice<u64>, usize, usize)>,
2906 /// ROUND-STREAM (lane/draftcost-moe, v0.100 train merge): Some((token stream, device
2907 /// round counter)) routes the FA attend through the dc rows kernels and the Linear
2908 /// mixer through `linear_attn_verify_t` (the stream arms the old inline body carried).
2909 /// Never armed together with `graph_cap` (the verify-level merge guard refuses).
2910 pub stream: Option<(&'a CudaSlice<u32>, &'a CudaSlice<i32>)>,
2911 /// VerifyCkpt for the stream-Linear arm's GdnStash install; None in graph mode and
2912 /// for FA layers that never touch it.
2913 pub ckpt: Option<&'a mut VerifyCkpt>,
2914}
2915
2916// SAFETY: `CudaGraph` is not marked Send by cudarc because its raw driver handles carry
2917// no automatic trait; CUDA driver graph handles are context-scoped rather than
2918// OS-thread-affine (the SpecPipeSessionPtr precedent above). The ctx lives in
2919// `HybridModel::dspark_vgraphs` behind a Mutex and every touch happens on the engine's
2920// single decode-stream thread.
2921unsafe impl Send for DsparkVerifyGraphs {}
2922
2923impl DsparkVerifyGraphs {
2924 /// Live capture count (segment + full graphs) — the denominator of
2925 /// [`dspark_vg_debt_projection`]'s observed bytes/capture mean.
2926 pub(crate) fn captures(&self) -> usize {
2927 self.graphs.len() + self.full.len()
2928 }
2929
2930 /// Take the marginal-growth debt reading and record this observation for the next one.
2931 /// Called under the pool mutex by `HybridModel::dspark_vg_admission_debt`.
2932 pub(crate) fn admission_debt(&mut self, reserved_bytes: usize) -> usize {
2933 let captures = self.captures();
2934 let debt =
2935 dspark_vg_debt_projection(captures, dspark_vg_cap(), reserved_bytes, self.debt_obs);
2936 if captures > 0 {
2937 match self.debt_obs {
2938 Some((c0, _)) if captures <= c0 => {}
2939 _ => self.debt_obs = Some((captures, reserved_bytes)),
2940 }
2941 }
2942 debt
2943 }
2944
2945 /// Build for this cache's shape. None when there are no linear layers, sizes are
2946 /// non-uniform, or the trunk keeps a gemma4 config (never on the qwen35 family).
2947 pub(crate) fn new(
2948 e: &Engine,
2949 cache: &Cache,
2950 t_max: usize,
2951 n_embd: usize,
2952 ) -> Result<Option<Self>, Box<dyn std::error::Error>> {
2953 let lin: Vec<usize> = (0..cache.recur.len())
2954 .filter(|&il| cache.recur[il].is_some())
2955 .collect();
2956 if lin.is_empty() || t_max < 2 {
2957 return Ok(None);
2958 }
2959 let first = cache.recur[lin[0]].as_ref().unwrap();
2960 let (conv_words, ssm_words) = (first.conv_state.len(), first.ssm_state.len());
2961 for &il in &lin {
2962 let rl = cache.recur[il].as_ref().unwrap();
2963 if rl.conv_state.len() != conv_words || rl.ssm_state.len() != ssm_words {
2964 return Ok(None);
2965 }
2966 }
2967 let n = lin.len();
2968 let mut lin_pos = std::collections::HashMap::with_capacity(n);
2969 for (k, &il) in lin.iter().enumerate() {
2970 lin_pos.insert(il, k);
2971 }
2972 // longest run of consecutive linear layers (save-scratch sizing)
2973 let mut max_run = 1usize;
2974 let mut run = 1usize;
2975 for w in lin.windows(2) {
2976 if w[1] == w[0] + 1 {
2977 run += 1;
2978 max_run = max_run.max(run);
2979 } else {
2980 run = 1;
2981 }
2982 }
2983 let rows = t_max - 1;
2984 let mut stash_conv = Vec::with_capacity(n);
2985 let mut stash_ssm = Vec::with_capacity(n);
2986 for _ in 0..n {
2987 stash_conv.push(e.uninit(rows * conv_words)?);
2988 stash_ssm.push(e.uninit(rows * ssm_words)?);
2989 }
2990 let host_table = vec![0u64; n * 6];
2991 let table_all = e.htod_u64(&host_table)?;
2992 // slice 4c: full-attention census for the full-verify graphs.
2993 let fa: Vec<usize> = (0..cache.kv.len())
2994 .filter(|&il| cache.kv[il].is_some())
2995 .collect();
2996 let mut fa_pos = std::collections::HashMap::with_capacity(fa.len());
2997 for (k, &il) in fa.iter().enumerate() {
2998 fa_pos.insert(il, k);
2999 }
3000 let n_layers = cache.kv.len().max(cache.recur.len());
3001 // exactly one of (linear state, kv cache) per layer — no MLA/unknown mixers.
3002 let walk_uniform = (0..n_layers).all(|il| {
3003 cache.recur.get(il).is_some_and(|r| r.is_some())
3004 != cache.kv.get(il).is_some_and(|k| k.is_some())
3005 });
3006 // Contiguous covered prefix: the largest n such that every layer in [0, n) is
3007 // linear or full-attention. The TRUNK walk is [0, layers.len()) and the cache
3008 // vecs can carry EXTRA state slots past it (the q38 export keeps the MTP head
3009 // layer's kv at the tail — hi == lin+fa never held, the s4c battery's zero
3010 // 'full' captures). The full-graph guard is walk coverage, not slot arithmetic.
3011 let covered = (0..n_layers)
3012 .take_while(|il| lin_pos.contains_key(il) || fa_pos.contains_key(il))
3013 .count();
3014 let t_cap = t_max;
3015 let fa_host_table = vec![0u64; fa.len() * 2 * t_cap];
3016 let fa_table = e.htod_u64(&fa_host_table)?;
3017 Ok(Some(Self {
3018 lin,
3019 lin_pos,
3020 table_all,
3021 host_table,
3022 stash_conv,
3023 stash_ssm,
3024 conv_words,
3025 ssm_words,
3026 stage: std::collections::HashMap::new(),
3027 tap_bufs: std::collections::HashMap::new(),
3028 graphs: std::collections::HashMap::new(),
3029 save_conv: e.uninit(n * conv_words)?,
3030 save_ssm: e.uninit(n * ssm_words)?,
3031 max_run,
3032 n_embd,
3033 round_slab: false,
3034 fa,
3035 fa_pos,
3036 fa_table,
3037 fa_host_table,
3038 t_cap,
3039 pos_stage: std::collections::HashMap::new(),
3040 full: std::collections::HashMap::new(),
3041 covered,
3042 walk_uniform,
3043 debt_obs: None,
3044 }))
3045 }
3046
3047 /// Rebuild the pointer tables from the live handles (once per verify — the gdn
3048 /// ping-pong swaps the canonical/alt handles between rounds; a fresh generation's
3049 /// cache buffers land at new addresses; a stale table would read the wrong state).
3050 pub(crate) fn refresh_tables(
3051 &mut self,
3052 e: &Engine,
3053 cache: &Cache,
3054 ) -> Result<(), Box<dyn std::error::Error>> {
3055 use cudarc::driver::DevicePtr;
3056 {
3057 let s = &e.gpu.stream();
3058 for (k, &il) in self.lin.iter().enumerate() {
3059 let rl = cache.recur[il].as_ref().unwrap();
3060 let (pc, _g0) = rl.conv_state.device_ptr(s);
3061 let (p0, _g1) = rl.ssm_state.device_ptr(s);
3062 let (p1, _g2) = rl.ssm_state_alt.device_ptr(s);
3063 let o = k * 6;
3064 self.host_table[o] = pc;
3065 self.host_table[o + 1] = p0;
3066 self.host_table[o + 2] = p1;
3067 self.host_table[o + 3] = pc;
3068 self.host_table[o + 4] = p1;
3069 self.host_table[o + 5] = p0;
3070 }
3071 for (k, &il) in self.fa.iter().enumerate() {
3072 let kvl = cache.kv[il].as_ref().unwrap();
3073 let (pk, _g0) = kvl.k.device_ptr(s);
3074 let (pv, _g1) = kvl.v.device_ptr(s);
3075 let o = k * 2 * self.t_cap;
3076 for z in 0..self.t_cap {
3077 self.fa_host_table[o + 2 * z] = pk;
3078 self.fa_host_table[o + 2 * z + 1] = pv;
3079 }
3080 }
3081 }
3082 e.htod_u64_into(&self.host_table, &mut self.table_all)?;
3083 if !self.fa_host_table.is_empty() {
3084 e.htod_u64_into(&self.fa_host_table, &mut self.fa_table)?;
3085 }
3086 Ok(())
3087 }
3088
3089 /// Slice 4c eligibility: Some(rung_end) when this round can replay (or capture) a
3090 /// full-verify graph — the whole walk [lo, hi) is covered, every layer is linear or
3091 /// full-attention, and ALL of the round's per-row t_kv values take the v4-seqs arm
3092 /// on ONE `fa_split_keys` ladder step that the rung also sits on (the straddle law;
3093 /// both gates are t_kv intervals, so ends-inside means all-inside). The rung is the
3094 /// round's next power of two — grid/partial sizing only (`n_splits_max` is pure
3095 /// stride; splits >= ns_eff write the empty partial the combine never reads), so one
3096 /// captured graph is bit-identical for every round the rung covers.
3097 #[allow(clippy::too_many_arguments)]
3098 pub(crate) fn full_rung(
3099 &self,
3100 model: &crate::hybrid::HybridModel,
3101 cache: &Cache,
3102 lo: usize,
3103 hi: usize,
3104 t: usize,
3105 seqs_arms_on: bool,
3106 ) -> Option<usize> {
3107 if std::env::var("MEMRA_DSPARK_FULLG_DEBUG").as_deref() == Ok("1") {
3108 static ONCE: std::sync::Once = std::sync::Once::new();
3109 let len0 = self
3110 .fa
3111 .first()
3112 .and_then(|&il| cache.kv[il].as_ref())
3113 .map(|k| k.len);
3114 ONCE.call_once(|| {
3115 eprintln!(
3116 "[fullg-debug] walk_uniform={} covered={} seqs_arms_on={} fa_rows_on={} t={} lo={} hi={} lin={} fa={} t_cap={} len0={:?}",
3117 self.walk_uniform, self.covered, seqs_arms_on, dspark_fa_rows_on(), t, lo, hi,
3118 self.lin.len(), self.fa.len(), self.t_cap, len0
3119 );
3120 });
3121 }
3122 if !self.walk_uniform
3123 || !seqs_arms_on
3124 || !dspark_fa_rows_on()
3125 || t < 2
3126 || lo != 0
3127 || hi > self.covered
3128 || t > self.t_cap
3129 || self.fa.is_empty()
3130 {
3131 return None;
3132 }
3133 let cfg = &model.cfg;
3134 let head_dim_global = cfg.head_dim_k as usize;
3135 let nkv = cfg.n_head_kv as usize;
3136 let kvl0 = cache.kv[self.fa[0]].as_ref().unwrap();
3137 // the z-batched twins read stacked rows at the cache's kv dims — must equal the
3138 // projection stride (the body's guard, hoisted so ineligible models fall back
3139 // instead of refusing mid-capture).
3140 let geom = cfg.full_attention_geometry_at(self.fa[0] as u32);
3141 let kv_dim = geom.n_head_kv as usize * geom.head_dim_k as usize;
3142 if kvl0.kv_dim_k != kv_dim || kvl0.kv_dim_v != kv_dim {
3143 return None;
3144 }
3145 let len0 = kvl0.len;
3146 let (t_kv_first, t_kv_last) = (len0 + 1, len0 + t);
3147 if !crate::fa_seqs_eligible(t_kv_first, head_dim_global)
3148 || !crate::fa_seqs_eligible(t_kv_last, head_dim_global)
3149 || crate::fa_split_keys(t_kv_first, nkv) != crate::fa_split_keys(t_kv_last, nkv)
3150 {
3151 return None;
3152 }
3153 let rung = t_kv_last.next_power_of_two().max(256);
3154 if crate::fa_split_keys(rung, nkv) != crate::fa_split_keys(t_kv_last, nkv) {
3155 return None;
3156 }
3157 Some(rung)
3158 }
3159
3160 /// Run the WHOLE verify walk [lo, hi) as one captured graph at (vt=t, rung): stage
3161 /// the residual + refresh the per-vt position staging, capture on first encounter
3162 /// (2 executing warmups bracketed by a full linear-state save/restore; KV warmup
3163 /// appends write the exact slots the replay writes — idempotent), launch, then apply
3164 /// the host bookkeeping the captured body skipped (per-linear-layer parity swap for
3165 /// odd t, per-fa-layer len bump). Returns the fresh residual.
3166 #[allow(clippy::too_many_arguments)]
3167 #[allow(clippy::map_entry)] // allow: the init body is fallible (`?`); Entry::or_insert_with cannot propagate errors
3168 pub(crate) fn run_full(
3169 &mut self,
3170 model: &crate::hybrid::HybridModel,
3171 e: &Engine,
3172 lo: usize,
3173 hi: usize,
3174 x: &CudaSlice<f32>,
3175 t: usize,
3176 pos0: usize,
3177 rung: usize,
3178 cache: &mut Cache,
3179 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3180 let n_embd = self.n_embd;
3181 if !self.stage.contains_key(&t) {
3182 let xin = e.uninit(t * n_embd)?;
3183 let xout = e.uninit(t * n_embd)?;
3184 self.stage.insert(t, (xin, xout));
3185 }
3186 if !self.pos_stage.contains_key(&t) {
3187 self.pos_stage.insert(t, e.htod_i32(&vec![0i32; t])?);
3188 }
3189 // Per-round refresh: position contents + input staging (both addresses are baked
3190 // by the captured bodies; only their CONTENTS change round to round).
3191 {
3192 let pos_host: Vec<i32> = (0..t).map(|r| (pos0 + r) as i32).collect();
3193 let pb = self.pos_stage.get_mut(&t).unwrap();
3194 e.htod_i32_into(pb, &pos_host)?;
3195 let (xin, _) = self.stage.get_mut(&t).unwrap();
3196 e.copy_into(xin, 0, x, t * n_embd)?;
3197 }
3198 let key = (t, rung, hi);
3199 if !self.full.contains_key(&key) {
3200 // The warmups EXECUTE the whole walk on live state — save every linear
3201 // layer's conv + canonical ssm first, restore after (KV needs no restore:
3202 // graph mode never bumps host lens and the appends write this round's own
3203 // slots).
3204 for (k, &il) in self.lin.iter().enumerate() {
3205 let rl = cache.recur[il].as_ref().unwrap();
3206 e.copy_into(
3207 &mut self.save_conv,
3208 k * self.conv_words,
3209 &rl.conv_state,
3210 self.conv_words,
3211 )?;
3212 e.copy_into(
3213 &mut self.save_ssm,
3214 k * self.ssm_words,
3215 &rl.ssm_state,
3216 self.ssm_words,
3217 )?;
3218 }
3219 let (graph, keeper) = {
3220 let table_all = &self.table_all;
3221 let lin_pos = &self.lin_pos;
3222 let fa_pos = &self.fa_pos;
3223 let fa_table = &self.fa_table;
3224 let t_cap = self.t_cap;
3225 let stash_conv = &mut self.stash_conv;
3226 let stash_ssm = &mut self.stash_ssm;
3227 let pos_d: &CudaSlice<i32> = &self.pos_stage[&t];
3228 let (xin, xout) = self
3229 .stage
3230 .get_mut(&t)
3231 .map(|(a, b)| (&*a, b))
3232 .expect("stage bucket created above");
3233 let cache_ref: &mut Cache = cache;
3234 let iflag = if std::env::var("MEMRA_DSPARK_VG_AUTOFREE").as_deref() == Ok("1") {
3235 cudarc::driver::sys::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH
3236 } else {
3237 cudarc::driver::sys::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY
3238 };
3239 e.capture_graph_retained_flags(iflag, move |e| {
3240 let mut xc: Option<CudaSlice<f32>> = None;
3241 for il in lo..hi {
3242 let xr: &CudaSlice<f32> = xc.as_ref().unwrap_or(xin);
3243 let nx = if let Some(&k) = lin_pos.get(&il) {
3244 model.qwen35_tparallel_linear_layer(
3245 e,
3246 il,
3247 xr,
3248 t,
3249 cache_ref,
3250 None,
3251 Some((&mut stash_conv[k], &mut stash_ssm[k])),
3252 Some((table_all, k * 6)),
3253 )?
3254 } else if let Some(&kf) = fa_pos.get(&il) {
3255 let mut no_rows: Option<Vec<CudaSlice<i32>>> = None;
3256 model.qwen35_tparallel_fa_layer(
3257 e,
3258 il,
3259 xr,
3260 t,
3261 cache_ref,
3262 FaLayerArgs {
3263 pos_d,
3264 pos_rows: &mut no_rows,
3265 pos0,
3266 seqs_append: true,
3267 batch_fa_on: true,
3268 graph_cap: Some((fa_table, kf * 2 * t_cap, rung)),
3269 stream: None,
3270 ckpt: None,
3271 },
3272 )?
3273 } else {
3274 return Err(format!(
3275 "run_full: layer {il} is neither linear nor full-attention"
3276 )
3277 .into());
3278 };
3279 xc = Some(nx);
3280 }
3281 e.copy_into(xout, 0, xc.as_ref().unwrap(), t * n_embd)?;
3282 Ok(())
3283 })?
3284 };
3285 // Undo the net host parity motion of the 3 body runs (each run swaps iff t
3286 // is odd -> 3 runs = net one swap), then restore the device state the
3287 // warmups consumed (walk scope only — layers past hi never executed). The
3288 // launch below then behaves exactly like one run.
3289 if t % 2 == 1 {
3290 for &il in &self.lin {
3291 if il < lo || il >= hi {
3292 continue;
3293 }
3294 let rl = cache.recur[il].as_mut().unwrap();
3295 std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
3296 }
3297 }
3298 for (k, &il) in self.lin.iter().enumerate() {
3299 if il < lo || il >= hi {
3300 continue;
3301 }
3302 let rl = cache.recur[il].as_mut().unwrap();
3303 let (cw, sw) = (self.conv_words, self.ssm_words);
3304 {
3305 let sv = e.view(&self.save_conv, self.lin.len() * cw);
3306 let win = sv.slice(k * cw..(k + 1) * cw);
3307 e.copy_view_into(&mut rl.conv_state, 0, &win, cw)?;
3308 }
3309 {
3310 let sv = e.view(&self.save_ssm, self.lin.len() * sw);
3311 let win = sv.slice(k * sw..(k + 1) * sw);
3312 e.copy_view_into(&mut rl.ssm_state, 0, &win, sw)?;
3313 }
3314 }
3315 if std::env::var("MEMRA_GRAPH_CENSUS").as_deref() == Ok("1")
3316 && let Ok(c) = crate::graph_update::node_census(&graph)
3317 {
3318 eprintln!("[dspark-vg-census] full vt={t} rung={rung} {c:?}");
3319 }
3320 self.full.insert(
3321 key,
3322 DsparkSegGraph {
3323 graph,
3324 _keeper: keeper,
3325 },
3326 );
3327 }
3328 self.full[&key].graph.launch()?;
3329 // Host bookkeeping for the replayed body (captured host code does not re-run):
3330 // gdn parity swap per linear layer (t odd), kv len bump per fa layer — scoped
3331 // to the WALK [lo, hi): the cache can carry extra state slots past it (the MTP
3332 // head layer's kv) that the walk never touches.
3333 if t % 2 == 1 {
3334 for &il in &self.lin {
3335 if il < lo || il >= hi {
3336 continue;
3337 }
3338 let rl = cache.recur[il].as_mut().unwrap();
3339 std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
3340 }
3341 }
3342 for &il in &self.fa {
3343 if il < lo || il >= hi {
3344 continue;
3345 }
3346 cache.kv[il].as_mut().unwrap().len += t;
3347 }
3348 let (_, xout) = self.stage.get(&t).unwrap();
3349 let mut out = e.uninit(t * n_embd)?;
3350 e.copy_into(&mut out, 0, xout, t * n_embd)?;
3351 Ok(out)
3352 }
3353
3354 /// Run layers [start, end) (all linear) as one captured graph at this vt: stage the
3355 /// residual into the bucket's x_in, capture on first encounter (2 executing warmups
3356 /// bracketed by a segment state save/restore), launch, then apply the host parity
3357 /// bookkeeping the captured body would have done. Returns the fresh residual.
3358 #[allow(clippy::too_many_arguments)]
3359 #[allow(clippy::map_entry)] // allow: the init body is fallible (`?`); Entry::or_insert_with cannot propagate errors
3360 fn run_segment(
3361 &mut self,
3362 model: &crate::hybrid::HybridModel,
3363 e: &Engine,
3364 start: usize,
3365 end: usize,
3366 x: &CudaSlice<f32>,
3367 t: usize,
3368 cache: &mut Cache,
3369 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
3370 let n_embd = self.n_embd;
3371 debug_assert!(end - start <= self.max_run);
3372 if !self.stage.contains_key(&t) {
3373 let xin = e.uninit(t * n_embd)?;
3374 let xout = e.uninit(t * n_embd)?;
3375 self.stage.insert(t, (xin, xout));
3376 }
3377 // Stage the residual at the bucket's baked input address.
3378 {
3379 let (xin, _) = self.stage.get_mut(&t).unwrap();
3380 e.copy_into(xin, 0, x, t * n_embd)?;
3381 }
3382 let key = (start, t);
3383 if !self.graphs.contains_key(&key) {
3384 // The 2 warmups EXECUTE the segment on live state — save conv + the canonical
3385 // ssm of every segment layer first, restore after, so the graph's first real
3386 // launch starts from the exact pre-round state (bytes gated e2e).
3387 for (k, il) in (start..end).enumerate() {
3388 let rl = cache.recur[il].as_ref().unwrap();
3389 e.copy_into(
3390 &mut self.save_conv,
3391 k * self.conv_words,
3392 &rl.conv_state,
3393 self.conv_words,
3394 )?;
3395 e.copy_into(
3396 &mut self.save_ssm,
3397 k * self.ssm_words,
3398 &rl.ssm_state,
3399 self.ssm_words,
3400 )?;
3401 }
3402 let (graph, keeper) = {
3403 let table_all = &self.table_all;
3404 let lin_pos = &self.lin_pos;
3405 let stash_conv = &mut self.stash_conv;
3406 let stash_ssm = &mut self.stash_ssm;
3407 let (xin, xout) = self
3408 .stage
3409 .get_mut(&t)
3410 .map(|(a, b)| (&*a, b))
3411 .expect("stage bucket created above");
3412 let cache_ref: &mut Cache = cache;
3413 // Slice 4 (fa-execupdate lane): USE_NODE_PRIORITY instead of
3414 // AUTO_FREE_ON_LAUNCH. The slice-3 measured limiter was AUTO_FREE's
3415 // launch-time mem-pool scan — 25.6 us per cuGraphLaunch x 16 segments
3416 // = ~0.41 ms/round, most of the eager-launch savings. The captured
3417 // body's cuMemAllocAsync transients are BALANCED by in-graph frees
3418 // (every transient drops inside the capture region — the generic
3419 // capture path's census precedent, 1589/1589), so AUTO_FREE has
3420 // nothing to reclaim and the graph is legal to instantiate without
3421 // it; PRIORITY is the flag the gemma slotted door ships for exactly
3422 // this reason (both alternatives drop the scan; UPLOAD via
3423 // cuGraphInstantiateWithFlags is WithParams-only and refused).
3424 // MEMRA_DSPARK_VG_AUTOFREE=1 reverts; MEMRA_GRAPH_CENSUS=1 prints
3425 // the node census at capture (the ALLOC==FREE receipt).
3426 let iflag = if std::env::var("MEMRA_DSPARK_VG_AUTOFREE").as_deref() == Ok("1") {
3427 cudarc::driver::sys::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_AUTO_FREE_ON_LAUNCH
3428 } else {
3429 cudarc::driver::sys::CUgraphInstantiate_flags::CUDA_GRAPH_INSTANTIATE_FLAG_USE_NODE_PRIORITY
3430 };
3431 e.capture_graph_retained_flags(iflag, move |e| {
3432 let mut xc: Option<CudaSlice<f32>> = None;
3433 for il in start..end {
3434 let k = lin_pos[&il];
3435 let xr: &CudaSlice<f32> = xc.as_ref().unwrap_or(xin);
3436 let nx = model.qwen35_tparallel_linear_layer(
3437 e,
3438 il,
3439 xr,
3440 t,
3441 cache_ref,
3442 None,
3443 Some((&mut stash_conv[k], &mut stash_ssm[k])),
3444 Some((table_all, k * 6)),
3445 )?;
3446 xc = Some(nx);
3447 }
3448 e.copy_into(xout, 0, xc.as_ref().unwrap(), t * n_embd)?;
3449 Ok(())
3450 })?
3451 };
3452 // Undo the net host parity motion of the 3 body runs (each run swaps iff t
3453 // is odd -> 3 runs = net one swap), then restore the device state the
3454 // warmups consumed. The launch below then behaves exactly like one run.
3455 if t % 2 == 1 {
3456 for il in start..end {
3457 let rl = cache.recur[il].as_mut().unwrap();
3458 std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
3459 }
3460 }
3461 for (k, il) in (start..end).enumerate() {
3462 let rl = cache.recur[il].as_mut().unwrap();
3463 let (cw, sw) = (self.conv_words, self.ssm_words);
3464 {
3465 let sv = e.view(&self.save_conv, self.lin.len() * cw);
3466 let win = sv.slice(k * cw..(k + 1) * cw);
3467 e.copy_view_into(&mut rl.conv_state, 0, &win, cw)?;
3468 }
3469 {
3470 let sv = e.view(&self.save_ssm, self.lin.len() * sw);
3471 let win = sv.slice(k * sw..(k + 1) * sw);
3472 e.copy_view_into(&mut rl.ssm_state, 0, &win, sw)?;
3473 }
3474 }
3475 if std::env::var("MEMRA_GRAPH_CENSUS").as_deref() == Ok("1")
3476 && let Ok(c) = crate::graph_update::node_census(&graph)
3477 {
3478 eprintln!("[dspark-vg-census] seg={start}..{end} vt={t} {c:?}");
3479 }
3480 self.graphs.insert(
3481 key,
3482 DsparkSegGraph {
3483 graph,
3484 _keeper: keeper,
3485 },
3486 );
3487 }
3488 self.graphs[&key].graph.launch()?;
3489 // Host parity bookkeeping for the replayed body (the captured host swaps do not
3490 // re-run at replay).
3491 if t % 2 == 1 {
3492 for il in start..end {
3493 let rl = cache.recur[il].as_mut().unwrap();
3494 std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
3495 }
3496 }
3497 let (_, xout) = self.stage.get(&t).unwrap();
3498 let mut out = e.uninit(t * n_embd)?;
3499 e.copy_into(&mut out, 0, xout, t * n_embd)?;
3500 Ok(out)
3501 }
3502
3503 /// Pool freeze check (`dspark_vg_cap`): below the ceiling new keys may capture.
3504 fn can_capture(&self) -> bool {
3505 self.graphs.len() + self.full.len() < dspark_vg_cap()
3506 }
3507
3508 /// Round-atomic segment-door readiness: TRUE when this round's walk can ride the
3509 /// per-(segment, vt) graphs without a NEW capture past the pool ceiling — every
3510 /// linear run in [lo, hi) already has its (run_start, t) key, or capture is still
3511 /// allowed. FALSE sends the WHOLE round down the eager cols-ckpt walk: a partial
3512 /// refusal would stash some layers in the ctx slabs and others in the round's cols
3513 /// while one commit reads only one of them.
3514 pub(crate) fn segments_ready(
3515 &self,
3516 model: &crate::hybrid::HybridModel,
3517 lo: usize,
3518 hi: usize,
3519 t: usize,
3520 ) -> bool {
3521 if self.can_capture() {
3522 return true;
3523 }
3524 let mut il = lo;
3525 while il < hi {
3526 if matches!(model.layers[il].mixer, Mixer::Linear(_)) {
3527 let start = il;
3528 while il < hi && matches!(model.layers[il].mixer, Mixer::Linear(_)) {
3529 il += 1;
3530 }
3531 if !self.graphs.contains_key(&(start, t)) {
3532 return false;
3533 }
3534 } else {
3535 il += 1;
3536 }
3537 }
3538 true
3539 }
3540
3541 /// Widest verify window this pool was built for. A caller whose round exceeds it must
3542 /// take the eager walk: the stash slabs hold `t_capacity() - 1` column rows, and slicing
3543 /// past them is a panic rather than a refusal.
3544 pub(crate) fn t_capacity(&self) -> usize {
3545 self.t_cap
3546 }
3547
3548 /// Slab row (conv, ssm) device pointers + lengths for the commit restore of column
3549 /// `row` (0-based) of layer `il`. None for non-linear layers.
3550 pub(crate) fn slab_row(
3551 &self,
3552 e: &Engine,
3553 il: usize,
3554 row: usize,
3555 ) -> Option<(u64, u64, usize, usize)> {
3556 use cudarc::driver::DevicePtr;
3557 let k = *self.lin_pos.get(&il)?;
3558 let s = &e.gpu.stream();
3559 let (pc, _g0) = self.stash_conv[k].device_ptr(s);
3560 let (ps, _g1) = self.stash_ssm[k].device_ptr(s);
3561 Some((
3562 pc + (row * self.conv_words * 4) as u64,
3563 ps + (row * self.ssm_words * 4) as u64,
3564 self.conv_words,
3565 self.ssm_words,
3566 ))
3567 }
3568}
3569
3570impl VerifyCkpt {
3571 fn new(n_layer: usize) -> Self {
3572 VerifyCkpt {
3573 gdn: (0..n_layer).map(|_| None).collect(),
3574 cols: (0..n_layer).map(|_| None).collect(),
3575 }
3576 }
3577}
3578
3579/// The stage-0/TX half of one PP verify. The boundary slot is the ownership token: stage 1
3580/// consumes exactly the slot selected by `tx()` / `tx_pipelined()`, never a slot inferred from
3581/// a logical round number.
3582struct VerifyBoundaryTicket {
3583 rt: &'static crate::pp::PpNRt,
3584 caller_stream: std::sync::Arc<cudarc::driver::CudaStream>,
3585 slot: usize,
3586 pos0: usize,
3587 t: usize,
3588 payload: usize,
3589 n_st: usize,
3590 pipelined: bool,
3591 pp_anatomy: bool,
3592 pp_started: std::time::Instant,
3593 reverse_ms: f64,
3594 stage0_ms: f64,
3595 tx_ms: f64,
3596 trace: Option<SpecPipeTraceCtx>,
3597 _walk_owner: crate::pp::PpWalkLease,
3598}
3599
3600/// Explicit OPTIPIPE diagnostic control. Forced modes are set only by `optipipe-gate`; the
3601/// increment-2 controller can also be armed by the server's fresh-process research door.
3602#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3603pub enum OptiForkGateMode {
3604 Disabled,
3605 Hit,
3606 Miss,
3607 Alternate,
3608 Abort,
3609 Controller,
3610}
3611
3612static OPTI_FORK_GATE_MODE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
3613static OPTI_CONTROLLER_THRESHOLD: std::sync::atomic::AtomicU32 =
3614 std::sync::atomic::AtomicU32::new(0);
3615static OPTI_FORK_ATTEMPTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3616static OPTI_FORK_HITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3617static OPTI_FORK_MISSES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3618static OPTI_FORK_ABORT_DRAINS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3619static OPTI_FORK_REFUSALS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3620static OPTI_GATE_CHECKS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3621static OPTI_GATE_ADMITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3622static OPTI_GATE_REJECTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3623static OPTI_RECONCILES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3624static OPTI_WASTED_DRAFT_TOKENS: std::sync::atomic::AtomicU64 =
3625 std::sync::atomic::AtomicU64::new(0);
3626static OPTI_SHADOW_DRAFT_TOKENS: std::sync::atomic::AtomicU64 =
3627 std::sync::atomic::AtomicU64::new(0);
3628static OPTI_BREAKER_TRIPS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3629
3630impl OptiForkGateMode {
3631 fn code(self) -> u8 {
3632 match self {
3633 Self::Disabled => 0,
3634 Self::Hit => 1,
3635 Self::Miss => 2,
3636 Self::Alternate => 3,
3637 Self::Abort => 4,
3638 Self::Controller => 5,
3639 }
3640 }
3641
3642 fn configured() -> Self {
3643 match OPTI_FORK_GATE_MODE.load(std::sync::atomic::Ordering::Relaxed) {
3644 1 => Self::Hit,
3645 2 => Self::Miss,
3646 3 => Self::Alternate,
3647 4 => Self::Abort,
3648 5 => Self::Controller,
3649 _ => Self::Disabled,
3650 }
3651 }
3652
3653 fn action(self, generation: u64) -> OptiForkAction {
3654 match self {
3655 Self::Hit => OptiForkAction::Hit,
3656 Self::Miss => OptiForkAction::Miss,
3657 Self::Alternate if generation & 1 == 0 => OptiForkAction::Hit,
3658 Self::Alternate => OptiForkAction::Miss,
3659 Self::Abort => OptiForkAction::Abort,
3660 Self::Disabled | Self::Controller => {
3661 unreachable!("non-forced mode cannot choose a forced fork action")
3662 }
3663 }
3664 }
3665
3666 fn is_forced(self) -> bool {
3667 matches!(self, Self::Hit | Self::Miss | Self::Alternate | Self::Abort)
3668 }
3669}
3670
3671/// Arm or disarm the forced harness. Serving uses only `set_optipipe_controller_threshold`.
3672pub fn set_optipipe_gate_mode(mode: OptiForkGateMode) {
3673 OPTI_FORK_GATE_MODE.store(mode.code(), std::sync::atomic::Ordering::Relaxed);
3674}
3675
3676/// Arm the increment-2 diagnostic controller. The threshold applies to the uncalibrated
3677/// two-token draft-probability product. Serving can call this only through its explicit
3678/// fresh-process research door; the absent-door default remains byte-for-byte disabled.
3679pub fn set_optipipe_controller_threshold(threshold: f32) {
3680 assert!(threshold.is_finite() && (0.0..=1.0).contains(&threshold));
3681 OPTI_CONTROLLER_THRESHOLD.store(threshold.to_bits(), std::sync::atomic::Ordering::Relaxed);
3682 set_optipipe_gate_mode(OptiForkGateMode::Controller);
3683}
3684
3685#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
3686pub struct OptiForkGateStats {
3687 pub attempts: u64,
3688 pub hits: u64,
3689 pub misses: u64,
3690 pub abort_drains: u64,
3691 pub refusals: u64,
3692 pub gate_checks: u64,
3693 pub gate_admits: u64,
3694 pub gate_rejects: u64,
3695 pub reconciles: u64,
3696 pub wasted_draft_tokens: u64,
3697 pub shadow_draft_tokens: u64,
3698 pub breaker_trips: u64,
3699}
3700
3701#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
3702pub struct OptiForkStateIdentity {
3703 pub trunk_kv_bytes: usize,
3704 pub recurrent_bytes: usize,
3705 pub scratch_kv_bytes: usize,
3706 pub hidden_bytes: usize,
3707}
3708
3709pub fn reset_optipipe_gate_stats() {
3710 for counter in [
3711 &OPTI_FORK_ATTEMPTS,
3712 &OPTI_FORK_HITS,
3713 &OPTI_FORK_MISSES,
3714 &OPTI_FORK_ABORT_DRAINS,
3715 &OPTI_FORK_REFUSALS,
3716 &OPTI_GATE_CHECKS,
3717 &OPTI_GATE_ADMITS,
3718 &OPTI_GATE_REJECTS,
3719 &OPTI_RECONCILES,
3720 &OPTI_WASTED_DRAFT_TOKENS,
3721 &OPTI_SHADOW_DRAFT_TOKENS,
3722 &OPTI_BREAKER_TRIPS,
3723 ] {
3724 counter.store(0, std::sync::atomic::Ordering::Relaxed);
3725 }
3726}
3727
3728pub fn optipipe_gate_stats() -> OptiForkGateStats {
3729 let load = |v: &std::sync::atomic::AtomicU64| v.load(std::sync::atomic::Ordering::Relaxed);
3730 OptiForkGateStats {
3731 attempts: load(&OPTI_FORK_ATTEMPTS),
3732 hits: load(&OPTI_FORK_HITS),
3733 misses: load(&OPTI_FORK_MISSES),
3734 abort_drains: load(&OPTI_FORK_ABORT_DRAINS),
3735 refusals: load(&OPTI_FORK_REFUSALS),
3736 gate_checks: load(&OPTI_GATE_CHECKS),
3737 gate_admits: load(&OPTI_GATE_ADMITS),
3738 gate_rejects: load(&OPTI_GATE_REJECTS),
3739 reconciles: load(&OPTI_RECONCILES),
3740 wasted_draft_tokens: load(&OPTI_WASTED_DRAFT_TOKENS),
3741 shadow_draft_tokens: load(&OPTI_SHADOW_DRAFT_TOKENS),
3742 breaker_trips: load(&OPTI_BREAKER_TRIPS),
3743 }
3744}
3745
3746#[derive(Clone, Copy, Debug)]
3747struct OptiControllerPolicy {
3748 threshold: f32,
3749 consecutive_misses: u8,
3750 breaker_tripped: bool,
3751}
3752
3753impl OptiControllerPolicy {
3754 fn configured() -> Self {
3755 Self {
3756 threshold: f32::from_bits(
3757 OPTI_CONTROLLER_THRESHOLD.load(std::sync::atomic::Ordering::Relaxed),
3758 ),
3759 consecutive_misses: 0,
3760 breaker_tripped: false,
3761 }
3762 }
3763
3764 fn admit(&self, q_proxy: f32) -> bool {
3765 q_proxy.is_finite()
3766 && (0.0..=1.0).contains(&q_proxy)
3767 && (self.threshold == 0.0 || (!self.breaker_tripped && q_proxy >= self.threshold))
3768 }
3769
3770 /// Returns true exactly when this resolution newly trips the three-miss breaker.
3771 fn resolve(&mut self, hit: bool) -> bool {
3772 // q*=0 is the lane's explicit unconditional measurement arm. Its purpose is to price
3773 // every optimistic opportunity, so the safety breaker is measured separately and must
3774 // not silently turn this arm into "three attempts then serial".
3775 if self.threshold == 0.0 {
3776 self.consecutive_misses = 0;
3777 return false;
3778 }
3779 if hit {
3780 self.consecutive_misses = 0;
3781 return false;
3782 }
3783 self.consecutive_misses = self.consecutive_misses.saturating_add(1);
3784 if !self.breaker_tripped && self.consecutive_misses >= 3 {
3785 self.breaker_tripped = true;
3786 return true;
3787 }
3788 false
3789 }
3790}
3791
3792#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3793enum OptiForkAction {
3794 Hit,
3795 Miss,
3796 Abort,
3797}
3798
3799#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3800struct OptiForkGeneration {
3801 id: u64,
3802 slot: usize,
3803}
3804
3805#[derive(Default)]
3806struct OptiForkGenerationTracker {
3807 next: u64,
3808 live: [Option<u64>; 2],
3809}
3810
3811impl OptiForkGenerationTracker {
3812 fn reserve(&mut self) -> Result<OptiForkGeneration, Box<dyn std::error::Error>> {
3813 let generation = OptiForkGeneration {
3814 id: self.next,
3815 slot: (self.next & 1) as usize,
3816 };
3817 if let Some(live) = self.live[generation.slot] {
3818 return Err(format!(
3819 "optipipe snapshot slot {} still owns generation {live}; refusing to overwrite it",
3820 generation.slot,
3821 )
3822 .into());
3823 }
3824 self.next += 1;
3825 self.live[generation.slot] = Some(generation.id);
3826 Ok(generation)
3827 }
3828
3829 fn retire(&mut self, generation: OptiForkGeneration) -> Result<(), Box<dyn std::error::Error>> {
3830 match self.live[generation.slot] {
3831 Some(id) if id == generation.id => {
3832 self.live[generation.slot] = None;
3833 Ok(())
3834 }
3835 other => Err(format!(
3836 "optipipe generation teardown mismatch: ticket={} slot={} live={other:?}",
3837 generation.id, generation.slot,
3838 )
3839 .into()),
3840 }
3841 }
3842}
3843
3844struct OptiForkSeedGeneration {
3845 h_seed: CudaSlice<f32>,
3846 fill_prev: CudaSlice<f32>,
3847 scratch_len: usize,
3848}
3849
3850/// Allocate or refresh one full checkpoint through the engine that owns each PP stage. The
3851/// generic cache helper accepts one device and therefore cannot copy GDN state split across
3852/// devices. KV lengths and position stay host metadata; only recurrent buffers need stage-local
3853/// device ownership.
3854fn opti_snapshot_stage_owned(
3855 e: &Engine,
3856 cache: &Cache,
3857 rt: &'static crate::pp::PpNRt,
3858 fence: &[usize],
3859) -> Result<crate::cache::CacheSnapshot, Box<dyn std::error::Error>> {
3860 let n = cache.kv.len();
3861 let mut snapshot = crate::cache::CacheSnapshot {
3862 kv_len: vec![None; n],
3863 tp_kv_len: vec![None; n],
3864 conv: (0..n).map(|_| None).collect(),
3865 ssm: (0..n).map(|_| None).collect(),
3866 pos: cache.pos,
3867 };
3868 opti_snapshot_stage_owned_into(e, cache, rt, fence, &mut snapshot)?;
3869 Ok(snapshot)
3870}
3871
3872fn opti_snapshot_stage_owned_into(
3873 e: &Engine,
3874 cache: &Cache,
3875 rt: &'static crate::pp::PpNRt,
3876 fence: &[usize],
3877 snapshot: &mut crate::cache::CacheSnapshot,
3878) -> Result<(), Box<dyn std::error::Error>> {
3879 if fence.len() != rt.n_stages() + 1
3880 || snapshot.kv_len.len() != cache.kv.len()
3881 || snapshot.tp_kv_len.len() != cache.tp_kv.len()
3882 {
3883 return Err("optipipe stage-owned snapshot shape mismatch".into());
3884 }
3885 for stage in 0..rt.n_stages() {
3886 opti_snapshot_one_stage_owned_into(e, cache, rt, fence, stage, snapshot)?;
3887 }
3888 snapshot.pos = cache.pos;
3889 Ok(())
3890}
3891
3892/// Refresh one PP stage of a checkpoint. Increment 2 uses this split form so stage 0's
3893/// optimistic post-N state is captured before N+1 stage 0 is queued, while stage 1's matching
3894/// post-N state is captured only after N stage 1 is enqueued. Calling the all-stage helper at
3895/// either point would capture one side of the fork at the wrong generation.
3896fn opti_snapshot_one_stage_owned_into(
3897 e: &Engine,
3898 cache: &Cache,
3899 rt: &'static crate::pp::PpNRt,
3900 fence: &[usize],
3901 stage: usize,
3902 snapshot: &mut crate::cache::CacheSnapshot,
3903) -> Result<(), Box<dyn std::error::Error>> {
3904 if fence.len() != rt.n_stages() + 1
3905 || snapshot.kv_len.len() != cache.kv.len()
3906 || snapshot.tp_kv_len.len() != cache.tp_kv.len()
3907 || stage >= rt.n_stages()
3908 {
3909 return Err("optipipe single-stage snapshot shape mismatch".into());
3910 }
3911 let _scope = rt.enter(stage);
3912 let owner = rt.engine(stage, e);
3913 for il in fence[stage]..fence[stage + 1] {
3914 snapshot.kv_len[il] = cache.kv[il].as_ref().map(|kv| kv.len);
3915 snapshot.tp_kv_len[il] = cache.tp_kv[il]
3916 .as_ref()
3917 .map(crate::tp::ResidentTpKvCache::committed_len);
3918 match &cache.recur[il] {
3919 Some(recur) => {
3920 match snapshot.conv[il].as_mut() {
3921 Some(dst) => {
3922 owner.copy_into(dst, 0, &recur.conv_state, recur.conv_state.len())?
3923 }
3924 None => snapshot.conv[il] = Some(owner.clone_dtod(&recur.conv_state)?),
3925 }
3926 match snapshot.ssm[il].as_mut() {
3927 Some(dst) => {
3928 owner.copy_into(dst, 0, &recur.ssm_state, recur.ssm_state.len())?
3929 }
3930 None => snapshot.ssm[il] = Some(owner.clone_dtod(&recur.ssm_state)?),
3931 }
3932 }
3933 None if snapshot.conv[il].is_some() || snapshot.ssm[il].is_some() => {
3934 return Err(
3935 format!("optipipe stage-owned snapshot layer {il} changed shape").into(),
3936 );
3937 }
3938 None => {}
3939 }
3940 }
3941 snapshot.pos = cache.pos;
3942 Ok(())
3943}
3944
3945/// Increment-1 persistent fork state. Exactly two snapshot/seed slots alternate; a live ticket
3946/// names its generation and keeps teardown fail-closed. Only stage 0 is allowed to mutate before
3947/// resolve, so the reconcile tables and conditional restores are stage-local.
3948struct OptiForkState {
3949 mode: OptiForkGateMode,
3950 controller: Option<OptiControllerPolicy>,
3951 generations: OptiForkGenerationTracker,
3952 active_snapshot_slot: usize,
3953 alternate_snapshot: crate::cache::CacheSnapshot,
3954 seeds: [OptiForkSeedGeneration; 2],
3955 rt: &'static crate::pp::PpNRt,
3956 fence: [usize; 3],
3957 split: usize,
3958 len_ptrs: CudaSlice<u64>,
3959 saved_lens: CudaSlice<i32>,
3960 forced_acc: CudaSlice<u32>,
3961 valid: CudaSlice<u32>,
3962 stage0_stream: std::sync::Arc<cudarc::driver::CudaStream>,
3963 logical_payload_bytes: [usize; 2],
3964}
3965
3966struct OptiForkTicket {
3967 generation: OptiForkGeneration,
3968 boundary: Option<VerifyBoundaryTicket>,
3969 drain: std::sync::Arc<cudarc::driver::CudaStream>,
3970 settled: bool,
3971}
3972
3973struct OptiControllerTicket {
3974 generation: OptiForkGeneration,
3975 boundary: Option<VerifyBoundaryTicket>,
3976 ckpt: Option<VerifyCkpt>,
3977 verify_tokens: [u32; 2],
3978 draft_prob: f32,
3979 eager_seed: Option<CudaSlice<f32>>,
3980 q_proxy: f32,
3981 scratch_len: usize,
3982 issued_at: std::time::Instant,
3983 drain: std::sync::Arc<cudarc::driver::CudaStream>,
3984 settled: bool,
3985}
3986
3987struct OptiControllerPrepared {
3988 verify_tokens: [u32; 2],
3989 draft_prob: f32,
3990 eager_seed: Option<CudaSlice<f32>>,
3991 q_proxy: f32,
3992 scratch_len: usize,
3993}
3994
3995impl OptiControllerTicket {
3996 fn take_boundary(&mut self) -> VerifyBoundaryTicket {
3997 self.boundary
3998 .take()
3999 .expect("controller boundary ticket already consumed")
4000 }
4001
4002 fn take_ckpt(&mut self) -> VerifyCkpt {
4003 self.ckpt
4004 .take()
4005 .expect("controller verify checkpoint already consumed")
4006 }
4007
4008 fn take_eager_seed(&mut self) -> Option<CudaSlice<f32>> {
4009 self.eager_seed.take()
4010 }
4011
4012 fn settle(&mut self) {
4013 self.settled = true;
4014 }
4015}
4016
4017impl Drop for OptiControllerTicket {
4018 fn drop(&mut self) {
4019 if !self.settled {
4020 let _ = self.drain.synchronize();
4021 OPTI_FORK_ABORT_DRAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4022 }
4023 }
4024}
4025
4026impl OptiForkTicket {
4027 fn take_boundary(&mut self) -> VerifyBoundaryTicket {
4028 self.boundary
4029 .take()
4030 .expect("fork ticket boundary already consumed")
4031 }
4032
4033 fn settle(&mut self) {
4034 self.settled = true;
4035 }
4036}
4037
4038impl Drop for OptiForkTicket {
4039 fn drop(&mut self) {
4040 if !self.settled {
4041 let _ = self.drain.synchronize();
4042 OPTI_FORK_ABORT_DRAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4043 }
4044 }
4045}
4046
4047impl OptiForkState {
4048 #[allow(clippy::too_many_arguments)]
4049 fn new(
4050 e: &Engine,
4051 cache: &Cache,
4052 mode: OptiForkGateMode,
4053 alternate_snapshot: crate::cache::CacheSnapshot,
4054 h_seed: &CudaSlice<f32>,
4055 fill_prev: &CudaSlice<f32>,
4056 rt: &'static crate::pp::PpNRt,
4057 split: usize,
4058 n_layer: usize,
4059 ) -> Result<Self, Box<dyn std::error::Error>> {
4060 let fence = [0, split, n_layer];
4061 let mut logical_payload_bytes = [0usize; 2];
4062 for stage in 0..2 {
4063 for il in fence[stage]..fence[stage + 1] {
4064 logical_payload_bytes[stage] += alternate_snapshot.conv[il]
4065 .as_ref()
4066 .map_or(0, |v| v.len() * std::mem::size_of::<f32>());
4067 logical_payload_bytes[stage] += alternate_snapshot.ssm[il]
4068 .as_ref()
4069 .map_or(0, |v| v.len() * std::mem::size_of::<f32>());
4070 }
4071 }
4072 let seeds = [
4073 OptiForkSeedGeneration {
4074 h_seed: e.clone_dtod(h_seed)?,
4075 fill_prev: e.clone_dtod(fill_prev)?,
4076 scratch_len: 0,
4077 },
4078 OptiForkSeedGeneration {
4079 h_seed: e.clone_dtod(h_seed)?,
4080 fill_prev: e.clone_dtod(fill_prev)?,
4081 scratch_len: 0,
4082 },
4083 ];
4084 let (len_ptrs, saved_lens, forced_acc, valid, stage0_stream) = {
4085 let _stage = rt.enter(0);
4086 let e0 = rt.engine(0, e);
4087 (
4088 crate::round_stream::kv_len_ptr_table_range(e0, cache, 0..split, None)?,
4089 e0.htod_i32(&vec![0; split])?,
4090 e0.alloc_u32_zeroed(2)?,
4091 e0.alloc_u32_zeroed(1)?,
4092 e0.stream(),
4093 )
4094 };
4095 logical_payload_bytes[0] += seeds
4096 .iter()
4097 .map(|seed| (seed.h_seed.len() + seed.fill_prev.len()) * std::mem::size_of::<f32>())
4098 .sum::<usize>();
4099 logical_payload_bytes[0] += len_ptrs.len() * std::mem::size_of::<u64>()
4100 + saved_lens.len() * std::mem::size_of::<i32>()
4101 + forced_acc.len() * std::mem::size_of::<u32>()
4102 + valid.len() * std::mem::size_of::<u32>();
4103 Ok(Self {
4104 mode,
4105 controller: (mode == OptiForkGateMode::Controller)
4106 .then(OptiControllerPolicy::configured),
4107 generations: OptiForkGenerationTracker::default(),
4108 active_snapshot_slot: 0,
4109 alternate_snapshot,
4110 seeds,
4111 rt,
4112 fence,
4113 split,
4114 len_ptrs,
4115 saved_lens,
4116 forced_acc,
4117 valid,
4118 stage0_stream,
4119 logical_payload_bytes,
4120 })
4121 }
4122
4123 fn reserve(
4124 &mut self,
4125 current_snapshot: &mut crate::cache::CacheSnapshot,
4126 ) -> Result<OptiForkGeneration, Box<dyn std::error::Error>> {
4127 let generation = self.generations.reserve()?;
4128 if generation.slot != self.active_snapshot_slot {
4129 std::mem::swap(current_snapshot, &mut self.alternate_snapshot);
4130 self.active_snapshot_slot = generation.slot;
4131 }
4132 Ok(generation)
4133 }
4134
4135 fn capture_seed(
4136 &mut self,
4137 e: &Engine,
4138 generation: OptiForkGeneration,
4139 h_seed: &CudaSlice<f32>,
4140 fill_prev: &CudaSlice<f32>,
4141 scratch_len: usize,
4142 ) -> Result<(), Box<dyn std::error::Error>> {
4143 let seed = &mut self.seeds[generation.slot];
4144 e.copy_into(&mut seed.h_seed, 0, h_seed, h_seed.len())?;
4145 e.copy_into(&mut seed.fill_prev, 0, fill_prev, fill_prev.len())?;
4146 seed.scratch_len = scratch_len;
4147 Ok(())
4148 }
4149
4150 fn ticket(
4151 &self,
4152 generation: OptiForkGeneration,
4153 boundary: VerifyBoundaryTicket,
4154 ) -> OptiForkTicket {
4155 OptiForkTicket {
4156 generation,
4157 boundary: Some(boundary),
4158 drain: self.stage0_stream.clone(),
4159 settled: false,
4160 }
4161 }
4162
4163 #[allow(clippy::too_many_arguments)]
4164 fn controller_ticket(
4165 &self,
4166 generation: OptiForkGeneration,
4167 boundary: VerifyBoundaryTicket,
4168 ckpt: VerifyCkpt,
4169 verify_tokens: [u32; 2],
4170 draft_prob: f32,
4171 eager_seed: Option<CudaSlice<f32>>,
4172 q_proxy: f32,
4173 scratch_len: usize,
4174 ) -> OptiControllerTicket {
4175 OptiControllerTicket {
4176 generation,
4177 boundary: Some(boundary),
4178 ckpt: Some(ckpt),
4179 verify_tokens,
4180 draft_prob,
4181 eager_seed,
4182 q_proxy,
4183 scratch_len,
4184 issued_at: std::time::Instant::now(),
4185 drain: self.stage0_stream.clone(),
4186 settled: false,
4187 }
4188 }
4189
4190 fn reserve_successor(&mut self) -> Result<OptiForkGeneration, Box<dyn std::error::Error>> {
4191 self.generations.reserve()
4192 }
4193
4194 fn successor_snapshot_mut(&mut self) -> &mut crate::cache::CacheSnapshot {
4195 &mut self.alternate_snapshot
4196 }
4197
4198 fn promote_successor_snapshot(
4199 &mut self,
4200 current_snapshot: &mut crate::cache::CacheSnapshot,
4201 generation: OptiForkGeneration,
4202 ) {
4203 std::mem::swap(current_snapshot, &mut self.alternate_snapshot);
4204 self.active_snapshot_slot = generation.slot;
4205 }
4206
4207 fn queue_actual_reconcile(
4208 &mut self,
4209 e: &Engine,
4210 snapshot: &crate::cache::CacheSnapshot,
4211 acc: &CudaSlice<u32>,
4212 optimistic_pending: u32,
4213 base: usize,
4214 ) -> Result<(), Box<dyn std::error::Error>> {
4215 let saved: Vec<i32> = (0..self.split)
4216 .map(|il| snapshot.kv_len[il].map(|v| v as i32).unwrap_or(0))
4217 .collect();
4218 // Serving keeps the caller/accept walk on the head (stage-1) device. Record the accept
4219 // decision point there and append a wait to stage 0 after its optimistic successor/TX;
4220 // the validity/reconcile kernels must never peer-read acc before it is written. The
4221 // increment-1 harness uses primary stage 0, where stream order already provides this.
4222 if self.rt.engine(0, e).ctx().ordinal() != e.ctx().ordinal() {
4223 self.rt.fence_stages_behind(&e.stream())?;
4224 }
4225 let _stage = self.rt.enter(0);
4226 let e0 = self.rt.engine(0, e);
4227 e0.htod_i32_into(&mut self.saved_lens, &saved)?;
4228 e0.spec_fork_valid(acc, optimistic_pending, &mut self.valid)?;
4229 e0.spec_fork_reconcile_kv(
4230 &self.len_ptrs,
4231 &self.saved_lens,
4232 acc,
4233 &self.valid,
4234 base,
4235 self.split,
4236 )
4237 }
4238
4239 fn finish_actual_reconcile(
4240 &mut self,
4241 e: &Engine,
4242 cache: &mut Cache,
4243 snapshot: &crate::cache::CacheSnapshot,
4244 n_acc: usize,
4245 base: usize,
4246 hit: bool,
4247 ) -> Result<(), Box<dyn std::error::Error>> {
4248 if hit {
4249 return Ok(());
4250 }
4251 let len_delta = base + n_acc;
4252 for il in 0..self.split {
4253 if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
4254 kv.len = saved + len_delta;
4255 }
4256 }
4257 {
4258 let _stage = self.rt.enter(1);
4259 let e1 = self.rt.engine(1, e);
4260 for il in self.split..self.fence[2] {
4261 if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
4262 kv.len = saved + len_delta;
4263 e1.set_i32_one(&mut kv.len_d, kv.len as i32)?;
4264 }
4265 }
4266 }
4267 self.rt.publish_to(0, &e.stream())?;
4268 Ok(())
4269 }
4270
4271 fn cancel_controller_ticket(
4272 &mut self,
4273 e: &Engine,
4274 cache: &mut Cache,
4275 scratch: &mut MtpScratch,
4276 snapshot: &crate::cache::CacheSnapshot,
4277 ticket: &mut OptiControllerTicket,
4278 ) -> Result<(), Box<dyn std::error::Error>> {
4279 {
4280 let _stage = self.rt.enter(0);
4281 let e0 = self.rt.engine(0, e);
4282 for il in 0..self.split {
4283 if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
4284 kv.len = saved;
4285 e0.set_i32_one(&mut kv.len_d, saved as i32)?;
4286 }
4287 }
4288 }
4289 scratch.set_len(e, snapshot.pos)?;
4290 ticket.settle();
4291 self.generations.retire(ticket.generation)?;
4292 OPTI_FORK_ABORT_DRAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4293 OPTI_WASTED_DRAFT_TOKENS.fetch_add(2, std::sync::atomic::Ordering::Relaxed);
4294 eprintln!(
4295 "[opti-controller] tail-drain generation={} slot={}",
4296 ticket.generation.id, ticket.generation.slot,
4297 );
4298 Ok(())
4299 }
4300
4301 #[allow(clippy::too_many_arguments)]
4302 fn reconcile(
4303 &mut self,
4304 e: &Engine,
4305 cache: &mut Cache,
4306 scratch: &mut MtpScratch,
4307 snapshot: &crate::cache::CacheSnapshot,
4308 h_seed: &mut CudaSlice<f32>,
4309 fill_prev: &mut CudaSlice<f32>,
4310 generation: OptiForkGeneration,
4311 action: OptiForkAction,
4312 optimistic_pending: u32,
4313 ) -> Result<(), Box<dyn std::error::Error>> {
4314 debug_assert!(action != OptiForkAction::Abort);
4315 let miss_started = std::time::Instant::now();
4316 let keep = action == OptiForkAction::Hit;
4317 let saved: Vec<i32> = (0..self.split)
4318 .map(|il| snapshot.kv_len[il].map(|v| v as i32).unwrap_or(0))
4319 .collect();
4320 let seed = &self.seeds[generation.slot];
4321 {
4322 let _stage = self.rt.enter(0);
4323 let e0 = self.rt.engine(0, e);
4324 e0.htod_i32_into(&mut self.saved_lens, &saved)?;
4325 let forced = if keep {
4326 [1u32, optimistic_pending]
4327 } else {
4328 [0u32, optimistic_pending]
4329 };
4330 e0.htod_u32_into(&mut self.forced_acc, &forced)?;
4331 e0.spec_fork_valid(&self.forced_acc, optimistic_pending, &mut self.valid)?;
4332 e0.spec_fork_reconcile_kv(
4333 &self.len_ptrs,
4334 &self.saved_lens,
4335 &self.forced_acc,
4336 &self.valid,
4337 0,
4338 self.split,
4339 )?;
4340 for il in 0..self.split {
4341 if let Some(recur) = cache.recur[il].as_mut() {
4342 let conv = snapshot.conv[il]
4343 .as_ref()
4344 .ok_or("optipipe stage0 snapshot missing conv state")?;
4345 let ssm = snapshot.ssm[il]
4346 .as_ref()
4347 .ok_or("optipipe stage0 snapshot missing ssm state")?;
4348 e0.spec_fork_restore_f32(conv, &mut recur.conv_state, &self.valid)?;
4349 e0.spec_fork_restore_f32(ssm, &mut recur.ssm_state, &self.valid)?;
4350 }
4351 }
4352 e0.spec_fork_restore_f32(&seed.h_seed, h_seed, &self.valid)?;
4353 e0.spec_fork_restore_f32(&seed.fill_prev, fill_prev, &self.valid)?;
4354 }
4355
4356 if keep {
4357 OPTI_FORK_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4358 return Ok(());
4359 }
4360
4361 for il in 0..self.split {
4362 if let (Some(kv), Some(saved)) = (cache.kv[il].as_mut(), snapshot.kv_len[il]) {
4363 kv.len = saved;
4364 }
4365 }
4366 scratch.set_len(e, seed.scratch_len)?;
4367 // Targeted E_restart: publish only stage 0's reconcile to the caller, then bound the
4368 // forced diagnostic so the retained number is the actual miss cost, not enqueue time.
4369 let caller = e.stream();
4370 self.rt.publish_to(0, &caller)?;
4371 caller.synchronize()?;
4372 let miss_ms = miss_started.elapsed().as_secs_f64() * 1e3;
4373 eprintln!(
4374 "[opti-fork-reconcile] generation={} slot={} miss_ms={miss_ms:.3}",
4375 generation.id, generation.slot,
4376 );
4377 OPTI_FORK_MISSES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4378 Ok(())
4379 }
4380
4381 fn retire(&mut self, generation: OptiForkGeneration) -> Result<(), Box<dyn std::error::Error>> {
4382 self.generations.retire(generation)
4383 }
4384}
4385
4386fn rewind_tp_kv_verified_prefix(
4387 tp_kv: &mut [Option<crate::tp::ResidentTpKvCache>],
4388 saved_lens: &[Option<usize>],
4389 accepted: usize,
4390) -> Result<(), Box<dyn std::error::Error>> {
4391 if tp_kv.len() != saved_lens.len() {
4392 return Err("spec TP KV snapshot shape mismatch".into());
4393 }
4394 for (layer, (cache, saved)) in tp_kv.iter_mut().zip(saved_lens).enumerate() {
4395 match (cache.as_mut(), *saved) {
4396 (Some(cache), Some(saved)) => {
4397 let target = saved
4398 .checked_add(accepted)
4399 .ok_or("spec TP KV committed length overflow")?;
4400 cache.rewind_to(target)?;
4401 }
4402 (None, None) => {}
4403 _ => {
4404 return Err(
4405 format!("spec TP KV layer {layer} changed shape since its snapshot").into(),
4406 );
4407 }
4408 }
4409 }
4410 Ok(())
4411}
4412
4413/// MEMRA_SPEC_ROUND_PROF counters: whole-round wall, so the round can be weighed against the
4414/// draft-step ([spec-anatomy]) and verify-walk ([tcol-prof]) splits we already print.
4415static ROUND_PROF: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
4416static ROUND_MS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
4417static ROUND_N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
4418
4419impl HybridModel {
4420 fn mtp_head_count(&self) -> usize {
4421 usize::from(self.mtp.is_some()) + self.mtp_extra.len()
4422 }
4423
4424 fn mtp_head_at(&self, index: usize) -> &MtpHead {
4425 if index == 0 {
4426 self.mtp.as_ref().expect("MTP head 0 is unavailable")
4427 } else {
4428 &self.mtp_extra[index - 1]
4429 }
4430 }
4431
4432 fn new_mtp_scratch(
4433 &self,
4434 e: &Engine,
4435 cap: usize,
4436 ) -> Result<MtpScratch, Box<dyn std::error::Error>> {
4437 let mut scratch = MtpScratch::new(
4438 e,
4439 &self.cfg,
4440 &self.plan,
4441 cap,
4442 self.mtp.as_ref().and_then(|head| head.geom.as_ref()),
4443 )?;
4444 for head in &self.mtp_extra {
4445 scratch.push_plane(e, &self.cfg, &self.plan, head.geom.as_ref())?;
4446 }
4447 Ok(scratch)
4448 }
4449
4450 fn opti_graph_draft_step(
4451 &self,
4452 e: &Engine,
4453 mtp: &MtpHead,
4454 dctx: &mut DraftGraphCtx,
4455 scratch: &mut MtpScratch,
4456 d_vocab: usize,
4457 ) -> Result<(u32, f32), Box<dyn std::error::Error>> {
4458 // dcw door: one replay appends one device-counter row; pre-arm ring headroom
4459 // host-side before launching (no-op on flat planes).
4460 if step35_draft_dcw_on() {
4461 scratch.ensure_dcw_headroom(e, 2)?;
4462 }
4463 dctx.graph
4464 .as_ref()
4465 .ok_or("optipipe controller requires the greedy draft graph")?
4466 .launch()?;
4467 scratch.kv.len += 1;
4468 let idx = e.dtoh_u32_one(&dctx.g_tok)?;
4469 if (idx as usize) >= d_vocab {
4470 return Err(
4471 format!("optipipe draft argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab}").into(),
4472 );
4473 }
4474 let probability = e.dtoh(&dctx.g_p)?[0];
4475 if !probability.is_finite() || !(0.0..=1.0).contains(&probability) {
4476 return Err(format!("optipipe draft probability is invalid: {probability}").into());
4477 }
4478 let token = match &mtp.d2t {
4479 Some(map) => map[idx as usize],
4480 None => idx,
4481 };
4482 if token != idx {
4483 e.set_u32_one(&mut dctx.g_tok, token)?;
4484 }
4485 Ok((token, probability))
4486 }
4487
4488 #[allow(clippy::too_many_arguments)]
4489 fn opti_controller_draft_step(
4490 &self,
4491 e: &Engine,
4492 mtp: &MtpHead,
4493 dctx: &mut DraftGraphCtx,
4494 scratch: &mut MtpScratch,
4495 d_vocab: usize,
4496 eager_state: &mut Option<(u32, CudaSlice<f32>)>,
4497 eager_pos: usize,
4498 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4499 round_graph_ok: bool,
4500 ) -> Result<(u32, f32), Box<dyn std::error::Error>> {
4501 // GRAPH-LAUNCH HEADROOM GUARD (see GRAPH_LAUNCH_MIN_FREE): `round_graph_ok` is
4502 // the round's headroom snapshot. Below the floor the main draft arm already ran
4503 // eager (13651-class gate), which seeded `eager_state`, so the controller probe
4504 // rides its eager twin below instead of replaying the draft graph into an
4505 // exhausted card. The seed-unavailable Err beneath stays the recoverable
4506 // fail-closed for the shapes that never seed it.
4507 if dctx.graph.is_some() && round_graph_ok {
4508 return self.opti_graph_draft_step(e, mtp, dctx, scratch, d_vocab);
4509 }
4510 let (input_token, input_seed) = eager_state
4511 .take()
4512 .ok_or("optipipe eager continuation seed is unavailable")?;
4513 let (logits, next_seed) = self.mtp_head_forward_dev(
4514 e,
4515 mtp,
4516 input_token,
4517 &input_seed,
4518 scratch,
4519 eager_pos,
4520 embd_dev,
4521 None,
4522 )?;
4523 let token_d = e.argmax_token_device(&logits, d_vocab)?;
4524 let idx = e.dtoh_u32_one(&token_d)?;
4525 if (idx as usize) >= d_vocab {
4526 return Err(format!(
4527 "optipipe eager draft argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab}"
4528 )
4529 .into());
4530 }
4531 let probability_d = e.prob_of_token_device(&logits, &token_d, d_vocab)?;
4532 let probability = e.dtoh(&probability_d)?[0];
4533 if !probability.is_finite() || !(0.0..=1.0).contains(&probability) {
4534 return Err(
4535 format!("optipipe eager draft probability is invalid: {probability}").into(),
4536 );
4537 }
4538 let token = match &mtp.d2t {
4539 Some(map) => map[idx as usize],
4540 None => idx,
4541 };
4542 *eager_state = Some((token, next_seed));
4543 Ok((token, probability))
4544 }
4545
4546 /// NextN head forward for ONE draft token (§A ops 1-13, T=1).
4547 /// Inputs: `e_tok` = the token to predict FROM (last committed / previous draft); `h_seed` =
4548 /// the trunk's pre-output_norm hidden of that token (§A op 2 input). `mtp_pos` = absolute
4549 /// position of the token being predicted from. Returns (draft_logits[n_vocab] host, h_nextn dev).
4550 /// `h_nextn` (§A op 10) becomes `h_seed` for the next autoregressive draft step.
4551 /// Device-resident: returns draft logits ON DEVICE (no [n_vocab] dtoh). The greedy draft
4552 /// loop only needs argmax — paired with `argmax_token_device` this cuts the ~600KB logits
4553 /// transfer + host argmax per draft token from the K-token draft chain.
4554 #[allow(clippy::too_many_arguments)]
4555 fn mtp_head_forward_dev(
4556 &self,
4557 e: &Engine,
4558 mtp: &MtpHead,
4559 e_tok: u32,
4560 h_seed: &CudaSlice<f32>,
4561 scratch: &mut MtpScratch,
4562 mtp_pos: usize,
4563 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4564 mask: Option<(&CudaSlice<u32>, usize)>,
4565 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4566 self.mtp_head_forward_dev_at(e, mtp, e_tok, h_seed, scratch, 0, mtp_pos, embd_dev, mask)
4567 }
4568
4569 #[allow(clippy::too_many_arguments)]
4570 fn mtp_head_forward_dev_at(
4571 &self,
4572 e: &Engine,
4573 mtp: &MtpHead,
4574 e_tok: u32,
4575 h_seed: &CudaSlice<f32>,
4576 scratch: &mut MtpScratch,
4577 scratch_index: usize,
4578 mtp_pos: usize,
4579 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4580 // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): (packed draft-vocab allowed set, words).
4581 // Applied to the head logits BEFORE they are returned, so every consumer (argmax,
4582 // gumbel draw, p-min prob) sees the grammar-legal row. None = unmasked (pre-lane).
4583 mask: Option<(&CudaSlice<u32>, usize)>,
4584 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4585 // MEMRA_SPEC_ANATOMY=1 — eager-step phase timers (diagnostic only). Phase boundaries
4586 // sync the stream, so absolute time inflates; the BREAKDOWN is the signal. Cumulative
4587 // summary on stderr every 128 steps: glue (embed..attn_norm), attn, ffn, head.
4588 use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
4589 static ANAT_NS: [AtomicU64; 5] = [
4590 AtomicU64::new(0),
4591 AtomicU64::new(0),
4592 AtomicU64::new(0),
4593 AtomicU64::new(0),
4594 AtomicU64::new(0),
4595 ];
4596 static ANAT_STEPS: AtomicU64 = AtomicU64::new(0);
4597 let anat = {
4598 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
4599 *ON.get_or_init(|| std::env::var("MEMRA_SPEC_ANATOMY").as_deref() == Ok("1"))
4600 };
4601 if anat {
4602 e.stream().synchronize()?; // drain prior queue so phase 0 starts clean
4603 }
4604 let t_all = std::time::Instant::now();
4605 let mut t_ph = std::time::Instant::now();
4606 let anat_mark = |i: usize,
4607 e: &Engine,
4608 t: &mut std::time::Instant|
4609 -> Result<(), Box<dyn std::error::Error>> {
4610 if anat {
4611 e.stream().synchronize()?;
4612 ANAT_NS[i].fetch_add(t.elapsed().as_nanos() as u64, Relaxed);
4613 *t = std::time::Instant::now();
4614 }
4615 Ok(())
4616 };
4617 let cfg = &self.cfg;
4618 let n_embd = cfg.n_embd as usize;
4619 // Distilled-student geometry: the block runs at the INNER width `di` (eh_proj out /
4620 // attn / ffn); the n_embd interface (embed, norms in, carrier out, head in) is unchanged.
4621 let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
4622 let eps = cfg.rms_eps;
4623 let pos_d = e.htod_i32(&[mtp_pos as i32])?;
4624
4625 // op A: a resident table transfers one 4B token id. The exact host-row capacity path
4626 // expands this one row on CPU and transfers n_embd f32 values instead.
4627 let e_emb = match embd_dev {
4628 Some((g, qt, rb)) => e.embed_gather_device_t(g, &[e_tok], n_embd, qt, rb)?,
4629 None => e.htod(&self.embd.gather(n_embd, &[e_tok]))?,
4630 };
4631
4632 // op 1/2: e_norm = RMSNorm(e, enorm); h_norm = RMSNorm(h_seed, hnorm)
4633 let mut e_norm = e.zeros(n_embd)?;
4634 e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, 1, eps)?;
4635 let mut h_norm = e.zeros(n_embd)?;
4636 e.rms_norm(h_seed, mtp.hnorm.float_data(), &mut h_norm, n_embd, 1, eps)?;
4637
4638 // op 3: concat = [e_norm ; h_norm] -> [2*n_embd], e_norm in [0,n_embd), h_norm in [n_embd,2n_embd)
4639 let mut concat = e.zeros(2 * n_embd)?;
4640 e.copy_into(&mut concat, 0, &e_norm, n_embd)?;
4641 e.copy_into(&mut concat, n_embd, &h_norm, n_embd)?;
4642
4643 // op 4: inpSA = eh_proj @ concat (eh_proj [2*n_embd, n_embd]) -> [n_embd]
4644 let inp_sa = e.matmul(&mtp.eh_proj, &concat, 1)?;
4645
4646 // op 5: a_norm = RMSNorm(inpSA, attn_norm)
4647 let mut a_norm = e.zeros(di)?;
4648 e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, 1, eps)?;
4649 anat_mark(0, e, &mut t_ph)?;
4650
4651 // op 6: attention on the scratch KV. SAME dc launcher as the graph path (bucket_max =
4652 // scratch.cap, length from the device len_d) so eager drafts match graph drafts
4653 // bit-for-bit at any t_kv (the parity gate). Host len mirrored here (the dc append
4654 // advances only the device counter).
4655 let attn_out = match (&mtp.mixer, mtp.step35.as_ref()) {
4656 // step35 MTP block, dcw door armed: the SAME windowed device-counter launcher as
4657 // the captured chain (draft parity by construction). Per-step ring headroom runs
4658 // HERE (eager is host-len work, a rebase is legal); host len mirrored like the
4659 // plain dc arm below.
4660 (Mixer::Full(fa), Some(g))
4661 if self.step35_dcw_eligible(g, scratch.plane(scratch_index).1) =>
4662 {
4663 {
4664 let (kv, _) = scratch.plane_mut(scratch_index);
4665 let retain = match kv.ring.as_ref() {
4666 Some(ring) => memra_kv::swa_retain_from(kv.len, ring.window(), ring.base()),
4667 None => 0,
4668 };
4669 e.prepare_kv_append(kv, retain, 1)?;
4670 }
4671 let out =
4672 self.mtp_step35_attn_dcw(e, fa, g, &a_norm, &pos_d, scratch, scratch_index)?;
4673 scratch.plane_mut(scratch_index).0.len += 1;
4674 out
4675 }
4676 // step35 MTP block, door off (MEMRA_STEP35_DRAFT_DCW=0 rollback) or class-
4677 // ineligible: PER-LAYER geometry + a separate head-wise gate + an SWA window,
4678 // none of which the plain dc launcher can express (see `mtp_step35_attn`).
4679 // Host-len arm. Advances BOTH the
4680 // host len and the device counter itself (unlike the dc arm, whose host-side
4681 // mirror the caller does).
4682 (Mixer::Full(fa), Some(g)) => {
4683 self.mtp_step35_attn(e, fa, g, &a_norm, &pos_d, scratch, scratch_index)?
4684 }
4685 (Mixer::Full(fa), None) => {
4686 let out = self.mtp_full_attn_dc(
4687 e,
4688 fa,
4689 &a_norm,
4690 &pos_d,
4691 scratch,
4692 scratch_index,
4693 mtp.geom.as_ref(),
4694 )?;
4695 scratch.plane_mut(scratch_index).0.len += 1;
4696 out
4697 }
4698 (Mixer::Linear(_), _) => {
4699 panic!("MTP block is full-attn in qwen35; linear MTP not supported")
4700 }
4701 (Mixer::Mla(_), _) => crate::hybrid::mla_path_unimplemented("MTP head forward"),
4702 (Mixer::Kda(_), _) => crate::hybrid::kda_path_unimplemented("MTP head forward"),
4703 };
4704 anat_mark(1, e, &mut t_ph)?;
4705
4706 // op 7: x1 = inpSA + attn_out
4707 let mut x1 = e.zeros(di)?;
4708 e.add(&inp_sa, &attn_out, &mut x1, di)?;
4709
4710 // op 8: z = RMSNorm(x1, post_attn_norm) (pre-FFN norm)
4711 let mut z = e.zeros(di)?;
4712 e.rms_norm(&x1, mtp.post_attn_norm.float_data(), &mut z, di, 1, eps)?;
4713
4714 // op 9: FFN (Dense or MoE) — same as the trunk decode FFN
4715 let ffn_out = match &mtp.ffn {
4716 crate::hybrid::Ffn::Dense {
4717 ffn_gate,
4718 ffn_up,
4719 ffn_down,
4720 } => {
4721 let n_ff = ffn_gate.out_features();
4722 let (gate, up) = if e.uses_q8_1_fast(ffn_gate) && e.uses_q8_1_fast(ffn_up) {
4723 let (zq, zd) = e.quantize_q8_1(&z, 1, di)?;
4724 (
4725 e.matmul_pre(ffn_gate, &zq, &zd, &z, 1)?,
4726 e.matmul_pre(ffn_up, &zq, &zd, &z, 1)?,
4727 )
4728 } else {
4729 (e.matmul(ffn_gate, &z, 1)?, e.matmul(ffn_up, &z, 1)?)
4730 };
4731 let mut act = e.zeros(n_ff)?;
4732 // step35: a DENSE FFN reads the per-layer SHEXP clamp (upstream's one `build_ffn`
4733 // serves the dense MLP and the shared expert off `swiglu_clamp_shexp` —
4734 // llama-graph.cpp:1751), resolved for the MTP block's OWN index. Every other arch
4735 // passes None, which is `ffn_act`'s dispatch verbatim.
4736 Self::ffn_act_lim(
4737 e,
4738 &self.cfg,
4739 &gate,
4740 &up,
4741 1.0,
4742 1.0,
4743 mtp.step35
4744 .as_ref()
4745 .and_then(|s| s.clamp_shexp)
4746 .map(SwigluClamp::Post),
4747 &mut act,
4748 n_ff,
4749 )?;
4750 e.matmul(ffn_down, &act, 1)?
4751 }
4752 // MTP head is a distinct block — key its experts under a separate layer index (u16::MAX)
4753 // so they never alias trunk layer 0's cache keys.
4754 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, 1, u16::MAX)?,
4755 };
4756 anat_mark(2, e, &mut t_ph)?;
4757
4758 // op 10: h_nextn = x1 + ffn_out (at di)
4759 let mut h_inner = e.zeros(di)?;
4760 e.add(&x1, &ffn_out, &mut h_inner, di)?;
4761
4762 // op 10.5 (student): up-project the inner hidden back to n_embd — training semantics:
4763 // the chain carrier AND the head input are out_up(h_inner) (pre-final-norm).
4764 let h_nextn = match mtp.geom.as_ref() {
4765 Some(g) => e.matmul(&g.out_up, &h_inner, 1)?,
4766 None => h_inner,
4767 };
4768
4769 // op 11: final = RMSNorm(h_nextn, shared_head_norm OR output_norm)
4770 let final_norm = mtp.shared_head_norm.as_ref().unwrap_or(&self.output_norm);
4771 let mut final_h = e.zeros(n_embd)?;
4772 e.rms_norm(
4773 &h_nextn,
4774 final_norm.float_data(),
4775 &mut final_h,
4776 n_embd,
4777 1,
4778 eps,
4779 )?;
4780
4781 // op 12: draft_logits = (shared_head_head OR output) @ final — stays ON DEVICE.
4782 let head = mtp.shared_head_head.as_ref().unwrap_or(&self.output);
4783 let mut logits = e.matmul(head, &final_h, 1)?;
4784 // op 12b (lane/draft-mask): grammar mask over the DRAFT vocab, applied here so the
4785 // caller's argmax / gumbel draw / p-min prob all read the grammar-legal row.
4786 if let Some((mask_d, mw)) = mask {
4787 let d_vocab = head.out_features();
4788 e.mask_logits_col(&mut logits, mask_d, 0, d_vocab, mw)?;
4789 }
4790 anat_mark(3, e, &mut t_ph)?;
4791 if anat {
4792 ANAT_NS[4].fetch_add(t_all.elapsed().as_nanos() as u64, Relaxed);
4793 let n = ANAT_STEPS.fetch_add(1, Relaxed) + 1;
4794 if n.is_multiple_of(128) {
4795 let us = |i: usize| ANAT_NS[i].load(Relaxed) / n / 1000;
4796 eprintln!(
4797 "[spec-anatomy] steps={n} avg us/step: glue={} attn={} ffn={} head={} total={}",
4798 us(0),
4799 us(1),
4800 us(2),
4801 us(3),
4802 us(4)
4803 );
4804 }
4805 }
4806 // Chain recurrence hand-over: pre-norm h_nextn (default) or post-norm final_h
4807 // (MEMRA_SPEC_HPOST — llama.cpp #24025's t_h_nextn is taken AFTER the head norm).
4808 Ok((logits, if spec_hpost() { final_h } else { h_nextn }))
4809 }
4810
4811 /// One NextN/MTP draft step for an **MLA-mixer** MTP block (glm5_next class: MLA + own
4812 /// k-pool indexer + MoE, serial residual — the NextN layer carries no hc_* tensors), on
4813 /// the model `Cache`'s own MTP latent plane rather than the full-attn `MtpScratch` the
4814 /// qwen35/step35 chain uses. Gate: `glm5_mtp_head_gpu` (engine vs `memra_reference`
4815 /// `execute_mtp`, teacher-forced walk, eh_proj-transpose and h_seed-off-by-one red arms).
4816 ///
4817 /// The interface, stated precisely for the verify arc:
4818 /// - `h_seed`: `[n_embd]` f32 device — the trunk's COLLAPSED PRE-output_norm hidden of
4819 /// the position whose next token is being drafted (MTP-PLAN §A; exactly what
4820 /// `prime_cache`/`decode_step` return for hc models). `MEMRA_SPEC_HPOST` flips both
4821 /// this producer and the returned carrier to the post-norm variant, same as the dev path.
4822 /// - `e_tok`: the token at the seeded position's SUCCESSOR — the token the trunk just
4823 /// sampled/accepted (reference oracle pairing: `fused[i] = eh_proj([enorm(embed(ids[i]));
4824 /// hnorm(trunk_hidden[i])])`, i.e. this call with `e_tok = ids[i]`, `h_seed = h[i]`,
4825 /// `mtp_pos = i` reproduces the reference's row `i`).
4826 /// - `mtp_pos`: the absolute position this step appends to the MTP block's latent plane;
4827 /// must equal that plane's current length (the plane advances by ONE row per call inside
4828 /// `mla_attn_cached`; rollback on rejection = the verify arc's latent-plane len reset).
4829 /// - returns `(draft_logits [n_vocab], carrier [n_embd])` on device. glm5_next ships no
4830 /// private MTP head, so the logits ride the trunk `lm_head` (full vocab, no d2t).
4831 pub fn mtp_head_forward_mla_cached(
4832 &self,
4833 e: &Engine,
4834 depth: usize,
4835 e_tok: u32,
4836 h_seed: &CudaSlice<f32>,
4837 cache: &mut Cache,
4838 mtp_pos: usize,
4839 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4840 if depth >= self.mtp_head_count() {
4841 return Err(format!(
4842 "MTP depth {depth} out of range: {} embedded head(s) loaded \
4843 (is MEMRA_GLM5_MTP=1 set for a glm5_next model?)",
4844 self.mtp_head_count()
4845 )
4846 .into());
4847 }
4848 let mtp = self.mtp_head_at(depth);
4849 let block = self
4850 .plan
4851 .mtp_blocks
4852 .get(depth)
4853 .ok_or_else(|| format!("ModelPlan declares no MTP block at depth {depth}"))?;
4854 let il = block.layer.index as usize;
4855 let Mixer::Mla(mla) = &mtp.mixer else {
4856 return Err(
4857 "mtp_head_forward_mla_cached serves MLA-mixer MTP blocks only; full-attn \
4858 blocks take mtp_head_forward_dev's scratch path"
4859 .into(),
4860 );
4861 };
4862 if matches!(mtp.ffn, crate::hybrid::Ffn::Dense { .. }) {
4863 return Err(
4864 "MLA-mixer MTP block with a Dense FFN has no gated arm yet (glm5_next and \
4865 glm-dsa NextN blocks are MoE); refusing rather than running ungated math"
4866 .into(),
4867 );
4868 }
4869 let plane_len = cache
4870 .latent
4871 .get(il)
4872 .and_then(|plane| plane.as_ref())
4873 .map(|plane| plane.len)
4874 .ok_or_else(|| {
4875 format!(
4876 "MTP block layer {il} has no latent cache plane — the Cache must be \
4877 built from a plan whose mtp_blocks declare StatePlan::LatentKvCache"
4878 )
4879 })?;
4880 if mtp_pos != plane_len {
4881 return Err(format!(
4882 "MTP draft position {mtp_pos} != the MTP latent plane's length {plane_len} — \
4883 the plane advances one row per draft step and rolls back by len reset; a \
4884 skipped or repeated position would attend the wrong horizon"
4885 )
4886 .into());
4887 }
4888
4889 let cfg = &self.cfg;
4890 let n_embd = cfg.n_embd as usize;
4891 let eps = cfg.rms_eps;
4892 let pos_d = e.htod_i32(&[mtp_pos as i32])?;
4893
4894 // Same op chain as `mtp_head_forward_dev_at` (ops 1-12), same kernels — only the
4895 // attention arm differs: `mla_attn_cached` on the plan's own MTP plane instead of
4896 // `mtp_full_attn_dc` on the MtpScratch.
4897 let e_emb = e.htod(&self.embd.gather(n_embd, &[e_tok]))?;
4898 let mut e_norm = e.zeros(n_embd)?;
4899 e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, 1, eps)?;
4900 let mut h_norm = e.zeros(n_embd)?;
4901 e.rms_norm(h_seed, mtp.hnorm.float_data(), &mut h_norm, n_embd, 1, eps)?;
4902
4903 let mut concat = e.zeros(2 * n_embd)?;
4904 e.copy_into(&mut concat, 0, &e_norm, n_embd)?;
4905 e.copy_into(&mut concat, n_embd, &h_norm, n_embd)?;
4906 let inp_sa = e.matmul(&mtp.eh_proj, &concat, 1)?;
4907
4908 let mut a_norm = e.zeros(n_embd)?;
4909 e.rms_norm(
4910 &inp_sa,
4911 mtp.attn_norm.float_data(),
4912 &mut a_norm,
4913 n_embd,
4914 1,
4915 eps,
4916 )?;
4917 let attn_out = self.mla_attn_cached(e, mla, &a_norm, &pos_d, 1, il, cache)?;
4918
4919 let mut x1 = e.zeros(n_embd)?;
4920 e.add(&inp_sa, &attn_out, &mut x1, n_embd)?;
4921 let mut z = e.zeros(n_embd)?;
4922 e.rms_norm(&x1, mtp.post_attn_norm.float_data(), &mut z, n_embd, 1, eps)?;
4923 let ffn_out = match &mtp.ffn {
4924 // Distinct block — key its experts off the trunk layers' cache keys (dev-path rule).
4925 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, 1, u16::MAX)?,
4926 crate::hybrid::Ffn::Dense { .. } => unreachable!("refused above"),
4927 };
4928 let mut h_nextn = e.zeros(n_embd)?;
4929 e.add(&x1, &ffn_out, &mut h_nextn, n_embd)?;
4930
4931 let final_norm = mtp.shared_head_norm.as_ref().unwrap_or(&self.output_norm);
4932 let mut final_h = e.zeros(n_embd)?;
4933 e.rms_norm(
4934 &h_nextn,
4935 final_norm.float_data(),
4936 &mut final_h,
4937 n_embd,
4938 1,
4939 eps,
4940 )?;
4941 let head = mtp.shared_head_head.as_ref().unwrap_or(&self.output);
4942 let logits = e.matmul(head, &final_h, 1)?;
4943 Ok((logits, if spec_hpost() { final_h } else { h_nextn }))
4944 }
4945
4946 #[allow(clippy::too_many_arguments)]
4947 fn mtp_chain_forward_dev(
4948 &self,
4949 e: &Engine,
4950 tokens: &[u32],
4951 seeds: &[CudaSlice<f32>],
4952 scratch: &mut MtpScratch,
4953 committed_scratch_len: usize,
4954 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
4955 mask: Option<(&CudaSlice<u32>, usize)>,
4956 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
4957 if tokens.is_empty() || tokens.len() != seeds.len() {
4958 return Err("multi-head MTP prefix tokens/seeds are malformed".into());
4959 }
4960 let index = mtp_chain_head_index(tokens.len() - 1, self.mtp_head_count());
4961 let head = self.mtp_head_at(index);
4962 scratch.set_plane_len(e, index, committed_scratch_len)?;
4963
4964 let mut last = None;
4965 for row in 0..tokens.len() {
4966 let is_last = row + 1 == tokens.len();
4967 last = Some(self.mtp_head_forward_dev_at(
4968 e,
4969 head,
4970 tokens[row],
4971 &seeds[row],
4972 scratch,
4973 index,
4974 committed_scratch_len + row + 1,
4975 embd_dev,
4976 if is_last { mask } else { None },
4977 )?);
4978 }
4979 Ok(last.expect("non-empty MTP prefix produced no row"))
4980 }
4981
4982 /// step35 MTP-block attention, T=1, on the scratch KV — the EAGER-ONLY twin of
4983 /// `mtp_full_attn_dc`. Three things force a separate arm rather than a geometry parameter on
4984 /// the dc path, and all three are properties of this arch's MTP block:
4985 ///
4986 /// 1. **The SWA window.** Block 45 is an SWA-type block (`sliding_window_pattern[45]=true`,
4987 /// window 512). Windowed decode in memra is a token-aligned VIEW OFFSET into the quantized
4988 /// cache (the gemma4 R6 / `step35_decode_attn` pattern: keys carry absolute rope and the
4989 /// mask is purely positional, so one query at `len-1` attending the last `win` rows IS the
4990 /// windowed result). `fa_decode_dc` takes the key count from a DEVICE counter and always
4991 /// starts at row 0 — it cannot express a nonzero offset. The windowed dc arm is
4992 /// `mtp_step35_attn_dcw` (`fa_decode_dcw`, doored via MEMRA_STEP35_DRAFT_DCW —
4993 /// default ON since lane/step37-draft-graph-serving-20260830); this host-len arm is
4994 /// the =0 rollback and the class-ineligibility fallback.
4995 /// 2. **Per-layer head count.** 96 q heads over 8 KV (GQA 12) at this block, vs the trunk's 64
4996 /// on its full-attn layers. The trunk cfg's `n_head` scalar is the MAX over layers, and the
4997 /// trunk ARTIFACT's per-layer arrays stop at index 44 — so the count must come from the
4998 /// resolved `Step35MtpGeom`, never from `cfg`.
4999 /// 3. **The separate head-wise gate.** `blk.45.attn_gate.weight [n_embd, 96]` produces one
5000 /// sigmoid scalar per head (broadcast over head_dim) — `attn_head_gate`, not the qwen35
5001 /// fused-into-wq `q_gate_split` form the dc arm handles.
5002 ///
5003 /// DOOR STATE: with MEMRA_STEP35_DRAFT_DCW=0 (or a sub-eligible kernel class),
5004 /// `mtp_head_forward_cap` refuses step35 heads explicitly (rather than silently capturing
5005 /// a window-less, wrong-past-`win` graph) and this eager chain IS the served path. With
5006 /// the door armed (the default), BOTH draft modes run the `mtp_step35_attn_dcw` twin
5007 /// instead of this arm.
5008 ///
5009 /// Unlike the dc arm this advances BOTH the host `kv.len` and the device counter, so the
5010 /// caller must not mirror.
5011 #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
5012 fn mtp_step35_attn(
5013 &self,
5014 e: &Engine,
5015 fa: &FullAttnLayer,
5016 g: &crate::hybrid::Step35MtpGeom,
5017 h: &CudaSlice<f32>,
5018 pos_d: &CudaSlice<i32>,
5019 scratch: &mut MtpScratch,
5020 scratch_index: usize,
5021 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5022 let (nh, nkv, hd) = (g.n_head, g.n_head_kv, self.cfg.head_dim_k as usize);
5023 // MTP-GEOM RECEIPT, once per process, on the SERVED draft path. Slot-0 acceptance is
5024 // 0.725 here against 0.994 for vLLM MTP3 on the same checkpoint family and card class, and
5025 // the first three explanations for that gap were all wrong: head assignment (step-modulo
5026 // is index 0 at K=1, correct), MEMRA_SPEC_HPOST (identical 84/116 both arms), and this
5027 // block's geometry. Geometry was the one that could have failed SILENTLY — a wrong window
5028 // makes the draft attend the whole context instead of Step-3.7's 512, stays fluent, and
5029 // shows up only as acceptance — so it gets a standing receipt rather than another reading
5030 // of the source. Prints the resolved Step35MtpGeom the served path actually runs on;
5031 // `full_attention_geometry_at`'s missing-row fallback (window: None) does NOT reach here.
5032 {
5033 static ONCE: std::sync::OnceLock<()> = std::sync::OnceLock::new();
5034 ONCE.get_or_init(|| {
5035 eprintln!(
5036 "[mtp-geom] arm=eager block={} swa={} window={} n_head={nh} n_head_kv={nkv} \
5037 head_dim_k={hd} n_rot={} rope_base={} clamp_shexp={:?}",
5038 g.il, g.swa, g.window, g.n_rot, g.rope_base, g.clamp_shexp,
5039 );
5040 });
5041 }
5042 let eps = self.cfg.rms_eps;
5043 let scale = 1.0 / (hd as f32).sqrt(); // step35.cpp:255 kq_scale
5044 let n_embd = self.cfg.n_embd as usize;
5045 let gw = fa
5046 .attn_gate
5047 .as_ref()
5048 .ok_or("step35 MTP block is missing attn_gate.weight (head-wise attention gate)")?;
5049
5050 let (q0, k0, v0, gt) = if e.uses_q8_1_fast(&fa.wq)
5051 && e.uses_q8_1_fast(&fa.wk)
5052 && e.uses_q8_1_fast(&fa.wv)
5053 && e.uses_q8_1_fast(gw)
5054 {
5055 let (hq, hdq) = e.quantize_q8_1(h, 1, n_embd)?;
5056 let (a, b, c) = match e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, &hq, &hdq)? {
5057 Some(t3) => t3,
5058 None => (
5059 e.matmul_pre(&fa.wq, &hq, &hdq, h, 1)?,
5060 e.matmul_pre(&fa.wk, &hq, &hdq, h, 1)?,
5061 e.matmul_pre(&fa.wv, &hq, &hdq, h, 1)?,
5062 ),
5063 };
5064 (a, b, c, e.matmul_pre(gw, &hq, &hdq, h, 1)?)
5065 } else {
5066 (
5067 e.matmul(&fa.wq, h, 1)?,
5068 e.matmul(&fa.wk, h, 1)?,
5069 e.matmul(&fa.wv, h, 1)?,
5070 e.matmul(gw, h, 1)?,
5071 )
5072 };
5073
5074 let mut q = e.uninit(nh * hd)?;
5075 e.rms_norm(&q0, fa.q_norm.float_data(), &mut q, hd, nh, eps)?;
5076 let mut k = e.uninit(nkv * hd)?;
5077 e.rms_norm(&k0, fa.k_norm.float_data(), &mut k, hd, nkv, eps)?;
5078 // `rope_freqs.weight` (llama3 factors) applies to the FULL-attn layers ONLY; SWA passes
5079 // null (llama-hparams / step35.cpp). Block 45 is SWA, so `ff` is None there — but read
5080 // the resolved flag, not the constant, so an all-full sibling stays correct.
5081 let ff = if g.swa {
5082 None
5083 } else {
5084 self.step35_aux.as_ref().and_then(|a| a.rope_freqs(e))
5085 };
5086 #[cfg(debug_assertions)]
5087 if let Some(ff) = ff {
5088 crate::debug_assert_tensor_stream_device(ff, &e.stream(), "mtp_step35_attn.rope_freqs");
5089 }
5090 e.rope_neox2(
5091 &mut q,
5092 &mut k,
5093 pos_d,
5094 hd,
5095 g.n_rot,
5096 nh,
5097 nkv,
5098 1,
5099 g.rope_base,
5100 1.0,
5101 ff,
5102 )?;
5103
5104 // Append at the HOST slot, then re-stamp the device counter: the eager chain has the
5105 // length on the host anyway, and the windowed view below needs it there to compute the
5106 // offset. The device counter is kept in lockstep so `mtp_kv_fill`'s `set_i32_one` and any
5107 // dc-family consumer of this scratch still agree.
5108 let (kv, scratch_cap) = scratch.plane_mut(scratch_index);
5109 assert!(
5110 kv.len < scratch_cap,
5111 "step35 MTP scratch overflow ({} >= {})",
5112 kv.len,
5113 scratch_cap
5114 );
5115 let next_len = kv.len + 1;
5116 let (off, t_kv) = if g.swa && next_len > g.window {
5117 (next_len - g.window, g.window)
5118 } else {
5119 (0, next_len)
5120 };
5121 // `off`/`t_kv` stay the ATTENTION view; the retain is a separate, lower bound so the
5122 // rewind that follows this append is still resident. THIS is the only site that rebases
5123 // this plane (MEMRA_KV_REBASE_TRACE, one run: 1 rebase, all from here), so it is the site
5124 // that decides `base` for everyone.
5125 let retain_from = match kv.ring.as_ref() {
5126 Some(ring) => memra_kv::swa_retain_from(kv.len, ring.window(), ring.base()),
5127 None => off & !31usize,
5128 };
5129 let write_row = e.prepare_kv_append(kv, retain_from, 1)?;
5130 e.append_kv_quantized(
5131 &k,
5132 &v0,
5133 &mut kv.k,
5134 &mut kv.v,
5135 write_row,
5136 kv.kv_dim_k,
5137 kv.kv_dim_v,
5138 kv.k_tok_bytes,
5139 kv.v_tok_bytes,
5140 false,
5141 )?;
5142 kv.len = next_len;
5143 e.set_i32_one(&mut kv.len_d, kv.len as i32)?;
5144 // SWA view offset (see note 1). The draft chain is short (k+2 rows), but the scratch is
5145 // PERSISTENT across rounds — `mtp_kv_fill` leaves one row per committed token behind, so
5146 // `kv.len` tracks absolute position and crosses 512 in any real generation. The window is
5147 // therefore live, not theoretical.
5148 let physical = kv.physical_rows(off, off + t_kv)?;
5149 let k_view = e.view_u8_range(
5150 &kv.k,
5151 physical.start * kv.k_tok_bytes,
5152 physical.end * kv.k_tok_bytes,
5153 );
5154 let v_view = e.view_u8_range(
5155 &kv.v,
5156 physical.start * kv.v_tok_bytes,
5157 physical.end * kv.v_tok_bytes,
5158 );
5159 let mut attn = e.uninit(nh * hd)?;
5160 e.fa_decode_kvmod(
5161 &q,
5162 &k_view,
5163 &v_view,
5164 &mut attn,
5165 hd,
5166 nh,
5167 nkv,
5168 t_kv,
5169 scale,
5170 kv.k_tok_bytes,
5171 kv.v_tok_bytes,
5172 false,
5173 )?;
5174
5175 let mut ag = e.uninit(nh * hd)?;
5176 e.attn_head_gate(&attn, >, &mut ag, None, hd, nh, 1)?;
5177 e.matmul(&fa.wo, &ag, 1)
5178 }
5179
5180 /// The dcw draft arm's kernel-class precondition, mirrored from `fa_decode_dcw`'s own
5181 /// refusal plus the v3 walk's format contract (`fa_v3_active`), so the DEV dispatch can
5182 /// never pick an arm the launcher would refuse mid-chain (the eager chain has no graceful
5183 /// fallback point) and the CAP site refuses with the named reason instead.
5184 ///
5185 /// `cap` = the SESSION's scratch-plane row capacity: the launcher's vec gate reads
5186 /// `bucket_max = min(window, cap)`, so a SMALL session (tiny prompt + tiny max_tokens,
5187 /// e.g. a max_tokens=8 probe: cap ~62 < the 96 vec floor) is OUTSIDE the dcw domain even
5188 /// though the WINDOW clears the floor. Mirroring the window alone shipped exactly that
5189 /// hole when the door default flipped ON (2026-08-30, vision-cell receipt: sampled
5190 /// capture WARN + `[engine-error] fa_decode_dcw supports the default v3-vec class only`
5191 /// hard-failing the burst — the eager dcw arm has no graceful fallback point). Sub-floor
5192 /// sessions now take the host-len kvmod arm, byte-for-byte the door-off serving.
5193 fn step35_dcw_eligible(&self, g: &crate::hybrid::Step35MtpGeom, cap: usize) -> bool {
5194 let hd = self.cfg.head_dim_k as usize;
5195 step35_draft_dcw_on()
5196 && g.swa
5197 && g.window.min(cap) >= crate::fa_vec_min_tkv()
5198 && std::env::var("MEMRA_NO_FA_VEC").is_err()
5199 && crate::fa_v3_active(hd)
5200 && hd <= 256
5201 && hd.is_multiple_of(32)
5202 }
5203
5204 /// step35 MTP-block attention, T=1, on the scratch KV: the WINDOWED DEVICE-COUNTER twin
5205 /// of `mtp_step35_attn`, serving BOTH draft paths when `step35_draft_dcw_on`. Write slot,
5206 /// key bound and SWA view offset all derive from device state (`len_d`, `base_d` written
5207 /// only at host-side rebases, and the block's `window`), so ONE captured graph serves the
5208 /// whole chain and replays see KV growth through the counter: the `mtp_full_attn_dc`
5209 /// contract plus the view offset the plain `_dc` kernel could not express (the old
5210 /// capture-refusal root cause). The three step35 properties stay per-geom exactly as in
5211 /// the eager twin: nh/nkv from `Step35MtpGeom`, the separate head-wise gate
5212 /// (`attn_head_gate`), per-layer rope width/base with SWA passing null freqs.
5213 ///
5214 /// bucket_max = min(cap, window): the windowed view never exceeds `window` rows, so the
5215 /// capture-time grid stays valid for every replayed len, and the kernel derives ns_eff
5216 /// from the LIVE T_kv at the fixed split_keys (one-partition law). Both arms call THIS
5217 /// launcher at THIS bucket, so eager and captured drafts are bit-identical by
5218 /// construction; vs the retired-by-flag `mtp_step35_attn` the only numeric-class deltas
5219 /// are the sub-vec-floor region (t_kv < 96: kvmod ran scalar, dcw stays vec) and any
5220 /// live-len split-ladder rung below the bucket's, both draft-side only (the verify
5221 /// arbitrates emitted bytes; acceptance is gated by the battery).
5222 ///
5223 /// Host len is NOT advanced here (graph contract); callers mirror. The EAGER caller runs
5224 /// `prepare_kv_append` per step (ring headroom, rebase legal there); the CAPTURED path
5225 /// pre-arms headroom at capture time and round start (`MtpScratch::ensure_dcw_headroom`)
5226 /// because a rebase is host work no captured chain may contain.
5227 #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the capture/call contract; bundling into a struct is a refactor, not a lint fix
5228 fn mtp_step35_attn_dcw(
5229 &self,
5230 e: &Engine,
5231 fa: &FullAttnLayer,
5232 g: &crate::hybrid::Step35MtpGeom,
5233 h: &CudaSlice<f32>,
5234 pos_d: &CudaSlice<i32>,
5235 scratch: &mut MtpScratch,
5236 scratch_index: usize,
5237 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5238 let (nh, nkv, hd) = (g.n_head, g.n_head_kv, self.cfg.head_dim_k as usize);
5239 // MTP-GEOM RECEIPT (dcw twin of the `mtp_step35_attn` receipt): once per process,
5240 // naming the arm, so a serving log proves WHICH draft attention program ran (the
5241 // engagement receipt for the flag door, both directions).
5242 {
5243 static ONCE: std::sync::OnceLock<()> = std::sync::OnceLock::new();
5244 ONCE.get_or_init(|| {
5245 eprintln!(
5246 "[mtp-geom] arm=dcw block={} swa={} window={} n_head={nh} n_head_kv={nkv} \
5247 head_dim_k={hd} n_rot={} rope_base={} clamp_shexp={:?}",
5248 g.il, g.swa, g.window, g.n_rot, g.rope_base, g.clamp_shexp,
5249 );
5250 });
5251 }
5252 let eps = self.cfg.rms_eps;
5253 let scale = 1.0 / (hd as f32).sqrt(); // step35.cpp:255 kq_scale
5254 let n_embd = self.cfg.n_embd as usize;
5255 let gw = fa
5256 .attn_gate
5257 .as_ref()
5258 .ok_or("step35 MTP block is missing attn_gate.weight (head-wise attention gate)")?;
5259
5260 let (q0, k0, v0, gt) = if e.uses_q8_1_fast(&fa.wq)
5261 && e.uses_q8_1_fast(&fa.wk)
5262 && e.uses_q8_1_fast(&fa.wv)
5263 && e.uses_q8_1_fast(gw)
5264 {
5265 let (hq, hdq) = e.quantize_q8_1(h, 1, n_embd)?;
5266 let (a, b, c) = match e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, &hq, &hdq)? {
5267 Some(t3) => t3,
5268 None => (
5269 e.matmul_pre(&fa.wq, &hq, &hdq, h, 1)?,
5270 e.matmul_pre(&fa.wk, &hq, &hdq, h, 1)?,
5271 e.matmul_pre(&fa.wv, &hq, &hdq, h, 1)?,
5272 ),
5273 };
5274 (a, b, c, e.matmul_pre(gw, &hq, &hdq, h, 1)?)
5275 } else {
5276 (
5277 e.matmul(&fa.wq, h, 1)?,
5278 e.matmul(&fa.wk, h, 1)?,
5279 e.matmul(&fa.wv, h, 1)?,
5280 e.matmul(gw, h, 1)?,
5281 )
5282 };
5283
5284 let mut q = e.zeros(nh * hd)?;
5285 e.rms_norm(&q0, fa.q_norm.float_data(), &mut q, hd, nh, eps)?;
5286 let mut k = e.zeros(nkv * hd)?;
5287 e.rms_norm(&k0, fa.k_norm.float_data(), &mut k, hd, nkv, eps)?;
5288 // rope_freqs (llama3 factors) apply to the FULL-attn layers ONLY; SWA passes null
5289 // (the eager twin's rule, resolved from the flag, not the constant).
5290 let ff = if g.swa {
5291 None
5292 } else {
5293 self.step35_aux.as_ref().and_then(|a| a.rope_freqs(e))
5294 };
5295 #[cfg(debug_assertions)]
5296 if let Some(ff) = ff {
5297 crate::debug_assert_tensor_stream_device(
5298 ff,
5299 &e.stream(),
5300 "mtp_step35_attn_dcw.rope_freqs",
5301 );
5302 }
5303 e.rope_neox2(
5304 &mut q,
5305 &mut k,
5306 pos_d,
5307 hd,
5308 g.n_rot,
5309 nh,
5310 nkv,
5311 1,
5312 g.rope_base,
5313 1.0,
5314 ff,
5315 )?;
5316
5317 let (kv, cap) = scratch.plane_mut(scratch_index);
5318 // Append at the DEVICE slot's PHYSICAL row (len_d - base_d), then advance the counter
5319 // in-graph. Physical room is the callers' headroom contract (see the fn doc).
5320 e.append_kv_quantized_dcw(
5321 &k,
5322 &v0,
5323 &mut kv.k,
5324 &mut kv.v,
5325 &kv.len_d,
5326 kv.base_d.as_ref(),
5327 kv.kv_dim_k,
5328 kv.kv_dim_v,
5329 kv.k_tok_bytes,
5330 kv.v_tok_bytes,
5331 )?;
5332 e.inc_seqlen(&mut kv.len_d)?;
5333 // Full-buffer views (any in-round physical row stays in range under the headroom
5334 // contract); the kernel bounds and offsets the key range from (len_d, base_d, window).
5335 let k_view = e.view_u8(&kv.k, kv.k.len());
5336 let v_view = e.view_u8(&kv.v, kv.v.len());
5337 let bucket = g.window.min(cap);
5338 let mut attn = e.zeros(nh * hd)?;
5339 e.fa_decode_dcw(
5340 &q,
5341 &k_view,
5342 &v_view,
5343 &mut attn,
5344 hd,
5345 nh,
5346 nkv,
5347 &kv.len_d,
5348 kv.base_d.as_ref(),
5349 if g.swa { g.window } else { 0 },
5350 bucket,
5351 scale,
5352 kv.k_tok_bytes,
5353 kv.v_tok_bytes,
5354 None,
5355 )?;
5356
5357 let mut ag = e.zeros(nh * hd)?;
5358 e.attn_head_gate(&attn, >, &mut ag, None, hd, nh, 1)?;
5359 e.matmul(&fa.wo, &ag, 1)
5360 }
5361
5362 /// MTP-block full attention, T=1, on the scratch KV (BOTH draft paths — eager and graph):
5363 /// the scratch write slot and the attention bound come from `scratch.kv.len_d` (device i32[1])
5364 /// so the launch args are FIXED across draft steps — ONE captured graph serves the whole
5365 /// chain, and replays keep seeing KV growth through the device counter (no recapture).
5366 /// Geometry contract: n_splits is sized from `scratch.cap` (the persistent capacity); splits
5367 /// whose key range lies beyond the device t_kv exit empty and the shared combine skips them
5368 /// (fa_decode_dc bit-correct-for-any-t_kv<=bucket_max contract). The eager path uses the SAME
5369 /// launcher with the SAME bucket_max -> identical dispatch -> bit-identical draft tokens (the
5370 /// graph-vs-eager parity gate). Host len is NOT advanced here (graph contract); callers mirror.
5371 #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
5372 fn mtp_full_attn_dc(
5373 &self,
5374 e: &Engine,
5375 fa: &FullAttnLayer,
5376 h: &CudaSlice<f32>,
5377 pos_d: &CudaSlice<i32>,
5378 scratch: &mut MtpScratch,
5379 scratch_index: usize,
5380 geom: Option<&crate::hybrid::DraftGeom>,
5381 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
5382 let cfg = &self.cfg;
5383 let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
5384 let geometry = cfg.full_attention_geometry_at(mtp_il);
5385 let n_head = geom.map(|g| g.n_head).unwrap_or(geometry.n_head as usize);
5386 let n_head_kv = geom
5387 .map(|g| g.n_head_kv)
5388 .unwrap_or(geometry.n_head_kv as usize);
5389 let head_dim = geometry.head_dim_k as usize;
5390 let eps = cfg.rms_eps;
5391 let scale = geometry.attention_scale();
5392 let n_embd = geom.map(|g| g.d_inner).unwrap_or(cfg.n_embd as usize);
5393 let bucket_max = scratch.plane(scratch_index).1;
5394
5395 let (qf, mut k, v) =
5396 if e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk) && e.uses_q8_1_fast(&fa.wv) {
5397 let (hq, hd) = e.quantize_q8_1(h, 1, n_embd)?;
5398 (
5399 e.matmul_pre(&fa.wq, &hq, &hd, h, 1)?,
5400 e.matmul_pre(&fa.wk, &hq, &hd, h, 1)?,
5401 e.matmul_pre(&fa.wv, &hq, &hd, h, 1)?,
5402 )
5403 } else {
5404 (
5405 e.matmul(&fa.wq, h, 1)?,
5406 e.matmul(&fa.wk, h, 1)?,
5407 e.matmul(&fa.wv, h, 1)?,
5408 )
5409 };
5410 // M3/Hy3 have no attention output gate — wq out is exactly q; skip the split.
5411 let gated = geometry.attention_gate == memra_gguf::config::AttentionGateKind::FusedQ;
5412 let (mut q, gate) = if gated {
5413 let mut q = e.zeros(n_head * head_dim)?;
5414 let mut gate = e.zeros(n_head * head_dim)?;
5415 e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, 1)?;
5416 (q, Some(gate))
5417 } else {
5418 (qf, None)
5419 };
5420
5421 let mut qn = e.zeros(n_head * head_dim)?;
5422 e.rms_norm(&q, fa.q_norm.float_data(), &mut qn, head_dim, n_head, eps)?;
5423 q = qn;
5424 let mut kn = e.zeros(n_head_kv * head_dim)?;
5425 e.rms_norm(
5426 &k,
5427 fa.k_norm.float_data(),
5428 &mut kn,
5429 head_dim,
5430 n_head_kv,
5431 eps,
5432 )?;
5433 k = kn;
5434 let rope_dims = geometry.n_rot as usize;
5435 e.rope_neox(
5436 &mut q,
5437 pos_d,
5438 head_dim,
5439 rope_dims,
5440 n_head,
5441 1,
5442 geometry.rope_base,
5443 1.0,
5444 )?;
5445 e.rope_neox(
5446 &mut k,
5447 pos_d,
5448 head_dim,
5449 rope_dims,
5450 n_head_kv,
5451 1,
5452 geometry.rope_base,
5453 1.0,
5454 )?;
5455
5456 let kv = scratch.plane_mut(scratch_index).0;
5457 // append at the DEVICE slot (kv.len_d == old len), then advance the counter in-graph.
5458 e.append_kv_quantized_dc(
5459 &k,
5460 &v,
5461 &mut kv.k,
5462 &mut kv.v,
5463 &kv.len_d,
5464 kv.kv_dim_k,
5465 kv.kv_dim_v,
5466 kv.k_tok_bytes,
5467 kv.v_tok_bytes,
5468 false,
5469 )?;
5470 e.inc_seqlen(&mut kv.len_d)?;
5471 // full-buffer views (any in-round t_kv stays in range on replay); the kernel bounds the
5472 // key range from the device counter.
5473 let k_view = e.view_u8(&kv.k, kv.k.len());
5474 let v_view = e.view_u8(&kv.v, kv.v.len());
5475 let (ktb, vtb) = (kv.k_tok_bytes, kv.v_tok_bytes);
5476 let mut attn = e.zeros(n_head * head_dim)?;
5477 e.fa_decode_dc(
5478 &q, &k_view, &v_view, &mut attn, head_dim, n_head, n_head_kv, &kv.len_d, bucket_max,
5479 scale, ktb, vtb, false,
5480 )?;
5481
5482 let attn_g = match &gate {
5483 Some(gate) => {
5484 let mut gsig = e.zeros(n_head * head_dim)?;
5485 e.sigmoid(gate, &mut gsig, n_head * head_dim)?;
5486 let mut ag = e.zeros(n_head * head_dim)?;
5487 e.mul(&attn, &gsig, &mut ag, n_head * head_dim)?;
5488 ag
5489 }
5490 None => attn,
5491 };
5492 e.matmul(&fa.wo, &attn_g, 1)
5493 }
5494
5495 /// PERSISTENT-DRAFT-KV fill (the reference engine's "mtp_update" analogue): compute the MTP
5496 /// block's K/V for `tokens` (committed tokens at positions pos0..pos0+T) from their EXACT
5497 /// trunk hiddens `h` ([T, n_embd] token-major, pre-output_norm) and append at slots pos0.. of
5498 /// the scratch KV. K/V-ONLY — ops A/1-5 plus the K-side of op 6 (wk/wv + k_norm + rope +
5499 /// quantized append); no wq/attention/FFN/lm_head, so per-token cost ~= eh_proj + wk/wv (a
5500 /// small fraction of one trunk layer), T-batched. Rope follows the chain convention
5501 /// rope(token@p) = p+1. Runs at round boundaries OUTSIDE the captured graph in BOTH draft
5502 /// modes -> draft parity by construction. Caller must have scratch.kv.len == pos0.
5503 #[allow(clippy::too_many_arguments)]
5504 fn mtp_kv_fill_at(
5505 &self,
5506 e: &Engine,
5507 mtp: &MtpHead,
5508 tokens: &[u32],
5509 h: &CudaSlice<f32>,
5510 pos0: usize,
5511 scratch: &mut MtpScratch,
5512 scratch_index: usize,
5513 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
5514 ) -> Result<(), Box<dyn std::error::Error>> {
5515 let cfg = &self.cfg;
5516 let n_embd = cfg.n_embd as usize;
5517 let eps = cfg.rms_eps;
5518 let t = tokens.len();
5519 let (scratch_kv, scratch_cap) = scratch.plane(scratch_index);
5520 assert_eq!(scratch_kv.len, pos0, "mtp_kv_fill: append slot mismatch");
5521 assert!(pos0 + t <= scratch_cap, "mtp_kv_fill: scratch overflow");
5522 let Mixer::Full(fa) = &mtp.mixer else {
5523 panic!("MTP block is full-attn in qwen35; linear MTP not supported")
5524 };
5525 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i + 1) as i32).collect();
5526 let pos_d = e.htod_i32(&pos_vec)?;
5527
5528 // ops A/1/2: embed + the two input norms, T-wide.
5529 let e_emb = match embd_dev {
5530 Some((g, qt, rb)) => e.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
5531 None => e.htod(&self.embd.gather(n_embd, tokens))?,
5532 };
5533 let mut e_norm = e.zeros(t * n_embd)?;
5534 e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, t, eps)?;
5535 let mut h_norm = e.zeros(t * n_embd)?;
5536 e.rms_norm(h, mtp.hnorm.float_data(), &mut h_norm, n_embd, t, eps)?;
5537
5538 // op 3: per-row [e_norm ; h_norm] concat, token-major [T, 2*n_embd].
5539 let mut concat = e.zeros(t * 2 * n_embd)?;
5540 for i in 0..t {
5541 e.copy_view_into(
5542 &mut concat,
5543 i * 2 * n_embd,
5544 &e_norm.slice(i * n_embd..(i + 1) * n_embd),
5545 n_embd,
5546 )?;
5547 e.copy_view_into(
5548 &mut concat,
5549 i * 2 * n_embd + n_embd,
5550 &h_norm.slice(i * n_embd..(i + 1) * n_embd),
5551 n_embd,
5552 )?;
5553 }
5554
5555 // ops 4/5: eh_proj + attn_norm, T-wide (at the student inner width when geom is set).
5556 let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
5557 let inp_sa = e.matmul(&mtp.eh_proj, &concat, t)?;
5558 let mut a_norm = e.zeros(t * di)?;
5559 e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, t, eps)?;
5560
5561 // op 6 (K/V half): wk/wv + k_norm + rope + per-row quantized append. No wq/attention —
5562 // the fill only has to leave correct K/V rows behind for later chains to attend over.
5563 let n_head_kv = mtp
5564 .geom
5565 .as_ref()
5566 .map(|g| g.n_head_kv)
5567 .or(mtp.step35.as_ref().map(|s| s.n_head_kv))
5568 .unwrap_or_else(|| {
5569 let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
5570 cfg.full_attention_geometry_at(mtp_il).n_head_kv as usize
5571 });
5572 let mtp_il = cfg.n_layer.saturating_sub(cfg.nextn_predict_layers);
5573 let geometry = cfg.full_attention_geometry_at(mtp_il);
5574 let head_dim = geometry.head_dim_k as usize;
5575 let mut k = e.matmul(&fa.wk, &a_norm, t)?;
5576 let v = e.matmul(&fa.wv, &a_norm, t)?;
5577 let mut kn = e.zeros(t * n_head_kv * head_dim)?;
5578 e.rms_norm(
5579 &k,
5580 fa.k_norm.float_data(),
5581 &mut kn,
5582 head_dim,
5583 n_head_kv * t,
5584 eps,
5585 )?;
5586 k = kn;
5587 // step35: rotary width AND base are per-layer, and the MTP block's values come from the
5588 // resolved `Step35MtpGeom` — NOT from `cfg.rope_dim_count`/`cfg.rope_freq_base`, which
5589 // carry the arch defaults (128 / 5e6, i.e. the FULL-attn layers' base). Getting this wrong
5590 // writes K rows the attention arm then re-derives at a different theta: correct-looking
5591 // output with dead acceptance, invisible to the exactness gates.
5592 let (rope_dims, rope_base, ff) = match mtp.step35.as_ref() {
5593 Some(s) => (
5594 s.n_rot,
5595 s.rope_base,
5596 if s.swa {
5597 None
5598 } else {
5599 self.step35_aux.as_ref().and_then(|a| a.rope_freqs(e))
5600 },
5601 ),
5602 None => (geometry.n_rot as usize, geometry.rope_base, None),
5603 };
5604 #[cfg(debug_assertions)]
5605 if let Some(ff) = ff {
5606 crate::debug_assert_tensor_stream_device(ff, &e.stream(), "mtp_kv_fill.rope_freqs");
5607 }
5608 match ff {
5609 Some(f) => e.rope_neox_ff(
5610 &mut k, &pos_d, head_dim, rope_dims, n_head_kv, t, rope_base, 1.0, f,
5611 )?,
5612 None => e.rope_neox(
5613 &mut k, &pos_d, head_dim, rope_dims, n_head_kv, t, rope_base, 1.0,
5614 )?,
5615 }
5616
5617 let kv = scratch.plane_mut(scratch_index).0;
5618 // Match the trunk prime contract: a chunk may need the aligned window immediately before
5619 // its first row, so preserve that prefix when the physical tail rebases at wrap.
5620 let retain_from = kv
5621 .ring
5622 .as_ref()
5623 .map(|ring| memra_kv::swa_retain_from(pos0, ring.window(), ring.base()))
5624 .unwrap_or(0);
5625 let write_row = e.prepare_kv_append(kv, retain_from, t)?;
5626 for i in 0..t {
5627 let k_row = k.slice(i * kv.kv_dim_k..(i + 1) * kv.kv_dim_k);
5628 let v_row = v.slice(i * kv.kv_dim_v..(i + 1) * kv.kv_dim_v);
5629 e.append_kv_quantized_view(
5630 &k_row,
5631 &v_row,
5632 &mut kv.k,
5633 &mut kv.v,
5634 write_row + i,
5635 kv.kv_dim_k,
5636 kv.kv_dim_v,
5637 kv.k_tok_bytes,
5638 kv.v_tok_bytes,
5639 false,
5640 )?;
5641 }
5642 kv.len = pos0 + t;
5643 e.set_i32_one(&mut kv.len_d, kv.len as i32)?;
5644 Ok(())
5645 }
5646
5647 #[allow(clippy::too_many_arguments)]
5648 fn mtp_kv_fill_all(
5649 &self,
5650 e: &Engine,
5651 tokens: &[u32],
5652 h: &CudaSlice<f32>,
5653 pos0: usize,
5654 scratch: &mut MtpScratch,
5655 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
5656 ) -> Result<(), Box<dyn std::error::Error>> {
5657 debug_assert_eq!(self.mtp_head_count(), scratch.plane_count());
5658 for index in 0..self.mtp_head_count() {
5659 self.mtp_kv_fill_at(
5660 e,
5661 self.mtp_head_at(index),
5662 tokens,
5663 h,
5664 pos0,
5665 scratch,
5666 index,
5667 embd_dev,
5668 )?;
5669 }
5670 Ok(())
5671 }
5672
5673 /// CAPTURE body for the GRAPH DRAFT (stage 2 of graph-grade spec): ONE MTP head forward with
5674 /// every varying input device-resident —
5675 /// - token id from the persistent `tok_d` (the previous replay's in-graph argmax wrote it,
5676 /// so the chain feeds itself; the host reads the same 4 bytes for the draft list),
5677 /// - h_seed from the persistent `h_seed_d` (h_nextn is copied BACK into it at the end),
5678 /// - rope pos from the persistent `pos_d` counter (inc'd in-graph),
5679 /// - scratch KV slot/bound from `scratch.kv.len_d` (see mtp_full_attn_dc).
5680 /// The p-min confidence lands in the persistent `p_d` iff `with_prob` (env is fixed per run).
5681 /// Same kernels, same dispatch as the eager mtp_head_forward_dev chain -> same draft tokens
5682 /// (exactness never depends on drafts — the verify arbitrates — but acceptance parity does).
5683 /// `with_head=false` captures the HEAD-LESS twin for the pseudo-seed replay (2026-07-03):
5684 /// the pseudo pass only needs h_nextn (op 10) + the scratch append — the lm_head read
5685 /// (~1.06ms q6_K on the 9B), argmax and prob are dead weight there. h_nextn's inputs are
5686 /// untouched, so the seed value is identical; round-start resets overwrite tok_d/p_d anyway.
5687 /// `sampled_cap` = Some((ctr_d, perturb_d, q_out_d, seed, temp)) captures the SAMPLED twin
5688 /// (step 3 of the sampled-spec arc): head logits are retained in the persistent `q_out_d`
5689 /// (host D2Ds them to the round's q slot after each replay), the DEVICE event counter is
5690 /// bumped in-graph, and the argmax reads GUMBEL-PERTURBED logits — one categorical draw per
5691 /// replay, bit-identical to the eager arm's gumbel_perturb at the same (seed, sctr, temp).
5692 /// seed/temp are capture-time constants (fixed per generate call, like p_min).
5693 #[allow(clippy::too_many_arguments)]
5694 #[allow(clippy::type_complexity)] // allow: one-shot composite type; naming it would hide the shape that matters at the call site
5695 fn mtp_head_forward_cap(
5696 &self,
5697 e: &Engine,
5698 mtp: &MtpHead,
5699 tok_d: &mut CudaSlice<u32>,
5700 pos_d: &mut CudaSlice<i32>,
5701 h_seed_d: &mut CudaSlice<f32>,
5702 p_d: &mut CudaSlice<f32>,
5703 scratch: &mut MtpScratch,
5704 // Which scratch plane this head appends to / attends over: 0 for the single-head
5705 // chain (every pre-lane caller), the head's own plane index for the multi-head
5706 // chain graphs (each head owns one plane — `mtp_chain_forward_dev`'s contract).
5707 scratch_index: usize,
5708 with_prob: bool,
5709 with_head: bool,
5710 embd_gpu: &CudaSlice<u8>,
5711 embd_qt: i32,
5712 embd_rb: usize,
5713 d_vocab: usize,
5714 sampled_cap: Option<SampledCapArgs<'_>>,
5715 stream_pack: Option<(&mut CudaSlice<u32>, usize, Option<&CudaSlice<u32>>)>,
5716 // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask): (packed draft-vocab allowed-set buffer,
5717 // word count). Captured as ONE mask_logits_f32 node between the head matmul and the
5718 // in-graph argmax; the buffer address is baked, its CONTENTS are re-uploaded by the
5719 // host before every replay (the decode.rs graph-mask pattern). All-ones contents = a
5720 // no-op ban, so a position the grammar cannot constrain costs one pass over the row.
5721 mask_cap: Option<(&CudaSlice<u32>, usize)>,
5722 ) -> Result<(), Box<dyn std::error::Error>> {
5723 let cfg = &self.cfg;
5724 let n_embd = cfg.n_embd as usize;
5725 // step35: capturable through the WINDOWED device-counter arm (`mtp_step35_attn_dcw`)
5726 // once the dcw door is armed and the v3-vec class is live. Without the door this stays
5727 // the deliberate, named refusal: the plain `_dc` attention's key bound always starts at
5728 // row 0, cannot express this block's SWA view offset, and a captured chain would
5729 // silently attend OUTSIDE the window once the persistent scratch passes 512 rows.
5730 // Returning Err (not a panic) is what the capture sites already handle by degrading to
5731 // the eager chain (`mtp_head_forward_dev` -> `mtp_step35_attn`).
5732 // ROUND-STREAM stays refused EITHER WAY: the stream VERIFY has no step35 twin (see the
5733 // step35_verify refusal), so a stream capture that succeeded here would only move the
5734 // failure from capture time (graceful stream-off) to serve time (a failed round).
5735 if let Some(g) = mtp.step35.as_ref() {
5736 if stream_pack.is_some() {
5737 return Err(
5738 "step35 has no ROUND-STREAM draft arm (the stream verify has no step35 \
5739 twin); stream off"
5740 .into(),
5741 );
5742 }
5743 if !self.step35_dcw_eligible(g, scratch.plane(scratch_index).1) {
5744 return Err(format!(
5745 "step35 has no captured draft chain (fa_decode_dc cannot express the MTP \
5746 block's SWA view offset; the windowed dcw capture needs \
5747 MEMRA_STEP35_DRAFT_DCW armed [default ON, =0 disarms] and the v3-vec \
5748 class live at bucket=min(window {}, scratch cap {})) - the eager draft \
5749 chain serves this shape",
5750 g.window,
5751 scratch.plane(scratch_index).1,
5752 )
5753 .into());
5754 }
5755 }
5756 // student inner width (see mtp_head_forward_dev) — interface dims stay n_embd.
5757 let di = mtp.geom.as_ref().map(|g| g.d_inner).unwrap_or(n_embd);
5758 let eps = cfg.rms_eps;
5759 let e_emb = e.embed_gather_device(embd_gpu, tok_d, n_embd, embd_qt, embd_rb)?;
5760 let mut e_norm = e.zeros(n_embd)?;
5761 e.rms_norm(&e_emb, mtp.enorm.float_data(), &mut e_norm, n_embd, 1, eps)?;
5762 let mut h_norm = e.zeros(n_embd)?;
5763 e.rms_norm(
5764 &*h_seed_d,
5765 mtp.hnorm.float_data(),
5766 &mut h_norm,
5767 n_embd,
5768 1,
5769 eps,
5770 )?;
5771 let mut concat = e.zeros(2 * n_embd)?;
5772 e.copy_into(&mut concat, 0, &e_norm, n_embd)?;
5773 e.copy_into(&mut concat, n_embd, &h_norm, n_embd)?;
5774 let inp_sa = e.matmul(&mtp.eh_proj, &concat, 1)?;
5775 let mut a_norm = e.zeros(di)?;
5776 e.rms_norm(&inp_sa, mtp.attn_norm.float_data(), &mut a_norm, di, 1, eps)?;
5777 let attn_out = match (&mtp.mixer, mtp.step35.as_ref()) {
5778 // step35 (eligibility already enforced by the refusal above): the windowed dcw
5779 // arm, the SAME launcher the eager dev arm runs when the door is armed. No host
5780 // work here (this is the capture body); headroom is the callers' pre-arm.
5781 (Mixer::Full(fa), Some(g)) => {
5782 self.mtp_step35_attn_dcw(e, fa, g, &a_norm, pos_d, scratch, scratch_index)?
5783 }
5784 (Mixer::Full(fa), None) => self.mtp_full_attn_dc(
5785 e,
5786 fa,
5787 &a_norm,
5788 pos_d,
5789 scratch,
5790 scratch_index,
5791 mtp.geom.as_ref(),
5792 )?,
5793 (Mixer::Linear(_), _) => {
5794 panic!("MTP block is full-attn in qwen35; linear MTP not supported")
5795 }
5796 (Mixer::Mla(_), _) => {
5797 crate::hybrid::mla_path_unimplemented("captured MTP head forward")
5798 }
5799 (Mixer::Kda(_), _) => {
5800 crate::hybrid::kda_path_unimplemented("captured MTP head forward")
5801 }
5802 };
5803 let mut x1 = e.zeros(di)?;
5804 e.add(&inp_sa, &attn_out, &mut x1, di)?;
5805 let mut z = e.zeros(di)?;
5806 e.rms_norm(&x1, mtp.post_attn_norm.float_data(), &mut z, di, 1, eps)?;
5807 let ffn_out = match &mtp.ffn {
5808 crate::hybrid::Ffn::Dense {
5809 ffn_gate,
5810 ffn_up,
5811 ffn_down,
5812 } => {
5813 let n_ff = ffn_gate.out_features();
5814 let (gate, up) = if e.uses_q8_1_fast(ffn_gate) && e.uses_q8_1_fast(ffn_up) {
5815 let (zq, zd) = e.quantize_q8_1(&z, 1, di)?;
5816 (
5817 e.matmul_pre(ffn_gate, &zq, &zd, &z, 1)?,
5818 e.matmul_pre(ffn_up, &zq, &zd, &z, 1)?,
5819 )
5820 } else {
5821 (e.matmul(ffn_gate, &z, 1)?, e.matmul(ffn_up, &z, 1)?)
5822 };
5823 let mut act = e.zeros(n_ff)?;
5824 // step35: the dense FFN reads the per-layer SHEXP clamp, resolved for the MTP
5825 // block's own index (the mtp_head_forward_dev rule; None for every other arch,
5826 // which is `ffn_act`'s dispatch verbatim). The eager and captured chains must
5827 // run the ONE activation program.
5828 Self::ffn_act_lim(
5829 e,
5830 &self.cfg,
5831 &gate,
5832 &up,
5833 1.0,
5834 1.0,
5835 mtp.step35
5836 .as_ref()
5837 .and_then(|s| s.clamp_shexp)
5838 .map(SwigluClamp::Post),
5839 &mut act,
5840 n_ff,
5841 )?;
5842 e.matmul(ffn_down, &act, 1)?
5843 }
5844 // ROUND-STREAM: a softmax-routed resident MoE takes the zero-D2H device router +
5845 // expert program and is capture-legal. Sigmoid-routed MoE (Hy3/M3/Step) still
5846 // selects through the host-visible sigmoid router; capturing that stream sync
5847 // invalidates CUDA capture, so it stays on the eager draft chain even when every
5848 // expert is resident. Non-resident (SLRU-lock) is likewise rejected.
5849 crate::hybrid::Ffn::Moe(m)
5850 if m.dev_exps.is_some() && self.cfg.sigmoid_router().is_none() =>
5851 {
5852 self.moe_ffn_il(e, m, &z, 1, u16::MAX)?
5853 }
5854 crate::hybrid::Ffn::Moe(_) => {
5855 return Err(
5856 "graph draft requires a Dense or device-routed resident-MoE MTP FFN".into(),
5857 );
5858 }
5859 };
5860 let mut h_inner = e.zeros(di)?;
5861 e.add(&x1, &ffn_out, &mut h_inner, di)?;
5862 // student: up-project back to n_embd (carrier + head input; see mtp_head_forward_dev).
5863 let h_nextn = match mtp.geom.as_ref() {
5864 Some(g) => e.matmul(&g.out_up, &h_inner, 1)?,
5865 None => h_inner,
5866 };
5867 // MEMRA_SPEC_HPOST needs final_h even head-less (it IS the next seed under that convention).
5868 let final_h = if with_head || spec_hpost() {
5869 let final_norm = mtp.shared_head_norm.as_ref().unwrap_or(&self.output_norm);
5870 let mut fh = e.zeros(n_embd)?;
5871 e.rms_norm(&h_nextn, final_norm.float_data(), &mut fh, n_embd, 1, eps)?;
5872 Some(fh)
5873 } else {
5874 None
5875 };
5876 if with_head {
5877 let head = mtp.shared_head_head.as_ref().unwrap_or(&self.output);
5878 let mut logits = e.matmul(head, final_h.as_ref().unwrap(), 1)?;
5879 // DRAFT-SIDE GRAMMAR MASK: ban the grammar-illegal draft ids IN the captured chain,
5880 // before the argmax — proposals become legal by construction. Contents-only
5881 // per-replay upload keeps the capture valid.
5882 if let Some((mask_d, mw)) = mask_cap {
5883 e.mask_logits_col(&mut logits, mask_d, 0, d_vocab, mw)?;
5884 }
5885 if let Some(SampledCapArgs {
5886 ctr: ctr_d,
5887 perturb: perturb_d,
5888 q_out: q_out_d,
5889 seed,
5890 temp,
5891 filt,
5892 }) = sampled_cap
5893 {
5894 // SAMPLED chain: retain q (raw head logits -> persistent q_out_d; the matmul's
5895 // own buffer is pool-recycled after the capture body returns, so it can't be the
5896 // retention target), bump the device event counter, gumbel-perturb reading it,
5897 // and argmax the PERTURBED logits into tok_d — the in-graph categorical draw.
5898 e.copy_into(q_out_d, 0, &logits, d_vocab)?;
5899 e.sctr_inc(ctr_d)?;
5900 match filt {
5901 // PURE-TEMP: gumbel over the raw softmax — byte-identical to the
5902 // pre-lane capture body.
5903 None => e.gumbel_perturb_ctr(&logits, perturb_d, d_vocab, seed, ctr_d, temp)?,
5904 // FILTERED (lane/step37-draft-graph-serving-20260830): the SAME
5905 // filter_stats program the eager arm and the accept path run (the
5906 // wrapper's coop/plain choice is deployment-keyed, never per-call), then
5907 // the device-stat/device-counter perturb twin — the draft draws from the
5908 // exact filtered distribution the verify gathers `q` from. q was
5909 // retained ABOVE, pre-perturb, so the accept path's post-replay stats
5910 // recompute (same kernel, same bits) reconstructs these th/z exactly.
5911 Some(f) => {
5912 e.filter_stats(
5913 &logits, d_vocab, f.rows0, f.th, f.z, f.mx, d_vocab, 1, temp, f.top_k,
5914 f.top_p, f.min_p,
5915 )?;
5916 e.gumbel_perturb_filtered_ctr(
5917 &logits, perturb_d, d_vocab, seed, ctr_d, temp, f.mx, f.th,
5918 )?;
5919 }
5920 }
5921 e.argmax_token_device_into(perturb_d, tok_d, d_vocab)?;
5922 // p-min prob = the head's RAW softmax confidence in the SAMPLED pick — same
5923 // semantics as the eager sampled arm's prob_of_token_device(dl_d, tok_d).
5924 if with_prob {
5925 e.prob_of_token_device_into(&logits, tok_d, p_d, d_vocab)?;
5926 }
5927 } else {
5928 // draft token -> persistent tok_d (next replay's embed reads it; host reads the 4 bytes).
5929 e.argmax_token_device_into(&logits, tok_d, d_vocab)?;
5930 // p-min under a draft mask reads the MASKED row: confidence relative to the
5931 // grammar-LEGAL alternatives (illegal ids leave the softmax denominator), which
5932 // is the right semantics for "does the drafter know what comes next here" and
5933 // the same row the pick came from. Draft-quality only — verify arbitrates.
5934 if with_prob {
5935 e.prob_of_token_device_into(&logits, tok_d, p_d, d_vocab)?;
5936 }
5937 }
5938 }
5939 // ROUND-STREAM K-chain: pack (tok, p) into slot j, then remap tok through d2t so the
5940 // NEXT chained body's embed reads the TARGET id — zero host involvement per step.
5941 if let Some((out, slot, d2t)) = stream_pack {
5942 e.pack_tok_p(tok_d, p_d, out, slot)?;
5943 if let Some(map) = d2t {
5944 e.tok_map_u32(tok_d, map)?;
5945 }
5946 }
5947 // Next draft step's h_seed: pre-norm h_nextn (default) or post-norm final_h (HPOST).
5948 if spec_hpost() {
5949 e.copy_into(h_seed_d, 0, final_h.as_ref().unwrap(), n_embd)?;
5950 } else {
5951 e.copy_into(h_seed_d, 0, &h_nextn, n_embd)?;
5952 }
5953 // advance the draft rope position in-graph.
5954 e.inc_seqlen(pos_d)?;
5955 Ok(())
5956 }
5957
5958 /// Batched target verify forward over `tokens` at positions `pos0..pos0+T` (§D.3, T=K+1).
5959 /// Returns ALL T logit columns (host f32, [T*n_vocab]); appends T cols to every full-attn KV
5960 /// and advances every linear-attn recur state by T steps (the recur steps are SEQUENTIAL T=1).
5961 /// Advances `cache.pos` by T.
5962 pub fn decode_step_t(
5963 &self,
5964 e: &Engine,
5965 tokens: &[u32],
5966 pos0: usize,
5967 cache: &mut Cache,
5968 ) -> Result<Vec<f32>, Box<dyn std::error::Error>> {
5969 if self.is_gemma4_e4b() {
5970 return Ok(self.gemma4_e4b_decode_step_t_h(e, tokens, pos0, cache)?.0);
5971 }
5972 if self.gemma_batch_program() {
5973 return self.gemma4_decode_step_t(e, tokens, pos0, cache);
5974 }
5975 Ok(self.decode_step_t_h(e, tokens, pos0, cache)?.0)
5976 }
5977
5978 /// Like `decode_step_t` but ALSO returns the LAST column's pre-output_norm hidden (h_seed for
5979 /// the next draft round). This lets partial-accept replay run as ONE batched T=(n_acc+1) forward
5980 /// (single weight read) instead of n_acc+1 separate T=1 decode_steps (n_acc+1 weight reads).
5981 /// At batch=1 decode is bandwidth-bound, so batching the replay is THE MTP profitability lever.
5982 pub fn decode_step_t_h(
5983 &self,
5984 e: &Engine,
5985 tokens: &[u32],
5986 pos0: usize,
5987 cache: &mut Cache,
5988 ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
5989 self.decode_step_t_h_emb(e, tokens, pos0, cache, None)
5990 }
5991
5992 /// Like `decode_step_t_h` with an optional RESIDENT embed table (spec hot loop): device
5993 /// gather instead of host dequant + [T, n_embd] f32 htod. Bit-identical rows.
5994 pub fn decode_step_t_h_emb(
5995 &self,
5996 e: &Engine,
5997 tokens: &[u32],
5998 pos0: usize,
5999 cache: &mut Cache,
6000 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
6001 ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
6002 let (logits_d, h_seed) = self.decode_step_t_h_emb_dev(e, tokens, pos0, cache, embd_dev)?;
6003 Ok((e.dtoh(&logits_d)?, h_seed))
6004 }
6005
6006 /// DEVICE-LOGITS verify forward (spec device-argmax lever): identical kernel chain to
6007 /// `decode_step_t_h_emb` but returns the [T, n_vocab] logits ON DEVICE — the accept walk
6008 /// argmaxes each column on-device and reads back ONE [T] u32 instead of dtoh'ing the full
6009 /// T x n_vocab f32 block (~1-4 MB + T host argmaxes, every round). Kernel dispatch is
6010 /// UNCHANGED (same decode-exact kernels); only the post-logits transfer moves.
6011 pub fn decode_step_t_h_emb_dev(
6012 &self,
6013 e: &Engine,
6014 tokens: &[u32],
6015 pos0: usize,
6016 cache: &mut Cache,
6017 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
6018 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
6019 cache.ensure_usable("decode_step_t")?;
6020 let n_embd = self.cfg.n_embd as usize;
6021 let t = tokens.len();
6022 let (logits, x) = self.decode_step_t_core(e, tokens, pos0, cache, embd_dev, None)?;
6023 // h_seed for the next round = LAST column's pre-output_norm hidden ([n_embd]).
6024 let mut hs = vbuf(e, n_embd)?; // fully written by copy_view_into below
6025 e.copy_view_into(&mut hs, 0, &x.slice((t - 1) * n_embd..t * n_embd), n_embd)?;
6026 Ok((logits, hs))
6027 }
6028
6029 /// CORE verify forward: the `decode_step_t_h_emb_dev` kernel chain, returning the FULL
6030 /// pre-output_norm hidden stack x ([T, n_embd], any column extractable) and optionally
6031 /// filling a `VerifyCkpt` (retained per-layer state-rebuild inputs) for the REPLAY-FREE
6032 /// partial accept. `ckpt: None` => byte-for-byte the old behavior (the ckpt writes are pure
6033 /// retains/copies — they never change what any kernel computes).
6034 fn decode_step_t_core(
6035 &self,
6036 e: &Engine,
6037 tokens: &[u32],
6038 pos0: usize,
6039 cache: &mut Cache,
6040 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
6041 mut ckpt: Option<&mut VerifyCkpt>,
6042 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
6043 self.decode_step_t_core_stream(
6044 e,
6045 tokens,
6046 pos0,
6047 cache,
6048 embd_dev,
6049 ckpt.take(),
6050 None,
6051 None,
6052 None,
6053 None,
6054 )
6055 }
6056
6057 /// [`Self::decode_step_t_core`] with the MTP route's verify-graph pool armed
6058 /// (`MEMRA_SPEC_VERIFY_GRAPH`). `graphs: None` reproduces `decode_step_t_core`
6059 /// argument-for-argument, so the eager walk stays the byte-identical fallback.
6060 #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
6061 fn decode_step_t_core_vg(
6062 &self,
6063 e: &Engine,
6064 tokens: &[u32],
6065 pos0: usize,
6066 cache: &mut Cache,
6067 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
6068 mut ckpt: Option<&mut VerifyCkpt>,
6069 graphs: Option<&mut DsparkVerifyGraphs>,
6070 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
6071 self.decode_step_t_core_stream(
6072 e,
6073 tokens,
6074 pos0,
6075 cache,
6076 embd_dev,
6077 ckpt.take(),
6078 None,
6079 None,
6080 None,
6081 graphs,
6082 )
6083 }
6084
6085 /// Increment-0 two-session PP seam: release the peer after this lane's stage-0 boundary TX.
6086 /// The two independent sessions keep their own cache/checkpoint state; only issue order moves.
6087 #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
6088 fn decode_step_t_core_pipelined(
6089 &self,
6090 e: &Engine,
6091 tokens: &[u32],
6092 pos0: usize,
6093 cache: &mut Cache,
6094 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
6095 mut ckpt: Option<&mut VerifyCkpt>,
6096 pipe: &SpecPipeLane,
6097 round: usize,
6098 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
6099 let fence = crate::pp::pp_cuts(self.layers.len())
6100 .ok_or("two-session speculative pipeline requires a PP stage cut")?;
6101 if crate::pp::pp2_streams_off() || !crate::pp::spec_pp_on() {
6102 return Err("two-session speculative pipeline requires the PP verify split".into());
6103 }
6104 let interval_fence = pipe.stage0_begin(round)?;
6105 let _walk = pipe.coordinated_walk()?;
6106 let ticket = self.verify_stage0_issue(
6107 e,
6108 tokens,
6109 pos0,
6110 cache,
6111 embd_dev,
6112 ckpt.as_deref_mut(),
6113 None,
6114 &fence,
6115 Some(interval_fence),
6116 pipe.trace(round),
6117 )?;
6118 pipe.stage0_end(round);
6119 pipe.stage1_begin(round)?;
6120 let result = self.verify_stage1_finish(e, ticket, cache, ckpt, None, &fence, true)?;
6121 pipe.verify_end(round);
6122 Ok(result)
6123 }
6124
6125 /// ROUND-STREAM stage (c) 4: `stream` = (device verify tokens [t], device pos counter) —
6126 /// when Some, rope positions come from pos_iota over the counter, the embed gathers the
6127 /// device tokens, and full_attn_verify routes appends/FA through the _dc twins reading the
6128 /// SAME counter (every layer's kvl.len == cache.pos, one counter drives all three). The
6129 /// host `tokens`/`pos0` args still size buffers (t is FIXED K+1 in stream mode).
6130 /// `vtok_dev` (engine-bundle slice 2): device verify tokens for the EMBED only —
6131 /// unlike `stream` mode it changes nothing else (host pos iota, host-len KV appends).
6132 /// `tokens` then only sizes buffers (the dummy-slice pattern the round-stream arm uses).
6133 #[allow(clippy::too_many_arguments)]
6134 fn decode_step_t_core_stream(
6135 &self,
6136 e: &Engine,
6137 tokens: &[u32],
6138 pos0: usize,
6139 cache: &mut Cache,
6140 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
6141 mut ckpt: Option<&mut VerifyCkpt>,
6142 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
6143 pp_pipe: Option<bool>,
6144 vtok_dev: Option<&CudaSlice<u32>>,
6145 graphs: Option<&mut DsparkVerifyGraphs>,
6146 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
6147 // PP DOOR (lane/pp2-spec 2026-08-06): the verify trunk now takes its OWN stage split,
6148 // exactly as the eager and batched steps do. This is the single funnel every verify
6149 // forward reaches (decode_step_t / _h / _h_emb / _h_emb_dev / _core all land here), so
6150 // wiring it here wires the whole spec surface — the draft/accept/commit machinery above
6151 // is untouched.
6152 //
6153 // History: pp2-hardening (2026-08-06) made this funnel FAIL CLOSED, because its trunk
6154 // walk was unsplit on one stream and a sharded cross-device placement peer-read every
6155 // remote layer's weights on every spec round (measured 13.9-28x on the batched twin).
6156 // The refusal below survives to cover the residue — MEMRA_SPEC_PP=0, MEMRA_PP_STREAMS=0,
6157 // or a placement whose PpNRt fails to build — so a config that would still walk the
6158 // whole trunk on one stream refuses instead of regressing 28x.
6159 if let Some(fence) = crate::pp::pp_cuts(self.layers.len())
6160 && !crate::pp::pp2_streams_off()
6161 && crate::pp::spec_pp_on()
6162 {
6163 if vtok_dev.is_some() {
6164 return Err(
6165 "device-token dspark verify (slice-2 deferred readback) has no PP \
6166 stage-split arm; set MEMRA_DSPARK_DEFER_READBACK=0 or run the dspark \
6167 route on one device"
6168 .into(),
6169 );
6170 }
6171 return self.decode_step_t_core_ppn(
6172 e,
6173 tokens,
6174 pos0,
6175 cache,
6176 embd_dev,
6177 ckpt.take(),
6178 stream,
6179 &fence,
6180 pp_pipe,
6181 );
6182 }
6183 crate::pp::refuse_unsplit_if_remote(
6184 "decode_step_t (spec verify)",
6185 "drop MEMRA_SPEC_PP=0 / MEMRA_PP_STREAMS=0 so the verify trunk takes its OWN stage \
6186 split (decode_step_t_core_ppn); or run spec on one device",
6187 )?;
6188 let cfg = &self.cfg;
6189 let n_embd = cfg.n_embd as usize;
6190 let eps = cfg.rms_eps;
6191 let t = tokens.len();
6192 let pos_d = match stream {
6193 Some((_, ctr)) => {
6194 let mut p = e.alloc_uninit::<i32>(t)?;
6195 e.pos_iota(ctr, &mut p, t)?;
6196 p
6197 }
6198 None => {
6199 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
6200 e.htod_i32(&pos_vec)?
6201 }
6202 };
6203
6204 // embed T tokens -> [T, n_embd] token-major (device gather on the spec hot loop)
6205 let x = match (stream, embd_dev) {
6206 (Some((vtok, _)), Some((g, qt, rb))) => {
6207 e.embed_gather_device_td(g, vtok, t, n_embd, qt, rb)?
6208 }
6209 (None, Some((g, qt, rb))) => match vtok_dev {
6210 // slice 2: device verify tokens, same embed_gather_u32_t kernel —
6211 // bit-identical rows to the host-token arm (same per-dtype deq).
6212 Some(vt_d) => e.embed_gather_device_td(g, vt_d, t, n_embd, qt, rb)?,
6213 None => e.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
6214 },
6215 _ => {
6216 assert!(
6217 vtok_dev.is_none(),
6218 "device-token verify requires the resident embed table (embd_dev)"
6219 );
6220 e.htod(&self.embd.gather(n_embd, tokens))?
6221 }
6222 };
6223
6224 // TRUNK WALK: layers [0, n_layers) through the SAME range-scoped subgraph the PP-N
6225 // stage split calls per stage (`verify_layers`) — one code path, so the split cannot
6226 // drift from the unsplit dispatch mirroring. lane/pp2-spec 2026-08-06.
6227 let x = self.verify_layers(
6228 e,
6229 x,
6230 0,
6231 self.layers.len(),
6232 &pos_d,
6233 pos0,
6234 t,
6235 cache,
6236 ckpt.take(),
6237 stream,
6238 graphs,
6239 )?;
6240 if spec_nan_scan() {
6241 nan_scan_rows(e, &x, t, n_embd, &format!("verify trunk exit pos0={pos0}"))?;
6242 }
6243
6244 let mut hn = vbuf(e, t * n_embd)?;
6245 // Stage-A door: with the serving-class row-outer verify walk, the TAIL must be the
6246 // t=1 decode program per row too (rms_norm t=1 + the single-row bf16 head — the
6247 // split head's concat is receipted bit-identical to it). The batched cuBLASLt head
6248 // is a different ULP class and flips near-tie argmaxes off the greedy tape.
6249 let eager_tail = self.sliding_gated_moe_batch_program() && spec_verify_eager_on();
6250 if eager_tail {
6251 let n_vocab = self.cfg.n_vocab as usize;
6252 // MEMRA_SPEC_HEAD_ROWS=1 — THE VERIFY TAIL'S REDUNDANT HEAD READ.
6253 //
6254 // The loop below runs the head at m=1 once PER COLUMN, so the LM head's weights are
6255 // streamed t times per verify pass. On step37 that head is ~0.49 GiB per card after the
6256 // rank split, ~1.07 ms of pure re-read at t=2 and worse at every wider t — which is a
6257 // large part of why the fixed K ladder LOSES (K=1 81.2 > K=2 73.1 > K=3 62.7 tok/s).
6258 //
6259 // The loop's justification is the comment above: the batched cuBLASLt head is a
6260 // different ULP class and flips near-tie argmaxes off the greedy tape. That is true of
6261 // cuBLASLt and it does NOT apply here, because a FloatBf16 head at 1..=32 rows never
6262 // reaches cuBLASLt: `matmul` routes it to `matvec_bf16_rows_into` (lib.rs:12248), whose
6263 // own doc says `matvec_bf16_f32acc_x4_rows` "runs the t=1 decode head program PER ROW
6264 // (identical dot + reduce), so decode/verify tiers keep the t=1 numeric class". Under
6265 // the W8 doors both widths route to the q8 mirror instead, and the t-column mirror is
6266 // documented "bit-identical to t single-row calls". So the batched form is the SAME
6267 // arithmetic per row on both paths, with one weight read instead of t.
6268 //
6269 // rms_norm is row-wise, so norm(t) is per-row identical to t x norm(1) by construction.
6270 //
6271 // DEFAULT OFF for exactly one turn of the crank: "bit-identical by two documented
6272 // claims" is still an argument. The greedy byte tape decides, and the door flips only
6273 // once the tape is a receipt.
6274 if head_rows_on() {
6275 e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
6276 let logits = e.matmul(&self.output, &hn, t)?;
6277 if stream.is_none() {
6278 cache.pos += t;
6279 }
6280 return Ok((logits, if spec_hpost() { hn } else { x }));
6281 }
6282 let mut logits = vbuf(e, t * n_vocab)?;
6283 for r in 0..t {
6284 let mut row = e.uninit(n_embd)?;
6285 e.dtod_copy_view(&x.slice(r * n_embd..(r + 1) * n_embd), &mut row)?;
6286 let mut hr = e.uninit(n_embd)?;
6287 e.rms_norm(&row, self.output_norm.float_data(), &mut hr, n_embd, 1, eps)?;
6288 let lr = e.matmul(&self.output, &hr, 1)?;
6289 e.dtod_copy_into(&lr, &mut logits, r * n_vocab)?;
6290 e.dtod_copy_into(&hr, &mut hn, r * n_embd)?;
6291 }
6292 if stream.is_none() {
6293 cache.pos += t;
6294 }
6295 return Ok((logits, if spec_hpost() { hn } else { x }));
6296 }
6297 let serving_head =
6298 self.sliding_gated_moe_batch_program() || self.batched_serving_numeric_class();
6299 let logits = if serving_head {
6300 // Step35 and the qwen35 family (MoE 2026-08-14 AM, dense-hybrid same day PM — the
6301 // Q3.8 bring-up reproduced the identical near-tie class on dense: eager-class verify
6302 // vs batched-class live serving, ULP drift amplified through the GDN recurrence)
6303 // serve one batched numeric class at every live width, including B=1. Keep the
6304 // verify head in that same class; other generic families retain the decode-exact
6305 // head that their run-spec contract pins.
6306 e.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
6307 e.matmul(&self.output, &hn, t)?
6308 } else {
6309 e.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
6310 e.matmul_decode_exact(&self.output, &hn, t)?
6311 };
6312 // stream: the device pos counter owns position; host mirror reconciles at drain.
6313 if stream.is_none() {
6314 cache.pos += t;
6315 }
6316 // Hidden stack for seeds/refresh-fills: pre-norm x (default) or post-norm hn (HPOST).
6317 Ok((logits, if spec_hpost() { hn } else { x }))
6318 }
6319
6320 /// THE VERIFY TRUNK OVER PP-N (lane/pp2-spec 2026-08-06): `decode_step_t_core_stream`'s walk
6321 /// as N stage subgraphs, each on its own engine/stream (and, under `MEMRA_PP_DEVICES`, its own
6322 /// device), with a `[T, n_embd]` boundary transfer between them. T = K+1 (the verify batch),
6323 /// so this is the batched-boundary shape the pp2-batch lane's grow-only slots already handle
6324 /// (`tx(b, x, t*n_embd)`; the slot grows to the high-water T and the transport moves exactly
6325 /// the payload).
6326 ///
6327 /// Structure is `decode_step_batch_ppn`'s, which is `decode_step_h_ppn`'s. FOUR THINGS ARE
6328 /// PER-STAGE and each for a measured reason (see `decode_step_batch_ppn`'s header for the
6329 /// receipts):
6330 ///
6331 /// 1. THE ENGINE (`rt.engine(s, e)`) — `Engine` owns lazily-grown stable-pointer scratch
6332 /// (`fa_part_pool`, `fa_vf16_scratch`, `argmax_partials`) that is single-stream-safe BY
6333 /// DESIGN. Two stage streams through one Engine is the 2026-08-02 shared-scratch race
6334 /// (35% flake, nondeterministic all-logits divergence). `PpNRt::build` gives every stage
6335 /// s>0 its own Engine even on the primary device; honouring it here is what scopes the
6336 /// pools. The verify path allocates MORE of that scratch than eager decode does (FA at
6337 /// m=T, and the per-layer `GdnStash` retains), so this is load-bearing, not inherited.
6338 ///
6339 /// 2. `pos_d` — each stage uploads its OWN copy of the T rope positions on ITS stream, so the
6340 /// buffer is allocated, consumed and freed on one stream. In `stream` mode that means each
6341 /// stage runs its own `pos_iota` over the SHARED device counter (`pos_ctr`): the counter is
6342 /// read-only during the forward (the round's `inc`/`copy_add` happen outside it), so every
6343 /// stage derives the identical iota, and each stage's own output buffer is stream-local.
6344 ///
6345 /// 3. THE EMBED lives with stage 0 (`self.embd` / `embd_gpu` are host/primary-side; the
6346 /// sharded loader leaves the table with stage 0 by construction).
6347 ///
6348 /// 4. THE HEAD (`output_norm` + `output`) runs on the LAST stage — the sharded loader uploaded
6349 /// both through that stage's engine (`hybrid.rs`: `e_head = layer_engine(e, n_trunk,
6350 /// n_trunk-1)`), so reading them anywhere else is a peer read of the biggest tensor in the
6351 /// model, every round.
6352 ///
6353 /// WHAT STAYS ON THE PRIMARY, deliberately: the returned logits and hidden stack `x`. Both are
6354 /// last-stage-allocated device buffers, and every consumer (the device argmax walk, the accept
6355 /// kernels, `spec_seed_gather`, the ckpt rebuild in `commit_verified_prefix`) reads them
6356 /// through the primary context by UVA — the same read the batched serving epilogue's
6357 /// `last_logits_dev` park does. Those consumers are per-round O(T x n_vocab) and O(n_embd),
6358 /// not per-layer, so they are not the 28x class; splitting them is a separate lane.
6359 ///
6360 /// The MTP HEAD (draft side) is NOT split: it is one block, it lives wherever the loader put
6361 /// it (`load_mtp` uses the primary engine), and it is ~1-2 GB against the trunk's tens. Draft
6362 /// placement is measured, not assumed — see `research/pp2-spec-20260806`.
6363 ///
6364 /// EXACTNESS: PP-N adds ZERO deviation. Each stage runs the SAME kernels on the SAME bytes in
6365 /// the same order via the SAME `verify_layers` the unsplit body calls; the only change is
6366 /// where the residual is materialized, and the boundary is a straight f32 copy (dtod
6367 /// same-device / `cudaMemcpyPeerAsync` cross-device, no conversion). So the split MUST be
6368 /// BIT-IDENTICAL to the unsplit verify at the same T, in both placement orders. Gate:
6369 /// `decode-batch-gate --mode ppspec`. Acceptance counts are a DERIVED consequence — greedy
6370 /// accept argmaxes these logits, so bit-identical logits force identical accept walks; the
6371 /// `run-spec` K=1..8 arm checks that end-to-end rather than trusting the implication.
6372 #[allow(clippy::too_many_arguments)]
6373 fn decode_step_t_core_ppn(
6374 &self,
6375 e: &Engine,
6376 tokens: &[u32],
6377 pos0: usize,
6378 cache: &mut Cache,
6379 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
6380 mut ckpt: Option<&mut VerifyCkpt>,
6381 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
6382 fence: &[usize],
6383 pp_pipe: Option<bool>,
6384 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
6385 let ticket = self.verify_stage0_issue(
6386 e,
6387 tokens,
6388 pos0,
6389 cache,
6390 embd_dev,
6391 ckpt.as_deref_mut(),
6392 stream,
6393 fence,
6394 pp_pipe,
6395 None,
6396 )?;
6397 self.verify_stage1_finish(e, ticket, cache, ckpt, stream, fence, true)
6398 }
6399
6400 /// Enqueue embed, stage 0, and the first boundary TX, then return the actual boundary slot.
6401 /// The ordinary PP verify wrapper calls `verify_stage1_finish` immediately after this return.
6402 #[allow(clippy::too_many_arguments)]
6403 fn verify_stage0_issue(
6404 &self,
6405 e: &Engine,
6406 tokens: &[u32],
6407 pos0: usize,
6408 cache: &mut Cache,
6409 embd_dev: Option<(&CudaSlice<u8>, i32, usize)>,
6410 ckpt: Option<&mut VerifyCkpt>,
6411 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
6412 fence: &[usize],
6413 pp_pipe: Option<bool>,
6414 trace: Option<SpecPipeTraceCtx>,
6415 ) -> Result<VerifyBoundaryTicket, Box<dyn std::error::Error>> {
6416 assert!(
6417 !self.is_gemma4_e4b() && !self.gemma_batch_program(),
6418 "decode_step_t_core_ppn covers the hybrid non-gemma4 verify trunk only \
6419 (the gemma4 arms have their own decode_step_t twins)"
6420 );
6421 if crate::pp::pp_host_bounce_active() && (stream.is_some() || embd_dev.is_some()) {
6422 return Err(
6423 "decode_step_t_core_ppn: refused with MEMRA_PP_HOST_BOUNCE=1 — the trunk \
6424 boundary itself is host-staged, but device-resident verify still peer-reads \
6425 primary-device token/position/embedding buffers from stage 0. Run plain PP \
6426 serving on this host class; spec requires local per-stage inputs first."
6427 .into(),
6428 );
6429 }
6430 let rt = crate::pp::PpNRt::get(e)?;
6431 // Pipelined callers do not bypass ownership: their explicit coordinator borrow makes
6432 // this acquire clone the same active generation. Ordinary callers acquire a fresh lease.
6433 let walk_owner = rt.acquire_walk("verify_stage0_issue")?;
6434 let n_st = fence.len() - 1;
6435 assert_eq!(
6436 rt.n_stages(),
6437 n_st,
6438 "PpNRt stage count {} != fence stages {n_st}",
6439 rt.n_stages()
6440 );
6441 let n_embd = self.cfg.n_embd as usize;
6442 let t = tokens.len();
6443 let payload = t * n_embd;
6444 if pp_pipe.is_some() {
6445 assert_eq!(n_st, 2, "spec pipeline requires exactly two PP stages");
6446 }
6447 // One-shot lane diagnostic: force natural PP-2 boundaries to completion so the server
6448 // log can price stage 0, the peer hop, the RX copy, and stage 1 + head separately without
6449 // nsys. The ordinary path keeps every enqueue asynchronous. N>2 is deliberately excluded:
6450 // the report below names exactly two stages and must never imply it measured middle ones.
6451 let pp_anatomy = n_st == 2 && std::env::var("MEMRA_SPEC_PP_ANATOMY").as_deref() == Ok("1");
6452 let pp_started = std::time::Instant::now();
6453 let (mut reverse_ms, mut stage0_ms, mut tx_ms) = (0.0f64, 0.0f64, 0.0f64);
6454 // The CALLER's ambient stream, captured BEFORE any `rt.enter()` pushes a stage stream:
6455 // this body returns DEVICE-RESIDENT buffers (the device-argmax accept walk's contract),
6456 // so the exit needs the same publication the boundaries get — see `PpNRt::publish_to`.
6457 // Taken here, not at the end, because inside the last-stage scope `e.stream()` IS the
6458 // stage stream and the wait would self-order into a no-op.
6459 let caller_stream = e.stream();
6460 // #87 ROOT-CAUSE FENCE (lane/pp2spec-crash): the PREVIOUS round's stage-allocated
6461 // outputs (logits/hidden/ckpt stashes) freed stream-ordered on the STAGE streams while
6462 // the primary stream still holds queued reads of them — with event tracking elided,
6463 // nothing stops the pool from reusing those blocks for THIS round's stage allocations,
6464 // whose writes then race the queued reads (measured: 13/4096-NaN random-bits garbage in
6465 // the spec round seed; the full anatomy is on `PpNRt::fence_stages_behind`). Order every
6466 // stage stream behind the caller before enqueueing new stage work.
6467 let reverse_started = std::time::Instant::now();
6468 if pp_pipe != Some(false) {
6469 rt.fence_stages_behind(&caller_stream)?;
6470 }
6471 if pp_pipe == Some(true) {
6472 // Both session verifies must alternate boundary slots even when the ordinary
6473 // decode overlap experiment is off. Prewarm before A's stage 0 so B cannot grow
6474 // slot 1 by synchronizing the RX stream while A's stage 1 is in flight.
6475 rt.prepare_overlap_slots(0, payload)?;
6476 }
6477 if pp_anatomy {
6478 // Drain the reverse-publication dependency before timing stage 0 itself. At c=1 this
6479 // prices any primary-stream rollback/refresh tail inherited from the prior round.
6480 for s in 0..n_st {
6481 let _st = rt.enter(s);
6482 rt.engine(s, e).stream().synchronize()?;
6483 }
6484 reverse_ms = reverse_started.elapsed().as_secs_f64() * 1e3;
6485 }
6486
6487 // Per-stage rope positions: in host mode the same [T] iota each stage uploads itself; in
6488 // stream mode each stage's own `pos_iota` over the shared read-only device counter.
6489 let stage_pos = |es: &Engine| -> Result<CudaSlice<i32>, Box<dyn std::error::Error>> {
6490 match stream {
6491 Some((_, ctr)) => {
6492 let mut p = es.alloc_uninit::<i32>(t)?;
6493 es.pos_iota(ctr, &mut p, t)?;
6494 Ok(p)
6495 }
6496 None => {
6497 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
6498 es.htod_i32(&pos_vec)
6499 }
6500 }
6501 };
6502
6503 // ---- STAGE 0: embed (the table lives with stage 0) + layers [0, fence[1]) + TX ----
6504 let slot = {
6505 let _st0 = rt.enter(0);
6506 let e0 = rt.engine(0, e);
6507 enqueue_spec_pipe_trace_marker(&e0.stream(), trace.as_ref(), "S0", "start", None)?;
6508 let stage0_started = std::time::Instant::now();
6509 let pos_d = stage_pos(e0)?;
6510 let x = match (stream, embd_dev) {
6511 (Some((vtok, _)), Some((g, qt, rb))) => {
6512 e0.embed_gather_device_td(g, vtok, t, n_embd, qt, rb)?
6513 }
6514 (None, Some((g, qt, rb))) => e0.embed_gather_device_t(g, tokens, n_embd, qt, rb)?,
6515 _ => e0.htod(&self.embd.gather(n_embd, tokens))?,
6516 };
6517 let x = self.verify_layers(
6518 e0, x, fence[0], fence[1], &pos_d, pos0, t, cache, ckpt, stream, None,
6519 )?;
6520 if pp_anatomy {
6521 e0.stream().synchronize()?;
6522 stage0_ms = stage0_started.elapsed().as_secs_f64() * 1e3;
6523 }
6524 let tx_started = std::time::Instant::now();
6525 let slot = if pp_pipe.is_some() {
6526 rt.tx_pipelined(0, &x, payload)?
6527 } else {
6528 rt.tx(0, &x, payload)?
6529 };
6530 enqueue_spec_pipe_trace_marker(&e0.stream(), trace.as_ref(), "S0", "end", Some(slot))?;
6531 if pp_anatomy {
6532 e0.stream().synchronize()?;
6533 tx_ms = tx_started.elapsed().as_secs_f64() * 1e3;
6534 }
6535 slot
6536 // x + pos_d drop here: freed stream-ordered on stage-0's stream after use.
6537 };
6538
6539 Ok(VerifyBoundaryTicket {
6540 rt,
6541 caller_stream,
6542 slot,
6543 pos0,
6544 t,
6545 payload,
6546 n_st,
6547 pipelined: pp_pipe.is_some(),
6548 pp_anatomy,
6549 pp_started,
6550 reverse_ms,
6551 stage0_ms,
6552 tx_ms,
6553 trace,
6554 _walk_owner: walk_owner,
6555 })
6556 }
6557
6558 /// Consume a stage-0 boundary ticket and enqueue the remaining PP stages plus the head.
6559 /// On PP-2 this is exactly stage 1; PP-N keeps its pre-existing middle-stage walk here.
6560 #[allow(clippy::too_many_arguments)]
6561 fn verify_stage1_finish(
6562 &self,
6563 e: &Engine,
6564 ticket: VerifyBoundaryTicket,
6565 cache: &mut Cache,
6566 mut ckpt: Option<&mut VerifyCkpt>,
6567 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
6568 fence: &[usize],
6569 publish_to_caller: bool,
6570 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
6571 let VerifyBoundaryTicket {
6572 rt,
6573 caller_stream,
6574 slot,
6575 pos0,
6576 t,
6577 payload,
6578 n_st,
6579 pipelined,
6580 pp_anatomy,
6581 pp_started,
6582 reverse_ms,
6583 stage0_ms,
6584 tx_ms,
6585 trace,
6586 _walk_owner,
6587 } = ticket;
6588 let n_embd = self.cfg.n_embd as usize;
6589 let eps = self.cfg.rms_eps;
6590 let mut slot = slot;
6591 let (mut rx_ms, mut stage1_ms) = (0.0f64, 0.0f64);
6592 let stage_pos = |es: &Engine| -> Result<CudaSlice<i32>, Box<dyn std::error::Error>> {
6593 match stream {
6594 Some((_, ctr)) => {
6595 let mut p = es.alloc_uninit::<i32>(t)?;
6596 es.pos_iota(ctr, &mut p, t)?;
6597 Ok(p)
6598 }
6599 None => {
6600 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
6601 es.htod_i32(&pos_vec)
6602 }
6603 }
6604 };
6605
6606 // ---- MIDDLE STAGES: RX boundary s-1 -> range -> TX boundary s ----
6607 for s in 1..n_st - 1 {
6608 let _st = rt.enter(s);
6609 let es = rt.engine(s, e);
6610 let pos_d = stage_pos(es)?;
6611 let x = rt.rx(s - 1, slot, payload)?;
6612 let x = self.verify_layers(
6613 es,
6614 x,
6615 fence[s],
6616 fence[s + 1],
6617 &pos_d,
6618 pos0,
6619 t,
6620 cache,
6621 ckpt.as_deref_mut(),
6622 stream,
6623 None,
6624 )?;
6625 slot = if pipelined {
6626 rt.tx_pipelined(s, &x, payload)?
6627 } else {
6628 rt.tx(s, &x, payload)?
6629 };
6630 }
6631
6632 // ---- LAST STAGE: RX + final range + output_norm + lm head ----
6633 let _stl = rt.enter(n_st - 1);
6634 let el = rt.engine(n_st - 1, e);
6635 let pos_d = stage_pos(el)?;
6636 let rx_started = std::time::Instant::now();
6637 let x = rt.rx(n_st - 2, slot, payload)?;
6638 if pp_anatomy {
6639 el.stream().synchronize()?;
6640 rx_ms = rx_started.elapsed().as_secs_f64() * 1e3;
6641 }
6642 enqueue_spec_pipe_trace_marker(&el.stream(), trace.as_ref(), "S1", "start", Some(slot))?;
6643 let stage1_started = std::time::Instant::now();
6644 let x = self.verify_layers(
6645 el,
6646 x,
6647 fence[n_st - 1],
6648 fence[n_st],
6649 &pos_d,
6650 pos0,
6651 t,
6652 cache,
6653 ckpt,
6654 stream,
6655 None,
6656 )?;
6657
6658 let mut hn = vbuf(el, payload)?;
6659 let logits = if self.sliding_gated_moe_batch_program() {
6660 // The PP Step35 serving path uses rms_norm + matmul for B=1 as well as B>1.
6661 // Verify must not switch numeric class merely because the same session speculates.
6662 el.rms_norm(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
6663 el.matmul(&self.output, &hn, t)?
6664 } else {
6665 el.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
6666 el.matmul_decode_exact(&self.output, &hn, t)?
6667 };
6668 enqueue_spec_pipe_trace_marker(&el.stream(), trace.as_ref(), "S1", "end", Some(slot))?;
6669 if pp_anatomy {
6670 el.stream().synchronize()?;
6671 stage1_ms = stage1_started.elapsed().as_secs_f64() * 1e3;
6672 }
6673 // EXIT PUBLICATION: both returned buffers are still being produced on the last stage's
6674 // stream. Order the caller's stream behind that work before the buffers escape this
6675 // scope (the 2026-08-06 same-device ppspec find: without it the caller's primary-stream
6676 // consumer read unwritten logits — nondeterministic, one-device-only, and it poisoned
6677 // the following arm's KV in the same process).
6678 if publish_to_caller {
6679 rt.publish_to(n_st - 1, &caller_stream)?;
6680 }
6681 if pp_anatomy {
6682 if publish_to_caller {
6683 caller_stream.synchronize()?;
6684 }
6685 eprintln!(
6686 "[spec-pp-anatomy] t={t} reverse={reverse_ms:.3}ms stage0={stage0_ms:.3}ms \
6687 tx={tx_ms:.3}ms rx={rx_ms:.3}ms stage1-head={stage1_ms:.3}ms total={:.3}ms",
6688 pp_started.elapsed().as_secs_f64() * 1e3,
6689 );
6690 }
6691 // stream: the device pos counter owns position; host mirror reconciles at drain.
6692 if stream.is_none() {
6693 cache.pos += t;
6694 }
6695 Ok((logits, if spec_hpost() { hn } else { x }))
6696 }
6697
6698 /// Step3.5/Step3.7 verify trunk in the serving batched numeric class.
6699 ///
6700 /// `step35_decode_batch_layers` is now authoritative at every live serving width, including
6701 /// B=1 (lane/cx-b1fix). The older verify walk deliberately mirrored the eager T=1 class:
6702 /// it replayed `step35_decode_attn` per row and used the eager/decode-exact FFN dispatch.
6703 /// Those classes are individually stable, but a near-tie prompt can choose different greedy
6704 /// bytes when a request moves from batched plain serving into speculative verify. Run the
6705 /// same authoritative B=1 stage subgraph for each verify row here. Rows still advance
6706 /// layer-by-layer, so every layer sees the preceding verify rows in its attention cache while
6707 /// every norm/projection/FFN uses exactly the live serving dispatch.
6708 #[allow(clippy::too_many_arguments)]
6709 /// PRIME-BY-T-ROWS (MEMRA_PRIME_TROWS=1): prefill the prompt through the same-session
6710 /// t-row walk in 32-row chunks — every row runs the t=1 decode program bit-for-bit
6711 /// (the TOKENWISE-prime ORACLE class), so this door is exact against the exactness
6712 /// reference while replacing the host-canonical per-token prime. Requires the walk
6713 /// doors (MEMRA_SPEC_VERIFY_EAGER/TCOL); returns the prime contract trio.
6714 #[allow(clippy::type_complexity)]
6715 pub(crate) fn step35_prime_trows(
6716 &self,
6717 e: &Engine,
6718 tokens: &[u32],
6719 cache: &mut Cache,
6720 ) -> Result<Option<(Vec<f32>, CudaSlice<f32>, CudaSlice<f32>)>, Box<dyn std::error::Error>>
6721 {
6722 let dbg = std::env::var("MEMRA_SPEC_FA2_DEBUG").as_deref() == Ok("1");
6723 if !prime_trows_on() {
6724 return Ok(None);
6725 }
6726 if !self.uses_sliding_gated_moe_program()
6727 || cache.pos != 0
6728 || cache.dflash_taps.is_some()
6729 || !spec_verify_eager_on()
6730 || !spec_verify_tcol_on()
6731 {
6732 if dbg {
6733 eprintln!(
6734 "[prime-trows] refuse: program={} pos={} taps={} eager={:?} tcol={:?}",
6735 self.uses_sliding_gated_moe_program(),
6736 cache.pos,
6737 cache.dflash_taps.is_some(),
6738 std::env::var("MEMRA_SPEC_VERIFY_EAGER").ok(),
6739 std::env::var("MEMRA_SPEC_VERIFY_TCOL").ok()
6740 );
6741 }
6742 return Ok(None);
6743 }
6744 let n_embd = self.cfg.n_embd as usize;
6745 let n_layers = self.layers.len();
6746 let t_total = tokens.len();
6747 let Some(embd_gpu) = self.embd_gpu_try(e) else {
6748 if dbg {
6749 eprintln!("[prime-trows] refuse: no device embed table");
6750 }
6751 return Ok(None);
6752 };
6753 let embd_qtype = match self.embd.ggml_type {
6754 memra_gguf::GgmlType::BF16 => crate::QT_BF16,
6755 memra_gguf::GgmlType::Q8_0 => crate::QT_Q8_0,
6756 other => {
6757 if dbg {
6758 eprintln!("[prime-trows] refuse: embed dtype {other:?}");
6759 }
6760 return Ok(None);
6761 }
6762 };
6763 let embd_row_bytes = self.embd.raw.len() / self.cfg.n_vocab as usize;
6764 // Chunk plan: 32-row chunks; a 1-token tail folds into the previous chunk
6765 // (the walk floor is t >= 2).
6766 let mut bounds = Vec::new();
6767 let mut start = 0usize;
6768 while start < t_total {
6769 let mut end = (start + 32).min(t_total);
6770 if t_total - end == 1 {
6771 end -= 1;
6772 }
6773 bounds.push((start, end));
6774 start = end;
6775 }
6776 if bounds.iter().any(|(a, b)| b - a < 2) {
6777 return Ok(None); // degenerate short prompt keeps the ordinary prime
6778 }
6779 let mut hiddens = e.uninit(t_total * n_embd)?;
6780 let mut last: Option<CudaSlice<f32>> = None;
6781 for &(a, b) in &bounds {
6782 let tc = b - a;
6783 let tok_d = e.stream().clone_htod(&tokens[a..b])?;
6784 let x =
6785 e.embed_gather_device_td(embd_gpu, &tok_d, tc, n_embd, embd_qtype, embd_row_bytes)?;
6786 let out = self.step35_verify_batch_layers(e, x, 0, n_layers, a, tc, cache)?;
6787 e.copy_into(&mut hiddens, a * n_embd, &out, tc * n_embd)?;
6788 if b == t_total {
6789 let mut h = e.uninit(n_embd)?;
6790 e.dtod_copy_view(&out.slice((tc - 1) * n_embd..tc * n_embd), &mut h)?;
6791 last = Some(h);
6792 }
6793 }
6794 let h_seed = last.expect("last chunk produced the seed row");
6795 let mut hn = e.uninit(n_embd)?;
6796 e.rms_norm_decode(
6797 &h_seed,
6798 self.output_norm.float_data(),
6799 &mut hn,
6800 n_embd,
6801 1,
6802 self.cfg.rms_eps,
6803 )?;
6804 let logits_d = e.matmul_decode_exact(&self.output, &hn, 1)?;
6805 let logits = e.dtoh(&logits_d)?;
6806 cache.pos = t_total;
6807 Ok(Some((logits, h_seed, hiddens)))
6808 }
6809
6810 #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
6811 fn step35_verify_batch_layers(
6812 &self,
6813 e: &Engine,
6814 mut x: CudaSlice<f32>,
6815 lo: usize,
6816 hi: usize,
6817 pos0: usize,
6818 t: usize,
6819 cache: &mut Cache,
6820 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
6821 let n_embd = self.cfg.n_embd as usize;
6822 if !self.uses_sliding_gated_moe_program() {
6823 return Err(
6824 "serving-class verify requires sliding-gated-MoE canonical operations".into(),
6825 );
6826 }
6827 // SERVING-CLASS VERIFY (MEMRA_SPEC_VERIFY_EAGER=1, step37 MTP bring-up): each verify
6828 // column rides decode_layers_eager — the EXACT t=1 program live serving runs (all TP2
6829 // doors) — row-outer, so row r's appends land before row r+1 attends: bit-equal to
6830 // plain greedy by construction. Only the unsplit full-range walk qualifies; PP splits
6831 // and the tap path keep the batch-layer class.
6832 static VE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
6833 let eager_verify =
6834 *VE.get_or_init(spec_verify_eager_on) && lo == 0 && hi == self.layers.len();
6835 if eager_verify {
6836 // T-COLUMN LAYER-OUTER WALK (MEMRA_SPEC_VERIFY_TCOL=1): per layer, one t-grid
6837 // attn norm + ONE weight-amortized QKV(+gate) over all T columns, then each
6838 // column runs the UNMODIFIED t=1 attention program via the col-select door and
6839 // the ordinary residual/FFN body. Values per column are bit-equal to the
6840 // row-outer walk: rms over the materialized residual == the fused add+norm
6841 // (kernel_check identity), the tcol kernel's per-column FP order == the t=1
6842 // kernel, and every downstream op IS the t=1 program.
6843 static TCOL: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
6844 let tcol = *TCOL.get_or_init(spec_verify_tcol_on);
6845 // T > 32 (prefill-class): run the SAME walk in 32-row chunks — each chunk's
6846 // rows are the t=1 program bit-for-bit and the rope pass advances the cache,
6847 // so a chunked call is value-identical to the row-outer loop it replaces.
6848 static TROWS_PREFILL: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
6849 // MEMRA_STEP_GEMM_PRIME outranks the walk: with the grouped GEMM prime armed, the
6850 // t-row walk defers so the batch path (GEMM trunk + grouped MoE) takes the prompt —
6851 // flag precedence between two existing doors, not a new flag. Without this, both
6852 // doors ON meant the walk still won and the GEMM prime needed PRIME_TROWS=0 by hand.
6853 let trows_prefill =
6854 *TROWS_PREFILL.get_or_init(|| prime_trows_on() && !crate::step_gemm_prime_on());
6855 // MEMRA_PRIME_TROWS_T=<w>: chunk width, default 8 = the REAL cap of this walk.
6856 // The workspace slabs go to 32 rows, but `matvec_bf16_qkvg_tcol_into` refuses
6857 // t > 8 (compile-time-T twins exist for 2/4/8 only; the runtime-t kernel spills
6858 // its accumulators to local memory), so a wider chunk fails the request with
6859 // "matvec_bf16_qkvg_tcol geometry" — which is exactly how the first server-path
6860 // TROWS arm died. Measured at 193 tokens: w=8 2.459 s, w=4 2.574 s.
6861 static TROWS_W: std::sync::OnceLock<Result<usize, String>> = std::sync::OnceLock::new();
6862 let trows_w = match TROWS_W.get_or_init(|| {
6863 let value = std::env::var("MEMRA_PRIME_TROWS_T").ok();
6864 parse_prime_trows_width(value.as_deref())
6865 }) {
6866 Ok(width) => *width,
6867 Err(err) => return Err(err.clone().into()),
6868 };
6869 if tcol && trows_prefill && t > trows_w {
6870 // One-time engagement receipt: without it a prefill gate cannot tell a
6871 // chunked walk from the row-outer fallback it is supposed to replace
6872 // (the first PRIME_TROWS gate passed vacuously on exactly that).
6873 static SEEN: std::sync::atomic::AtomicBool =
6874 std::sync::atomic::AtomicBool::new(false);
6875 if !SEEN.swap(true, std::sync::atomic::Ordering::Relaxed) {
6876 eprintln!(
6877 "[prime-trows] ENGAGED t={t} width={trows_w} chunks={} layers={}..{}",
6878 t.div_ceil(trows_w),
6879 lo,
6880 hi
6881 );
6882 }
6883 let mut out = e.uninit(t * n_embd)?;
6884 let mut start = 0usize;
6885 while start < t {
6886 let mut end = (start + trows_w).min(t);
6887 if t - end == 1 {
6888 end -= 1;
6889 }
6890 let tc = end - start;
6891 let mut xc = e.uninit(tc * n_embd)?;
6892 e.dtod_copy_view(&x.slice(start * n_embd..end * n_embd), &mut xc)?;
6893 let oc =
6894 self.step35_verify_batch_layers(e, xc, lo, hi, pos0 + start, tc, cache)?;
6895 e.copy_into(&mut out, start * n_embd, &oc, tc * n_embd)?;
6896 start = end;
6897 }
6898 return Ok(out);
6899 }
6900 if tcol && (2..=32).contains(&t) {
6901 // MEMRA_TCOL_PROF=1: synchronized per-segment wall profile of the walk
6902 // (norm+QKV precompute / per-col attention / per-col residual+FFN). The
6903 // syncs serialize the stream, so the split is for TARGETING amortization
6904 // work only — never a perf claim.
6905 static PROF: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
6906 let prof =
6907 *PROF.get_or_init(|| std::env::var("MEMRA_TCOL_PROF").as_deref() == Ok("1"));
6908 let mut prof_ms = [0f64; 3];
6909 let eps = self.cfg.rms_eps;
6910 let mut x_t = x;
6911 let mut h_t = e.uninit(t * n_embd)?;
6912 let mut h_row = e.uninit(n_embd)?; // real row: the non-dcw fallback reads it
6913 // Per-column pos buffers hoisted out of the layer loop (a per-col-per-layer
6914 // pageable htod was an in-stream engine turnaround x t x 45).
6915 let mut pos_rows = Vec::with_capacity(t);
6916 for r in 0..t {
6917 pos_rows.push(e.htod_i32(&[(pos0 + r) as i32])?);
6918 }
6919 let mut ok = true;
6920 // MEMRA_TCOL_OPROJ=1: defer each column's o_proj — the finish seam
6921 // stashes `gated` instead of joining per column; one b4_tcol per rank +
6922 // one slab join produce every column's `mixed` after the attention pass.
6923 // Bit-exact per column (t=1 b4 program per column; elementwise join).
6924 // MEMRA_TCOL_FFN=1: today this only IMPLIES the o_proj defer above. Its
6925 // named feature, the two-column device-routed FFN sweep, rode the
6926 // slot-major v2 TP banks and was REMOVED with the MEMRA_NVFP4_BANK_V2 door
6927 // (2026-08-29, research/step37-bankv2-removal-20260829): the v2 layout
6928 // changed generated text in serving. The flag itself stays because it is
6929 // family-armed in the step37 serving defaults and killing it here would
6930 // silently drop the o_proj defer from the qualified serving shape.
6931 static FFN2: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
6932 let ffn_batch = *FFN2.get_or_init(tcol_ffn_on);
6933 let oproj_batch = crate::tp::tcol_oproj_on() || ffn_batch;
6934 // MEMRA_SPEC_FA2=1 (T=2 only): eligible layers defer BOTH columns' fa —
6935 // the per-column pass norms/ropes/appends and stashes q+gate, then one
6936 // shared-KV fa_decode_dcw2 per rank + the o_proj join produce the
6937 // [2, o_out] mixed slab. The precheck runs before arming (stashing is
6938 // unrecoverable); ineligible/boundary layers run the ordinary program.
6939 let fa2 = crate::tp::spec_fa2_on() && t <= 32;
6940 let mut mixed_row = e.uninit(n_embd)?;
6941 let mut pos_staged = false;
6942 for il in lo..hi {
6943 let layer = &self.layers[il];
6944 // BEFORE this layer touches its planes: is the history it is about to
6945 // attend already poisoned? Global (non-ring) layers only, which are the
6946 // ones the level-2 bitmap implicates.
6947 if kv_plane_scan_on()
6948 && self.step35_geom(il).window.is_none()
6949 && let Some(distributed) = cache.tp_kv[il].as_ref()
6950 {
6951 scan_kv_plane(e, distributed, il, pos0)?;
6952 }
6953 let fa2_layer = fa2 && self.step35_fa_rows_precheck(cache, il, pos0, t)?;
6954 let mut seg = std::time::Instant::now();
6955 e.rms_norm(&x_t, layer.attn_norm.float_data(), &mut h_t, n_embd, t, eps)?;
6956 if !self.step35_verify_qkv_precompute(e, il, &h_t, t)? {
6957 ok = false;
6958 break;
6959 }
6960 // FULL t-row attention pass (rope/append + fa + combine + o_proj in
6961 // 3 launches/rank): same-session rows, slot = len-base+r, one len
6962 // advance by t. Host cache bookkeeping mirrors the per-column tail.
6963 if fa2_layer
6964 && let Some(mixed_t) =
6965 self.step35_verify_rope_fa_pass(e, il, cache, pos0, t, !pos_staged)?
6966 {
6967 pos_staged = true;
6968 {
6969 let tp_kv = cache.tp_kv[il]
6970 .as_mut()
6971 .expect("precheck verified the distributed cache");
6972 let transaction = tp_kv.begin_transaction()?;
6973 let crate::hybrid::Mixer::Full(fa) = &layer.mixer else {
6974 return Err("verify rope pass expects full attention".into());
6975 };
6976 let tp = fa
6977 .step_tp_qkv
6978 .as_ref()
6979 .ok_or("verify rope pass lost its TP state")?;
6980 let empty: [CudaSlice<f32>; 0] = [];
6981 tp.runtime.append_tp_kv_transaction_inner(
6982 tp_kv,
6983 transaction,
6984 &empty,
6985 &empty,
6986 t,
6987 true,
6988 )?;
6989 tp.runtime
6990 .commit_tp_kv_transaction_external(tp_kv, transaction, t)?;
6991 if let Some(local) = cache.kv[il].as_mut() {
6992 local.len = pos0 + t;
6993 if !crate::tp::len_mirror_lazy_on() {
6994 e.set_i32_one(&mut local.len_d, local.len as i32)?;
6995 }
6996 }
6997 }
6998 if prof {
6999 e.stream().synchronize()?;
7000 prof_ms[1] += seg.elapsed().as_secs_f64() * 1e3;
7001 seg = std::time::Instant::now();
7002 }
7003 let o_out = mixed_t.len() / t;
7004 let mut next = e.uninit(t * n_embd)?;
7005 {
7006 for r in 0..t {
7007 e.dtod_copy_view(
7008 &mixed_t.slice(r * o_out..(r + 1) * o_out),
7009 &mut mixed_row,
7010 )?;
7011 let mut x_row = e.uninit(n_embd)?;
7012 e.dtod_copy_view(
7013 &x_t.slice(r * n_embd..(r + 1) * n_embd),
7014 &mut x_row,
7015 )?;
7016 let (x1, ffn_out) = self.residual_norm_ffn(
7017 e, layer, &x_row, &mixed_row, n_embd, il, eps,
7018 )?;
7019 let mut x2 = e.uninit(n_embd)?;
7020 e.add(&x1, &ffn_out, &mut x2, n_embd)?;
7021 e.dtod_copy_into(&x2, &mut next, r * n_embd)?;
7022 }
7023 }
7024 if prof {
7025 e.stream().synchronize()?;
7026 prof_ms[2] += seg.elapsed().as_secs_f64() * 1e3;
7027 }
7028 x_t = next;
7029 if spec_nan_scan() {
7030 // The scan MUST sit on this arm too. It used to live only on
7031 // the non-fused tail, so a fused layer's poison was first
7032 // reported by the next non-fused layer.
7033 verify_arm_receipt(
7034 "fused",
7035 il,
7036 pos0,
7037 t,
7038 cache.tp_kv[il].as_ref().map(|d| d.staged_len()),
7039 );
7040 nan_scan_rows(
7041 e,
7042 &x_t,
7043 t,
7044 n_embd,
7045 &format!("tcol layer {il} pos0={pos0} arm=fused"),
7046 )?;
7047 }
7048 continue;
7049 }
7050 if prof {
7051 e.stream().synchronize()?;
7052 prof_ms[0] += seg.elapsed().as_secs_f64() * 1e3;
7053 seg = std::time::Instant::now();
7054 }
7055 let mut next = e.uninit(t * n_embd)?;
7056 // Columns whose o_proj was deferred (their FFN runs after the join).
7057 // A NON-deferred column's FFN must run INSIDE the column loop: the
7058 // oproj-tail handoff is a single cell that the same column's
7059 // residual_norm_ffn consumes before the next column's finish.
7060 let mut deferred: Vec<usize> = Vec::new();
7061 let mut fa2_deferred: Vec<usize> = Vec::new();
7062 let ffn_col = |r: usize,
7063 mixed: &CudaSlice<f32>,
7064 next: &mut CudaSlice<f32>|
7065 -> Result<(), Box<dyn std::error::Error>> {
7066 let mut x_row = e.uninit(n_embd)?;
7067 e.dtod_copy_view(&x_t.slice(r * n_embd..(r + 1) * n_embd), &mut x_row)?;
7068 let (x1, ffn_out) =
7069 self.residual_norm_ffn(e, layer, &x_row, mixed, n_embd, il, eps)?;
7070 if spec_nan_scan_level() >= 2 {
7071 nan_scan_rows(
7072 e,
7073 &ffn_out,
7074 1,
7075 n_embd,
7076 &format!("tcol layer {il} col {r} per-column FFN out"),
7077 )?;
7078 }
7079 let mut x2 = e.uninit(n_embd)?;
7080 e.add(&x1, &ffn_out, &mut x2, n_embd)?;
7081 e.dtod_copy_into(&x2, next, r * n_embd)?;
7082 Ok(())
7083 };
7084 #[allow(clippy::needless_range_loop)]
7085 // allow: the explicit index loop keeps the offset arithmetic visible and aligned with the device-side indexing
7086 for r in 0..t {
7087 e.dtod_copy_view(&h_t.slice(r * n_embd..(r + 1) * n_embd), &mut h_row)?;
7088 let row_pos = &pos_rows[r];
7089 crate::tp::set_verify_tcol(Some(r));
7090 if fa2_layer {
7091 crate::tp::set_spec_fa2_defer(Some(r));
7092 } else if oproj_batch {
7093 crate::tp::set_tcol_oproj_defer(Some(r));
7094 }
7095 let mixed = match &layer.mixer {
7096 crate::hybrid::Mixer::Full(fa) => {
7097 self.full_attn_decode(e, fa, &h_row, row_pos, pos0 + r, cache, il)
7098 }
7099 _ => Err("step35 verify expects full attention".into()),
7100 };
7101 crate::tp::set_verify_tcol(None);
7102 crate::tp::set_spec_fa2_defer(None);
7103 crate::tp::set_tcol_oproj_defer(None);
7104 let mixed = mixed?;
7105 if fa2_layer && crate::tp::take_spec_fa2_stashed() {
7106 fa2_deferred.push(r);
7107 } else if oproj_batch && crate::tp::take_tcol_oproj_stashed() {
7108 deferred.push(r);
7109 } else {
7110 if spec_nan_scan_level() >= 2 {
7111 let cols = mixed.len();
7112 nan_scan_rows(
7113 e,
7114 &mixed,
7115 1,
7116 cols,
7117 &format!("tcol layer {il} col {r} per-column ATTN out"),
7118 )?;
7119 }
7120 ffn_col(r, &mixed, &mut next)?;
7121 }
7122 }
7123 if !fa2_deferred.is_empty() && fa2_deferred.len() != t {
7124 // The precheck guarantees both columns stash or neither; a strict
7125 // subset means a column's output was never produced anywhere.
7126 return Err("spec fa2 stash engaged for a subset of columns".into());
7127 }
7128 if prof {
7129 e.stream().synchronize()?;
7130 prof_ms[1] += seg.elapsed().as_secs_f64() * 1e3;
7131 seg = std::time::Instant::now();
7132 }
7133 if !fa2_deferred.is_empty() {
7134 deferred = fa2_deferred;
7135 }
7136 if !deferred.is_empty() {
7137 let mixed_t = if fa2_layer {
7138 self.step35_verify_fa_rows_join(e, il, cache, pos0, t)?
7139 } else {
7140 self.step35_verify_oproj_tcol(e, il, t)?
7141 };
7142 let o_out = mixed_t.len() / t;
7143 if spec_nan_scan_level() >= 2 {
7144 nan_scan_rows(
7145 e,
7146 &mixed_t,
7147 t,
7148 o_out,
7149 &format!("tcol layer {il} JOINED attn over deferred cols"),
7150 )?;
7151 }
7152 // Batched t=2 residual+MoE: one t-grid add_rms_norm (per-row
7153 // program == t=1; bit-identical to the oproj-tail join per the
7154 // M2 verbatim-program contract) feeding the two-column routed
7155 // sweep. Ineligible layers (dense FFN, non-nvfp4) fall through
7156 // to the per-column body.
7157 {
7158 for &r in &deferred {
7159 e.dtod_copy_view(
7160 &mixed_t.slice(r * o_out..(r + 1) * o_out),
7161 &mut mixed_row,
7162 )?;
7163 ffn_col(r, &mixed_row, &mut next)?;
7164 }
7165 }
7166 }
7167 if prof {
7168 e.stream().synchronize()?;
7169 prof_ms[2] += seg.elapsed().as_secs_f64() * 1e3;
7170 }
7171 x_t = next;
7172 if spec_nan_scan() {
7173 verify_arm_receipt(
7174 if fa2_layer { "join" } else { "percol" },
7175 il,
7176 pos0,
7177 t,
7178 cache.tp_kv[il].as_ref().map(|d| d.staged_len()),
7179 );
7180 nan_scan_rows(
7181 e,
7182 &x_t,
7183 t,
7184 n_embd,
7185 &format!(
7186 "tcol layer {il} pos0={pos0} arm={}",
7187 if fa2_layer { "join" } else { "percol" }
7188 ),
7189 )?;
7190 }
7191 }
7192 if prof {
7193 eprintln!(
7194 "[tcol-prof] t={t} norm+qkv={:.3}ms attn={:.3}ms ffn={:.3}ms",
7195 prof_ms[0], prof_ms[1], prof_ms[2]
7196 );
7197 }
7198 if ok {
7199 return Ok(x_t);
7200 }
7201 // fall through to the row-outer walk on ineligible layers
7202 x = x_t;
7203 }
7204 let mut next = e.uninit(t * n_embd)?;
7205 let scan = spec_nan_scan();
7206 for r in 0..t {
7207 let mut row = e.uninit(n_embd)?;
7208 e.dtod_copy_view(&x.slice(r * n_embd..(r + 1) * n_embd), &mut row)?;
7209 let row_pos = e.htod_i32(&[(pos0 + r) as i32])?;
7210 let out = if scan {
7211 // Diagnostic arm: the same range walked one layer at a time so the first
7212 // poisoned layer names itself. `decode_layers_eager(lo, hi)` is range-scoped
7213 // and executes its trailing residual add, so a per-layer chain is the same
7214 // program with the cross-layer add+norm fusion unrolled.
7215 nan_scan_rows(
7216 e,
7217 &row,
7218 1,
7219 n_embd,
7220 &format!("embed row r={r} pos={}", pos0 + r),
7221 )?;
7222 let mut acc = row;
7223 for il in lo..hi {
7224 acc = self.decode_layers_eager(
7225 e,
7226 acc,
7227 il,
7228 il + 1,
7229 &row_pos,
7230 pos0 + r,
7231 cache,
7232 )?;
7233 nan_scan_rows(
7234 e,
7235 &acc,
7236 1,
7237 n_embd,
7238 &format!("row-outer layer {il} r={r} pos={}", pos0 + r),
7239 )?;
7240 }
7241 acc
7242 } else {
7243 self.decode_layers_eager(e, row, lo, hi, &row_pos, pos0 + r, cache)?
7244 };
7245 e.dtod_copy_into(&out, &mut next, r * n_embd)?;
7246 }
7247 // dflash taps are NOT produced on this arm (they need per-layer hiddens the
7248 // row-outer walk does not materialize); the door is a step37 MTP bring-up
7249 // surface where taps are unused.
7250 return Ok(next);
7251 }
7252 let mut ph_last = std::time::Instant::now();
7253 for il in lo..hi {
7254 let mut next = e.uninit(t * n_embd)?;
7255 for r in 0..t {
7256 let mut row = e.uninit(n_embd)?;
7257 e.dtod_copy_view(&x.slice(r * n_embd..(r + 1) * n_embd), &mut row)?;
7258 // The caller owns this verify's position. During controller overlap, cache.pos
7259 // still describes generation N while this stage-0 walk belongs to N+1.
7260 let row_pos = e.htod_i32(&[(pos0 + r) as i32])?;
7261 let mut one = [&mut *cache];
7262 let out = self.step35_decode_batch_layers(
7263 e,
7264 row,
7265 &mut one,
7266 &[(pos0 + r) as i32],
7267 &row_pos,
7268 il,
7269 il + 1,
7270 &mut ph_last,
7271 )?;
7272 e.dtod_copy_into(&out, &mut next, r * n_embd)?;
7273 }
7274 self.dflash_tap(e, cache, il, &next, t)?;
7275 x = next;
7276 if spec_nan_scan() {
7277 nan_scan_rows(e, &x, t, n_embd, &format!("batch-layer {il} pos0={pos0}"))?;
7278 }
7279 }
7280 Ok(x)
7281 }
7282
7283 /// DSpark drafter verify (lane/dspark-q38-recover): one t-row forward through the
7284 /// SERVING-CLASS verify funnel (`decode_step_t_core_stream` — the same numeric class
7285 /// MTP verify rides, GDN state advanced in place), returning per-row argmax tokens.
7286 /// Advances `cache.pos += t`; the caller owns snapshot/rollback (block acceptance is
7287 /// prefix-keep, not all-or-nothing).
7288 pub(crate) fn dspark_verify_t_am(
7289 &self,
7290 e: &Engine,
7291 tokens: &[u32],
7292 pos0: usize,
7293 cache: &mut Cache,
7294 ) -> Result<Vec<u32>, Box<dyn std::error::Error>> {
7295 let (logits, _hn) = self.decode_step_t_core_stream(
7296 e, tokens, pos0, cache, None, None, None, None, None, None,
7297 )?;
7298 let t = tokens.len();
7299 let v = self.output.out_features();
7300 let mut am_d = e.stream().alloc_zeros::<u32>(t)?;
7301 for r in 0..t {
7302 e.argmax_token_device_col(&logits, r, v, &mut am_d, r)?;
7303 }
7304 e.dtoh_u32(&am_d)
7305 }
7306
7307 /// DSpark verify returning the RAW verify logits [t, n_vocab] (device-resident) instead
7308 /// of per-row argmaxes — the sampled-admission arm's input (rejection-sampling accept
7309 /// gathers filtered p from these columns; lane/dspark-sampled-admission-20260820). Same
7310 /// forward as `dspark_verify_t_am`; the greedy arm keeps its argmax wrapper untouched.
7311 pub(crate) fn dspark_verify_t_logits(
7312 &self,
7313 e: &Engine,
7314 tokens: &[u32],
7315 pos0: usize,
7316 cache: &mut Cache,
7317 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
7318 let (logits, _hn) = self.decode_step_t_core_stream(
7319 e, tokens, pos0, cache, None, None, None, None, None, None,
7320 )?;
7321 Ok(logits)
7322 }
7323
7324 /// DSpark verify with the MTP column-stash armed: identical forward to
7325 /// `dspark_verify_t_am`, but fills a `VerifyCkpt` so a partial accept can restore
7326 /// column state directly (`dspark_commit_prefix`) instead of snapshot-replay.
7327 /// The ckpt type is opaque outside spec.rs (newtype) — dflash.rs threads it through.
7328 pub(crate) fn dspark_verify_t_am_ckpt(
7329 &self,
7330 e: &Engine,
7331 tokens: &[u32],
7332 pos0: usize,
7333 cache: &mut Cache,
7334 ) -> Result<(Vec<u32>, DsparkVerifyCkpt), Box<dyn std::error::Error>> {
7335 let mut ck = VerifyCkpt::new(self.layers.len());
7336 let (logits, _hn) = self.decode_step_t_core_stream(
7337 e,
7338 tokens,
7339 pos0,
7340 cache,
7341 None,
7342 Some(&mut ck),
7343 None,
7344 None,
7345 None,
7346 None,
7347 )?;
7348 let t = tokens.len();
7349 let v = self.output.out_features();
7350 let mut am_d = e.stream().alloc_zeros::<u32>(t)?;
7351 for r in 0..t {
7352 e.argmax_token_device_col(&logits, r, v, &mut am_d, r)?;
7353 }
7354 Ok((e.dtoh_u32(&am_d)?, DsparkVerifyCkpt(ck)))
7355 }
7356
7357 /// Engine-bundle slice 2: `dspark_verify_t_am_ckpt` with DEVICE tokens and NO readback.
7358 /// The verify tokens are the round's `chain_d` (cand layout: [anchor, drafts...]); the
7359 /// embed gathers its first `t` entries on-device (`embed_gather_u32_t` — bit-identical
7360 /// rows to the host arm), so the host never blocks on the draft chain before dispatching
7361 /// verify. Returns the device per-row argmax buffer; the caller merges its readback with
7362 /// the chain's into ONE sync. Forward, ckpt fill and argmax walk are `_ckpt` verbatim.
7363 #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
7364 pub(crate) fn dspark_verify_t_am_ckpt_dev(
7365 &self,
7366 e: &Engine,
7367 vtok: &CudaSlice<u32>,
7368 t: usize,
7369 pos0: usize,
7370 cache: &mut Cache,
7371 embd_dev: (&CudaSlice<u8>, i32, usize),
7372 graphs: Option<&mut DsparkVerifyGraphs>,
7373 ) -> Result<(CudaSlice<u32>, DsparkVerifyCkpt), Box<dyn std::error::Error>> {
7374 debug_assert!(
7375 vtok.len() >= t,
7376 "verify window exceeds the device token buffer"
7377 );
7378 // The slab flag is a per-round statement: clear it here so a verify that never
7379 // reaches the graphs door (rowwise env, a non-tparallel arm) cannot leave a
7380 // stale `true` steering the commit at slabs the round never wrote.
7381 let mut graphs = graphs;
7382 if let Some(g) = graphs.as_deref_mut() {
7383 g.round_slab = false;
7384 }
7385 let mut ck = VerifyCkpt::new(self.layers.len());
7386 // Dummy host tokens size the funnel; the embed reads `vtok` (the round-stream
7387 // arm's established pattern — spec.rs stream-mode verify does the same).
7388 let dummy = vec![0u32; t];
7389 let (logits, _hn) = self.decode_step_t_core_stream(
7390 e,
7391 &dummy,
7392 pos0,
7393 cache,
7394 Some(embd_dev),
7395 Some(&mut ck),
7396 None,
7397 None,
7398 Some(vtok),
7399 graphs,
7400 )?;
7401 let v = self.output.out_features();
7402 let mut am_d = e.stream().alloc_zeros::<u32>(t)?;
7403 for r in 0..t {
7404 e.argmax_token_device_col(&logits, r, v, &mut am_d, r)?;
7405 }
7406 Ok((am_d, DsparkVerifyCkpt(ck)))
7407 }
7408
7409 /// Ckpt-armed twin of [`Self::dspark_verify_t_logits`] (sampled-admission arm).
7410 pub(crate) fn dspark_verify_t_logits_ckpt(
7411 &self,
7412 e: &Engine,
7413 tokens: &[u32],
7414 pos0: usize,
7415 cache: &mut Cache,
7416 ) -> Result<(CudaSlice<f32>, DsparkVerifyCkpt), Box<dyn std::error::Error>> {
7417 let mut ck = VerifyCkpt::new(self.layers.len());
7418 let (logits, _hn) = self.decode_step_t_core_stream(
7419 e,
7420 tokens,
7421 pos0,
7422 cache,
7423 None,
7424 Some(&mut ck),
7425 None,
7426 None,
7427 None,
7428 None,
7429 )?;
7430 Ok((logits, DsparkVerifyCkpt(ck)))
7431 }
7432
7433 /// Restore the round to `keep` accepted columns from the verify stash: KV lens and
7434 /// pos from the pre-verify snapshot + keep, GDN conv/ssm from the stashed column
7435 /// state — no replay forward. The exact `commit_verified_prefix` the MTP path ships.
7436 pub(crate) fn dspark_commit_prefix(
7437 &self,
7438 e: &Engine,
7439 cache: &mut Cache,
7440 snap: &crate::cache::CacheSnapshot,
7441 ckpt: &DsparkVerifyCkpt,
7442 keep: usize,
7443 ) -> Result<(), Box<dyn std::error::Error>> {
7444 self.commit_verified_prefix(e, cache, snap, &ckpt.0, keep, false, None)
7445 }
7446
7447 /// Slice-3 commit twin: restore to `keep` accepted columns when the round's linear
7448 /// column stash lives in the graphs ctx's persistent slabs (`DsparkVerifyGraphs`) —
7449 /// the cols arm's exact semantics (KV lens + pos from the snapshot, GDN conv/ssm
7450 /// from the stash of column keep-1), slab-addressed and batched into two copy
7451 /// launches. `MEMRA_STATE_COPY_BATCH=0` falls back to per-layer view copies.
7452 pub(crate) fn dspark_commit_prefix_slab(
7453 &self,
7454 e: &Engine,
7455 cache: &mut Cache,
7456 snap: &crate::cache::CacheSnapshot,
7457 ctx: &DsparkVerifyGraphs,
7458 keep: usize,
7459 ) -> Result<(), Box<dyn std::error::Error>> {
7460 use cudarc::driver::DevicePtr;
7461 debug_assert!(keep >= 1, "keep==0 rounds take the legacy rollback");
7462 let mut conv_src: Vec<u64> = Vec::new();
7463 let mut ssm_src: Vec<u64> = Vec::new();
7464 let mut conv_dst: Vec<u64> = Vec::new();
7465 let mut ssm_dst: Vec<u64> = Vec::new();
7466 for il in 0..self.layers.len() {
7467 if let (Some(kvl), Some(saved)) = (cache.kv[il].as_mut(), snap.kv_len[il]) {
7468 kvl.len = saved + keep;
7469 e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
7470 }
7471 if let Some(rl) = cache.recur[il].as_ref() {
7472 let (pc, ps, _cw, _sw) = ctx
7473 .slab_row(e, il, keep - 1)
7474 .ok_or("slab commit: linear layer missing from the graphs ctx")?;
7475 conv_src.push(pc);
7476 ssm_src.push(ps);
7477 let st = &e.gpu.stream();
7478 let (dc, _g0) = rl.conv_state.device_ptr(st);
7479 let (ds, _g1) = rl.ssm_state.device_ptr(st);
7480 conv_dst.push(dc);
7481 ssm_dst.push(ds);
7482 }
7483 }
7484 let n = conv_src.len();
7485 if n > 0 {
7486 if state_copy_batch_on() {
7487 let mut tt = vec![0u64; 2 * n];
7488 tt[..n].copy_from_slice(&conv_src);
7489 tt[n..].copy_from_slice(&conv_dst);
7490 let ct = e.htod_u64(&tt)?;
7491 tt[..n].copy_from_slice(&ssm_src);
7492 tt[n..].copy_from_slice(&ssm_dst);
7493 let st = e.htod_u64(&tt)?;
7494 e.copy_batch_uniform_f32(&ct, n, ctx.conv_words)?;
7495 e.copy_batch_uniform_f32(&st, n, ctx.ssm_words)?;
7496 } else {
7497 let (cw, sw) = (ctx.conv_words, ctx.ssm_words);
7498 let row = keep - 1;
7499 for il in 0..self.layers.len() {
7500 let Some(rl) = cache.recur[il].as_mut() else {
7501 continue;
7502 };
7503 let k = ctx.lin_pos[&il];
7504 {
7505 let sv = e.view(&ctx.stash_conv[k], (row + 1) * cw);
7506 let win = sv.slice(row * cw..(row + 1) * cw);
7507 e.copy_view_into(&mut rl.conv_state, 0, &win, cw)?;
7508 }
7509 {
7510 let sv = e.view(&ctx.stash_ssm[k], (row + 1) * sw);
7511 let win = sv.slice(row * sw..(row + 1) * sw);
7512 e.copy_view_into(&mut rl.ssm_state, 0, &win, sw)?;
7513 }
7514 }
7515 }
7516 }
7517 cache.pos = snap.pos + keep;
7518 Ok(())
7519 }
7520
7521 /// Qwen35-family verify trunk in the live serving numeric class.
7522 ///
7523 /// Serving intentionally keeps this architecture in the generic batched program even at
7524 /// B=1. The older verify walk used its own mirrored dispatch and can flip near-tie argmaxes.
7525 ///
7526 /// Two arms, one numeric class:
7527 /// - DENSE GDN (`DenseMlp`, t<=16): `qwen35_verify_tparallel` — the weight ops (norms,
7528 /// projections, FFN) hoist to m=T through the exact-tier batched kernels whose per-row
7529 /// program IS the m=1 program (`matmul_pre == fused2 per (tensor,row); _bN mmvq per-row
7530 /// == m=1` — decode_batch.rs v2 note), while the state ops (conv ring, gdn scan, KV
7531 /// append, fa decode) stay a per-row loop running the b_n=1 serving kernels with each
7532 /// row's own t_kv-driven arm pick (the straddle law: every row executes the exact
7533 /// program its isolated serving step would). One weight read per layer per round
7534 /// instead of T — this is what makes MTP profitable in the exact class (the per-row
7535 /// walk measured verify(K+1) ~= (K+1) plain steps: 69 -> 44 tok/s served, 2026-08-15).
7536 /// - MoE / t>16 / `MEMRA_SPEC_VERIFY_ROWWISE=1`: the per-row replay of the authoritative
7537 /// serving layer body, preserving single-session autoregressive cache order (the
7538 /// correctness reference; also the rollback seam for the t-parallel arm).
7539 ///
7540 /// Bit-identity of the t-parallel arm vs the rowwise arm is gated by spec-serve-gate
7541 /// (zero differing logits at T=1..4, K arms) + the 8-prompt ON/OFF canary before ship.
7542 #[allow(clippy::too_many_arguments)]
7543 fn qwen35_verify_batch_layers(
7544 &self,
7545 e: &Engine,
7546 x: CudaSlice<f32>,
7547 lo: usize,
7548 hi: usize,
7549 pos0: usize,
7550 t: usize,
7551 cache: &mut Cache,
7552 ckpt: Option<&mut VerifyCkpt>,
7553 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
7554 graphs: Option<&mut DsparkVerifyGraphs>,
7555 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
7556 // Qwen35Moe admitted 2026-08-20 (lane/draftcost-moe): the t-parallel arm already
7557 // carries the MoE FFN (`moe_ffn_il_zq8` at m=T) and the GDN per-row state loop; the
7558 // arch fence was a qualification gate, not a mechanism gap. Measured disease on the
7559 // 35B-A3B class: rowwise verify ~= 5.6 ms per drafted token (one full trunk step
7560 // each) — the same (K+1)-plain-steps wall the dense admission fixed on 2026-08-15.
7561 // Rollback seam unchanged: MEMRA_SPEC_VERIFY_ROWWISE=1.
7562 let rowwise = std::env::var("MEMRA_SPEC_VERIFY_ROWWISE").as_deref() == Ok("1")
7563 || !self.batched_serving_numeric_class()
7564 || t > 16;
7565 if rowwise {
7566 if stream.is_some() {
7567 // rowwise replays per row with host cache.pos — irreconcilable with a
7568 // device position counter. Burst callers must keep t <= 16 and the
7569 // ROWWISE env unset; refusing beats silently mispositioned rows.
7570 return Err("qwen35 rowwise verify has no ROUND-STREAM arm \
7571 (t > 16 or MEMRA_SPEC_VERIFY_ROWWISE=1)"
7572 .into());
7573 }
7574 self.qwen35_verify_rowwise(e, x, lo, hi, pos0, t, cache, ckpt)
7575 } else {
7576 self.qwen35_verify_tparallel(e, x, lo, hi, pos0, t, cache, ckpt, stream, graphs)
7577 }
7578 }
7579
7580 /// The per-row correctness reference: replay each verify row through the authoritative
7581 /// serving layer body (`decode_batch_layers` at b_n=1). T full weight reads per layer.
7582 #[allow(clippy::too_many_arguments)]
7583 fn qwen35_verify_rowwise(
7584 &self,
7585 e: &Engine,
7586 mut x: CudaSlice<f32>,
7587 lo: usize,
7588 hi: usize,
7589 pos0: usize,
7590 t: usize,
7591 cache: &mut Cache,
7592 mut ckpt: Option<&mut VerifyCkpt>,
7593 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
7594 let n_embd = self.cfg.n_embd as usize;
7595 let saved_pos = cache.pos;
7596 let mut ph_last = std::time::Instant::now();
7597 for il in lo..hi {
7598 let mut next = e.uninit(t * n_embd)?;
7599 let mut col_states: Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>> =
7600 if ckpt.is_some() && t >= 2 && matches!(self.layers[il].mixer, Mixer::Linear(_)) {
7601 Some(Vec::with_capacity(t - 1))
7602 } else {
7603 None
7604 };
7605 for r in 0..t {
7606 cache.pos = pos0 + r;
7607 let mut row = e.uninit(n_embd)?;
7608 e.dtod_copy_view(&x.slice(r * n_embd..(r + 1) * n_embd), &mut row)?;
7609 let row_pos = e.htod_i32(&[(pos0 + r) as i32])?;
7610 let mut one = [&mut *cache];
7611 let ctx = self.batch_layer_ctx(e, &one, il, il + 1)?;
7612 let out = match self.decode_batch_layers(
7613 e,
7614 row,
7615 &mut one,
7616 &ctx,
7617 &row_pos,
7618 &mut ph_last,
7619 ) {
7620 Ok(out) => out,
7621 Err(error) => {
7622 cache.pos = saved_pos;
7623 return Err(error);
7624 }
7625 };
7626 e.dtod_copy_into(&out, &mut next, r * n_embd)?;
7627 if r + 1 < t
7628 && let Some(states) = col_states.as_mut()
7629 {
7630 let recur = cache.recur[il]
7631 .as_ref()
7632 .ok_or("Qwen35-MoE linear verify layer has no recurrent state")?;
7633 states.push((
7634 e.clone_dtod(&recur.conv_state)?,
7635 e.clone_dtod(&recur.ssm_state)?,
7636 ));
7637 }
7638 }
7639 if let (Some(checkpoint), Some(states)) = (ckpt.as_deref_mut(), col_states) {
7640 checkpoint.cols[il] = Some(states);
7641 }
7642 x = next;
7643 }
7644 cache.pos = saved_pos;
7645 Ok(x)
7646 }
7647
7648 /// T-PARALLEL VERIFY IN THE SERVING NUMERIC CLASS (lane/tparallel-verify, 2026-08-15).
7649 ///
7650 /// The weight ops run ONCE per layer at m=T; the state ops run per row through the same
7651 /// b_n=1 serving kernels the rowwise replay uses. Per-row bit-identity rests on the two
7652 /// pins the serving batch tier already carries:
7653 /// * `matmul_pre` / `_bN` mmvq: per-row program == m=1 program (decode_batch.rs v2 note,
7654 /// kernel-check pinned) — so a [T, n_embd] projection row equals the row projected
7655 /// alone;
7656 /// * row-indexed norms/elementwise (`rms_norm`, `quantize_q8_1`, `add_rms_norm`,
7657 /// `gated_rmsnorm[_q8_1]`, `silu_mul`, `rope_neox` with per-row positions): the T-row
7658 /// launch is the per-row program (same pin the generic verify's fused norms rely on).
7659 /// The sequential dependencies keep their exact serving order: the conv ring / gdn scan
7660 /// chain state row -> row through the `_b` kernels at b_n=1 (ping-pong via a 6-entry
7661 /// alternating pointer table, host handles swapped per row so VerifyCkpt clones the
7662 /// canonical state exactly as the rowwise arm does), and each row's KV append + fa decode
7663 /// picks its arm from ITS OWN t_kv (append: format-only; fa: `fa_seqs_eligible` + its own
7664 /// `fa_split_keys` rung at b_n=1) — the straddle law per row, so every row executes the
7665 /// program its isolated B=1 serving step would.
7666 ///
7667 /// Cost: 1 weight read per layer per round + T state micro-launches, vs the rowwise arm's
7668 /// T weight reads. Gated bit-identical vs the rowwise arm by spec-serve-gate + canary.
7669 #[allow(clippy::too_many_arguments)]
7670 fn qwen35_verify_tparallel(
7671 &self,
7672 e: &Engine,
7673 mut x: CudaSlice<f32>,
7674 lo: usize,
7675 hi: usize,
7676 pos0: usize,
7677 t: usize,
7678 cache: &mut Cache,
7679 mut ckpt: Option<&mut VerifyCkpt>,
7680 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
7681 mut graphs: Option<&mut DsparkVerifyGraphs>,
7682 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
7683 let seqs_append =
7684 std::env::var("MEMRA_BATCH_APPEND").as_deref() != Ok("0") && !Engine::kv_fp8_on();
7685 let batch_fa_on = std::env::var("MEMRA_BATCH_FA").as_deref() != Ok("0");
7686
7687 // Merge guard (v0.98 train, re-affirmed on the v0.100 train over slice 4c): the
7688 // ROUND-STREAM arm (lane/draftcost-moe, device position counter) and the dspark
7689 // verify graphs (engine-bundle slice 3 / trunk slice 4c) have no common caller —
7690 // stream rides the qwen35moe burst, graphs ride the dspark route. If a future
7691 // caller arms both, refuse loudly instead of silently dropping the graphs ctx
7692 // (the stream linear arm takes linear_attn_verify_t, not the graphed segment or
7693 // full-verify bodies).
7694 if stream.is_some() && graphs.is_some() {
7695 return Err(
7696 "qwen35 tparallel verify: ROUND-STREAM and dspark verify graphs \
7697 cannot arm together"
7698 .into(),
7699 );
7700 }
7701 // Engine-bundle slice 3 + slice 4c: with a graphs ctx armed, pointer tables are
7702 // refreshed once per verify (the gdn ping-pong moves handles; a fresh generation
7703 // moves the kv caches). Then:
7704 // - slice 4c: when the WHOLE round rides one seqs rung (every row batchable, one
7705 // split-ladder step, rung covers the round), the ENTIRE walk replays as ONE
7706 // full-verify graph per (vt, rung) — linear layers through the shared
7707 // `qwen35_tparallel_linear_layer` body, full-attention layers through the
7708 // shared `qwen35_tparallel_fa_layer` body in graph mode.
7709 // - fallback (straddle rounds, below the vec floor, partial walks): runs of
7710 // consecutive LINEAR layers replay the slice-3 per-(segment, vt) graphs and
7711 // the full-attention layers run eager (batched rows when eligible).
7712 //
7713 // GRAPH-LAUNCH HEADROOM GUARD (see GRAPH_LAUNCH_MIN_FREE): the dspark verify
7714 // graphs replay through this walk from THREE callers — the MTP spec round's vg
7715 // door (already dropped per round by `graph_round_ok` before it gets here), the
7716 // dspark one-shot, and the dspark SERVE round (default ON since v0.108). Below
7717 // the driver-free floor the WHOLE round takes the byte-identical eager
7718 // cols-ckpt walk — the same drop-the-ctx fallback the pool ceiling already
7719 // takes — instead of feeding cuGraphLaunch a card it segfaults on.
7720 if let Some(g) = graphs.as_deref_mut()
7721 && !graph_launch_headroom_ok(e)
7722 {
7723 g.round_slab = false;
7724 graphs = None;
7725 static NOTED: std::sync::Once = std::sync::Once::new();
7726 NOTED.call_once(|| graph_replay_suspended_note("dspark-vg"));
7727 }
7728 if let Some(g) = graphs.as_deref_mut() {
7729 g.refresh_tables(e, cache)?;
7730 g.round_slab = false;
7731 if let Some(rung) = g.full_rung(self, cache, lo, hi, t, seqs_append && batch_fa_on) {
7732 // Pool ceiling (dspark_vg_cap): an existing key always replays; a NEW
7733 // full capture past the ceiling falls through to the segment/eager arms.
7734 if g.full.contains_key(&(t, rung, hi)) || g.can_capture() {
7735 let out = g.run_full(self, e, lo, hi, &x, t, pos0, rung, cache)?;
7736 g.round_slab = true;
7737 return Ok(out);
7738 }
7739 }
7740 // Round-atomic ceiling check for the segment door: if any linear run in this
7741 // walk would need a NEW capture past the ceiling, the whole round runs the
7742 // eager cols-ckpt walk (mixing slab- and cols-stashed layers in one round
7743 // would corrupt the commit).
7744 if !g.segments_ready(self, lo, hi, t) {
7745 graphs = None;
7746 }
7747 }
7748 // STREAM (2b, lane/draftcost-moe): positions come from the device round counter
7749 // (pos_iota / i32_copy_add) so a burst round needs no host position knowledge.
7750 let pos_d = match stream {
7751 Some((_, ctr)) => {
7752 let mut p = e.alloc_uninit::<i32>(t)?;
7753 e.pos_iota(ctr, &mut p, t)?;
7754 p
7755 }
7756 None => {
7757 let pos_host: Vec<i32> = (0..t).map(|r| (pos0 + r) as i32).collect();
7758 e.htod_i32(&pos_host)?
7759 }
7760 };
7761 // Per-row 1-element position buffers, built ONCE per verify (the append/fa wrappers
7762 // take owned pos slices; building these inside the layer x row loops cost 16xT H2Ds).
7763 // LAZY since slice 4: the batched fa/append arm never touches them — they are built
7764 // on the first per-row fallback layer only (stream-aware there; the stream FA arm
7765 // rides the dc rows kernels and never reaches the fallback).
7766 let mut pos_rows: Option<Vec<CudaSlice<i32>>> = None;
7767 let mut il = lo;
7768 while il < hi {
7769 if graphs.is_some() && matches!(self.layers[il].mixer, Mixer::Linear(_)) {
7770 let mut end = il;
7771 while end < hi && matches!(self.layers[end].mixer, Mixer::Linear(_)) {
7772 end += 1;
7773 }
7774 let g = graphs.as_deref_mut().expect("checked above");
7775 x = g.run_segment(self, e, il, end, &x, t, cache)?;
7776 g.round_slab = true;
7777 il = end;
7778 continue;
7779 }
7780 let layer = &self.layers[il];
7781 if stream.is_none() && matches!(layer.mixer, Mixer::Linear(_)) {
7782 // Eager linear layer (no graphs ctx): the shared body, legacy cols-ckpt arm.
7783 // Under ROUND-STREAM the linear layers ride the fa-body match's stream arm
7784 // below (linear_attn_verify_t — the stream COMMIT needs its GdnStash).
7785 x = self.qwen35_tparallel_linear_layer(
7786 e,
7787 il,
7788 &x,
7789 t,
7790 cache,
7791 ckpt.as_deref_mut(),
7792 None,
7793 None,
7794 )?;
7795 il += 1;
7796 continue;
7797 }
7798 // Full-attention (or stream-Linear, or MLA-refusing) layer: the extracted
7799 // shared body — eager arm (fresh per-verify pos/table, exact t_kv sizing,
7800 // in-body len bump). The slice-4c captured full-verify graphs run the SAME
7801 // body in graph mode; under ROUND-STREAM the body's dc-rows / GDN stream arms
7802 // run (lane/draftcost-moe).
7803 x = self.qwen35_tparallel_fa_layer(
7804 e,
7805 il,
7806 &x,
7807 t,
7808 cache,
7809 FaLayerArgs {
7810 pos_d: &pos_d,
7811 pos_rows: &mut pos_rows,
7812 pos0,
7813 seqs_append,
7814 batch_fa_on,
7815 graph_cap: None,
7816 stream,
7817 ckpt: ckpt.as_deref_mut(),
7818 },
7819 )?;
7820 il += 1;
7821 }
7822 Ok(x)
7823 }
7824
7825 /// SHARED dense-FFN body for the qwen35 t-parallel layers (trunk-kernels slice B) —
7826 /// ONE copy for the fa and linear layer bodies (the verify_layers extraction lesson).
7827 /// Dual arm (MEMRA_TK_FFN_DUAL, default on): gate+up in ONE dual launch from the
7828 /// pre-quantized activation with macro-scales DEFERRED into the fused SwiGLU+q8_1
7829 /// epilogue, then ffn_down from the fused (aq, ad) — the q27 verify chain verbatim.
7830 /// Every door is the bit-identical proven one: `matmul_decode_exact_dual_pre` (per
7831 /// (tensor,token,row) == the two singles), `silu_mul_scaled_q8_1` (y*s inline == the
7832 /// scale_inplace store, value-exact; fused quantize == quantize_q8_1 bytes),
7833 /// `matmul_decode_exact_pre` (dispatch mirror of the singles' q8_1-fast tail).
7834 /// Dual-refused (t outside 2..=7, non-NVFP4, layout mismatch) or seam off -> the
7835 /// original singles chain, byte-for-byte.
7836 #[allow(clippy::too_many_arguments)]
7837 fn qwen35_tparallel_dense_ffn(
7838 &self,
7839 e: &Engine,
7840 ffn_gate: &crate::model::GpuTensor,
7841 ffn_up: &crate::model::GpuTensor,
7842 ffn_down: &crate::model::GpuTensor,
7843 zn: &CudaSlice<f32>,
7844 t: usize,
7845 n_embd: usize,
7846 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
7847 let n_ff = ffn_gate.out_features();
7848 let (zq, zd) = e.quantize_q8_1(zn, t, n_embd)?;
7849 if Engine::tk_ffn_dual_on()
7850 && let Some(((g, gs), (u, us))) =
7851 e.matmul_decode_exact_dual_pre(ffn_gate, ffn_up, &zq, &zd, t)?
7852 {
7853 if e.uses_q8_1_fast(ffn_down) {
7854 let (aq, ad) = e.silu_mul_scaled_q8_1(&g, &u, gs, us, t * n_ff)?;
7855 return e.matmul_decode_exact_pre(ffn_down, &aq, &ad, t);
7856 }
7857 let mut act = e.uninit(t * n_ff)?;
7858 e.silu_mul_scaled(&g, &u, gs, us, &mut act, t * n_ff)?;
7859 let (aq, ad) = e.quantize_q8_1(&act, t, n_ff)?;
7860 return e.matmul_pre(ffn_down, &aq, &ad, &act, t);
7861 }
7862 // v1 singles chain (seam off or dual-refused) — the pre-slice-B body verbatim.
7863 let g = e.matmul_pre(ffn_gate, &zq, &zd, zn, t)?;
7864 let u = e.matmul_pre(ffn_up, &zq, &zd, zn, t)?;
7865 let mut act = e.uninit(t * n_ff)?;
7866 e.silu_mul(&g, &u, &mut act, t * n_ff)?;
7867 let (aq, ad) = e.quantize_q8_1(&act, t, n_ff)?;
7868 e.matmul_pre(ffn_down, &aq, &ad, &act, t)
7869 }
7870
7871 /// ONE t-parallel FULL-ATTENTION layer (attn_norm + fa mixer + post_attn_norm + FFN +
7872 /// tap) — extracted from the walk exactly like `qwen35_tparallel_linear_layer` so the
7873 /// eager walk and the slice-4c captured full-verify graphs execute the SAME body (a
7874 /// second copy is how dispatch mirrors drift — the verify_layers extraction lesson).
7875 ///
7876 /// `args.graph_cap = Some((table, off, rung_end))` is the captured-graph mode:
7877 /// - kv base-pointer pairs come from the ctx-owned persistent table at `off` (a fresh
7878 /// generation's cache lands at new addresses that only the per-verify table refresh
7879 /// knows — the slice-3 baked-address lesson);
7880 /// - the seqs twins size partials/grid at `rung_end` and pin `split_keys` to the
7881 /// rung's ladder value: `n_splits_max` is pure stride, splits >= ns_eff write the
7882 /// EMPTY partial the combine never reads, and every per-row T_kv derives in-kernel
7883 /// from `pos_seq[z]` — so one captured launch replays bit-identically for every
7884 /// round whose rows all sit inside the rung;
7885 /// - the host len bump moves to the replay caller (captured host code does not
7886 /// re-run at replay).
7887 /// Graph mode REFUSES any round the batched arm cannot take: the per-row fallback
7888 /// host-branches on t_kv and must never be captured.
7889 #[allow(clippy::too_many_arguments)]
7890 fn qwen35_tparallel_fa_layer(
7891 &self,
7892 e: &Engine,
7893 il: usize,
7894 x: &CudaSlice<f32>,
7895 t: usize,
7896 cache: &mut Cache,
7897 args: FaLayerArgs<'_>,
7898 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
7899 use cudarc::driver::DevicePtr;
7900 let cfg = &self.cfg;
7901 let n_embd = cfg.n_embd as usize;
7902 let eps = cfg.rms_eps;
7903 let head_dim_global = cfg.head_dim_k as usize;
7904 let layer = &self.layers[il];
7905 let FaLayerArgs {
7906 pos_d,
7907 pos_rows,
7908 pos0,
7909 seqs_append,
7910 batch_fa_on,
7911 graph_cap,
7912 stream,
7913 ckpt,
7914 } = args;
7915
7916 // ---- attn_norm + q8_1 quantize at m=T (row-indexed == per-row) ----
7917 let anorm = layer.attn_norm.float_data();
7918 let mut xn = e.uninit(t * n_embd)?;
7919 e.rms_norm(x, anorm, &mut xn, n_embd, t, eps)?;
7920 let (hq, hd) = e.quantize_q8_1(&xn, t, n_embd)?;
7921
7922 let mixed: CudaSlice<f32> = match &layer.mixer {
7923 Mixer::Mla(_) => crate::hybrid::mla_path_unimplemented("tensor-parallel attention"),
7924 Mixer::Kda(_) => crate::hybrid::kda_path_unimplemented("T-parallel attention"),
7925 // STREAM ARM (2b, lane/draftcost-moe): under a device position counter the
7926 // per-row serving-kernel chain cannot run (host state swaps keyed on host
7927 // row index are fine, but the stream COMMIT needs the GdnStash for its _dc
7928 // rebuild — the per-row chain only produces per-column clones). GDN rides
7929 // `linear_attn_verify_t`: batched q8_1-class projections, stash-producing,
7930 // and its one-scan recurrence is pinned bit-identical to T chained T=1
7931 // steps (its header + kernel-check). Position-independent, so no counter
7932 // plumbing is needed. Guards mirror the generic call site exactly.
7933 Mixer::Linear(la) if stream.is_some() => {
7934 if !(t >= 3 || (t == 2 && spec_m2()))
7935 || !self.mixer_in_q8_1_fast(e, &layer.mixer)
7936 || !e.uses_q8_1_fast(&la.ssm_out)
7937 {
7938 return Err("qwen35 stream verify: GDN batched arm requires t>=3 \
7939 (or MEMRA_SPEC_M2 at t=2) and q8_1-fast projections"
7940 .into());
7941 }
7942 let want = ckpt.is_some();
7943 let (out, stash) =
7944 self.linear_attn_verify_t(e, la, &xn, Some((&hq, &hd)), t, cache, il, want)?;
7945 if let (Some(ck), Some(st)) = (ckpt, stash) {
7946 ck.gdn[il] = Some(st);
7947 }
7948 out
7949 }
7950 Mixer::Linear(_) => {
7951 unreachable!("linear layers ride qwen35_tparallel_linear_layer")
7952 }
7953 Mixer::Full(fa) => {
7954 let geometry = cfg.full_attention_geometry_at(il as u32);
7955 let n_head = geometry.n_head as usize;
7956 let n_head_kv = geometry.n_head_kv as usize;
7957 let head_dim = geometry.head_dim_k as usize;
7958 let rope_dims = geometry.n_rot as usize;
7959 let rope_base = geometry.rope_base;
7960 let scale = geometry.attention_scale();
7961 // Batched projections: one weight read serves all T rows.
7962 // GROUP-3 twin (trunk-kernels slice D): q/k/v in ONE launch — the group4
7963 // kernel with n3=0, bit-identical per (tensor, token, row) to the three
7964 // singles; refused or MEMRA_TK_FA_GROUP=0 -> singles byte-for-byte.
7965 let (qf, mut k, v) = match e.matmul_decode_exact_group3_pre(
7966 [&fa.wq, &fa.wk, &fa.wv],
7967 &hq,
7968 &hd,
7969 t,
7970 )? {
7971 Some(mut g3) => {
7972 let v = g3.pop().unwrap();
7973 let k = g3.pop().unwrap();
7974 let qf = g3.pop().unwrap();
7975 (qf, k, v)
7976 }
7977 None => (
7978 e.matmul_pre(&fa.wq, &hq, &hd, &xn, t)?,
7979 e.matmul_pre(&fa.wk, &hq, &hd, &xn, t)?,
7980 e.matmul_pre(&fa.wv, &hq, &hd, &xn, t)?,
7981 ),
7982 };
7983 let gated =
7984 geometry.attention_gate == memra_gguf::config::AttentionGateKind::FusedQ;
7985 let (mut q, gate) = if gated {
7986 let mut qs = e.uninit(t * n_head * head_dim)?;
7987 let mut gs = e.uninit(t * n_head * head_dim)?;
7988 e.q_gate_split(&qf, &mut qs, &mut gs, head_dim, n_head, t)?;
7989 (qs, Some(gs))
7990 } else {
7991 (qf, None)
7992 };
7993 let mut qn = e.uninit(t * n_head * head_dim)?;
7994 e.rms_norm(
7995 &q,
7996 fa.q_norm.float_data(),
7997 &mut qn,
7998 head_dim,
7999 t * n_head,
8000 eps,
8001 )?;
8002 q = qn;
8003 let mut kn = e.uninit(t * n_head_kv * head_dim)?;
8004 e.rms_norm(
8005 &k,
8006 fa.k_norm.float_data(),
8007 &mut kn,
8008 head_dim,
8009 t * n_head_kv,
8010 eps,
8011 )?;
8012 k = kn;
8013 e.rope_neox(
8014 &mut q, pos_d, head_dim, rope_dims, n_head, t, rope_base, 1.0,
8015 )?;
8016 e.rope_neox(
8017 &mut k, pos_d, head_dim, rope_dims, n_head_kv, t, rope_base, 1.0,
8018 )?;
8019
8020 // Per-row append + attend: row r sees rows 0..r in KV (causal within the
8021 // draft), each through the b_n=1 serving kernels at its own t_kv.
8022 let q_dim = n_head * head_dim;
8023 let kv_dim = n_head_kv * head_dim;
8024 let mut attn = e.uninit(t * q_dim)?;
8025 let (kdk, kdv, ktb, vtb, len0, kv_local) = {
8026 let kvl = cache.kv[il].as_ref().unwrap();
8027 // [2T] interleaved k,v base pointers: entry pair z serves row z of
8028 // the batched twins; the per-row fallback reads pair 0 (same cache
8029 // for every row of one layer). Graph mode reads the ctx table.
8030 let local: Option<CudaSlice<u64>> = match graph_cap {
8031 Some(_) => None,
8032 None => {
8033 let s = &e.gpu.stream();
8034 let (pk, _g) = kvl.k.device_ptr(s);
8035 let (pv, _g2) = kvl.v.device_ptr(s);
8036 let mut tbl = Vec::with_capacity(2 * t);
8037 for _ in 0..t {
8038 tbl.push(pk);
8039 tbl.push(pv);
8040 }
8041 Some(e.htod_u64(&tbl)?)
8042 }
8043 };
8044 (
8045 kvl.kv_dim_k,
8046 kvl.kv_dim_v,
8047 kvl.k_tok_bytes,
8048 kvl.v_tok_bytes,
8049 kvl.len,
8050 local,
8051 )
8052 };
8053 let (kv_tbl, kv_off): (&CudaSlice<u64>, usize) = match graph_cap {
8054 Some((tb, off, _)) => (tb, off),
8055 None => (kv_local.as_ref().expect("built above"), 0),
8056 };
8057 // Slice 4 (fa/append rows — see dspark_fa_rows_on): the whole per-row
8058 // section batches into the z-batched serving twins when every row of
8059 // this round takes the v4-seqs arm on ONE fa_split_keys rung. Both
8060 // guards are evaluated at the round's FIRST and LAST t_kv — the
8061 // eligibility window (vec floor .. v4 max) and each split-ladder rung
8062 // are intervals in t_kv, so ends-inside means all-inside (the straddle
8063 // law). Appending all T rows before any attend is read-equivalent to
8064 // the interleaved order: row r's walk reads keys 0..len0+r only, and
8065 // rows > r land at slots it never touches; every written cache row is
8066 // the per-token appender's exact warp program (kernel-check pinned).
8067 let t_kv_first = len0 + 1;
8068 let t_kv_last = len0 + t;
8069 let rows_batched = t >= 2
8070 && seqs_append
8071 && batch_fa_on
8072 && dspark_fa_rows_on()
8073 // the z-batched twins read stacked rows at the CACHE's kv dims;
8074 // the projection stack is [T, n_head_kv*head_dim] — they must be
8075 // the same stride or row z misaligns (true for this family; the
8076 // guard keeps any asymmetric-kv model on the per-row loop).
8077 && kdk == kv_dim
8078 && kdv == kv_dim
8079 && crate::fa_seqs_eligible(t_kv_first, head_dim_global)
8080 && crate::fa_seqs_eligible(t_kv_last, head_dim_global)
8081 && crate::fa_split_keys(t_kv_first, cfg.n_head_kv as usize)
8082 == crate::fa_split_keys(t_kv_last, cfg.n_head_kv as usize);
8083 // Sizing: eager = exact round bound; graph mode = the rung end (stride +
8084 // grid only — bytes proven equal above). Capture-time invariants refuse
8085 // loudly rather than bake a divergent body.
8086 let (size_kv_max, sp) = match graph_cap {
8087 Some((_, _, rung)) => {
8088 if !rows_batched {
8089 return Err(format!(
8090 "fa graph capture: layer {il} round is not batchable \
8091 (t_kv {t_kv_first}..{t_kv_last}) — the per-row fallback \
8092 must never be captured"
8093 )
8094 .into());
8095 }
8096 let sp_r = crate::fa_split_keys(rung, cfg.n_head_kv as usize);
8097 if t_kv_last > rung
8098 || sp_r != crate::fa_split_keys(t_kv_last, cfg.n_head_kv as usize)
8099 {
8100 return Err(format!(
8101 "fa graph capture: rung {rung} does not cover round \
8102 t_kv {t_kv_first}..{t_kv_last} on one split ladder step"
8103 )
8104 .into());
8105 }
8106 (rung, sp_r)
8107 }
8108 None => (
8109 t_kv_last,
8110 crate::fa_split_keys(t_kv_last, cfg.n_head_kv as usize),
8111 ),
8112 };
8113 if let Some((_, ctr)) = stream {
8114 // STREAM ARM (2b): one batched dc append + the multi-row dc attention
8115 // — the generic stream arm's exact shape (rows kernels are pinned
8116 // byte-identical to the per-row programs by kernel-check). Host len
8117 // stays a stale lower bound; the burst drain reconciles it.
8118 let kvl = cache.kv[il].as_mut().unwrap();
8119 e.append_kv_quantized_rows_dc(
8120 &k,
8121 &v,
8122 &mut kvl.k,
8123 &mut kvl.v,
8124 ctr,
8125 t,
8126 kdk,
8127 kdv,
8128 ktb,
8129 vtb,
8130 Engine::kv_fp8_on(),
8131 )?;
8132 let upper = (kvl.len + t + 64).min(cache.max_ctx);
8133 let k_view = e.view_u8(&kvl.k, upper * ktb);
8134 let v_view = e.view_u8(&kvl.v, upper * vtb);
8135 e.fa_decode_rows_dc(
8136 &q, &k_view, &v_view, &mut attn, head_dim, n_head, n_head_kv, ctr, upper,
8137 t, scale, ktb, vtb, 0, false,
8138 )?;
8139 } else if rows_batched {
8140 e.append_kv_quantized_seqs(
8141 &k,
8142 &v,
8143 &kv_tbl.slice(kv_off..kv_off + 2 * t),
8144 pos_d,
8145 t,
8146 kdk,
8147 kdv,
8148 ktb,
8149 vtb,
8150 )?;
8151 if graph_cap.is_none() {
8152 cache.kv[il].as_mut().unwrap().len += t;
8153 }
8154 e.fa_decode_batch_seqs_v4(
8155 &q,
8156 &kv_tbl.slice(kv_off..kv_off + 2 * t),
8157 pos_d,
8158 &mut attn,
8159 head_dim,
8160 n_head,
8161 n_head_kv,
8162 t,
8163 size_kv_max,
8164 scale,
8165 sp,
8166 ktb,
8167 vtb,
8168 )?;
8169 } else {
8170 if pos_rows.is_none() {
8171 // Stream-aware for symmetry with pos_d (the stream FA arm rides
8172 // the dc rows kernels above and never reaches this fallback).
8173 *pos_rows = Some(match stream {
8174 Some((_, ctr)) => (0..t)
8175 .map(|r| {
8176 let mut b = e.alloc_uninit::<i32>(1)?;
8177 e.i32_copy_add(ctr, &mut b, r as i32)?;
8178 Ok(b)
8179 })
8180 .collect::<Result<_, Box<dyn std::error::Error>>>()?,
8181 None => (0..t)
8182 .map(|r| e.htod_i32(&[(pos0 + r) as i32]))
8183 .collect::<Result<_, _>>()?,
8184 });
8185 }
8186 let pos_rows = pos_rows.as_ref().unwrap();
8187 #[allow(clippy::needless_range_loop)]
8188 // allow: the explicit index loop keeps the offset arithmetic visible and aligned with the device-side indexing
8189 for r in 0..t {
8190 // Owned per-row scratch: the b_n=1 kernels take packed batch buffers
8191 // whose row 0 is this row (arithmetic-free materialization copies,
8192 // same as decode's per-seq fallback arm).
8193 let mut k_row = e.uninit(kv_dim)?;
8194 e.dtod_copy_view(&k.slice(r * kv_dim..(r + 1) * kv_dim), &mut k_row)?;
8195 let mut v_row = e.uninit(kv_dim)?;
8196 e.dtod_copy_view(&v.slice(r * kv_dim..(r + 1) * kv_dim), &mut v_row)?;
8197 let pos_row = &pos_rows[r];
8198 let kvl = cache.kv[il].as_mut().unwrap();
8199 if seqs_append {
8200 e.append_kv_quantized_seqs(
8201 &k_row,
8202 &v_row,
8203 &kv_tbl.slice(kv_off..kv_off + 2),
8204 pos_row,
8205 1,
8206 kdk,
8207 kdv,
8208 ktb,
8209 vtb,
8210 )?;
8211 kvl.len += 1;
8212 } else {
8213 e.append_kv_quantized_view(
8214 &k_row.slice(0..kv_dim),
8215 &v_row.slice(0..kv_dim),
8216 &mut kvl.k,
8217 &mut kvl.v,
8218 kvl.len,
8219 kvl.kv_dim_k,
8220 kvl.kv_dim_v,
8221 kvl.k_tok_bytes,
8222 kvl.v_tok_bytes,
8223 Engine::kv_fp8_on(),
8224 )?;
8225 kvl.len += 1;
8226 }
8227 let t_kv = kvl.len;
8228 let mut q_row = e.uninit(q_dim)?;
8229 e.dtod_copy_view(&q.slice(r * q_dim..(r + 1) * q_dim), &mut q_row)?;
8230 let mut a_row = e.uninit(q_dim)?;
8231 if batch_fa_on && crate::fa_seqs_eligible(t_kv, head_dim_global) {
8232 let sp0_r = crate::fa_split_keys(t_kv, cfg.n_head_kv as usize);
8233 e.fa_decode_batch_seqs_v4(
8234 &q_row,
8235 &kv_tbl.slice(kv_off..kv_off + 2),
8236 pos_row,
8237 &mut a_row,
8238 head_dim,
8239 n_head,
8240 n_head_kv,
8241 1,
8242 t_kv,
8243 scale,
8244 sp0_r,
8245 ktb,
8246 vtb,
8247 )?;
8248 } else {
8249 let k_view = e.view_u8(&kvl.k, t_kv * kvl.k_tok_bytes);
8250 let v_view = e.view_u8(&kvl.v, t_kv * kvl.v_tok_bytes);
8251 let mut a_view = a_row.slice_mut(0..q_dim);
8252 e.fa_decode_kvmod_view(
8253 &q_row.slice(0..q_dim),
8254 &k_view,
8255 &v_view,
8256 &mut a_view,
8257 head_dim,
8258 n_head,
8259 n_head_kv,
8260 t_kv,
8261 scale,
8262 kvl.k_tok_bytes,
8263 kvl.v_tok_bytes,
8264 Engine::kv_fp8_on(),
8265 )?;
8266 }
8267 e.dtod_copy_into(&a_row, &mut attn, r * q_dim)?;
8268 }
8269 }
8270
8271 // Output gate (element-wise) + o-proj at m=T.
8272 let attn_g = match &gate {
8273 Some(g) => {
8274 let n = t * q_dim;
8275 let mut gsig = e.uninit(n)?;
8276 e.sigmoid(g, &mut gsig, n)?;
8277 let mut ag = e.uninit(n)?;
8278 e.mul(&attn, &gsig, &mut ag, n)?;
8279 ag
8280 }
8281 None => attn,
8282 };
8283 e.matmul(&fa.wo, &attn_g, t)?
8284 }
8285 };
8286
8287 // ---- residual add + post_attn_norm + FFN at m=T (serving dispatch verbatim) ----
8288 let pnorm = layer.post_attn_norm.float_data();
8289 let mut x1 = e.uninit(t * n_embd)?;
8290 let mut zn = e.uninit(t * n_embd)?;
8291 e.add_rms_norm(x, &mixed, pnorm, &mut x1, &mut zn, n_embd, t, eps)?;
8292 let ffn_out = match &layer.ffn {
8293 crate::hybrid::Ffn::Dense {
8294 ffn_gate,
8295 ffn_up,
8296 ffn_down,
8297 } => {
8298 assert!(
8299 self.cfg.m3.is_none(),
8300 "qwen35 t-parallel verify: M3 swigluoai FFN not yet batched"
8301 );
8302 self.qwen35_tparallel_dense_ffn(e, ffn_gate, ffn_up, ffn_down, &zn, t, n_embd)?
8303 }
8304 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il_zq8(e, m, &zn, None, t, il as u16)?,
8305 };
8306 let mut x2 = e.uninit(t * n_embd)?;
8307 e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
8308 // dspark drafter tap (no-op when no sink armed): post-layer residual verify rows
8309 self.dflash_tap(e, cache, il, &x2, t)?;
8310 Ok(x2)
8311 }
8312
8313 /// ONE t-parallel LINEAR layer (attn_norm + gdn mixer + post_attn_norm + FFN + tap) —
8314 /// the exact body the old in-loop Linear arm ran, extracted so the eager walk and the
8315 /// slice-3 captured segments execute the SAME code (a second copy is how dispatch
8316 /// mirrors drift — the verify_layers extraction lesson). Two deliberate changes, both
8317 /// bit-identical by construction:
8318 /// - the gdn ping-pong host swap moves from per-row to ONE end-of-body swap (t odd):
8319 /// the device sequence is driven entirely by the 6-entry pointer table, which
8320 /// already encodes both parities; the ckpt stash reads name row r's out buffer
8321 /// directly (r even -> alt handle, odd -> canonical) — the same physical bytes the
8322 /// legacy post-swap clone read.
8323 /// - `stash` (slice-3 ctx): persistent per-layer slabs written by copy_into instead of
8324 /// per-row clone_dtod allocs — same bytes, capture-legal (no per-round host objects).
8325 /// `table_src` = (persistent pointer table, offset) when the ctx owns the tables;
8326 /// None builds the per-verify table exactly as before.
8327 #[allow(clippy::too_many_arguments)]
8328 fn qwen35_tparallel_linear_layer(
8329 &self,
8330 e: &Engine,
8331 il: usize,
8332 x: &CudaSlice<f32>,
8333 t: usize,
8334 cache: &mut Cache,
8335 ckpt: Option<&mut VerifyCkpt>,
8336 stash: Option<(&mut CudaSlice<f32>, &mut CudaSlice<f32>)>,
8337 table_src: Option<(&CudaSlice<u64>, usize)>,
8338 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
8339 use cudarc::driver::DevicePtr;
8340 let cfg = &self.cfg;
8341 let n_embd = cfg.n_embd as usize;
8342 let eps = cfg.rms_eps;
8343 let layer = &self.layers[il];
8344 let Mixer::Linear(la) = &layer.mixer else {
8345 return Err("qwen35_tparallel_linear_layer on a non-linear layer".into());
8346 };
8347 // ---- attn_norm + q8_1 quantize at m=T (row-indexed == per-row) ----
8348 let anorm = layer.attn_norm.float_data();
8349 let mut xn = e.uninit(t * n_embd)?;
8350 e.rms_norm(x, anorm, &mut xn, n_embd, t, eps)?;
8351 let (hq, hd) = e.quantize_q8_1(&xn, t, n_embd)?;
8352
8353 let geometry = la.geometry;
8354 let d_state = geometry.key_head_dim as usize;
8355 let num_k = geometry.key_heads as usize;
8356 let num_v = geometry.value_heads as usize;
8357 let d_conv = geometry.conv_kernel as usize;
8358 let key_dim = d_state * num_k;
8359 let value_dim = geometry.value_head_dim as usize * num_v;
8360 let conv_dim = key_dim * 2 + value_dim;
8361 let gdn_scale = 1.0 / (d_state as f32).sqrt();
8362
8363 // ---- batched projections: one weight read for all T rows ----
8364 // GROUP-4 twin (trunk-kernels slice C): the whole 4-tuple in ONE launch, bit-identical
8365 // per (tensor, token, row) to the four singles; refused (layout/tier) or
8366 // MEMRA_TK_GDN_GROUP=0 -> the singles chain byte-for-byte.
8367 let (qkv_mixed, z, beta_raw, alpha) = match e.matmul_decode_exact_group4_pre(
8368 [&la.wqkv, &la.wqkv_gate, &la.ssm_beta, &la.ssm_alpha],
8369 &hq,
8370 &hd,
8371 t,
8372 )? {
8373 Some(mut g4) => {
8374 let alpha = g4.pop().unwrap();
8375 let beta_raw = g4.pop().unwrap();
8376 let z = g4.pop().unwrap();
8377 let qkv_mixed = g4.pop().unwrap();
8378 (qkv_mixed, z, beta_raw, alpha)
8379 }
8380 None => (
8381 e.matmul_pre(&la.wqkv, &hq, &hd, &xn, t)?,
8382 e.matmul_pre(&la.wqkv_gate, &hq, &hd, &xn, t)?,
8383 e.matmul_pre(&la.ssm_beta, &hq, &hd, &xn, t)?,
8384 e.matmul_pre(&la.ssm_alpha, &hq, &hd, &xn, t)?,
8385 ),
8386 };
8387 let beta_w = la.ssm_beta.out_features();
8388 let alpha_w = la.ssm_alpha.out_features();
8389 let qkv_w = la.wqkv.out_features();
8390
8391 // ---- per-row state chain through the b_n=1 serving kernels ----
8392 // 6-entry alternating pointer table expresses the ping-pong without a rebuild per
8393 // row: even rows scan s0 -> s1, odd rows s1 -> s0.
8394 let table_local: Option<CudaSlice<u64>> = match table_src {
8395 Some(_) => None,
8396 None => {
8397 let rl = cache.recur[il].as_ref().unwrap();
8398 let s = &e.gpu.stream();
8399 let (pc, _g0) = rl.conv_state.device_ptr(s);
8400 let (p0, _g1) = rl.ssm_state.device_ptr(s);
8401 let (p1, _g2) = rl.ssm_state_alt.device_ptr(s);
8402 Some(e.htod_u64(&[pc, p0, p1, pc, p1, p0])?)
8403 }
8404 };
8405 let (table, toff): (&CudaSlice<u64>, usize) = match table_src {
8406 Some((tb, off)) => (tb, off),
8407 None => (table_local.as_ref().unwrap(), 0),
8408 };
8409 let mut o_all = e.uninit(t * value_dim)?;
8410 let mut col_states: Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>> =
8411 if ckpt.is_some() && stash.is_none() && t >= 2 {
8412 Some(Vec::with_capacity(t - 1))
8413 } else {
8414 None
8415 };
8416 let mut stash = stash;
8417 // Per-row scratch reused across rows (uninit is cheap but not free at
8418 // 48 layers x T rows); row inputs/outputs pass as VIEWS into the packed
8419 // [T, ...] buffers — zero arithmetic-free copies in this loop.
8420 let mut conv_out = e.uninit(conv_dim)?;
8421 let mut q_l2 = e.uninit(value_dim)?;
8422 let mut k_l2 = e.uninit(value_dim)?;
8423 let mut v_gd = e.uninit(value_dim)?;
8424 let mut beta_b = e.uninit(num_v)?;
8425 let mut g_log = e.uninit(num_v)?;
8426 for r in 0..t {
8427 let base = toff + if r % 2 == 0 { 0 } else { 3 };
8428 let conv_view = table.slice(base..base + 1);
8429 let in_view = table.slice(base + 1..base + 2);
8430 let out_view = table.slice(base + 2..base + 3);
8431 e.ssm_conv1d_fused_decode_b_view(
8432 &qkv_mixed.slice(r * qkv_w..(r + 1) * qkv_w),
8433 &conv_view,
8434 la.ssm_conv1d.float_data(),
8435 &mut conv_out,
8436 conv_dim,
8437 d_conv,
8438 1,
8439 )?;
8440 e.gdn_prep_decode_b_view(
8441 &conv_out,
8442 &beta_raw.slice(r * beta_w..(r + 1) * beta_w),
8443 &alpha.slice(r * alpha_w..(r + 1) * alpha_w),
8444 la.ssm_dt.float_data(),
8445 la.ssm_a.float_data(),
8446 &mut q_l2,
8447 &mut k_l2,
8448 &mut v_gd,
8449 &mut beta_b,
8450 &mut g_log,
8451 d_state,
8452 num_v,
8453 num_k,
8454 key_dim,
8455 eps,
8456 conv_dim,
8457 1,
8458 )?;
8459 let mut o_row = o_all.slice_mut(r * value_dim..(r + 1) * value_dim);
8460 e.gdn_scan_s128_batched_view(
8461 &q_l2, &k_l2, &v_gd, &g_log, &beta_b, &in_view, &out_view, &mut o_row, num_v, 1,
8462 gdn_scale,
8463 )?;
8464 if r + 1 < t {
8465 // Row r's out buffer: even rows write s1 (the alt handle — no swaps ran),
8466 // odd rows write s0 — the same physical state the legacy post-swap
8467 // canonical clone read.
8468 let rl = cache.recur[il]
8469 .as_ref()
8470 .ok_or("qwen35 linear verify layer has no recurrent state")?;
8471 let ssm_src = if r % 2 == 0 {
8472 &rl.ssm_state_alt
8473 } else {
8474 &rl.ssm_state
8475 };
8476 match stash.as_mut() {
8477 Some((conv_slab, ssm_slab)) => {
8478 // BOTH stash reads go through the pointer table at run time: the
8479 // ssm handles ping-pong between rounds, and the ctx (with its
8480 // captured graphs) outlives the Cache — a fresh generation's
8481 // conv/ssm buffers land at new addresses that only the per-round
8482 // table refresh knows. A baked direct copy would read freed
8483 // memory (parity was the slice-3 smoke divergence; cache
8484 // lifetime is the cross-generation twin).
8485 e.copy_indirect_src_f32(
8486 &conv_view,
8487 conv_slab,
8488 r * conv_dim * (d_conv - 1),
8489 conv_dim * (d_conv - 1),
8490 )?;
8491 // The ssm handles PING-PONG between rounds: a captured direct
8492 // copy would bake the capture-time physical buffer and read the
8493 // wrong parity after any odd-vt round (the slice-3 smoke
8494 // divergence). Read the src address from row r's OUT table
8495 // entry at run time — the same entry the scan just wrote.
8496 e.copy_indirect_src_f32(
8497 &out_view,
8498 ssm_slab,
8499 r * d_state * d_state * num_v,
8500 d_state * d_state * num_v,
8501 )?;
8502 }
8503 None => {
8504 if let Some(states) = col_states.as_mut() {
8505 states.push((e.clone_dtod(&rl.conv_state)?, e.clone_dtod(ssm_src)?));
8506 }
8507 }
8508 }
8509 }
8510 }
8511 // ONE end-of-body parity swap (t odd) — the legacy loop swapped per row; the net
8512 // handle motion is identical and the device sequence never read the handles.
8513 if t % 2 == 1 {
8514 let rl = cache.recur[il].as_mut().unwrap();
8515 std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
8516 }
8517 if let (Some(checkpoint), Some(states)) = (ckpt, col_states) {
8518 checkpoint.cols[il] = Some(states);
8519 }
8520
8521 // ---- batched gated norm + out-projection at m=T ----
8522 let mixed = if e.uses_q8_1_fast(&la.ssm_out) {
8523 let (gq, gd) = e.gated_rmsnorm_q8_1(
8524 &o_all,
8525 la.ssm_norm.float_data(),
8526 &z,
8527 d_state,
8528 t * num_v,
8529 eps,
8530 )?;
8531 let g0 = e.zeros(0)?;
8532 e.matmul_pre(&la.ssm_out, &gq, &gd, &g0, t)?
8533 } else {
8534 let mut gn = e.uninit(t * value_dim)?;
8535 e.gated_rmsnorm(
8536 &o_all,
8537 la.ssm_norm.float_data(),
8538 &z,
8539 &mut gn,
8540 d_state,
8541 t * num_v,
8542 eps,
8543 )?;
8544 e.matmul(&la.ssm_out, &gn, t)?
8545 };
8546
8547 // ---- residual add + post_attn_norm + FFN at m=T (serving dispatch verbatim) ----
8548 let pnorm = layer.post_attn_norm.float_data();
8549 let mut x1 = e.uninit(t * n_embd)?;
8550 let mut zn = e.uninit(t * n_embd)?;
8551 e.add_rms_norm(x, &mixed, pnorm, &mut x1, &mut zn, n_embd, t, eps)?;
8552 let ffn_out = match &layer.ffn {
8553 crate::hybrid::Ffn::Dense {
8554 ffn_gate,
8555 ffn_up,
8556 ffn_down,
8557 } => {
8558 assert!(
8559 self.cfg.m3.is_none(),
8560 "qwen35 t-parallel verify: M3 swigluoai FFN not yet batched"
8561 );
8562 self.qwen35_tparallel_dense_ffn(e, ffn_gate, ffn_up, ffn_down, &zn, t, n_embd)?
8563 }
8564 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il_zq8(e, m, &zn, None, t, il as u16)?,
8565 };
8566 let mut x2 = e.uninit(t * n_embd)?;
8567 e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
8568 // dspark drafter tap (no-op when no sink armed): post-layer residual verify rows
8569 self.dflash_tap(e, cache, il, &x2, t)?;
8570 Ok(x2)
8571 }
8572
8573 /// PP-N STAGE SUBGRAPH of the verify trunk: layers `[lo, hi)` of `decode_step_t_core_stream`'s
8574 /// walk, verbatim. Enters with a MATERIALIZED `[T, n_embd]` residual (no pending fusion pair
8575 /// carried in from outside the range) and exits with the range's final residual materialized
8576 /// (the trailing add executed) — exactly the `decode_layers_eager(lo, hi)` contract, T rows
8577 /// instead of one.
8578 ///
8579 /// EXTRACTED (lane/pp2-spec 2026-08-06) rather than duplicated: `decode_step_t_core_stream` IS
8580 /// the single funnel every verify forward reaches, and its per-layer dispatch MIRRORING (norm
8581 /// fusion per layer, the t>=3/spec_m2 batched-linear window, the fused-q8 FFN chain, the
8582 /// decode-exact projections) is what makes verify bit-identical to eager decode. A second copy
8583 /// for the split arm is how those mirrors drift apart on the next lever. The unsplit body now
8584 /// calls this with `(0, n_layers)`, so the whole-trunk path and every stage range run the SAME
8585 /// code — there is no "split version" of the verify math.
8586 ///
8587 /// Bit-identity of a cut rests on the same kernel-check-pinned identity the eager arm's cut
8588 /// does — `add_rms_norm_q8_1 == add then rms_norm_q8_1` at nrows=T — because the ONLY thing a
8589 /// fence changes is that the cross-layer fusion carry breaks at `hi-1` and is re-materialized
8590 /// as an explicit `add`. `decode-batch-gate --mode ppspec` verifies end-to-end on real weights.
8591 #[allow(clippy::too_many_arguments)]
8592 fn verify_layers(
8593 &self,
8594 e: &Engine,
8595 mut x: CudaSlice<f32>,
8596 lo: usize,
8597 hi: usize,
8598 pos_d: &CudaSlice<i32>,
8599 pos0: usize,
8600 t: usize,
8601 cache: &mut Cache,
8602 mut ckpt: Option<&mut VerifyCkpt>,
8603 stream: Option<(&CudaSlice<u32>, &CudaSlice<i32>)>,
8604 graphs: Option<&mut DsparkVerifyGraphs>,
8605 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
8606 if self.sliding_gated_moe_batch_program() {
8607 if stream.is_some() {
8608 return Err(
8609 "step35 has no ROUND-STREAM verify arm (the device-counter _dc twins \
8610 cannot express the SWA offset KV view)"
8611 .into(),
8612 );
8613 }
8614 return self.step35_verify_batch_layers(e, x, lo, hi, pos0, t, cache);
8615 }
8616 if self.batched_serving_numeric_class() {
8617 return self.qwen35_verify_batch_layers(
8618 e,
8619 x,
8620 lo,
8621 hi,
8622 pos0,
8623 t,
8624 cache,
8625 ckpt.take(),
8626 stream,
8627 graphs,
8628 );
8629 }
8630 let n_embd = self.cfg.n_embd as usize;
8631 let eps = self.cfg.rms_eps;
8632 // CROSS-LAYER ADD+NORM FUSION (lane/vt-fixes fix 2, mirroring decode_step_h's
8633 // launch-arc form): layer il's post-FFN residual add (x2 = x1 + ffn_out) and layer
8634 // il+1's attn_norm(+quantize) are consecutive row-wise ops — ONE add_rms_norm_q8_1
8635 // launch at nrows=t does all three (bit-identity pinned by the T-row kernel-check
8636 // arms). Carry the un-added (x1, ffn_out) pair; the fused launch materializes x2 (the
8637 // residual the next layer needs) as its `res` output. Falls back to the separate add
8638 // when the next layer is off the fused-q8 path.
8639 let mut pending: Option<(CudaSlice<f32>, CudaSlice<f32>)> = None;
8640 for il in lo..hi {
8641 let layer = &self.layers[il];
8642 // DISPATCH-MIRRORED attn-input RMSNorm (FP-order lesson #8): eager decode fuses the
8643 // 1024-thread rms_norm_q8_1 ONLY when every mixer projection is q8_1-fast; layers with
8644 // Float projections (ssm_beta/ssm_alpha on layers 1/2/4 of the 9B NVFP4 GGUF) take the
8645 // UNFUSED 256-thread rms_norm. The verify norm must mirror that PER-LAYER choice —
8646 // blockDim changes the sum-of-squares reduce order, and the ULP shift amplifies through
8647 // the GDN recurrence into argmax flips (measured: 9B text prompt, 1 ULP at layer 2 ->
8648 // 2.3e-1 logit maxdiff at the head -> K=1..8 divergence at a 0.03-margin token).
8649 let mixer_fast = self.mixer_in_q8_1_fast(e, &layer.mixer);
8650 let norm_fused = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err() && mixer_fast;
8651 // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2, 2026-08-03): when the norm is
8652 // dispatch-fused AND every consumer of `h` reads only its q8_1 form (Full mixer:
8653 // projections only; Linear mixer: the batched arm — the per-column fallback needs
8654 // f32 h), emit the attn-input norm DIRECTLY as q8_1 via `rms_norm_q8_1` at nrows=t
8655 // (row-indexed kernel — the T-row launch is the per-row m=1 program, kernel-check
8656 // pins bit-identity vs rms_norm_decode -> quantize_q8_1). Kills the standalone
8657 // quantize launch(es) + the f32 h HBM round-trip that decode never pays.
8658 // step35 (Full mixer) is the third case that needs f32 `h`: its verify arm is a
8659 // per-ROW replay of the eager decode mixer, whose `pre_q` contract is a single row —
8660 // a T-row q8_1 pair cannot be handed to it, and re-deriving per-row q8_1 from the f32
8661 // rows is exactly the dispatch being mirrored. Keep step35 on the unfused arm.
8662 let lin_q8_only = match &layer.mixer {
8663 Mixer::Linear(la) => {
8664 (t >= 3 || (t == 2 && spec_m2())) && e.uses_q8_1_fast(&la.ssm_out)
8665 }
8666 Mixer::Full(_) if self.sliding_gated_moe_batch_program() => false,
8667 _ => true,
8668 };
8669 // NOTE decode.rs's take()-first lesson: take the pending pair BEFORE branching so
8670 // a non-fused layer still performs the residual add.
8671 let taken = pending.take();
8672 let (h, h_q8) = if norm_fused && lin_q8_only {
8673 let pair = match taken {
8674 // fused add + attn_norm + q8_1: ONE launch resolves the carried residual
8675 // AND emits this layer's mixer input pre-quantized. res -> x2 (= new x).
8676 Some((x1p, f1p)) => {
8677 let mut x2 = vbuf(e, t * n_embd)?; // fully written (res output)
8678 let p = e.add_rms_norm_q8_1(
8679 &x1p,
8680 &f1p,
8681 layer.attn_norm.float_data(),
8682 &mut x2,
8683 n_embd,
8684 t,
8685 eps,
8686 )?;
8687 x = x2;
8688 p
8689 }
8690 None => e.rms_norm_q8_1(&x, layer.attn_norm.float_data(), n_embd, t, eps)?,
8691 };
8692 (e.zeros(0)?, Some(pair)) // h unused on this path (q8-only consumers)
8693 } else {
8694 if let Some((x1p, f1p)) = taken {
8695 let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
8696 e.add(&x1p, &f1p, &mut x2, t * n_embd)?;
8697 x = x2;
8698 }
8699 let mut h = vbuf(e, t * n_embd)?; // fully written by either rms_norm arm
8700 if norm_fused {
8701 e.rms_norm_decode(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
8702 } else {
8703 e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
8704 }
8705 (h, None)
8706 };
8707 let h_q8_ref = h_q8.as_ref().map(|(q, d)| (q, d));
8708
8709 let mixed = match &layer.mixer {
8710 Mixer::Full(fa) => self.full_attn_verify(
8711 e,
8712 fa,
8713 &h,
8714 h_q8_ref,
8715 pos_d,
8716 t,
8717 cache,
8718 il,
8719 stream.map(|(_, c)| c),
8720 )?,
8721 Mixer::Mla(_) => crate::hybrid::mla_path_unimplemented("speculative verify"),
8722 Mixer::Kda(_) => crate::hybrid::kda_path_unimplemented("speculative verify"),
8723 Mixer::Linear(la) => {
8724 // BATCHED linear verify (2026-07-03, the MTP-profit lever): one T-token pass —
8725 // batched projections (weight read ONCE, hits the m=2-4 weight-resident matvec),
8726 // carried-state conv (ssm_conv1d_tm_state), GDN prep on the prefill kernels, and
8727 // ONE gdn_scan whose internal sequential t-loop is the SAME recurrence as T
8728 // chained T=1 steps (bit-identical). Falls back to the sequential per-column
8729 // chain when T < d_conv-1 (conv ring update needs T >= pad) — or when ANY
8730 // projection is off the q8_1 fast path: matmul_decode_exact would route a Float
8731 // tensor to cuBLAS at m=t (different FP accumulation than eager's per-token
8732 // GEMV), so mixed-dtype layers stay on the eager-identical per-column chain.
8733 // MEMRA_SPEC_M2 (lane/spec-m2): the t==2 batch rides the same arm — the conv
8734 // wrapper handles t<pad with a pure-copy ring rebuild; see spec_m2() header.
8735 if (t >= 3 || (t == 2 && spec_m2()))
8736 && mixer_fast
8737 && e.uses_q8_1_fast(&la.ssm_out)
8738 {
8739 let want = ckpt.is_some();
8740 let (out, stash) =
8741 self.linear_attn_verify_t(e, la, &h, h_q8_ref, t, cache, il, want)?;
8742 if let (Some(ck), Some(st)) = (ckpt.as_deref_mut(), stash) {
8743 ck.gdn[il] = Some(st);
8744 }
8745 out
8746 } else {
8747 let mut out = vbuf(e, t * n_embd)?; // every col written by copy_into
8748 let mut col_states: Option<Vec<(CudaSlice<f32>, CudaSlice<f32>)>> =
8749 if ckpt.is_some() && t >= 2 {
8750 Some(Vec::with_capacity(t - 1))
8751 } else {
8752 None
8753 };
8754 for col in 0..t {
8755 let mut h_col = vbuf(e, n_embd)?; // fully written by copy_view_into
8756 let src = h.slice(col * n_embd..(col + 1) * n_embd);
8757 e.copy_view_into(&mut h_col, 0, &src, n_embd)?;
8758 let m_col = self.linear_attn_decode(e, la, &h_col, cache, il)?;
8759 e.copy_into(&mut out, col * n_embd, &m_col, n_embd)?;
8760 // REPLAY-FREE ckpt: clone the chain's ACTUAL state after this column
8761 // (pure dtod — cannot change any computed value). Last column skipped:
8762 // rebuild targets are j <= t-1 columns.
8763 if let Some(cs) = col_states.as_mut()
8764 && col + 1 < t
8765 {
8766 let rl = cache.recur[il].as_ref().unwrap();
8767 cs.push((
8768 e.clone_dtod(&rl.conv_state)?,
8769 e.clone_dtod(&rl.ssm_state)?,
8770 ));
8771 }
8772 }
8773 if let (Some(ck), Some(cs)) = (ckpt.as_deref_mut(), col_states) {
8774 // ReplaySSM-assessment instrumentation (2026-07-30): the
8775 // per-column clones are the only true state snapshots left in
8776 // the verify (the batched path stashes INPUTS and replays).
8777 if std::env::var("MEMRA_SPEC_STATS").as_deref() == Ok("1") {
8778 static ONCE: std::sync::Once = std::sync::Once::new();
8779 let bytes: usize =
8780 cs.iter().map(|(c, s)| (c.len() + s.len()) * 4).sum();
8781 ONCE.call_once(|| eprintln!(
8782 "[verify-ckpt] per-column layer il={il}: {} clones, {:.2} MB/layer/round",
8783 cs.len(), bytes as f64 / 1e6));
8784 }
8785 ck.cols[il] = Some(cs);
8786 }
8787 out
8788 }
8789 }
8790 };
8791 if spec_nan_scan_level() >= 2 {
8792 let mixed_width = mixed.len() / t;
8793 nan_scan_rows(
8794 e,
8795 &mixed,
8796 t,
8797 mixed_width,
8798 &format!("verify layer {il} batched ATTN out pos0={pos0}"),
8799 )?;
8800 }
8801
8802 // DISPATCH-MIRRORED post-attn norm: eager residual_norm_ffn fuses add+norm+quant
8803 // (1024-thread add_rms_norm_q8_1) only for Dense FFNs whose gate+up are q8_1-fast;
8804 // otherwise (and for MoE) it runs the 256-thread fused add_rms_norm. Mirror per layer.
8805 let ffn_fuse = match &layer.ffn {
8806 crate::hybrid::Ffn::Dense {
8807 ffn_gate, ffn_up, ..
8808 } => {
8809 std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
8810 && e.uses_q8_1_fast(ffn_gate)
8811 && e.uses_q8_1_fast(ffn_up)
8812 }
8813 crate::hybrid::Ffn::Moe(_) => false,
8814 };
8815 // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): on the ffn_fuse path (Dense,
8816 // gate+up q8_1-fast, non-M3) the FFN input is emitted DIRECTLY as q8_1 by ONE
8817 // add_rms_norm_q8_1 launch at nrows=t (row-indexed kernel: the T-row launch is the
8818 // per-row m=1 program; kernel-check pins bit-identity vs the unfused
8819 // add_f32 -> rms_norm_decode -> quantize_q8_1 chain at T=2/4/5/8) — replacing the
8820 // add + rms_norm_decode launches AND the dual/singles' internal re-quantize.
8821 // M3's swigluoai must keep the f32 chain (the fused SwiGLU epilogue encodes plain
8822 // SiLU), mirroring residual_norm_ffn's m3 guard on the decode path.
8823 // step35: same guard per LAYER. A dense FFN's clamp is the SHEXP array (upstream's
8824 // one build_ffn serves dense + shared expert, llama-graph.cpp:1751), and verify MUST
8825 // mirror decode's dispatch or spec self-consistency fails.
8826 let dense_lim = self.cfg.clamp_shexp_at(il as u32);
8827 let fuse_q8 = ffn_fuse && self.cfg.m3.is_none() && dense_lim.is_none();
8828 let mut x1 = vbuf(e, t * n_embd)?; // fully written by add / add_rms_norm*
8829 let mut z = e.zeros(0)?; // replaced below on the unfused arms
8830 let z_q8 = if fuse_q8 {
8831 Some(e.add_rms_norm_q8_1(
8832 &x,
8833 &mixed,
8834 layer.post_attn_norm.float_data(),
8835 &mut x1,
8836 n_embd,
8837 t,
8838 eps,
8839 )?)
8840 } else {
8841 let mut zf = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode / add_rms_norm
8842 if ffn_fuse {
8843 e.add(&x, &mixed, &mut x1, t * n_embd)?;
8844 e.rms_norm_decode(
8845 &x1,
8846 layer.post_attn_norm.float_data(),
8847 &mut zf,
8848 n_embd,
8849 t,
8850 eps,
8851 )?;
8852 } else {
8853 e.add_rms_norm(
8854 &x,
8855 &mixed,
8856 layer.post_attn_norm.float_data(),
8857 &mut x1,
8858 &mut zf,
8859 n_embd,
8860 t,
8861 eps,
8862 )?;
8863 }
8864 z = zf;
8865 None
8866 };
8867 if spec_nan_scan_level() >= 2 && !z.is_empty() {
8868 nan_scan_rows(
8869 e,
8870 &z,
8871 t,
8872 n_embd,
8873 &format!("verify layer {il} post-attn norm z pos0={pos0}"),
8874 )?;
8875 }
8876 // DECODE-EXACT FFN projections: force MMVQ for gate/up/down at any T to match the
8877 // T=1 decode FP accumulation order. At T>=5 the generic matmul/matmul_pre falls to dp4a
8878 // (128-thread, different FP sum order). At T=2-4 the batched MMVQ is already bit-identical.
8879 let ffn_out = match &layer.ffn {
8880 crate::hybrid::Ffn::Dense {
8881 ffn_gate,
8882 ffn_up,
8883 ffn_down,
8884 } => {
8885 let n_ff = ffn_gate.out_features();
8886 if let Some((zq, zd)) = z_q8.as_ref() {
8887 // FUSED CHAIN (fix 2): pre-quantized z feeds the projections; the SwiGLU
8888 // epilogue emits act pre-quantized for ffn_down (silu_mul_scaled_q8_1,
8889 // bit-identical to silu_mul + quantize — kernel-check-pinned) with the
8890 // NVFP4 macro-scales folded (deferred-scale dual: y*s inline == the
8891 // scale_inplace store, value-exact) — the exact m=1 decode epilogue
8892 // structure at nrows=t.
8893 let pair = e
8894 .matmul_decode_exact_dual_pre(ffn_gate, ffn_up, zq, zd, t)?
8895 .map(|((g, gs), (u, us))| (g, gs, u, us));
8896 let (gate, gs, up, us) = match pair {
8897 Some(x4) => x4,
8898 None => (
8899 e.matmul_decode_exact_pre(ffn_gate, zq, zd, t)?,
8900 1.0, // scale already applied inside _pre
8901 e.matmul_decode_exact_pre(ffn_up, zq, zd, t)?,
8902 1.0,
8903 ),
8904 };
8905 if e.uses_q8_1_fast(ffn_down) {
8906 let (aq, ad) = e.silu_mul_scaled_q8_1(&gate, &up, gs, us, t * n_ff)?;
8907 e.matmul_decode_exact_pre(ffn_down, &aq, &ad, t)?
8908 } else {
8909 let mut act = vbuf(e, t * n_ff)?;
8910 e.silu_mul_scaled(&gate, &up, gs, us, &mut act, t * n_ff)?;
8911 e.matmul_decode_exact(ffn_down, &act, t)?
8912 }
8913 } else {
8914 // UNFUSED (pre-fix) chain — MoE-adjacent/M3/off-fast layers, unchanged.
8915 // DUAL gate+up batched twin (lane/verify-economics, 2026-08-02): one launch
8916 // for the pair at t=2..8 — bit-identical per (tensor,token,row) to the two
8917 // singles (kernel-check pins bitwise; MEMRA_SPEC_DUAL_T=0 reverts). None
8918 // (non-NVFP4 / t outside the tier / seam off) -> the two singles, unchanged.
8919 let (gate, up) =
8920 match e.matmul_decode_exact_dual(ffn_gate, ffn_up, &z, t)? {
8921 Some(pair) => pair,
8922 None => (
8923 e.matmul_decode_exact(ffn_gate, &z, t)?,
8924 e.matmul_decode_exact(ffn_up, &z, t)?,
8925 ),
8926 };
8927 let mut act = vbuf(e, t * n_ff)?; // fully written by ffn_act_lim
8928 Self::ffn_act_lim(
8929 e,
8930 &self.cfg,
8931 &gate,
8932 &up,
8933 1.0,
8934 1.0,
8935 dense_lim,
8936 &mut act,
8937 t * n_ff,
8938 )?;
8939 e.matmul_decode_exact(ffn_down, &act, t)?
8940 }
8941 }
8942 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, t, il as u16)?,
8943 };
8944 if spec_nan_scan_level() >= 2 {
8945 nan_scan_rows(
8946 e,
8947 &ffn_out,
8948 t,
8949 n_embd,
8950 &format!("verify layer {il} batched FFN out pos0={pos0}"),
8951 )?;
8952 }
8953 if spec_nan_scan() {
8954 let mut residual = vbuf(e, t * n_embd)?;
8955 e.add(&x1, &ffn_out, &mut residual, t * n_embd)?;
8956 nan_scan_rows(
8957 e,
8958 &residual,
8959 t,
8960 n_embd,
8961 &format!("verify layer {il} residual pos0={pos0}"),
8962 )?;
8963 }
8964 // CROSS-LAYER fusion: defer this layer's post-FFN residual add — the next layer's
8965 // fused-q8 attn norm folds it in (add_rms_norm_q8_1 == add; rms_norm; quantize,
8966 // kernel-check-pinned at nrows=T). Non-fused next layers add explicitly above.
8967 pending = Some((x1, ffn_out));
8968 }
8969 // RANGE's final add (no next norm INSIDE the range to fuse with; for the
8970 // whole-trunk call that is the last layer, whose next norm is output_norm — f32-out).
8971 if let Some((x1p, f1p)) = pending.take() {
8972 let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
8973 e.add(&x1p, &f1p, &mut x2, t * n_embd)?;
8974 x = x2;
8975 }
8976 Ok(x)
8977 }
8978 /// BATCHED linear-attn verify (T=K+1): the whole layer in ~10 launches instead of T x the
8979 /// T=1 decode chain (T x ~12 launches + T weight reads of the four projections). The GDN
8980 /// recurrence itself is inherently sequential — gdn_scan_s128 runs its internal t-loop with
8981 /// the SAME per-token math as chained T=1 calls (bit-identical state evolution); everything
8982 /// around it (projections, conv, prep, gated norm, out-proj) batches. Advances conv ring +
8983 /// ssm state exactly like T sequential decode steps.
8984 /// `want_stash`: additionally RETAIN the gdn-scan inputs (pure buffer keep-alives, zero extra
8985 /// kernels) so a partial accept can rebuild the state after any column prefix (REPLAY-FREE).
8986 #[allow(clippy::too_many_arguments)]
8987 fn linear_attn_verify_t(
8988 &self,
8989 e: &Engine,
8990 la: &LinearAttnLayer,
8991 h: &CudaSlice<f32>,
8992 h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
8993 t: usize,
8994 cache: &mut Cache,
8995 il: usize,
8996 want_stash: bool,
8997 ) -> Result<(CudaSlice<f32>, Option<GdnStash>), Box<dyn std::error::Error>> {
8998 let cfg = &self.cfg;
8999 let geometry = la.geometry;
9000 let d_state = geometry.key_head_dim as usize;
9001 let num_k = geometry.key_heads as usize;
9002 let num_v = geometry.value_heads as usize;
9003 let d_conv = geometry.conv_kernel as usize;
9004 let key_dim = d_state * num_k;
9005 let conv_dim = key_dim * 2 + geometry.value_head_dim as usize * num_v;
9006 let eps = cfg.rms_eps;
9007 let scale = 1.0 / (d_state as f32).sqrt();
9008
9009 // DECODE-EXACT projections: matmul_decode_exact forces the MMVQ (warp-per-row, 32-thread)
9010 // accumulation order for EVERY m, matching the T=1 decode path bit-for-bit. The generic
9011 // `matmul` at m>=5 falls to dp4a (128-thread, two-level reduce) which has a different FP
9012 // sum order — ULP differences propagate through gdn_scan and flip argmax on the 27B.
9013 // Q8 TRUNK-FUSION at T=1 (35B: wqkv+wqkv_gate both Q8_0): one fused2 launch, bit-identical
9014 // per (tensor,row) to the two m=1 MMVQ dispatches below — decode-exact contract holds.
9015 // VERIFY-TIER TRUNK FUSION (MEMRA_SPEC_FUSED_T, t=2-4): quantize h ONCE for every
9016 // fused-eligible same-input Q8_0 pair of this layer (35B wqkv+wqkv_gate; 9B
9017 // ssm_beta+ssm_alpha) — each fused2 batched launch then replaces two decode-exact
9018 // calls (each of which re-quantizes the same h + runs its own _b2/_b4 launch).
9019 // Bit-identical per (tensor,token,row) — see spec_fused_t().
9020 // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): `h_q8` = the attn-input norm emitted
9021 // directly as q8_1 by the caller's fused rms_norm_q8_1 (bit-identical to the unfused
9022 // chain, kernel-check-pinned). When present it REPLACES the standalone quantize below
9023 // and feeds every projection; the caller guaranteed all four input projections are
9024 // q8_1-fast. When absent, the old shared-quantize (fused-t window) stands.
9025 let h_q8_t = if h_q8.is_none()
9026 && spec_fused_t()
9027 && (2..=4).contains(&t)
9028 && ((e.uses_q8_1_fast(&la.wqkv) && e.uses_q8_1_fast(&la.wqkv_gate))
9029 || (e.uses_q8_1_fast(&la.ssm_beta) && e.uses_q8_1_fast(&la.ssm_alpha)))
9030 {
9031 Some(e.quantize_q8_1(h, t, cfg.n_embd as usize)?)
9032 } else {
9033 None
9034 };
9035 // one view: the caller's fused-norm q8 or this fn's own shared quantize.
9036 let hq8_any: Option<(&CudaSlice<i8>, &CudaSlice<f32>)> =
9037 h_q8.or(h_q8_t.as_ref().map(|(q, d)| (q, d)));
9038 let (qkv_mixed, z) = {
9039 let mut fused = None;
9040 if t == 1 && e.uses_q8_1_fast(&la.wqkv) && e.uses_q8_1_fast(&la.wqkv_gate) {
9041 let (hq, hd) = e.quantize_q8_1(h, 1, cfg.n_embd as usize)?;
9042 fused = e.matmul_q8_fused2(&la.wqkv, &la.wqkv_gate, &hq, &hd)?;
9043 } else if let Some((hq, hd)) = hq8_any
9044 && spec_fused_t()
9045 && (2..=4).contains(&t)
9046 {
9047 fused = e.matmul_q8_fused2_t(&la.wqkv, &la.wqkv_gate, hq, hd, t)?;
9048 }
9049 match (fused, hq8_any) {
9050 (Some(pair), _) => pair,
9051 (None, Some((hq, hd))) if h_q8.is_some() => (
9052 e.matmul_decode_exact_pre(&la.wqkv, hq, hd, t)?,
9053 e.matmul_decode_exact_pre(&la.wqkv_gate, hq, hd, t)?,
9054 ),
9055 (None, _) => (
9056 e.matmul_decode_exact(&la.wqkv, h, t)?,
9057 e.matmul_decode_exact(&la.wqkv_gate, h, t)?,
9058 ),
9059 }
9060 };
9061 // beta+alpha DUAL at T=1 (75% of p3 rounds run T=1 verify — p-min chain cuts): the dual
9062 // mr2 kernel is bit-identical per element to the m=1 MMVQ matmul_decode_exact dispatches
9063 // (same warp-per-row body, blockIdx.y picks the weight), so the decode-exact contract
9064 // holds; the run-spec battery is the arbiter. T>1 keeps the per-tensor decode-exact path.
9065 let (beta_raw, alpha) = if t == 1 {
9066 let (hq, hd) = e.quantize_q8_1(h, 1, cfg.n_embd as usize)?;
9067 match e.matmul_pre_dual_noscale(&la.ssm_beta, &la.ssm_alpha, &hq, &hd, 1)? {
9068 Some(((mut b, bs), (mut a, as_))) => {
9069 if bs != 1.0 {
9070 e.scale_inplace(&mut b, bs, la.ssm_beta.out_features())?;
9071 }
9072 if as_ != 1.0 {
9073 e.scale_inplace(&mut a, as_, la.ssm_alpha.out_features())?;
9074 }
9075 (b, a)
9076 }
9077 // Q8_0 fused2 twin (9B stores beta/alpha as Q8_0): DISPATCH-MIRRORS the eager
9078 // decode's beta_alpha closure — the fused body is qmatvec_q8_0_mmvq verbatim,
9079 // bit-identical per row (kernel-check rel=0.00e0 gate), so decode==verify holds.
9080 None => match e.matmul_q8_fused2(&la.ssm_beta, &la.ssm_alpha, &hq, &hd)? {
9081 Some((b, a)) => (b, a),
9082 None => (
9083 e.matmul_decode_exact(&la.ssm_beta, h, 1)?,
9084 e.matmul_decode_exact(&la.ssm_alpha, h, 1)?,
9085 ),
9086 },
9087 }
9088 } else {
9089 // fused-t twin (9B stores beta/alpha as Q8_0): same shared-quantize + one launch
9090 // contract as the wqkv pair above; 35B beta/alpha are Float -> None -> fallback.
9091 let mut nvfp4_fused = None;
9092 let mut q8_fused = None;
9093 if let Some((hq, hd)) = hq8_any {
9094 if t == 3 && std::env::var("MEMRA_NVFP4_AUX_DUAL").as_deref() != Ok("0") {
9095 nvfp4_fused =
9096 e.matmul_decode_exact_dual_pre(&la.ssm_beta, &la.ssm_alpha, hq, hd, t)?;
9097 if nvfp4_fused.is_some() && std::env::var("MEMRA_DEBUG").is_ok() {
9098 static ONCE: std::sync::Once = std::sync::Once::new();
9099 ONCE.call_once(|| {
9100 eprintln!("[memra] NVFP4 beta+alpha batched aux dual ENGAGED (t={t})")
9101 });
9102 }
9103 }
9104 if nvfp4_fused.is_none() && spec_fused_t() && (2..=4).contains(&t) {
9105 q8_fused = e.matmul_q8_fused2_t(&la.ssm_beta, &la.ssm_alpha, hq, hd, t)?;
9106 }
9107 }
9108 if let Some(((mut b, bs), (mut a, as_))) = nvfp4_fused {
9109 if bs != 1.0 {
9110 e.scale_inplace(&mut b, bs, t * la.ssm_beta.out_features())?;
9111 }
9112 if as_ != 1.0 {
9113 e.scale_inplace(&mut a, as_, t * la.ssm_alpha.out_features())?;
9114 }
9115 (b, a)
9116 } else if let Some(pair) = q8_fused {
9117 pair
9118 } else {
9119 match hq8_any {
9120 Some((hq, hd)) if h_q8.is_some() => (
9121 e.matmul_decode_exact_pre(&la.ssm_beta, hq, hd, t)?,
9122 e.matmul_decode_exact_pre(&la.ssm_alpha, hq, hd, t)?,
9123 ),
9124 _ => (
9125 e.matmul_decode_exact(&la.ssm_beta, h, t)?,
9126 e.matmul_decode_exact(&la.ssm_alpha, h, t)?,
9127 ),
9128 }
9129 }
9130 };
9131
9132 // conv with CARRIED state + ring roll (T >= pad rides the input-column update kernel;
9133 // T < pad — the MEMRA_SPEC_M2 t=2 arm — rolls via the pure-copy ring rebuild).
9134 let rl = cache.recur[il].as_mut().unwrap();
9135 let mut conv_out = e.uninit(conv_dim * t)?;
9136 e.ssm_conv1d_tm_state(
9137 &qkv_mixed,
9138 &mut rl.conv_state,
9139 la.ssm_conv1d.float_data(),
9140 &mut conv_out,
9141 conv_dim,
9142 t,
9143 d_conv,
9144 )?;
9145
9146 // GDN prep via the prefill kernels (repack + L2 + sigmoid + glog), T-wide.
9147 let mut q_g = e.uninit(d_state * num_v * t)?;
9148 let mut k_g = e.uninit(d_state * num_v * t)?;
9149 let mut v_g = e.uninit(d_state * num_v * t)?;
9150 e.qkv_to_gdn_repack(
9151 &conv_out, &mut q_g, &mut k_g, &mut v_g, d_state, num_v, num_k, key_dim, t,
9152 )?;
9153 let mut q_l2 = e.uninit(d_state * num_v * t)?;
9154 e.l2_norm_decode(&q_g, &mut q_l2, d_state, num_v * t, eps)?;
9155 let mut k_l2 = e.uninit(d_state * num_v * t)?;
9156 e.l2_norm_decode(&k_g, &mut k_l2, d_state, num_v * t, eps)?;
9157 let mut beta = e.uninit(t * num_v)?;
9158 e.sigmoid(&beta_raw, &mut beta, t * num_v)?;
9159 let mut g_log = e.uninit(t * num_v)?;
9160 e.gdn_glog(
9161 &alpha,
9162 la.ssm_dt.float_data(),
9163 la.ssm_a.float_data(),
9164 &mut g_log,
9165 num_v,
9166 t,
9167 )?;
9168
9169 // ONE gdn_scan over T tokens from the carried state (internal sequential loop ==
9170 // T chained T=1 steps). Ping-pong the resident buffers like eager decode.
9171 let mut o = e.uninit(d_state * num_v * t)?;
9172 {
9173 let crate::cache::RecurLayer {
9174 ssm_state,
9175 ssm_state_alt,
9176 ..
9177 } = rl;
9178 e.gdn_scan_s128(
9179 &q_l2,
9180 &k_l2,
9181 &v_g,
9182 &g_log,
9183 &beta,
9184 ssm_state,
9185 ssm_state_alt,
9186 &mut o,
9187 num_v,
9188 t,
9189 scale,
9190 )?;
9191 }
9192 std::mem::swap(&mut rl.ssm_state, &mut rl.ssm_state_alt);
9193
9194 // gated RMSNorm + out projection, T-wide. FUSED-QUANTIZE ARM (lane/vt-fixes fix 2,
9195 // mirroring the T=1 decode's launch-arc form): when ssm_out rides the q8_1 fast path,
9196 // emit q8_1 straight from the gated norm at nrows=num_v*t (row-indexed kernel, the
9197 // T-wide launch is the per-row program; kernel-check pins bit-identity vs
9198 // gated_rmsnorm -> quantize_q8_1 at T=1 and T=5) and feed the decode-exact dispatch
9199 // pre-quantized — one launch replaces norm + quantize. Fallback = the f32 chain.
9200 let out = if e.uses_q8_1_fast(&la.ssm_out) {
9201 let (gq, gd) =
9202 e.gated_rmsnorm_q8_1(&o, la.ssm_norm.float_data(), &z, d_state, num_v * t, eps)?;
9203 e.matmul_decode_exact_pre(&la.ssm_out, &gq, &gd, t)?
9204 } else {
9205 let mut gn = e.uninit(d_state * num_v * t)?;
9206 e.gated_rmsnorm(
9207 &o,
9208 la.ssm_norm.float_data(),
9209 &z,
9210 &mut gn,
9211 d_state,
9212 num_v * t,
9213 eps,
9214 )?;
9215 // DECODE-EXACT out-projection: same MMVQ path as the T=1 decode (ssm_out at m>=5
9216 // would fall to dp4a with a different FP reduction order — same class of bug as
9217 // the input projs).
9218 e.matmul_decode_exact(&la.ssm_out, &gn, t)?
9219 };
9220 let stash = if want_stash {
9221 Some(GdnStash {
9222 qkv_mixed,
9223 q_l2,
9224 k_l2,
9225 v_g,
9226 g_log,
9227 beta,
9228 })
9229 } else {
9230 None
9231 };
9232 Ok((out, stash))
9233 }
9234
9235 /// REPLAY-FREE partial-accept commit (2026-07-03): make the cache state == "committed through
9236 /// the first `j` verify columns" WITHOUT the legacy rollback + duplicate trunk replay.
9237 /// - Full-attn KV: truncate both the owning-stage shadow and every TP rank to snapshot + j.
9238 /// The verify's appended rows for those columns are bit-identical to what an eager T=1
9239 /// chain writes (the decode-exact contract the verify-probe gates), so keeping them ==
9240 /// replaying them.
9241 /// - Linear layers, batched path: rebuild the conv ring by PURE COPIES (ring holds raw input
9242 /// columns) and the ssm state by a prefix re-run of the SAME gdn_scan kernel (t=j) from the
9243 /// snapshot state over the stash's identical inputs — the kernel's t-loop carries state in
9244 /// registers and writes it once at the end, so iterations 0..j-1 are independent of T:
9245 /// bit-identical to the verify's own state after j tokens == the eager chain state.
9246 /// - Linear layers, per-column path: restore the cloned actual state after column j-1.
9247 /// Caller guarantees 1 <= j <= t-1 (j==0 rounds take the legacy rollback; j==t is full accept).
9248 #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
9249 fn commit_verified_prefix(
9250 &self,
9251 e: &Engine,
9252 cache: &mut Cache,
9253 snap: &crate::cache::CacheSnapshot,
9254 ckpt: &VerifyCkpt,
9255 j: usize,
9256 kv_lens_done: bool,
9257 dev_j: Option<(&CudaSlice<u32>, usize, usize)>,
9258 ) -> Result<(), Box<dyn std::error::Error>> {
9259 // GDN geometry derives lazily inside recurrent-layer arms. Full-attention plans carry no
9260 // recurrent state and must never be forced through a synthetic SSM geometry.
9261 // Engine-bundle slice 1 (DSF-ROUNDCOST-20260820 §1.1): the per-column-arm restores
9262 // are 2 tiny D2D copies per linear layer (~96 dispatches/partial round on the q38
9263 // route). When every cols-arm layer shares uniform state sizes (single ssm cfg —
9264 // always true today), batch them into two `copy_batch_uniform_f32` launches. Bytes,
9265 // buffers and stream order are identical to the per-layer memcpy sequence; the
9266 // kernel-rebuild (gdn-stash) arm below is untouched. MEMRA_STATE_COPY_BATCH=0 reverts.
9267 let mut batched_cols = false;
9268 if state_copy_batch_on() && dev_j.is_none() {
9269 use cudarc::driver::DevicePtr;
9270 let s = &e.gpu.stream();
9271 let mut conv_pairs: Vec<(u64, u64)> = Vec::new();
9272 let mut ssm_pairs: Vec<(u64, u64)> = Vec::new();
9273 let (mut conv_words, mut ssm_words) = (0usize, 0usize);
9274 let mut uniform = true;
9275 for il in 0..self.layers.len() {
9276 let Some(rl) = cache.recur[il].as_ref() else {
9277 continue;
9278 };
9279 if ckpt.gdn[il].is_some() {
9280 continue; // kernel-rebuild arm restores below, per layer
9281 }
9282 let Some(cols) = &ckpt.cols[il] else {
9283 continue; // missing-ckpt error surfaces in the main loop
9284 };
9285 let (c, st) = &cols[j - 1];
9286 if conv_pairs.is_empty() {
9287 conv_words = c.len();
9288 ssm_words = st.len();
9289 } else if c.len() != conv_words || st.len() != ssm_words {
9290 uniform = false;
9291 break;
9292 }
9293 let (pc, _g0) = c.device_ptr(s);
9294 let (dc, _g1) = rl.conv_state.device_ptr(s);
9295 let (ps, _g2) = st.device_ptr(s);
9296 let (ds, _g3) = rl.ssm_state.device_ptr(s);
9297 conv_pairs.push((pc, dc));
9298 ssm_pairs.push((ps, ds));
9299 }
9300 if uniform && !conv_pairs.is_empty() {
9301 let n = conv_pairs.len();
9302 let mut t = vec![0u64; 2 * n];
9303 for (k, &(src, dst)) in conv_pairs.iter().enumerate() {
9304 t[k] = src;
9305 t[n + k] = dst;
9306 }
9307 let conv_t = e.htod_u64(&t)?;
9308 for (k, &(src, dst)) in ssm_pairs.iter().enumerate() {
9309 t[k] = src;
9310 t[n + k] = dst;
9311 }
9312 let ssm_t = e.htod_u64(&t)?;
9313 e.copy_batch_uniform_f32(&conv_t, n, conv_words)?;
9314 e.copy_batch_uniform_f32(&ssm_t, n, ssm_words)?;
9315 batched_cols = true;
9316 }
9317 }
9318 rewind_tp_kv_verified_prefix(&mut cache.tp_kv, &snap.tp_kv_len, j)?;
9319 for il in 0..self.layers.len() {
9320 if let (Some(kvl), Some(saved)) = (cache.kv[il].as_mut(), snap.kv_len[il]) {
9321 kvl.len = saved + j;
9322 // devacc 3a: spec_rollback_kv already wrote len_d on-device (same value).
9323 if !kv_lens_done {
9324 e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
9325 }
9326 }
9327 if let Some(rl) = cache.recur[il].as_mut() {
9328 let Mixer::Linear(linear) = &self.layers[il].mixer else {
9329 return Err(format!("recurrent cache layer {il} has no GDN plan").into());
9330 };
9331 let geometry = linear.geometry;
9332 let d_state = geometry.key_head_dim as usize;
9333 let num_k = geometry.key_heads as usize;
9334 let num_v = geometry.value_heads as usize;
9335 let d_conv = geometry.conv_kernel as usize;
9336 let conv_dim = d_state * num_k * 2 + geometry.value_head_dim as usize * num_v;
9337 let scale = 1.0 / (d_state as f32).sqrt();
9338 if let Some(st) = &ckpt.gdn[il] {
9339 let ring_old = snap.conv[il].as_ref().expect("snapshot missing conv");
9340 let state_in = snap.ssm[il].as_ref().expect("snapshot missing ssm");
9341 if let Some((acc, base, t_v)) = dev_j {
9342 // 3b: j read on-device (_dc twins, same bodies; full accept early-exits).
9343 e.ssm_conv_ring_rebuild_dc(
9344 &st.qkv_mixed,
9345 ring_old,
9346 &mut rl.conv_state,
9347 conv_dim,
9348 acc,
9349 base,
9350 t_v,
9351 d_conv,
9352 )?;
9353 let mut o = e.uninit(d_state * num_v * j.max(1))?;
9354 e.gdn_scan_s128_dc(
9355 &st.q_l2,
9356 &st.k_l2,
9357 &st.v_g,
9358 &st.g_log,
9359 &st.beta,
9360 state_in,
9361 &mut rl.ssm_state,
9362 &mut o,
9363 num_v,
9364 acc,
9365 base,
9366 t_v,
9367 scale,
9368 )?;
9369 } else {
9370 e.ssm_conv_ring_rebuild(
9371 &st.qkv_mixed,
9372 ring_old,
9373 &mut rl.conv_state,
9374 conv_dim,
9375 j,
9376 d_conv,
9377 )?;
9378 let mut o = e.uninit(d_state * num_v * j)?; // scan output, discarded
9379 e.gdn_scan_s128(
9380 &st.q_l2,
9381 &st.k_l2,
9382 &st.v_g,
9383 &st.g_log,
9384 &st.beta,
9385 state_in,
9386 &mut rl.ssm_state,
9387 &mut o,
9388 num_v,
9389 j,
9390 scale,
9391 )?;
9392 }
9393 } else if let Some(cols) = &ckpt.cols[il] {
9394 if !batched_cols {
9395 let (c, s) = &cols[j - 1];
9396 e.copy_into(&mut rl.conv_state, 0, c, c.len())?;
9397 e.copy_into(&mut rl.ssm_state, 0, s, s.len())?;
9398 }
9399 } else {
9400 return Err(
9401 "commit_verified_prefix: verify ckpt missing for linear layer".into(),
9402 );
9403 }
9404 }
9405 }
9406 cache.pos = snap.pos + j;
9407 Ok(())
9408 }
9409
9410 /// ROUND-STREAM: recur restore with device-j (the _dc twins; full accept early-exits
9411 /// in-kernel). Requires the batched-linear stash on every linear layer (stream gate).
9412 #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
9413 fn commit_verified_prefix_stream(
9414 &self,
9415 e: &Engine,
9416 cache: &mut Cache,
9417 snap: &crate::cache::CacheSnapshot,
9418 ckpt: &VerifyCkpt,
9419 acc: &CudaSlice<u32>,
9420 base: usize,
9421 t_v: usize,
9422 ) -> Result<(), Box<dyn std::error::Error>> {
9423 for il in 0..self.layers.len() {
9424 if let Some(rl) = cache.recur[il].as_mut() {
9425 let Mixer::Linear(linear) = &self.layers[il].mixer else {
9426 return Err(format!("recurrent cache layer {il} has no GDN plan").into());
9427 };
9428 let geometry = linear.geometry;
9429 let d_state = geometry.key_head_dim as usize;
9430 let num_k = geometry.key_heads as usize;
9431 let num_v = geometry.value_heads as usize;
9432 let d_conv = geometry.conv_kernel as usize;
9433 let conv_dim = d_state * num_k * 2 + geometry.value_head_dim as usize * num_v;
9434 let scale = 1.0 / (d_state as f32).sqrt();
9435 let st = ckpt.gdn[il]
9436 .as_ref()
9437 .ok_or("stream restore: batched-linear stash missing")?;
9438 let ring_old = snap.conv[il].as_ref().expect("snapshot missing conv");
9439 let state_in = snap.ssm[il].as_ref().expect("snapshot missing ssm");
9440 e.ssm_conv_ring_rebuild_dc(
9441 &st.qkv_mixed,
9442 ring_old,
9443 &mut rl.conv_state,
9444 conv_dim,
9445 acc,
9446 base,
9447 t_v,
9448 d_conv,
9449 )?;
9450 let mut o = e.uninit(d_state * num_v * t_v)?;
9451 e.gdn_scan_s128_dc(
9452 &st.q_l2,
9453 &st.k_l2,
9454 &st.v_g,
9455 &st.g_log,
9456 &st.beta,
9457 state_in,
9458 &mut rl.ssm_state,
9459 &mut o,
9460 num_v,
9461 acc,
9462 base,
9463 t_v,
9464 scale,
9465 )?;
9466 }
9467 }
9468 Ok(())
9469 }
9470
9471 /// EAGLE3 aux-capturing verify forward over `tokens` (T) — mirrors `decode_step_t_h` exactly
9472 /// (same KV append, same causal verify, same recur advance) but ALSO clones the aux residual-
9473 /// stream hiddens (blocks in `aux_layers`) for TWO columns: the LAST column (always) and the
9474 /// optional `pred_col` (the EAGLE seed = bonus's predecessor). Returns
9475 /// (all_T_logits host, last_col_aux, pred_col_aux?). Used by the EAGLE3 orchestrator's commit.
9476 #[allow(clippy::type_complexity)] // allow: one-shot composite type; naming it would hide the shape that matters at the call site
9477 pub fn decode_step_t_aux2(
9478 &self,
9479 e: &Engine,
9480 tokens: &[u32],
9481 pos0: usize,
9482 cache: &mut Cache,
9483 aux_layers: &[usize],
9484 pred_col: Option<usize>,
9485 ) -> Result<
9486 (Vec<f32>, Vec<CudaSlice<f32>>, Option<Vec<CudaSlice<f32>>>),
9487 Box<dyn std::error::Error>,
9488 > {
9489 cache.ensure_usable("decode_step_t_aux2")?;
9490 let cfg = &self.cfg;
9491 let n_embd = cfg.n_embd as usize;
9492 let eps = cfg.rms_eps;
9493 let t = tokens.len();
9494 let pos_vec: Vec<i32> = (0..t).map(|i| (pos0 + i) as i32).collect();
9495 let pos_d = e.htod_i32(&pos_vec)?;
9496 let mut x = e.htod(&self.embd.gather(n_embd, tokens))?;
9497 let mut aux_last: Vec<CudaSlice<f32>> = Vec::with_capacity(aux_layers.len());
9498 let mut aux_pred: Vec<CudaSlice<f32>> = Vec::new();
9499 let want_pred = pred_col.is_some();
9500
9501 for (il, layer) in self.layers.iter().enumerate() {
9502 // DISPATCH-MIRRORED norms (FP-order lesson #8) — see decode_step_t_h_emb.
9503 let mixer_fast = self.mixer_in_q8_1_fast(e, &layer.mixer);
9504 let norm_fused = std::env::var("MEMRA_NO_FUSE_NORMQ").is_err() && mixer_fast;
9505 let mut h = vbuf(e, t * n_embd)?; // fully written by either rms_norm arm
9506 if norm_fused {
9507 e.rms_norm_decode(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
9508 } else {
9509 e.rms_norm(&x, layer.attn_norm.float_data(), &mut h, n_embd, t, eps)?;
9510 }
9511 let mixed = match &layer.mixer {
9512 Mixer::Full(fa) => {
9513 self.full_attn_verify(e, fa, &h, None, &pos_d, t, cache, il, None)?
9514 }
9515 Mixer::Mla(_) => {
9516 crate::hybrid::mla_path_unimplemented("auxiliary T-parallel decode")
9517 }
9518 Mixer::Kda(_) => crate::hybrid::kda_path_unimplemented("aux decode step"),
9519 Mixer::Linear(la) => {
9520 let mut out = e.zeros(t * n_embd)?;
9521 for col in 0..t {
9522 let mut h_col = e.zeros(n_embd)?;
9523 let src = h.slice(col * n_embd..(col + 1) * n_embd);
9524 e.copy_view_into(&mut h_col, 0, &src, n_embd)?;
9525 let m_col = self.linear_attn_decode(e, la, &h_col, cache, il)?;
9526 e.copy_into(&mut out, col * n_embd, &m_col, n_embd)?;
9527 }
9528 out
9529 }
9530 };
9531 let ffn_fuse = match &layer.ffn {
9532 crate::hybrid::Ffn::Dense {
9533 ffn_gate, ffn_up, ..
9534 } => {
9535 std::env::var("MEMRA_NO_FUSE_NORMQ").is_err()
9536 && e.uses_q8_1_fast(ffn_gate)
9537 && e.uses_q8_1_fast(ffn_up)
9538 }
9539 crate::hybrid::Ffn::Moe(_) => false,
9540 };
9541 let mut x1 = vbuf(e, t * n_embd)?; // fully written by add / add_rms_norm
9542 let mut z = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode / add_rms_norm
9543 if ffn_fuse {
9544 e.add(&x, &mixed, &mut x1, t * n_embd)?;
9545 e.rms_norm_decode(
9546 &x1,
9547 layer.post_attn_norm.float_data(),
9548 &mut z,
9549 n_embd,
9550 t,
9551 eps,
9552 )?;
9553 } else {
9554 e.add_rms_norm(
9555 &x,
9556 &mixed,
9557 layer.post_attn_norm.float_data(),
9558 &mut x1,
9559 &mut z,
9560 n_embd,
9561 t,
9562 eps,
9563 )?;
9564 }
9565 let ffn_out = match &layer.ffn {
9566 crate::hybrid::Ffn::Dense {
9567 ffn_gate,
9568 ffn_up,
9569 ffn_down,
9570 } => {
9571 let n_ff = ffn_gate.out_features();
9572 let gate = e.matmul_decode_exact(ffn_gate, &z, t)?;
9573 let up = e.matmul_decode_exact(ffn_up, &z, t)?;
9574 let mut act = vbuf(e, t * n_ff)?; // fully written by ffn_act_lim
9575 // dense FFN clamp = the SHEXP array (upstream build_ffn serves both).
9576 Self::ffn_act_lim(
9577 e,
9578 &self.cfg,
9579 &gate,
9580 &up,
9581 1.0,
9582 1.0,
9583 self.cfg.clamp_shexp_at(il as u32),
9584 &mut act,
9585 t * n_ff,
9586 )?;
9587 e.matmul_decode_exact(ffn_down, &act, t)?
9588 }
9589 crate::hybrid::Ffn::Moe(m) => self.moe_ffn_il(e, m, &z, t, il as u16)?,
9590 };
9591 let mut x2 = vbuf(e, t * n_embd)?; // fully written by add
9592 e.add(&x1, &ffn_out, &mut x2, t * n_embd)?;
9593 if aux_layers.contains(&il) {
9594 let mut a = e.zeros(n_embd)?;
9595 e.copy_view_into(&mut a, 0, &x2.slice((t - 1) * n_embd..t * n_embd), n_embd)?;
9596 aux_last.push(a);
9597 if let Some(pc) = pred_col {
9598 let mut ap = e.zeros(n_embd)?;
9599 e.copy_view_into(
9600 &mut ap,
9601 0,
9602 &x2.slice(pc * n_embd..(pc + 1) * n_embd),
9603 n_embd,
9604 )?;
9605 aux_pred.push(ap);
9606 }
9607 }
9608 x = x2;
9609 }
9610 let mut hn = vbuf(e, t * n_embd)?; // fully written by rms_norm_decode
9611 e.rms_norm_decode(&x, self.output_norm.float_data(), &mut hn, n_embd, t, eps)?;
9612 let logits = e.matmul_decode_exact(&self.output, &hn, t)?;
9613 let host = e.dtoh(&logits)?;
9614 cache.pos += t;
9615 Ok((
9616 host,
9617 aux_last,
9618 if want_pred { Some(aux_pred) } else { None },
9619 ))
9620 }
9621
9622 /// step35 SPEC-VERIFY attention over T query tokens — a per-row REPLAY of the eager
9623 /// `step35_decode_attn`.
9624 ///
9625 /// WHY A REPLAY AND NOT A BATCHED TWIN. The verify's whole job is to be bit-identical to what
9626 /// the eager decode would have computed for the same tokens; that is what makes greedy spec
9627 /// decode exact (run-spec asserts token identity for K=1..8). Every other verify arm in this
9628 /// file earns that identity by carefully mirroring dispatch (`matmul_decode_exact` to force
9629 /// MMVQ at any m, per-layer `ffn_fuse` mirroring, per-row `fa_decode` key bounds). step35
9630 /// stacks FOUR more per-layer degrees of freedom on top of that — per-layer `n_head`
9631 /// (64 full / 96 SWA), per-layer rotary width (64 full / 128 SWA), per-layer rope base, and a
9632 /// SEPARATE `attn_gate` tensor whose projection shares the attn-normed input — and its SWA
9633 /// layers attend through a token-OFFSET view whose offset is a function of the ABSOLUTE
9634 /// position of each query row. A batched twin would have to reproduce all of that AND the
9635 /// per-row offset in one launch; the offset alone rules out the existing rows kernels (they
9636 /// take one `base_len`, not a per-row offset).
9637 ///
9638 /// So this arm calls the eager path itself, once per row, on the same cache. Identity is then
9639 /// true BY CONSTRUCTION rather than by mirroring: row r runs exactly the kernel sequence that
9640 /// eager decode step r runs (same projections, same q8_1 fusion decision, same append, same
9641 /// view arithmetic, same `fa_decode_kvmod`, same gate), because it IS that code. Cost: T x the
9642 /// eager decode mixer instead of one batched pass — the same trade the generic arm's `else`
9643 /// per-row loop already accepts when `fa_rows_eligible` says no. Correctness first; a batched
9644 /// step35 twin is a perf lane's job and must be gated against this arm.
9645 ///
9646 /// The `h_q8` pre-quantized pair from the caller's fused norm is NOT forwarded: it is a
9647 /// T-row buffer and `step35_decode_attn`'s `pre_q` contract is one row. Instead each row's
9648 /// f32 `h` slice is handed over and the callee re-derives its own q8_1 exactly as eager decode
9649 /// does (`quantize_q8_1(h, 1, n_embd)`) — which is the dispatch being mirrored. Callers that
9650 /// took the fused arm therefore MUST still pass a live `h`; `step35_verify` asserts that.
9651 #[allow(clippy::too_many_arguments)]
9652 fn step35_verify(
9653 &self,
9654 e: &Engine,
9655 fa: &FullAttnLayer,
9656 h: &CudaSlice<f32>,
9657 h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
9658 t: usize,
9659 cache: &mut Cache,
9660 il: usize,
9661 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
9662 let n_embd = self.cfg.n_embd as usize;
9663 // The fused (h-less) attn-norm arm hands `h` as a zero-length placeholder. This arm needs
9664 // the f32 rows, so the caller must not take that lever for step35 — enforced at the call
9665 // site by the sliding-gated-MoE `Mixer::Full(_) => false` arm of
9666 // `lin_q8_only` in `decode_step_t_core_stream`, and asserted here so a future caller
9667 // cannot regress it into silently reading an empty buffer.
9668 assert_eq!(
9669 h.len(),
9670 t * n_embd,
9671 "step35_verify needs the f32 attn-normed rows ([t*n_embd]); the caller took the \
9672 fused q8-only norm arm (h_q8={}) — step35 must stay on the unfused arm",
9673 h_q8.is_some()
9674 );
9675 // ROW WIDTH IS n_embd, NOT n_head*head_dim: `step35_decode_attn` returns the mixer output
9676 // AFTER `wo`, so a row is [n_embd] — the same contract the generic arm's
9677 // `matmul_decode_exact(&fa.wo, &attn_g, t)` return has. Sizing this buffer from the
9678 // per-layer head geometry (8192 on full-attn, 12288 on SWA) instead overran the row on the
9679 // FIRST copy and panicked inside `copy_into`'s `CudaView::slice` unwrap
9680 // (raw/mtp-bt-20260806T212127Z.log frames 12-13).
9681 let mut out = vbuf(e, t * n_embd)?; // each row fully written by the copy below
9682 for r in 0..t {
9683 // Absolute position of this query row. `cache.pos` is the committed length at round
9684 // start and every row before r has already been appended by this loop, so the r-th
9685 // verify token sits at cache.pos + r — the same position eager decode would give it.
9686 let pos_d = e.htod_i32(&[(cache.pos + r) as i32])?;
9687 let mut h_row = vbuf(e, n_embd)?; // fully written by copy_view_into
9688 e.copy_view_into(
9689 &mut h_row,
9690 0,
9691 &h.slice(r * n_embd..(r + 1) * n_embd),
9692 n_embd,
9693 )?;
9694 // THE eager decode mixer: appends this row's K/V at kvl.len, advances it, then
9695 // attends over the (SWA-offset) view. Post-`wo`, same contract as this fn returns.
9696 let o = self.step35_decode_attn(e, fa, il, &h_row, None, &pos_d, cache)?;
9697 debug_assert_eq!(
9698 o.len(),
9699 n_embd,
9700 "step35_decode_attn returns post-wo [n_embd]"
9701 );
9702 e.copy_into(&mut out, r * n_embd, &o, n_embd)?;
9703 }
9704 Ok(out)
9705 }
9706
9707 /// Full-attention mixer over T query tokens with a GROWING resident KV (verify path, §D.3).
9708 /// Appends the T new K/V columns to cache.kv[il] then attends causally over [0..len) via
9709 /// fa_prefill. Token-major [T, kv_dim] projection layout == cache row layout (single copy).
9710 #[allow(clippy::too_many_arguments)]
9711 fn full_attn_verify(
9712 &self,
9713 e: &Engine,
9714 fa: &FullAttnLayer,
9715 h: &CudaSlice<f32>,
9716 h_q8: Option<(&CudaSlice<i8>, &CudaSlice<f32>)>,
9717 pos_d: &CudaSlice<i32>,
9718 t: usize,
9719 cache: &mut Cache,
9720 il: usize,
9721 stream_ctr: Option<&CudaSlice<i32>>,
9722 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
9723 // step35: the generic geometry below is wrong for this arch (per-layer n_head, partial
9724 // per-layer rope, the SWA offset view, and a SEPARATE head-wise gate tensor), so it takes
9725 // its own arm. A verify that silently computes different attention than decode defeats the
9726 // whole self-consistency gate, so the arm is a per-row REPLAY of `step35_decode_attn`
9727 // rather than a batched twin — see `step35_verify` for why that is the exactness-correct
9728 // shape and not laziness.
9729 if self.sliding_gated_moe_batch_program() {
9730 if stream_ctr.is_some() {
9731 return Err(
9732 "step35 has no ROUND-STREAM verify arm (the device-counter _dc twins \
9733 cannot express the SWA offset KV view; same root cause as the dc \
9734 decode refusal) — run spec without the stream arm"
9735 .into(),
9736 );
9737 }
9738 return self.step35_verify(e, fa, h, h_q8, t, cache, il);
9739 }
9740 let cfg = &self.cfg;
9741 let geometry = cfg.full_attention_geometry_at(il as u32);
9742 let n_head = geometry.n_head as usize;
9743 let n_head_kv = geometry.n_head_kv as usize;
9744 let head_dim = geometry.head_dim_k as usize;
9745 let eps = cfg.rms_eps;
9746 let scale = geometry.attention_scale();
9747 let n_embd = cfg.n_embd as usize;
9748
9749 // DECODE-EXACT Q/K/V projections: matmul_decode_exact forces the MMVQ (warp-per-row) path
9750 // for every m, matching the T=1 decode's FP accumulation order. matmul_pre at m>=5 would
9751 // fall to dp4a (128-thread, two-level reduce) with a different FP sum order.
9752 // Q8 TRUNK-FUSION at T=1: DISPATCH-MIRRORS the eager decode's fused3 (bit-identical body).
9753 // BATCHED EPILOGUE RE-FUSE (lane/vt-fixes fix 2): `h_q8` = the attn-input norm's q8_1
9754 // form emitted by the fused rms_norm_q8_1 (bit-identical to rms_norm_decode ->
9755 // quantize_q8_1, kernel-check-pinned). When present (caller checked mixer q8_1-fast),
9756 // every projection consumes it — `h` may be a zero-len placeholder and must not be read.
9757 let (qf, mut k, v) = if let Some(mut qkv) = self.full_attn_tp_qkv(e, fa, h, t)? {
9758 let v = qkv.pop().ok_or("full-attention TP verify QKV omitted V")?;
9759 let k = qkv.pop().ok_or("full-attention TP verify QKV omitted K")?;
9760 let q = qkv.pop().ok_or("full-attention TP verify QKV omitted Q")?;
9761 if !qkv.is_empty() {
9762 return Err("full-attention TP verify QKV returned extra projections".into());
9763 }
9764 (q, k, v)
9765 } else {
9766 let mut fused = None;
9767 let qkv_fast =
9768 e.uses_q8_1_fast(&fa.wq) && e.uses_q8_1_fast(&fa.wk) && e.uses_q8_1_fast(&fa.wv);
9769 if t == 1 && qkv_fast {
9770 let (hq_o, hd_o);
9771 let (hq, hd): (&CudaSlice<i8>, &CudaSlice<f32>) = match h_q8 {
9772 Some(p) => p,
9773 None => {
9774 (hq_o, hd_o) = e.quantize_q8_1(h, 1, n_embd)?;
9775 (&hq_o, &hd_o)
9776 }
9777 };
9778 fused = e.matmul_q8_fused3(&fa.wq, &fa.wk, &fa.wv, hq, hd)?;
9779 } else if spec_fused_t() && (2..=4).contains(&t) && qkv_fast {
9780 // VERIFY-TIER TRUNK FUSION (MEMRA_SPEC_FUSED_T): one shared quantize + one
9781 // fused3 batched launch replaces three decode-exact calls (3 re-quantizes of
9782 // the same h + 3 _b2/_b4 launches). Bit-identical per (tensor,token,row).
9783 let (hq_o, hd_o);
9784 let (hq, hd): (&CudaSlice<i8>, &CudaSlice<f32>) = match h_q8 {
9785 Some(p) => p,
9786 None => {
9787 (hq_o, hd_o) = e.quantize_q8_1(h, t, n_embd)?;
9788 (&hq_o, &hd_o)
9789 }
9790 };
9791 fused = e.matmul_q8_fused3_t(&fa.wq, &fa.wk, &fa.wv, hq, hd, t)?;
9792 }
9793 match (fused, h_q8) {
9794 (Some(triple), _) => triple,
9795 // shared pre-quantized activation (q8_1-fast guaranteed by the caller): the
9796 // decode-exact dispatch consumes (hq, hd) instead of re-quantizing 3x.
9797 (None, Some((hq, hd))) if qkv_fast => (
9798 e.matmul_decode_exact_pre(&fa.wq, hq, hd, t)?,
9799 e.matmul_decode_exact_pre(&fa.wk, hq, hd, t)?,
9800 e.matmul_decode_exact_pre(&fa.wv, hq, hd, t)?,
9801 ),
9802 (None, _) => (
9803 e.matmul_decode_exact(&fa.wq, h, t)?,
9804 e.matmul_decode_exact(&fa.wk, h, t)?,
9805 e.matmul_decode_exact(&fa.wv, h, t)?,
9806 ),
9807 }
9808 };
9809 // M3/Hy3 have no attention output gate — wq out is exactly q; skip the split.
9810 let gated = geometry.attention_gate == memra_gguf::config::AttentionGateKind::FusedQ;
9811 let (mut q, gate) = if gated {
9812 let mut q = vbuf(e, t * n_head * head_dim)?; // fully written by q_gate_split
9813 let mut gate = vbuf(e, t * n_head * head_dim)?; // fully written by q_gate_split
9814 e.q_gate_split(&qf, &mut q, &mut gate, head_dim, n_head, t)?;
9815 (q, Some(gate))
9816 } else {
9817 (qf, None)
9818 };
9819
9820 let mut qn = vbuf(e, t * n_head * head_dim)?; // fully written by rms_norm
9821 e.rms_norm(
9822 &q,
9823 fa.q_norm.float_data(),
9824 &mut qn,
9825 head_dim,
9826 n_head * t,
9827 eps,
9828 )?;
9829 q = qn;
9830 let mut kn = vbuf(e, t * n_head_kv * head_dim)?; // fully written by rms_norm
9831 e.rms_norm(
9832 &k,
9833 fa.k_norm.float_data(),
9834 &mut kn,
9835 head_dim,
9836 n_head_kv * t,
9837 eps,
9838 )?;
9839 k = kn;
9840 let rope_dims = geometry.n_rot as usize;
9841 e.rope_neox(
9842 &mut q,
9843 pos_d,
9844 head_dim,
9845 rope_dims,
9846 n_head,
9847 t,
9848 geometry.rope_base,
9849 1.0,
9850 )?;
9851 e.rope_neox(
9852 &mut k,
9853 pos_d,
9854 head_dim,
9855 rope_dims,
9856 n_head_kv,
9857 t,
9858 geometry.rope_base,
9859 1.0,
9860 )?;
9861
9862 // append T new K/V columns to the resident QUANTIZED cache. k/v are token-major [T, kv_dim]
9863 // f32; append-quantize each of the T token rows into the byte cache (q8_0 K / q5_1 V).
9864 let kvl = cache.kv[il].as_mut().unwrap();
9865 let (kv_dim_k, kv_dim_v, ktb, vtb) =
9866 (kvl.kv_dim_k, kvl.kv_dim_v, kvl.k_tok_bytes, kvl.v_tok_bytes);
9867 if let Some(ctr) = stream_ctr {
9868 // stream: ONE batched append at the device counter (rows kernel = the per-view warp
9869 // math on a (block, token) grid, documented byte-identical); host len is a stale
9870 // LOWER BOUND under pre-issue (drain reconciles it).
9871 e.append_kv_quantized_rows_dc(
9872 &k,
9873 &v,
9874 &mut kvl.k,
9875 &mut kvl.v,
9876 ctr,
9877 t,
9878 kv_dim_k,
9879 kv_dim_v,
9880 ktb,
9881 vtb,
9882 crate::Engine::kv_fp8_on(),
9883 )?;
9884 } else {
9885 for i in 0..t {
9886 let k_row = k.slice(i * kv_dim_k..(i + 1) * kv_dim_k);
9887 let v_row = v.slice(i * kv_dim_v..(i + 1) * kv_dim_v);
9888 e.append_kv_quantized_view(
9889 &k_row,
9890 &v_row,
9891 &mut kvl.k,
9892 &mut kvl.v,
9893 kvl.len + i,
9894 kv_dim_k,
9895 kv_dim_v,
9896 ktb,
9897 vtb,
9898 crate::Engine::kv_fp8_on(),
9899 )?;
9900 }
9901 kvl.len += t;
9902 }
9903
9904 // BIT-IDENTICAL VERIFY ATTENTION (spec-exactness fix): the FP accumulation order must be
9905 // byte-for-byte identical to the eager decode path. fa_prefill uses a different tile size
9906 // (BLOCK_Q=64, BK=32) and online-softmax structure than fa_decode's split-K + combine,
9907 // which changes FP summation order and can flip argmax at tight logit margins. Query row r
9908 // attends to keys [0..base_len+r+1) — each successive row sees one more key (the causal
9909 // property). This matches eager: decode appends k at len, then fa_decode sees t_kv = len+1
9910 // keys. The verify appends all T tokens first but bounds the key range per row.
9911 //
9912 // MULTI-ROW FUSED PATH (the long-ctx spec fix, 2026-07-03): when every row takes the vec
9913 // kernel (base_len+1 >= FA_VEC_MIN_TKV), ONE fa_decode_rows launch executes the exact
9914 // per-row program for all T rows (grid.z = row, per-row n_splits from the same
9915 // fa_split_keys formula) — replacing T x (2 launches + 2 dtod copies + 5 partial allocs)
9916 // and multiplying resident CTAs by T on a latency-bound kernel. Bit-identical per row by
9917 // construction; kernel-check pins rows-vs-loop byte identity, run-spec is the end gate.
9918 // Short ctx (any row below the vec crossover) and MEMRA_NO_FA_VEC/MEMRA_FA_ROWS_OFF keep the
9919 // per-row loop (whose fa_decode picks scalar/vec per row exactly like eager decode).
9920 let mut attn = vbuf(e, t * n_head * head_dim)?; // fully written by every FA arm below
9921 let base_len = kvl.len - t; // KV len BEFORE this round's T tokens were appended
9922 // T=1 INCLUDED (2026-07-05): p-min cuts the draft to 1 in ~75% of rounds on hard
9923 // (agentic) content — the old t>1 gate sent those rounds to the per-row loop (262us/row
9924 // + q-row copy + per-row allocs vs 93us/row through the fused kernel at grid.z=1, same
9925 // program). nsys accounting: 1088 of 1456 verify FA launches were T=1 escapees.
9926 // LEAN T=1 ARM (MEMRA_SPEC_LEAN, close35): at t==1, q IS one row and fa_decode on it is
9927 // the EXACT eager decode dispatch (vec_q_v2 + combine_f32; the rows pair measured +50us
9928 // at m=1). Byte-identical: kernel-check pins rows-vs-loop identity, and the per-row loop
9929 // at t=1 is fa_decode on the same q with zero-offset copies. Gates arbitrate.
9930 if let Some(ctr) = stream_ctr {
9931 // STREAM ARM: causal base from the device counter; host kvl.len is a stale lower
9932 // bound used only for the split-sizing upper bound (+64 slack covers M pre-issued
9933 // rounds at K<=8). Views span the bound; per-row limits derive in-kernel.
9934 let upper = kvl.len + t + 64;
9935 let k_view = e.view_u8(&kvl.k, (upper.min(cache.max_ctx)) * ktb);
9936 let v_view = e.view_u8(&kvl.v, (upper.min(cache.max_ctx)) * vtb);
9937 e.fa_decode_rows_dc(
9938 &q,
9939 &k_view,
9940 &v_view,
9941 &mut attn,
9942 head_dim,
9943 n_head,
9944 n_head_kv,
9945 ctr,
9946 upper.min(cache.max_ctx),
9947 t,
9948 scale,
9949 ktb,
9950 vtb,
9951 0,
9952 false,
9953 )?;
9954 } else if spec_lean() && t == 1 {
9955 let t_kv = base_len + 1;
9956 let k_view = e.view_u8(&kvl.k, t_kv * ktb);
9957 let v_view = e.view_u8(&kvl.v, t_kv * vtb);
9958 e.fa_decode_kvmod(
9959 &q,
9960 &k_view,
9961 &v_view,
9962 &mut attn,
9963 head_dim,
9964 n_head,
9965 n_head_kv,
9966 t_kv,
9967 scale,
9968 ktb,
9969 vtb,
9970 crate::Engine::kv_fp8_on(),
9971 )?;
9972 } else if e.fa_rows_eligible(base_len, head_dim) {
9973 let k_view = e.view_u8(&kvl.k, (base_len + t) * ktb);
9974 let v_view = e.view_u8(&kvl.v, (base_len + t) * vtb);
9975 e.fa_decode_rows(
9976 &q,
9977 &k_view,
9978 &v_view,
9979 &mut attn,
9980 head_dim,
9981 n_head,
9982 n_head_kv,
9983 base_len,
9984 t,
9985 scale,
9986 ktb,
9987 vtb,
9988 None,
9989 false,
9990 crate::Engine::kv_fp8_on(),
9991 None,
9992 )?;
9993 } else {
9994 for r in 0..t {
9995 let t_kv_r = base_len + r + 1; // this row sees keys [0..t_kv_r)
9996 let k_view_r = e.view_u8(&kvl.k, t_kv_r * ktb);
9997 let v_view_r = e.view_u8(&kvl.v, t_kv_r * vtb);
9998 // copy q row into an owned buffer (fa_decode takes &CudaSlice, not CudaView)
9999 let mut q_row = vbuf(e, n_head * head_dim)?; // fully written by copy_view_into
10000 let q_src = q.slice(r * n_head * head_dim..(r + 1) * n_head * head_dim);
10001 e.copy_view_into(&mut q_row, 0, &q_src, n_head * head_dim)?;
10002 let mut attn_row = vbuf(e, n_head * head_dim)?; // fully written by fa_decode
10003 e.fa_decode_kvmod(
10004 &q_row,
10005 &k_view_r,
10006 &v_view_r,
10007 &mut attn_row,
10008 head_dim,
10009 n_head,
10010 n_head_kv,
10011 t_kv_r,
10012 scale,
10013 ktb,
10014 vtb,
10015 crate::Engine::kv_fp8_on(),
10016 )?;
10017 e.copy_into(
10018 &mut attn,
10019 r * n_head * head_dim,
10020 &attn_row,
10021 n_head * head_dim,
10022 )?;
10023 }
10024 }
10025
10026 let attn_g = match &gate {
10027 Some(gate) => {
10028 let mut gsig = vbuf(e, t * n_head * head_dim)?; // fully written by sigmoid
10029 e.sigmoid(gate, &mut gsig, t * n_head * head_dim)?;
10030 let mut ag = vbuf(e, t * n_head * head_dim)?; // fully written by mul
10031 e.mul(&attn, &gsig, &mut ag, t * n_head * head_dim)?;
10032 ag
10033 }
10034 None => attn,
10035 };
10036 // DECODE-EXACT wo projection: at m>=5 (K=4+ with pending) the generic matmul would use dp4a
10037 // (128-thread, different FP sum order than MMVQ). Force MMVQ for bit-identity with decode.
10038 match self.full_attn_tp_o(e, fa, &attn_g, t)? {
10039 Some(output) => Ok(output),
10040 None => Ok(e.matmul_decode_exact(&fa.wo, &attn_g, t)?),
10041 }
10042 }
10043
10044 /// Context-linear bytes for a plain serving session's trunk cache.
10045 pub fn plain_session_kv_bytes_per_token(&self) -> usize {
10046 crate::cache::cache_bytes_per_token_for_plan(
10047 &self.cfg,
10048 &self.plan,
10049 0,
10050 self.plan.layers.len(),
10051 )
10052 }
10053
10054 /// `(logical bytes/token, ring-capped bytes/token, ring row cap)` for exact admission.
10055 pub fn plain_session_kv_shape(&self) -> (usize, usize, usize) {
10056 (
10057 self.plain_session_kv_bytes_per_token(),
10058 crate::cache::cache_ring_bytes_per_token_for_plan(
10059 &self.cfg,
10060 &self.plan,
10061 0,
10062 self.plan.layers.len(),
10063 ),
10064 crate::cache::cache_ring_row_cap_for_plan(&self.plan),
10065 )
10066 }
10067
10068 /// Context-linear bytes for a speculative serving session: trunk cache plus persistent MTP
10069 /// scratch. With no MTP head this equals the plain coefficient.
10070 pub fn spec_session_kv_bytes_per_token(&self) -> usize {
10071 let scratch = self
10072 .mtp
10073 .iter()
10074 .chain(self.mtp_extra.iter())
10075 .map(|mtp| {
10076 let (_, _, k, v) = mtp_scratch_layout(&self.cfg, mtp.geom.as_ref());
10077 k + v
10078 })
10079 .sum::<usize>();
10080 self.plain_session_kv_bytes_per_token()
10081 .saturating_add(scratch)
10082 }
10083
10084 /// Spec twin of [`HybridModel::plain_session_kv_shape`]; Step35's persistent MTP scratch is
10085 /// capped by the same SWA ring rows as the trunk.
10086 pub fn spec_session_kv_shape(&self) -> (usize, usize, usize) {
10087 let total = self.spec_session_kv_bytes_per_token();
10088 let (_, mut ring, rows) = self.plain_session_kv_shape();
10089 if rows > 0 {
10090 ring = ring.saturating_add(
10091 self.mtp
10092 .iter()
10093 .chain(self.mtp_extra.iter())
10094 .map(|mtp| {
10095 let (_, _, k, v) = mtp_scratch_layout(&self.cfg, mtp.geom.as_ref());
10096 k + v
10097 })
10098 .sum::<usize>(),
10099 );
10100 }
10101 (total, ring, rows)
10102 }
10103
10104 /// Greedy MTP speculative decode (§B). Token-identical to `generate(prompt, max_new)` but uses
10105 /// the NextN head to draft K tokens then verifies them in one batched target forward.
10106 /// Returns (generated tokens, total_drafted, total_accepted) so the caller can report
10107 /// acceptance rate. `k` = draft length per round.
10108 ///
10109 /// GRAPH DRAFT (stage 2 of graph-grade spec): when the model is all-Dense and the MTP head is
10110 /// Dense (no MoE host readbacks), the fixed-shape T=1 MTP forward is CUDA-graph-captured ONCE
10111 /// and replayed per draft step — the ~40 eager launches per drafted token collapse into one
10112 /// graph dispatch; only the 4-byte token id (and 4-byte p-min confidence) round-trip per step.
10113 /// Event tracking is disabled for the whole call (generate_graph pattern) so every buffer the
10114 /// captured graph references is event-free; the spec loop is strictly single-stream.
10115 /// MEMRA_SPEC_NOGRAPH=1 forces the eager draft chain.
10116 /// SAMPLED mode (MEMRA_SPEC_TEMP>0) has its OWN capture (gumbel-perturbed in-graph argmax,
10117 /// device Philox event counter, persistent q retention) — graph-vs-eager sampled streams are
10118 /// bit-identical for the same (seed, prompt, K, temp); see the sampled-graph setup in
10119 /// generate_spec_inner2.
10120 /// Multi-turn session: trunk cache + MTP draft scratch persist across generate calls, so
10121 /// turn N+1 primes ONLY its new suffix (the 124k-conversation daily pattern — re-priming a
10122 /// 32k history costs ~54s; a suffix prime costs seconds). APPEND-ONLY by construction: the
10123 /// hybrid linear-attn states are in-place (no position index), so a session can extend but
10124 /// never rewind — `committed` is the exact token list whose state the caches hold (includes
10125 /// any overshoot tokens past max_new; the caller renders from `committed`, not its own echo).
10126 pub fn new_session(
10127 &self,
10128 e: &Engine,
10129 max_ctx: usize,
10130 ) -> Result<SpecSession, Box<dyn std::error::Error>> {
10131 Ok(SpecSession {
10132 // STAGE-OWNED KV (lane/pp2-spec 2026-08-06): `pp::new_cache`, not `Cache::new`. This
10133 // is the SERVING spec-session path, and with the ppN door open across two cards a
10134 // primary-homed cache makes every remote stage peer-read its OWN KV on every verify
10135 // round — the wrong-card class already fixed on the two batched serving paths
10136 // (worker.rs 2483 / 2837). With the door shut `new_cache` IS `Cache::new` (same
10137 // branch, same allocations), so single-device behavior is byte-unchanged.
10138 cache: crate::pp::new_cache_planned(e, &self.cfg, &self.plan, max_ctx)?,
10139 scratch: self.new_mtp_scratch(e, max_ctx)?,
10140 committed: Vec::new(),
10141 last_h: None,
10142 next_pred: None,
10143 sctr: 0,
10144 uctr: 0,
10145 draft_ctx: None,
10146 pending_tok: None,
10147 turn_ckpt: None,
10148 telem: SpecTelemetryCounters::default(),
10149 capture_at: None,
10150 boundary_captures: Vec::new(),
10151 ckpt_at: None,
10152 capture_disabled: false,
10153 })
10154 }
10155
10156 /// SPEC-ON-CACHE-HIT restore (lane/spec-on-cache-hit, 2026-08-18 — PORT-PLAN item 3,
10157 /// research/cache-spec-design-20260814, scoped to WHOLE-ENTRY restores only): build a
10158 /// SpecSession around a trunk cache the worker already restored from a prefix-cache
10159 /// entry, re-installing the entry's published draft plane as the MTP scratch rows
10160 /// `[0..prefix.len())` and the entry's boundary hidden as `last_h`, then feeding the
10161 /// prompt SUFFIX here — through EXACTLY the plain path's program selection — so the
10162 /// worker always receives a fully-warm continuation session (committed = whole
10163 /// prompt, `next_pred` + `last_h` set; caller sets `next_pred` from the entry's
10164 /// boundary logits on the empty-suffix shape).
10165 ///
10166 /// PROGRAM LAW (the splitiso two-programs class, learned AGAIN in this lane's own
10167 /// gate): the identity target for a converted hit is the PLAIN hit serving the same
10168 /// request, and plain feeds a carried suffix via eager `decode_step` below
10169 /// PRIME_MIN_T and via `prime_cache` at/above it (prefill_tick's arms). The generate
10170 /// path's tokenwise arm routes qwen35-class through the BATCHED T=1 program
10171 /// (`spec_target_step_h`) instead — ULP-different suffix rows, and the gate measured
10172 /// the near-tie flip at generated token ~8 (research/spec-cache-20260818, qwen r3).
10173 /// So the suffix is fed HERE, mirroring prefill_tick arm-for-arm, not handed to the
10174 /// burst prime.
10175 ///
10176 /// SEED RULE (both sampling regimes; lane/sampled-hit-spec 2026-08-19, sampled draw
10177 /// added by lane/sampled-spec-quality 2026-08-19). The boundary token is produced by
10178 /// EXACTLY the rule the cold burst entry applies to its own first token from the same
10179 /// logits row: `argmax` when greedy, and a `sample_boundary_token` draw at Philox
10180 /// counter 0 when sampled. Both shapes are covered — the entry's boundary logits on a
10181 /// full-cover (empty-suffix) hit, this feed's own boundary logits on a suffix hit.
10182 /// That is what keeps a restored session seed-identical to a cold one PER SEED: the
10183 /// cold session draws from the identical row at counter 0 and then runs its rounds from
10184 /// counter 1, so the restored session admits with `sctr = 1` after its own draw.
10185 /// The WORKER owns the one refusal this constructor cannot see — a constrained request.
10186 /// (The penalized-sampled refusal was LIFTED once the burst's penalty window learned to
10187 /// span the session: `committed` here is the WHOLE prompt, so the restored session's
10188 /// window is the cold session's window. It comes back if `MEMRA_SPEC_PEN_SESSION=0`.)
10189 ///
10190 /// NOT the rolled-back partial-restore hazard: the caller restores at exactly the
10191 /// entry's captured endpoint (`e.pos`) through the shipping whole-entry path;
10192 /// mid-entry (`at < e.pos`) trunk restores stay behind MEMRA_PREFIX_PARTIAL_RESTORE
10193 /// and are never routed here.
10194 ///
10195 /// Failure contract: `Err((Some(cache), why))` before any trunk mutation — the
10196 /// worker rebuilds the plain carrier and the hit serves plain, byte-unchanged.
10197 /// `Err((None, why))` after the suffix feed began — the carrier is part-fed and
10198 /// UNUSABLE; the worker serves the request cold-plain (correct, slower) and the
10199 /// entry stays published for the next request.
10200 #[allow(clippy::too_many_arguments)]
10201 #[allow(clippy::result_large_err)] // allow: the fat error type is the diagnostic contract here; boxing it would change the error surface
10202 pub fn spec_session_from_restored(
10203 &self,
10204 e: &Engine,
10205 mut cache: Cache,
10206 prefix: Vec<u32>,
10207 suffix: &[u32],
10208 draft_k: &CudaSlice<u8>,
10209 draft_v: &CudaSlice<u8>,
10210 draft_k_tok_bytes: usize,
10211 draft_v_tok_bytes: usize,
10212 draft_len: usize,
10213 last_h: &[f32],
10214 // The ENTRY's boundary logits row (the full-cover shape's seed source). May be empty
10215 // when a suffix follows — the feed's own logits are the boundary then.
10216 boundary_logits: &[f32],
10217 // The request's sampler, or None for greedy. Owned here so the seed rule lives in
10218 // ONE place instead of being half-applied by the worker.
10219 sampling: Option<SpecSampling>,
10220 require_anchor: bool,
10221 max_ctx: usize,
10222 // STABLE-BOUNDARY REPUBLICATION (lane/frspec-multiturn-cache, 2026-08-21): ABSOLUTE
10223 // prompt position to split the suffix feed at and capture the extended-entry
10224 // publication + this session's `turn_ckpt` — the worker's stable pre-generation
10225 // boundary (`plain_checkpoint_boundary`). None = legacy prompt-end republication.
10226 // WHY: the prompt-end capture below includes the template's live generation header
10227 // (`<|im_start|>assistant\n<think>\n`), which the next turn's re-render replaces, so
10228 // for a hybrid (whole-entry restores only) every extended entry's last ~2 tokens
10229 // diverged from every future prompt and the hit boundary FROZE at the first
10230 // lcp-split entry forever (measured: cached 6811 of 38228 by turn 8, B4).
10231 republish_at: Option<usize>,
10232 ) -> Result<SpecSession, (Option<Cache>, String)> {
10233 let pos = prefix.len();
10234 let fail = |cache: Cache, msg: String| -> Result<SpecSession, (Option<Cache>, String)> {
10235 Err((Some(cache), msg))
10236 };
10237 if let Err(error) = cache.ensure_usable("spec_session_from_restored") {
10238 drop(cache);
10239 return Err((None, error.to_string()));
10240 }
10241 if self.mtp.is_none() {
10242 return fail(cache, "no MTP head attached (nothing to draft with)".into());
10243 }
10244 if pos == 0 {
10245 return fail(cache, "empty committed prefix".into());
10246 }
10247 if cache.pos != pos {
10248 let msg = format!(
10249 "restored cache pos {} != restored prefix len {pos}",
10250 cache.pos
10251 );
10252 return fail(cache, msg);
10253 }
10254 if draft_len != pos {
10255 return fail(
10256 cache,
10257 format!("draft plane len {draft_len} != restored prefix len {pos}"),
10258 );
10259 }
10260 if pos + suffix.len() >= max_ctx {
10261 return fail(
10262 cache,
10263 format!(
10264 "prompt {} + suffix would not leave generation room in ctx {max_ctx}",
10265 pos + suffix.len(),
10266 ),
10267 );
10268 }
10269 let mut scratch = match MtpScratch::new(
10270 e,
10271 &self.cfg,
10272 &self.plan,
10273 max_ctx,
10274 self.mtp.as_ref().and_then(|m| m.geom.as_ref()),
10275 ) {
10276 Ok(s) => s,
10277 Err(err) => return fail(cache, format!("draft scratch alloc failed: {err}")),
10278 };
10279 if scratch.kv.ring.is_some() {
10280 return fail(
10281 cache,
10282 "ring-backed draft scratch (Step35 SWA) cannot take a flat prefix restore".into(),
10283 );
10284 }
10285 if scratch.kv.k_tok_bytes != draft_k_tok_bytes
10286 || scratch.kv.v_tok_bytes != draft_v_tok_bytes
10287 {
10288 return fail(
10289 cache,
10290 format!(
10291 "draft plane layout {draft_k_tok_bytes}/{draft_v_tok_bytes} != scratch \
10292 {}/{} bytes/token (stale entry across a format change)",
10293 scratch.kv.k_tok_bytes, scratch.kv.v_tok_bytes,
10294 ),
10295 );
10296 }
10297 if pos > scratch.cap {
10298 return fail(
10299 cache,
10300 format!(
10301 "draft plane rows {pos} exceed scratch capacity {}",
10302 scratch.cap
10303 ),
10304 );
10305 }
10306 let kb = pos * draft_k_tok_bytes;
10307 let vb = pos * draft_v_tok_bytes;
10308 if draft_k.len() < kb || draft_v.len() < vb {
10309 return fail(
10310 cache,
10311 format!(
10312 "truncated draft plane: K {} < {kb} or V {} < {vb} bytes",
10313 draft_k.len(),
10314 draft_v.len(),
10315 ),
10316 );
10317 }
10318 if kb > 0
10319 && let Err(err) = e.copy_u8_into(&mut scratch.kv.k, 0, draft_k, kb)
10320 {
10321 return fail(cache, format!("draft K restore copy failed: {err}"));
10322 }
10323 if vb > 0
10324 && let Err(err) = e.copy_u8_into(&mut scratch.kv.v, 0, draft_v, vb)
10325 {
10326 return fail(cache, format!("draft V restore copy failed: {err}"));
10327 }
10328 if let Err(err) = scratch.set_len(e, pos) {
10329 return fail(cache, format!("draft scratch len set failed: {err}"));
10330 }
10331 let mut last_h_dev = if last_h.len() == self.cfg.n_embd as usize {
10332 // anchor upload failure is acceptance-only when a suffix feed follows (fill
10333 // row-0 falls back to zeros) but FATAL for an empty-suffix continuation (the
10334 // burst entry asserts committed + last_h + next_pred) — the caller says which.
10335 e.htod(last_h).ok()
10336 } else {
10337 None
10338 };
10339 if require_anchor && last_h_dev.is_none() {
10340 return fail(
10341 cache,
10342 "empty-suffix continuation requires the entry's boundary hidden anchor".into(),
10343 );
10344 }
10345 let mut committed = prefix;
10346 // Set on BOTH shapes below (suffix-fed and full-cover) — never left None, which is
10347 // what the empty-suffix continuation assert in the burst entry requires.
10348 let next_pred;
10349 // Philox: (0,0) at admit exactly like a fresh session; a sampled boundary draw below
10350 // consumes counter 0 and leaves 1, which is the state a cold session reaches after
10351 // drawing its own first token from the same row.
10352 let mut sctr = 0u32;
10353 let sampled = sampling.is_some_and(|s| s.temp > 0.0) && spec_sampled_boundary_on();
10354 // Penalty window for the boundary draw: the last `penalty_last_n` tokens of the WHOLE
10355 // prompt, which is what the cold session's own burst sees (Item 2's window). Built
10356 // after the suffix joins `committed` below.
10357 let mut boundary_captures: Vec<SpecBoundaryCapture> = Vec::new();
10358 let mut restored_turn_ckpt: Option<SpecCheckpoint> = None;
10359 if !suffix.is_empty() {
10360 // ---- SUFFIX FEED, mirroring prefill_tick's program selection exactly ----
10361 // From here on the trunk cache mutates: failures return Err((None, _)) and
10362 // the worker serves the request cold-plain instead of reusing the carrier.
10363 let dirty =
10364 |msg: String| -> Result<SpecSession, (Option<Cache>, String)> { Err((None, msg)) };
10365 let n_embd = self.cfg.n_embd as usize;
10366 let t = suffix.len();
10367 let mut h_rows = match e.uninit(t * n_embd) {
10368 Ok(b) => b,
10369 Err(err) => return fail(cache, format!("suffix hidden buffer alloc: {err}")),
10370 };
10371 // STABLE-BOUNDARY split (see `republish_at`): feed stops at the boundary so the
10372 // in-place GDN conv/ssm state can be snapshotted there — the only moment it
10373 // exists (the cold prime-split law). suffix-relative; None = one-segment legacy.
10374 let b_rel = republish_at
10375 .and_then(|abs| abs.checked_sub(pos))
10376 .filter(|&r| r > 0 && r < t);
10377 let mut feed_logits = Vec::new();
10378 let tokenwise_env = std::env::var("MEMRA_PRIME_TOKENWISE").is_ok()
10379 || e.frozen_cpu_experts_prefer_tokenwise_prime();
10380 let mut fed = 0usize;
10381 for seg_end in [b_rel, Some(t)].into_iter().flatten() {
10382 if seg_end <= fed {
10383 continue;
10384 }
10385 let seg = &suffix[fed..seg_end];
10386 let batched = seg.len() >= crate::hybrid_forward::PRIME_MIN_T && !tokenwise_env;
10387 if batched {
10388 // prefill_tick's prime arm: request-level prime_cache call; tokens still
10389 // queued after this segment ride `queued_after` so Step35 arm selection
10390 // stays keyed to the request's end (tick-seg law).
10391 match self.prime_cache(e, seg, &mut cache, t - seg_end) {
10392 Ok((l, _h_seed, hiddens)) => {
10393 if let Err(err) =
10394 e.copy_into(&mut h_rows, fed * n_embd, &hiddens, seg.len() * n_embd)
10395 {
10396 return dirty(format!("suffix hidden copy: {err}"));
10397 }
10398 feed_logits = l;
10399 }
10400 Err(err) => return dirty(format!("suffix prime failed: {err}")),
10401 }
10402 } else {
10403 // prefill_tick's tokenwise arm: eager decode_step, one token at a time.
10404 for (i, &tok) in seg.iter().enumerate() {
10405 match self.decode_step_h(e, tok, &mut cache) {
10406 Ok((l, h)) => {
10407 if let Err(err) =
10408 e.copy_into(&mut h_rows, (fed + i) * n_embd, &h, n_embd)
10409 {
10410 return dirty(format!("suffix hidden copy: {err}"));
10411 }
10412 feed_logits = l;
10413 }
10414 Err(err) => return dirty(format!("suffix decode_step failed: {err}")),
10415 }
10416 }
10417 }
10418 fed = seg_end;
10419 if Some(seg_end) == b_rel {
10420 // The stable pre-generation boundary: capture the extended-entry
10421 // publication AND this session's own turn checkpoint here instead of at
10422 // prompt-end (both would otherwise carry the volatile live-header tail
10423 // the next re-render replaces). Failure silent, turn_ckpt convention.
10424 debug_assert_eq!(
10425 cache.pos,
10426 pos + seg_end,
10427 "stable-boundary capture off the feed split"
10428 );
10429 if spec_restore_republish_on()
10430 && let Ok(snap) = cache.snapshot(e)
10431 {
10432 boundary_captures.push(SpecBoundaryCapture {
10433 snap,
10434 pos: pos + seg_end,
10435 logits: feed_logits.clone(),
10436 last_h: capture_boundary_hidden(e, &h_rows, seg_end, n_embd),
10437 latent_tails: Vec::new(),
10438 });
10439 }
10440 let anchor: Result<CudaSlice<f32>, Box<dyn std::error::Error>> =
10441 e.uninit(n_embd).and_then(|mut a| {
10442 e.copy_view_into(
10443 &mut a,
10444 0,
10445 &h_rows.slice((seg_end - 1) * n_embd..seg_end * n_embd),
10446 n_embd,
10447 )?;
10448 Ok(a)
10449 });
10450 if let (Ok(snap), Ok(last_h)) = (cache.snapshot(e), anchor) {
10451 restored_turn_ckpt = Some(SpecCheckpoint {
10452 snap,
10453 pos: pos + seg_end,
10454 last_h,
10455 });
10456 }
10457 }
10458 }
10459 // Draft-scratch fill for the suffix rows, predecessor-paired: row `pos` reads
10460 // the entry's boundary anchor (zeros fallback — acceptance-only), row `pos+i`
10461 // reads h_rows[i-1]. Chunked like the generate path's fill (transients scale
10462 // with T). Fill failures are acceptance-only — truncate to the restored rows
10463 // and continue; the burst's own set_len keeps the invariant.
10464 let _mtp = self.mtp.as_ref().expect("mtp checked above"); // invariant check only; the fill below re-reads self.mtp
10465 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
10466 let embd_gpu = if spec_host_embd() {
10467 None
10468 } else {
10469 Some(
10470 self.embd_gpu
10471 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
10472 )
10473 };
10474 let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
10475 let fill_chunk = 4096usize;
10476 let mut filled = true;
10477 let mut start = 0usize;
10478 'fill: while start < t {
10479 let end = (start + fill_chunk).min(t);
10480 let tc = end - start;
10481 let Ok(mut phs) = e.zeros(tc * n_embd) else {
10482 filled = false;
10483 break 'fill;
10484 };
10485 let (src_lo, dst_off, n_copy) = if start == 0 {
10486 (0, n_embd, (tc - 1) * n_embd)
10487 } else {
10488 ((start - 1) * n_embd, 0, tc * n_embd)
10489 };
10490 if start == 0
10491 && let Some(lh) = last_h_dev.as_ref()
10492 && e.copy_into(&mut phs, 0, lh, n_embd).is_err()
10493 {
10494 filled = false;
10495 break 'fill;
10496 }
10497 if n_copy > 0
10498 && e.copy_view_into(
10499 &mut phs,
10500 dst_off,
10501 &h_rows.slice(src_lo..src_lo + n_copy),
10502 n_copy,
10503 )
10504 .is_err()
10505 {
10506 filled = false;
10507 break 'fill;
10508 }
10509 if self
10510 .mtp_kv_fill_all(
10511 e,
10512 &suffix[start..end],
10513 &phs,
10514 pos + start,
10515 &mut scratch,
10516 embd_dev,
10517 )
10518 .is_err()
10519 {
10520 filled = false;
10521 break 'fill;
10522 }
10523 start = end;
10524 }
10525 if !filled {
10526 // acceptance-only: drafts over missing suffix rows are cheap and wrong,
10527 // so keep only the restored rows resident and let verify arbitrate.
10528 if let Err(err) = scratch.set_len(e, pos) {
10529 return dirty(format!("scratch truncation after failed fill: {err}"));
10530 }
10531 }
10532 // EXTENDED-ENTRY PUBLICATION (lane/sampled-spec-quality, Item 3 — the fix for
10533 // "a restored spec session never publishes an extended entry", SAMPLED-HIT.md
10534 // finding (d)). Pre-lane, publication was armed only for COLD sessions
10535 // (`spec_resumed == 0` in the worker) and both engine capture sites require a
10536 // non-continuation burst — but a converted hit's first burst IS a continuation,
10537 // so a growing conversation learned exactly ONE boundary and turn 3 could never
10538 // hit a longer prefix than turn 2 did.
10539 //
10540 // WHERE, and why it is safe here: `cache.pos == prefix + suffix` at this exact
10541 // line — the trunk is primed over the whole prompt, nothing is generated, and the
10542 // draft plane rows [0..prompt) are filled just above. That is a complete
10543 // whole-entry boundary (`pos == fed_len`), the same shape the cold seed capture
10544 // publishes; the worker's existing publication sweep picks it up because it is
10545 // keyed on non-empty `boundary_captures` and is sampler- and resume-independent.
10546 // NOT the partial-restore hazard: the boundary is this session's own prompt END,
10547 // never mid-entry, so `entry_pos != fed_len` still refuses on the way back in.
10548 // Failure is SILENT by design (the turn_ckpt / boundary-capture convention):
10549 // publication is an optimization, never a correctness dependency.
10550 //
10551 // SUPERSEDED WHEN `republish_at` FIRED (lane/frspec-multiturn-cache): a prompt-end
10552 // entry's tail is the live generation header the next re-render replaces, so on a
10553 // hybrid (whole-entry restores) it can never serve the conversation's next turn —
10554 // the stable-boundary capture above IS this publication, minus the poisoned tail.
10555 if spec_restore_republish_on() && boundary_captures.is_empty() {
10556 debug_assert_eq!(
10557 cache.pos,
10558 pos + t,
10559 "extended-entry capture must sit at the restored session's prompt end",
10560 );
10561 if let Ok(snap) = cache.snapshot(e) {
10562 boundary_captures.push(SpecBoundaryCapture {
10563 snap,
10564 pos: pos + t,
10565 logits: feed_logits.clone(),
10566 last_h: capture_boundary_hidden(e, &h_rows, t, n_embd),
10567 latent_tails: Vec::new(),
10568 });
10569 }
10570 }
10571 // continuation seed: the feed's boundary logits ARE the plain path's boundary
10572 // logits (same program), so greedy's argmax here is plain's first emitted token,
10573 // and the sampled draw is the cold sampled session's own first token.
10574 next_pred = Some(if sampled {
10575 let sp = sampling.expect("sampled implies a sampler");
10576 // `committed` is still the restored prefix here; the suffix joins it below —
10577 // so this is the last-N window over the WHOLE prompt, exactly the cold
10578 // session's own window at its first token.
10579 let hist = pen_window_seed(&committed, suffix, sp.penalty_last_n);
10580 match sample_boundary_token(
10581 e,
10582 &feed_logits,
10583 &sp,
10584 &hist,
10585 &mut sctr,
10586 "restore-suffix-feed",
10587 ) {
10588 Ok(t) => t,
10589 // the trunk is already fed: hand nothing back, the worker serves the
10590 // request cold-plain. Never fall back to an argmax — that would put a
10591 // greedy token in a sampled stream to save a slow path.
10592 Err(err) => {
10593 return dirty(format!("boundary token draw failed: {err}"));
10594 }
10595 }
10596 } else {
10597 argmax(&feed_logits) as u32
10598 });
10599 let mut lh = match e.uninit(n_embd) {
10600 Ok(b) => b,
10601 Err(err) => return dirty(format!("boundary hidden alloc: {err}")),
10602 };
10603 if let Err(err) = e.copy_view_into(
10604 &mut lh,
10605 0,
10606 &h_rows.slice((t - 1) * n_embd..t * n_embd),
10607 n_embd,
10608 ) {
10609 return dirty(format!("boundary hidden copy: {err}"));
10610 }
10611 last_h_dev = Some(lh);
10612 committed.extend_from_slice(suffix);
10613 } else {
10614 // FULL-COVER shape (empty suffix — the identical-repeat / agent-loop shape): the
10615 // ENTRY's boundary logits are the boundary row, and this is the token the cold
10616 // session emits from that same row. Owned here rather than in the worker so the
10617 // sampled draw cannot be half-applied on one shape (the worker used to argmax it).
10618 if boundary_logits.is_empty() {
10619 return fail(
10620 cache,
10621 "full-cover restore without the entry's boundary logits".into(),
10622 );
10623 }
10624 next_pred = Some(if sampled {
10625 let sp = sampling.expect("sampled implies a sampler");
10626 let hist = pen_window_seed(&committed, &[], sp.penalty_last_n);
10627 match sample_boundary_token(
10628 e,
10629 boundary_logits,
10630 &sp,
10631 &hist,
10632 &mut sctr,
10633 "restore-full-cover",
10634 ) {
10635 Ok(t) => t,
10636 // nothing has been mutated on this shape — hand the carrier back and let
10637 // the hit serve PLAIN (the banked pre-lane path).
10638 Err(err) => {
10639 return fail(cache, format!("boundary token draw failed: {err}"));
10640 }
10641 }
10642 } else {
10643 argmax(boundary_logits) as u32
10644 });
10645 }
10646 Ok(SpecSession {
10647 cache,
10648 scratch,
10649 committed,
10650 last_h: last_h_dev,
10651 next_pred,
10652 sctr,
10653 uctr: 0,
10654 draft_ctx: None,
10655 pending_tok: None,
10656 // Stable-boundary capture from the split feed above (None on the legacy shape):
10657 // a restored session previously parked WITHOUT a checkpoint, so the next turn's
10658 // affinity probe declined ("no turn checkpoint retained") and the conversation
10659 // fell back to the frozen prefix entry forever.
10660 turn_ckpt: restored_turn_ckpt,
10661 telem: SpecTelemetryCounters::default(),
10662 capture_at: None,
10663 boundary_captures,
10664 ckpt_at: None,
10665 capture_disabled: false,
10666 })
10667 }
10668
10669 /// Forced-gate exact state comparison. This intentionally reads the real live prefixes from
10670 /// their owning PP devices: matching emitted ids alone would miss a stale `len_d`, recurrent
10671 /// snapshot, or draft-KV row that only corrupts the following round.
10672 pub fn optipipe_compare_session_state(
10673 &self,
10674 e: &Engine,
10675 reference: &SpecSession,
10676 candidate: &SpecSession,
10677 ) -> Result<OptiForkStateIdentity, Box<dyn std::error::Error>> {
10678 fn fail(what: &str) -> Box<dyn std::error::Error> {
10679 format!("optipipe state mismatch: {what}").into()
10680 }
10681 fn same_f32(a: &[f32], b: &[f32]) -> bool {
10682 a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.to_bits() == y.to_bits())
10683 }
10684 fn compare_layers(
10685 es: &Engine,
10686 range: std::ops::Range<usize>,
10687 reference: &SpecSession,
10688 candidate: &SpecSession,
10689 report: &mut OptiForkStateIdentity,
10690 ) -> Result<(), Box<dyn std::error::Error>> {
10691 for il in range {
10692 match (&reference.cache.kv[il], &candidate.cache.kv[il]) {
10693 (Some(a), Some(b)) => {
10694 if a.len != b.len {
10695 return Err(fail(&format!(
10696 "layer {il} host KV len {} != {}",
10697 a.len, b.len
10698 )));
10699 }
10700 let ad = es.dtoh_i32(&a.len_d)?;
10701 let bd = es.dtoh_i32(&b.len_d)?;
10702 if ad != bd || ad.first().copied() != Some(a.len as i32) {
10703 return Err(fail(&format!(
10704 "layer {il} device KV len {ad:?} != {bd:?} (host={})",
10705 a.len,
10706 )));
10707 }
10708 let kb = a.len * a.k_tok_bytes;
10709 let vb = a.len * a.v_tok_bytes;
10710 if kb > 0 {
10711 let ak = es.dtoh_u8_view(&a.k.slice(0..kb))?;
10712 let bk = es.dtoh_u8_view(&b.k.slice(0..kb))?;
10713 if ak != bk {
10714 let at = ak.iter().zip(&bk).position(|(x, y)| x != y).unwrap();
10715 return Err(fail(&format!(
10716 "layer {il} K bytes at byte {at} row {} offset {}: {} != {}",
10717 at / a.k_tok_bytes,
10718 at % a.k_tok_bytes,
10719 ak[at],
10720 bk[at],
10721 )));
10722 }
10723 }
10724 if vb > 0 {
10725 let av = es.dtoh_u8_view(&a.v.slice(0..vb))?;
10726 let bv = es.dtoh_u8_view(&b.v.slice(0..vb))?;
10727 if av != bv {
10728 let at = av.iter().zip(&bv).position(|(x, y)| x != y).unwrap();
10729 return Err(fail(&format!(
10730 "layer {il} V bytes at byte {at} row {} offset {}: {} != {}",
10731 at / a.v_tok_bytes,
10732 at % a.v_tok_bytes,
10733 av[at],
10734 bv[at],
10735 )));
10736 }
10737 }
10738 report.trunk_kv_bytes += kb + vb;
10739 }
10740 (None, None) => {}
10741 _ => return Err(fail(&format!("layer {il} KV presence"))),
10742 }
10743 match (&reference.cache.recur[il], &candidate.cache.recur[il]) {
10744 (Some(a), Some(b)) => {
10745 let ac = es.dtoh(&a.conv_state)?;
10746 let bc = es.dtoh(&b.conv_state)?;
10747 if !same_f32(&ac, &bc) {
10748 return Err(fail(&format!("layer {il} conv state")));
10749 }
10750 let as_ = es.dtoh(&a.ssm_state)?;
10751 let bs = es.dtoh(&b.ssm_state)?;
10752 if !same_f32(&as_, &bs) {
10753 return Err(fail(&format!("layer {il} SSM state")));
10754 }
10755 report.recurrent_bytes += (ac.len() + as_.len()) * 4;
10756 }
10757 (None, None) => {}
10758 _ => return Err(fail(&format!("layer {il} recurrent presence"))),
10759 }
10760 }
10761 Ok(())
10762 }
10763
10764 if reference.committed != candidate.committed {
10765 return Err(fail("committed token ids"));
10766 }
10767 if reference.cache.pos != candidate.cache.pos
10768 || reference.cache.max_ctx != candidate.cache.max_ctx
10769 {
10770 return Err(fail("cache pos/capacity"));
10771 }
10772 if reference.pending_tok != candidate.pending_tok
10773 || reference.next_pred != candidate.next_pred
10774 || reference.sctr != candidate.sctr
10775 || reference.uctr != candidate.uctr
10776 {
10777 return Err(fail("pending/prediction/counter tail"));
10778 }
10779
10780 let mut report = OptiForkStateIdentity::default();
10781 if let Some(fence) = crate::pp::pp_cuts(self.layers.len()) {
10782 let rt = crate::pp::PpNRt::get(e)?;
10783 for stage in 0..rt.n_stages() {
10784 let _scope = rt.enter(stage);
10785 compare_layers(
10786 rt.engine(stage, e),
10787 fence[stage]..fence[stage + 1],
10788 reference,
10789 candidate,
10790 &mut report,
10791 )?;
10792 }
10793 } else {
10794 compare_layers(e, 0..self.layers.len(), reference, candidate, &mut report)?;
10795 }
10796
10797 if reference.scratch.plane_count() != candidate.scratch.plane_count() {
10798 return Err(fail("draft scratch plane count"));
10799 }
10800 for index in 0..reference.scratch.plane_count() {
10801 let (a, _) = reference.scratch.plane(index);
10802 let (b, _) = candidate.scratch.plane(index);
10803 if a.len != b.len
10804 || a.kv_dim_k != b.kv_dim_k
10805 || a.kv_dim_v != b.kv_dim_v
10806 || a.k_tok_bytes != b.k_tok_bytes
10807 || a.v_tok_bytes != b.v_tok_bytes
10808 || e.dtoh_i32(&a.len_d)? != e.dtoh_i32(&b.len_d)?
10809 {
10810 return Err(fail(&format!("draft scratch plane {index} length/layout")));
10811 }
10812 let kb = a.len * a.k_tok_bytes;
10813 let vb = a.len * a.v_tok_bytes;
10814 if kb > 0 && e.dtoh_u8_view(&a.k.slice(0..kb))? != e.dtoh_u8_view(&b.k.slice(0..kb))? {
10815 return Err(fail(&format!("draft scratch plane {index} K bytes")));
10816 }
10817 if vb > 0 && e.dtoh_u8_view(&a.v.slice(0..vb))? != e.dtoh_u8_view(&b.v.slice(0..vb))? {
10818 return Err(fail(&format!("draft scratch plane {index} V bytes")));
10819 }
10820 report.scratch_kv_bytes += kb + vb;
10821 }
10822
10823 match (&reference.last_h, &candidate.last_h) {
10824 (Some(a), Some(b)) => {
10825 let ah = e.dtoh(a)?;
10826 let bh = e.dtoh(b)?;
10827 if !same_f32(&ah, &bh) {
10828 return Err(fail("last hidden/seed bytes"));
10829 }
10830 report.hidden_bytes = ah.len() * 4;
10831 }
10832 (None, None) => {}
10833 _ => return Err(fail("last hidden/seed presence")),
10834 }
10835 Ok(report)
10836 }
10837
10838 /// SESSION-AFFINITY REWIND (lane/session-affinity, 2026-08-05): roll `sess` back to its
10839 /// retained prompt-end checkpoint, so a request whose prompt matches
10840 /// `committed[..rewind_pos()]` exactly can resume there and prime only its own delta.
10841 ///
10842 /// EXACTNESS. After this returns, the session is byte-for-byte the state it was in AT that
10843 /// boundary: full-attn KV truncated to it (append-only, position-addressed), GDN conv/ssm
10844 /// restored from the device copy taken there, draft scratch length reset, `committed`
10845 /// truncated, `last_h` = the boundary's predecessor anchor. That is precisely the state a
10846 /// fresh prime of `committed[..pos]` would have produced, so the following suffix prime and
10847 /// every burst after it are identical to a cold run of the same token stream — the
10848 /// committed-tokens-authoritative contract.
10849 ///
10850 /// `next_pred` and `pending_tok` are CLEARED: both describe generation past the boundary,
10851 /// which the rewind discards. The caller therefore must supply a non-empty suffix (a
10852 /// rewound session cannot serve an empty-suffix continuation burst — there is nothing to
10853 /// continue). The persistent draft graph survives: it bakes only session-stable pointers
10854 /// (the scratch KV, the resident embedding), none of which the rewind moves.
10855 ///
10856 /// The checkpoint is CONSUMED (`turn_ckpt` taken): its snapshot buffers are freed here, and
10857 /// this turn's own prime installs a fresh one at the new prompt end. Returns the position
10858 /// rewound to, or `None` when the session holds no checkpoint (caller: full re-prime).
10859 pub fn spec_rewind_to_checkpoint(
10860 &self,
10861 e: &Engine,
10862 sess: &mut SpecSession,
10863 ) -> Result<Option<usize>, Box<dyn std::error::Error>> {
10864 if sess.turn_ckpt.as_ref().is_some_and(|ckpt| {
10865 !sess.cache.can_rollback(&ckpt.snap, 0) || !sess.scratch.can_rewind_to(ckpt.pos)
10866 }) {
10867 return Err(
10868 "SWA ring rewind checkpoint has been lapped; full re-prime required".into(),
10869 );
10870 }
10871 let Some(ckpt) = sess.turn_ckpt.take() else {
10872 return Ok(None);
10873 };
10874 assert!(
10875 ckpt.pos <= sess.committed.len(),
10876 "checkpoint past committed ({} > {})",
10877 ckpt.pos,
10878 sess.committed.len()
10879 );
10880 // Restore through each layer's owning engine. A single primary-engine rollback is not
10881 // sufficient when the serving cache is stage-owned under cross-device PP.
10882 crate::pp::restore_cache_checkpoint(e, self, None, &mut sess.cache, &ckpt.snap)?;
10883 debug_assert_eq!(
10884 sess.cache.pos, ckpt.pos,
10885 "rollback landed off the checkpoint"
10886 );
10887 sess.scratch.set_len(e, ckpt.pos)?;
10888 sess.committed.truncate(ckpt.pos);
10889 sess.last_h = Some(ckpt.last_h);
10890 sess.next_pred = None;
10891 sess.pending_tok = None;
10892 Ok(Some(ckpt.pos))
10893 }
10894
10895 /// Grow a parked speculative session to `target_cap` and rewind it to its retained turn
10896 /// checkpoint without re-priming the checkpoint prefix.
10897 ///
10898 /// The trunk cache is restored exactly like a plain grown cache: append-only full-attention
10899 /// KV rows come from the parked cache, while recurrent state comes from the checkpoint's
10900 /// owned snapshot. The MTP scratch is also context-linear and its rows below the checkpoint
10901 /// remain authoritative, so they are copied into a fresh larger scratch before its length is
10902 /// truncated. Pointer-baking draft graphs are dropped and recaptured on the next burst.
10903 ///
10904 /// All fallible work completes before `sess` is mutated. A failed allocation or copy leaves
10905 /// the parked session intact, allowing the caller one reclaim-and-retry attempt.
10906 pub fn spec_grow_and_rewind_to_checkpoint(
10907 &self,
10908 e: &Engine,
10909 sess: &mut SpecSession,
10910 target_cap: usize,
10911 ) -> Result<Option<usize>, Box<dyn std::error::Error>> {
10912 if target_cap <= sess.cache.max_ctx {
10913 return self.spec_rewind_to_checkpoint(e, sess);
10914 }
10915 let Some(ckpt) = sess.turn_ckpt.as_ref() else {
10916 return Ok(None);
10917 };
10918 if ckpt.pos == 0 || ckpt.pos > sess.committed.len() {
10919 return Err(format!(
10920 "checkpoint pos {} outside committed length {}",
10921 ckpt.pos,
10922 sess.committed.len(),
10923 )
10924 .into());
10925 }
10926 if ckpt.pos > target_cap {
10927 return Err(format!(
10928 "checkpoint pos {} exceeds grown capacity {target_cap}",
10929 ckpt.pos,
10930 )
10931 .into());
10932 }
10933
10934 let mut grown_cache = crate::pp::new_cache_planned(e, &self.cfg, &self.plan, target_cap)?;
10935 let mut grown_scratch = self.new_mtp_scratch(e, target_cap)?;
10936 crate::pp::restore_cache_checkpoint(
10937 e,
10938 self,
10939 Some(&sess.cache),
10940 &mut grown_cache,
10941 &ckpt.snap,
10942 )?;
10943
10944 if sess.scratch.plane_count() != grown_scratch.plane_count() {
10945 return Err("checkpoint draft plane count mismatch".into());
10946 }
10947 for index in 0..sess.scratch.plane_count() {
10948 let (src, _) = sess.scratch.plane(index);
10949 let (dst, _) = grown_scratch.plane_mut(index);
10950 if ckpt.pos > src.len
10951 || src.kv_dim_k != dst.kv_dim_k
10952 || src.kv_dim_v != dst.kv_dim_v
10953 || src.k_tok_bytes != dst.k_tok_bytes
10954 || src.v_tok_bytes != dst.v_tok_bytes
10955 {
10956 return Err(format!(
10957 "checkpoint draft plane {index} layout mismatch (pos {}, source len {})",
10958 ckpt.pos, src.len,
10959 )
10960 .into());
10961 }
10962 match (&src.ring, dst.ring.as_ref()) {
10963 (Some(sring), Some(_)) => {
10964 // Ring-backed draft plane (step35): `ckpt.pos` is absolute and exceeds the
10965 // physical rows once lapped — same class as the trunk-KV restore panic
10966 // (2026-08-29 warm-turn-at-40k). Copy the aligned live window, rebase.
10967 let (new_base, phys) = sring.restore_plan(ckpt.pos).map_err(|err| {
10968 format!("checkpoint draft plane {index} SWA restore refused: {err}")
10969 })?;
10970 let rows = phys.len();
10971 let kb = rows * src.k_tok_bytes;
10972 let vb = rows * src.v_tok_bytes;
10973 if kb > 0 {
10974 e.copy_u8_range_into(
10975 &mut dst.k,
10976 0,
10977 &src.k,
10978 phys.start * src.k_tok_bytes,
10979 kb,
10980 )?;
10981 }
10982 if vb > 0 {
10983 e.copy_u8_range_into(
10984 &mut dst.v,
10985 0,
10986 &src.v,
10987 phys.start * src.v_tok_bytes,
10988 vb,
10989 )?;
10990 }
10991 dst.ring
10992 .as_mut()
10993 .expect("ring presence checked above")
10994 .apply_rebase(new_base);
10995 if let Some(base_d) = dst.base_d.as_mut() {
10996 e.set_i32_one(base_d, new_base as i32)?;
10997 }
10998 }
10999 (None, None) => {
11000 let kb = ckpt.pos * src.k_tok_bytes;
11001 let vb = ckpt.pos * src.v_tok_bytes;
11002 if kb > 0 {
11003 e.copy_u8_into(&mut dst.k, 0, &src.k, kb)?;
11004 }
11005 if vb > 0 {
11006 e.copy_u8_into(&mut dst.v, 0, &src.v, vb)?;
11007 }
11008 }
11009 _ => {
11010 return Err(format!("checkpoint draft plane {index} ring/flat mismatch").into());
11011 }
11012 }
11013 }
11014 grown_scratch.set_len(e, ckpt.pos)?;
11015 // The old scratch is dropped immediately after publication below. Bound its D2D reads
11016 // first; growth happens once per rewritten turn, outside the decode hot loop.
11017 e.stream().synchronize()?;
11018
11019 let ckpt = sess
11020 .turn_ckpt
11021 .take()
11022 .expect("checkpoint remained present through transactional grow");
11023 let pos = ckpt.pos;
11024 sess.cache = grown_cache;
11025 sess.scratch = grown_scratch;
11026 sess.committed.truncate(pos);
11027 sess.last_h = Some(ckpt.last_h);
11028 sess.next_pred = None;
11029 sess.pending_tok = None;
11030 sess.draft_ctx = None;
11031 debug_assert_eq!(sess.cache.pos, pos, "grown rewind landed off checkpoint");
11032 debug_assert!(
11033 (0..sess.scratch.plane_count()).all(|index| sess.scratch.plane(index).0.len == pos),
11034 "grown draft rewind landed off checkpoint"
11035 );
11036 Ok(Some(pos))
11037 }
11038
11039 /// Commit a carried pending bonus (see SpecSession::pending_tok): one T=1 trunk pass
11040 /// (its logits' argmax becomes next_pred) + the draft-KV fill at the carried anchor —
11041 /// byte-identical to the pre-carry session tail. Required before a non-empty-suffix
11042 /// prime, a sampled turn, or parking a session for pool reuse. No-op without a pending.
11043 /// `sampling` is the sampler of the request that will CONSUME the resulting `next_pred`
11044 /// (lane/sampled-spec-quality): this is a boundary site like any other, so a sampled
11045 /// consumer must get a DRAWN token, not an argmax. Pass `None` from the park/demote
11046 /// callers — a pending only ever exists on the GREEDY tail, and the consumer of a
11047 /// park-time flush is a future request whose sampler is not knowable here (residual
11048 /// named at the pool-resume probe in worker.rs and in SAMPLED-QUALITY.md).
11049 pub fn spec_flush_pending(
11050 &self,
11051 e: &Engine,
11052 sess: &mut SpecSession,
11053 sampling: Option<SpecSampling>,
11054 ) -> Result<(), Box<dyn std::error::Error>> {
11055 sess.cache.ensure_usable("spec_flush_pending")?;
11056 let Some(b) = sess.pending_tok.take() else {
11057 return Ok(());
11058 };
11059 if self.mtp.is_none() {
11060 return Err("pending carry requires an MTP head".into());
11061 }
11062 let n_embd = self.cfg.n_embd as usize;
11063 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
11064 let embd_gpu = if spec_host_embd() {
11065 None
11066 } else {
11067 Some(
11068 self.embd_gpu
11069 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
11070 )
11071 };
11072 let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
11073 let pos_b = sess.cache.pos;
11074 sess.scratch.set_len(e, pos_b)?;
11075 let (lg_b, hb) = self.spec_target_step_h(e, b, &mut sess.cache)?;
11076 sess.next_pred = Some(match sampling {
11077 Some(sp) if sp.temp > 0.0 && spec_sampled_boundary_on() => {
11078 // window includes `b` itself: it is committed by this pass, and the pre-lane
11079 // code never counted a boundary token in the penalty history at all.
11080 let hist = pen_window_seed(&sess.committed, &[b], sp.penalty_last_n);
11081 sample_boundary_token(e, &lg_b, &sp, &hist, &mut sess.sctr, "flush-pending")?
11082 }
11083 _ => argmax(&lg_b) as u32,
11084 });
11085 let anchor = sess
11086 .last_h
11087 .as_ref()
11088 .expect("pending carry requires last_h (the predecessor-row anchor)");
11089 self.mtp_kv_fill_all(e, &[b], anchor, pos_b, &mut sess.scratch, embd_dev)?;
11090 sess.last_h = Some(hb);
11091 sess.committed.push(b);
11092 Ok(())
11093 }
11094
11095 /// Solo target feed used only at speculative round boundaries. Step35 serving made its
11096 /// staged batched B=1 graph authoritative, so a speculative session must enter and leave
11097 /// rounds through that same graph. Other model families keep their eager T=1 contract.
11098 fn spec_target_step_h(
11099 &self,
11100 e: &Engine,
11101 token: u32,
11102 cache: &mut Cache,
11103 ) -> Result<(Vec<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
11104 cache.ensure_usable("spec_target_step_h")?;
11105 if !self.sliding_gated_moe_batch_program() && !self.batched_serving_numeric_class() {
11106 return self.decode_step_h(e, token, cache);
11107 }
11108 let pos0 = cache.pos;
11109 let (logits, hidden) = self.decode_step_t_core(e, &[token], pos0, cache, None, None)?;
11110 Ok((e.dtoh(&logits)?, hidden))
11111 }
11112
11113 /// The archs whose LIVE B=1 serving runs the generic BATCHED numeric class (decode_step_batch
11114 /// walk + batched head), so their spec verify must run the SAME class. MoE learned this
11115 /// 2026-08-14 AM (4b777ccc5); the dense hybrid reproduced the identical near-tie flip class
11116 /// the same day on Qwen3.8-27B — eager-class verify logits drift from batched-class serving
11117 /// logits ("1 ULP at layer 2 → 2.3e-1 logit maxdiff at the head"), and the GDN recurrence
11118 /// carries the drift until a near-tie flips deep in generation. One predicate so the five
11119 /// dispatch sites cannot drift apart again.
11120 /// Draft-graph head admissibility (lane/draftcost-moe, 2026-08-20): the capture body
11121 /// (`mtp_head_forward_cap`) supports Dense heads and SOFTMAX device-routed resident-MoE
11122 /// heads. Residency alone is insufficient: Hy3/M3/Step sigmoid routing returns selected
11123 /// experts through a host synchronization, which is capture-illegal. Those heads use the
11124 /// exact eager draft chain until a device-only sigmoid expert program lands. Trunk FFN class
11125 /// is irrelevant — the graph body is the HEAD forward only. One predicate for all three
11126 /// eligibility sites so they cannot drift (the serving numeric-class lesson).
11127 fn mtp_graph_capturable(&self) -> bool {
11128 let sigmoid_router = self.cfg.sigmoid_router().is_some();
11129 for head in self.mtp.iter().chain(self.mtp_extra.iter()) {
11130 let reason = match &head.ffn {
11131 crate::hybrid::Ffn::Dense { .. } => None,
11132 crate::hybrid::Ffn::Moe(mo) if mo.dev_exps.is_none() => {
11133 Some("non-resident MoE MTP head")
11134 }
11135 crate::hybrid::Ffn::Moe(_) if sigmoid_router => {
11136 Some("sigmoid-router MoE MTP head requires host-visible routing")
11137 }
11138 crate::hybrid::Ffn::Moe(_) => None,
11139 };
11140 if let Some(reason) = reason {
11141 static NOTICE: std::sync::Once = std::sync::Once::new();
11142 NOTICE.call_once(|| {
11143 eprintln!(
11144 "[spec] draft graph unavailable: {reason}; eager draft chain engaged"
11145 );
11146 });
11147 return false;
11148 }
11149 }
11150 self.mtp.is_some()
11151 }
11152
11153 fn batched_serving_numeric_class(&self) -> bool {
11154 self.plan
11155 .trunk_operations()
11156 .contains(&memra_gguf::model_plan::OperationKind::GatedDeltaNet)
11157 }
11158
11159 /// The family the MTP verify-graph default was measured on: GatedDeltaNet state layers
11160 /// (a `recur` mixer) together with a routed-MoE FFN — Ornith-1.5-35B-A3B and its kin. The
11161 /// server-side twin of this test is `model_forces_spec_replay` (GatedDeltaNet + MoeMlp);
11162 /// keeping the engine's own version structural rather than name-based means a new
11163 /// checkpoint of the same shape inherits the default, and a different shape does not.
11164 /// pub(crate) since lane/graph-launch-guard-sweep-20260831: `dspark_vg_admission_debt`
11165 /// consults it so the MTP-route pool stops escaping the admission charge.
11166 pub(crate) fn vgraph_family_default(&self) -> bool {
11167 let has_linear = self
11168 .layers
11169 .iter()
11170 .any(|l| matches!(l.mixer, Mixer::Linear(_)));
11171 let has_moe = self
11172 .layers
11173 .iter()
11174 .any(|l| matches!(l.ffn, crate::hybrid::Ffn::Moe(_)));
11175 has_linear && has_moe
11176 }
11177
11178 fn sliding_gated_moe_batch_program(&self) -> bool {
11179 self.uses_sliding_gated_moe_program()
11180 }
11181
11182 fn gemma_batch_program(&self) -> bool {
11183 self.uses_gemma_program()
11184 }
11185
11186 /// Reduced-matrix admission for increment 1. This deliberately does not change the PP-2
11187 /// serving policy: the worker calls it only after `MEMRA_SPEC_PIPE=1` and an explicit spec
11188 /// session already exist.
11189 pub fn spec_pipe_available(&self, e: &Engine) -> bool {
11190 if std::env::var("MEMRA_SPEC_PIPE").as_deref() != Ok("1")
11191 || !spec_devacc()
11192 || spec_replay_env_enabled()
11193 || spec_stream()
11194 || std::env::var("MEMRA_SPEC_ADAPT").as_deref() == Ok("1")
11195 || std::env::var("MEMRA_SPEC_PMIN0").as_deref() == Ok("1")
11196 || std::env::var("MEMRA_SPEC_PP_ANATOMY").as_deref() == Ok("1")
11197 || std::env::var("MEMRA_SPEC_PMIN")
11198 .ok()
11199 .and_then(|v| v.parse::<f32>().ok())
11200 .unwrap_or(0.0)
11201 > 0.0
11202 || self.is_gemma4_e4b()
11203 || self.gemma_batch_program()
11204 || self.mtp.is_none()
11205 || !self.mtp_extra.is_empty()
11206 // Both paired lanes would otherwise hold the model-global verify-graph mutex across
11207 // setup and wait for each other. Independent graph pools are future work; the pair
11208 // requires the explicit eager-verify arm today.
11209 || crate::spec::spec_verify_graph_env()
11210 .unwrap_or_else(|| self.vgraph_family_default())
11211 {
11212 return false;
11213 }
11214 let Some(cuts) = crate::pp::pp_cuts(self.layers.len()) else {
11215 return false;
11216 };
11217 if cuts.len() != 3 || crate::pp::pp2_streams_off() || !crate::pp::spec_pp_on() {
11218 return false;
11219 }
11220 crate::pp::PpNRt::get(e)
11221 .map(|rt| rt.n_stages() == 2 && rt.cross_device())
11222 .unwrap_or(false)
11223 }
11224
11225 /// Two warm greedy continuation bursts over one PP-2 interval coordinator. The two existing
11226 /// `generate_spec_inner2` call stacks own all per-session round locals; only phase issue order
11227 /// changes. No callback is accepted in increment 1 — the worker publishes each completed burst.
11228 #[allow(clippy::too_many_arguments)]
11229 #[allow(clippy::type_complexity)] // allow: one-shot composite type; naming it would hide the shape that matters at the call site
11230 pub fn generate_spec_session_pair(
11231 &self,
11232 e: &Engine,
11233 sess_a: &mut SpecSession,
11234 max_new_a: usize,
11235 k_a: usize,
11236 sess_b: &mut SpecSession,
11237 max_new_b: usize,
11238 k_b: usize,
11239 ) -> Result<((Vec<u32>, usize, usize), (Vec<u32>, usize, usize)), Box<dyn std::error::Error>>
11240 {
11241 self.refuse_hyper("generate_spec_session_pair")?;
11242 if !self.spec_pipe_available(e) {
11243 return Err("two-session speculative pipeline is outside its reduced matrix".into());
11244 }
11245 let rt = crate::pp::PpNRt::get(e)?;
11246 let pp_walk = rt.acquire_walk("generate_spec_session_pair")?;
11247 let pp_permit = rt.walk_permit(&pp_walk, "generate_spec_session_pair")?;
11248 if max_new_a == 0 || max_new_b == 0 || k_a == 0 || k_b == 0 {
11249 return Err(
11250 "two-session speculative pipeline requires non-empty positive-K bursts".into(),
11251 );
11252 }
11253 for sess in [&*sess_a, &*sess_b] {
11254 if sess.committed.is_empty()
11255 || sess.last_h.is_none()
11256 || (sess.next_pred.is_none() && sess.pending_tok.is_none())
11257 {
11258 return Err("two-session speculative pipeline requires warm continuations".into());
11259 }
11260 }
11261
11262 let graph_ok = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
11263 && !spec_host_embd()
11264 && self.mtp_graph_capturable()
11265 && self.mtp_extra.is_empty()
11266 && !crate::model::full_prec_enabled();
11267 let graph_a = graph_ok && k_a + 2 < 96;
11268 let graph_b = graph_ok && k_b + 2 < 96;
11269 let was_tracking = e.ctx().is_event_tracking();
11270 if (graph_a || graph_b) && was_tracking {
11271 unsafe {
11272 e.ctx().disable_event_tracking();
11273 }
11274 }
11275
11276 static LOGGED: std::sync::Once = std::sync::Once::new();
11277 LOGGED.call_once(|| {
11278 eprintln!("[spec-pipe] two-session PP-2 continuation pipeline engaged");
11279 });
11280 let sync = std::sync::Arc::new(SpecPipeSync::new());
11281 let lane_a = SpecPipeLane {
11282 sync: sync.clone(),
11283 lane: 0,
11284 rt,
11285 walk_permit: pp_permit.clone(),
11286 };
11287 let lane_b = SpecPipeLane {
11288 sync,
11289 lane: 1,
11290 rt,
11291 walk_permit: pp_permit,
11292 };
11293 let mut sess_b_ptr = SpecPipeSessionPtr(sess_b as *mut SpecSession);
11294 let (result_a, result_b) = std::thread::scope(|scope| {
11295 let b = scope.spawn(move || {
11296 let mut finish = SpecPipeFinish::new(&lane_b);
11297 let sess_b = unsafe { sess_b_ptr.get_mut() };
11298 let result = (|| -> Result<_, String> {
11299 e.ctx().bind_to_thread().map_err(|err| err.to_string())?;
11300 self.generate_spec_inner2(
11301 e,
11302 &[],
11303 max_new_b,
11304 k_b,
11305 graph_b,
11306 Some(sess_b),
11307 None,
11308 None,
11309 None,
11310 None,
11311 Some(&lane_b),
11312 )
11313 .map_err(|err| err.to_string())
11314 })();
11315 finish.close(result.is_err());
11316 result
11317 });
11318 let mut finish = SpecPipeFinish::new(&lane_a);
11319 let result_a = self.generate_spec_inner2(
11320 e,
11321 &[],
11322 max_new_a,
11323 k_a,
11324 graph_a,
11325 Some(sess_a),
11326 None,
11327 None,
11328 None,
11329 None,
11330 Some(&lane_a),
11331 );
11332 finish.close(result_a.is_err());
11333 let result_b = b
11334 .join()
11335 .map_err(|_| "paired speculative session B panicked".to_string())
11336 .and_then(|r| r);
11337 (result_a, result_b)
11338 });
11339
11340 if (graph_a || graph_b) && was_tracking {
11341 unsafe {
11342 e.ctx().enable_event_tracking();
11343 }
11344 }
11345 let result_a = result_a?;
11346 let result_b = result_b.map_err(|err| -> Box<dyn std::error::Error> { err.into() })?;
11347 Ok((result_a, result_b))
11348 }
11349
11350 /// One spec-decode turn on a live session. `suffix` = the NEW tokens only (turn N+1's user
11351 /// message rendered through the chat template continuation). Returns (new tokens emitted,
11352 /// drafted, accepted); session.committed grows by suffix + emitted.
11353 pub fn generate_spec_session(
11354 &self,
11355 e: &Engine,
11356 sess: &mut SpecSession,
11357 suffix: &[u32],
11358 max_new: usize,
11359 k: usize,
11360 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
11361 self.generate_spec_session_sampled(e, sess, suffix, max_new, k, None, None)
11362 }
11363
11364 /// Serve-path sampled spec: routes the burst through the rejection-sampling verify with
11365 /// per-SESSION Philox continuity (sess.sctr/uctr). None = env-driven (CLI) or greedy.
11366 /// Filters (top-k/p/min-p) apply SYMMETRICALLY to draft q and verify p — distribution-exact
11367 /// for the filtered target (feat/filtered-spec).
11368 ///
11369 /// `on_commit` (sse-cadence, 2026-08-05): called with each newly-emitted slice of the
11370 /// output — once right after the prime's first token, then once per round commit — so a
11371 /// streaming caller can flush text at round cadence instead of once per burst. The slices
11372 /// are disjoint, in order, and concatenate to exactly the returned token vec. Emission-
11373 /// timing only: token bytes, session state, and exactness are untouched.
11374 ///
11375 /// The returned bool is a CONTINUE-VERDICT (admission yield, 2026-08-06): `false` ends
11376 /// the burst at the current round boundary, exactly as if `max_new` had been reached —
11377 /// the caller's scheduler regains control without waiting the burst out. Burst size is
11378 /// content-neutral (spec-levers battery), so an early exit moves WHEN the burst returns,
11379 /// never what tokens say. The slice may be EMPTY (a poll-only boundary — round-stream
11380 /// drains and the defensive tail flush can land with nothing new committed).
11381 #[allow(clippy::too_many_arguments)]
11382 #[allow(clippy::type_complexity)] // allow: one-shot composite type; naming it would hide the shape that matters at the call site
11383 pub fn generate_spec_session_sampled(
11384 &self,
11385 e: &Engine,
11386 sess: &mut SpecSession,
11387 suffix: &[u32],
11388 max_new: usize,
11389 k: usize,
11390 sampling: Option<SpecSampling>,
11391 on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
11392 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
11393 self.generate_spec_session_sampled_prime_split(
11394 e, sess, suffix, max_new, k, sampling, None, on_commit,
11395 )
11396 }
11397
11398 /// Serve-only cold-prime segmentation twin. `prime_split` is the same stable boundary the
11399 /// plain worker would honor before entering its sub-floor tokenwise tail; warm continuations
11400 /// pass `None` and stay on the existing zero-prime path.
11401 #[allow(clippy::too_many_arguments)]
11402 #[allow(clippy::type_complexity)] // allow: one-shot composite type; naming it would hide the shape that matters at the call site
11403 pub fn generate_spec_session_sampled_prime_split(
11404 &self,
11405 e: &Engine,
11406 sess: &mut SpecSession,
11407 suffix: &[u32],
11408 max_new: usize,
11409 k: usize,
11410 sampling: Option<SpecSampling>,
11411 prime_split: Option<usize>,
11412 on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
11413 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
11414 self.generate_spec_session_constrained_prime_split(
11415 e,
11416 sess,
11417 suffix,
11418 max_new,
11419 k,
11420 sampling,
11421 None,
11422 prime_split,
11423 on_commit,
11424 )
11425 }
11426
11427 /// `generate_spec_session_sampled` + GRAMMAR (constrained decoding, 2026-08-03): the
11428 /// hook truncates acceptance at the first grammar-illegal token AFTER the exactness
11429 /// verify (grammar is an extra rejection rule, ordering like the batched-verify twins)
11430 /// and replaces an illegal bonus with the MASKED argmax of the target's own verify
11431 /// column — token-identical to constrained plain greedy decode. GREEDY only (the
11432 /// worker routes sampled constrained to plain decode). Acceptance under tight grammars
11433 /// may drop (drafter is unconstrained); that is measured, not hidden.
11434 #[allow(clippy::too_many_arguments)]
11435 #[allow(clippy::type_complexity)] // allow: one-shot composite type; naming it would hide the shape that matters at the call site
11436 pub fn generate_spec_session_constrained(
11437 &self,
11438 e: &Engine,
11439 sess: &mut SpecSession,
11440 suffix: &[u32],
11441 max_new: usize,
11442 k: usize,
11443 sampling: Option<SpecSampling>,
11444 constraint: Option<&mut dyn SpecConstraint>,
11445 on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
11446 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
11447 self.generate_spec_session_constrained_prime_split(
11448 e, sess, suffix, max_new, k, sampling, constraint, None, on_commit,
11449 )
11450 }
11451
11452 #[allow(clippy::too_many_arguments)]
11453 #[allow(clippy::type_complexity)] // allow: one-shot composite type; naming it would hide the shape that matters at the call site
11454 pub fn generate_spec_session_constrained_prime_split(
11455 &self,
11456 e: &Engine,
11457 sess: &mut SpecSession,
11458 suffix: &[u32],
11459 max_new: usize,
11460 k: usize,
11461 sampling: Option<SpecSampling>,
11462 constraint: Option<&mut dyn SpecConstraint>,
11463 prime_split: Option<usize>,
11464 on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
11465 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
11466 if constraint.is_some() && sampling.is_some_and(|s| s.temp > 0.0) {
11467 return Err(
11468 "constrained spec decode is greedy-only (worker routes sampled \
11469 constrained to plain decode)"
11470 .into(),
11471 );
11472 }
11473 // PENDING-CARRY entry flush: a carried bonus precedes any new suffix in the sequence,
11474 // so it must commit BEFORE the suffix primes; the sampled path doesn't carry (its
11475 // round-0 accept needs the commit pass's logits). Empty-suffix greedy bursts — the
11476 // serve continuation case — consume the carry in-loop with zero solo passes.
11477 if sess.pending_tok.is_some()
11478 && (!suffix.is_empty() || sampling.is_some_and(|s| s.temp > 0.0))
11479 {
11480 self.spec_flush_pending(e, sess, sampling)?;
11481 }
11482
11483 // FULL_PREC forces the EAGER draft: the graph capture would enclose cuBLASLt f32 GEMV
11484 // (the FloatBf16 else-branches) and a bf16_to_f32 dequant alloc — neither is stream-capture
11485 // safe. Eager rides matmul/matmul_decode_exact, which dequant FloatBf16 on use. (§item 2.)
11486 // Multi-head MTP (mtp_extra non-empty) no longer disqualifies: the chain captures
11487 // per-head graphs (lane/step37-draft-graph-serving-20260830, MEMRA_MTP_CHAIN_GRAPH).
11488 let graph_draft = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
11489 && !spec_host_embd()
11490 && self.mtp_graph_capturable()
11491 && k + 2 < 96
11492 && !crate::model::full_prec_enabled();
11493 let was_tracking = e.ctx().is_event_tracking();
11494 if graph_draft && was_tracking {
11495 unsafe {
11496 e.ctx().disable_event_tracking();
11497 }
11498 }
11499 let r = self.generate_spec_inner2(
11500 e,
11501 suffix,
11502 max_new,
11503 k,
11504 graph_draft,
11505 Some(sess),
11506 sampling,
11507 constraint,
11508 on_commit,
11509 prime_split,
11510 None,
11511 );
11512 if graph_draft && was_tracking {
11513 unsafe {
11514 e.ctx().enable_event_tracking();
11515 }
11516 }
11517 let (out, d, a) = r?;
11518 Ok((out, d, a))
11519 }
11520
11521 pub fn generate_spec(
11522 &self,
11523 e: &Engine,
11524 prompt: &[u32],
11525 max_new: usize,
11526 k: usize,
11527 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
11528 // glm5 T-parallel verify door (lane/glm5-tparallel-verify): an hc trunk with a
11529 // loaded DRAFT SOURCE — the embedded MTP head OR the DFlash2 drafter
11530 // (lane/glm5-dflash-draft-src) — routes to the glm5 draft->verify->rollback loop —
11531 // MEMRA_GLM5_SPEC=1 only (default OFF; flag row in FLAGS.md). Unset/0 falls
11532 // through to the standing named refusal below, byte-identical to the pre-lane
11533 // binary. Same fail-closed manifest stance as the generic path: an unqualified
11534 // MtpSpec rewrite refuses before any drafting.
11535 if self.hyper.is_some()
11536 && crate::glm_spec::glm5_spec_on()
11537 && (self.mtp.is_some() || self.glm5_dflash.is_some())
11538 {
11539 if !self.rewrite_allowed(memra_gguf::execution_manifest::RewriteSurface::MtpSpec) {
11540 return Err("speculative rewrite is not qualified for this ModelPlan".into());
11541 }
11542 return self.generate_spec_glm5(e, prompt, max_new, k);
11543 }
11544 self.refuse_hyper("generate_spec")?;
11545 if crate::pp::pp_cuts(self.layers.len()).is_some()
11546 && !self.rewrite_allowed(memra_gguf::execution_manifest::RewriteSurface::Pipeline)
11547 {
11548 return Err("pipeline rewrite is not qualified for speculative decode".into());
11549 }
11550 if !self.rewrite_allowed(memra_gguf::execution_manifest::RewriteSurface::MtpSpec) {
11551 return Err("speculative rewrite is not qualified for this ModelPlan".into());
11552 }
11553 // FULL_PREC forces eager (see generate_spec_session note): CUDA graph capture cannot
11554 // enclose cuBLASLt f32 GEMV or the bf16_to_f32 dequant alloc the FloatBf16 path needs.
11555 // Multi-head MTP no longer disqualifies (chain graphs; see generate_spec_session).
11556 let graph_draft = std::env::var("MEMRA_SPEC_NOGRAPH").is_err()
11557 && !spec_host_embd()
11558 && self.mtp_graph_capturable()
11559 && k + 2 < 96
11560 && !crate::model::full_prec_enabled();
11561 if !graph_draft {
11562 return self.generate_spec_inner2(
11563 e, prompt, max_new, k, false, None, None, None, None, None, None,
11564 );
11565 }
11566 let was_tracking = e.ctx().is_event_tracking();
11567 if was_tracking {
11568 unsafe {
11569 e.ctx().disable_event_tracking();
11570 }
11571 }
11572 let r = self.generate_spec_inner2(
11573 e, prompt, max_new, k, true, None, None, None, None, None, None,
11574 );
11575 if was_tracking {
11576 unsafe {
11577 e.ctx().enable_event_tracking();
11578 }
11579 }
11580 r
11581 }
11582
11583 #[allow(clippy::type_complexity)] // allow: one-shot composite type; naming it would hide the shape that matters at the call site
11584 #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
11585 fn generate_spec_inner2(
11586 &self,
11587 e: &Engine,
11588 prompt: &[u32],
11589 max_new: usize,
11590 k: usize,
11591 graph_draft: bool,
11592 mut sess: Option<&mut SpecSession>,
11593 sampling: Option<SpecSampling>,
11594 mut constraint: Option<&mut dyn SpecConstraint>,
11595 mut on_commit: Option<&mut dyn FnMut(&[u32]) -> bool>,
11596 prime_split: Option<usize>,
11597 pipe: Option<&SpecPipeLane>,
11598 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
11599 assert!(k >= 1, "k must be >= 1");
11600 let pipe_setup_walk = match pipe {
11601 Some(p) => Some(p.setup_begin()?),
11602 None => None,
11603 };
11604 // sse-cadence flush cursor: everything in out[..flushed] has been handed to on_commit.
11605 let mut flushed = 0usize;
11606 // admission yield (2026-08-06): on_commit's continue-verdict; false = end the burst
11607 // at the next round boundary (same exit as max_new reached — the session tail runs).
11608 // Initialized by the unconditional post-prime flush below.
11609 let mut keep_going;
11610 let mtp = self
11611 .mtp
11612 .as_ref()
11613 .expect("generate_spec requires an MTP head (nextn_predict_layers>0)");
11614 let n_vocab = self.output.out_features();
11615 // FR-Spec: the draft head may be TRIMMED (fewer rows than n_vocab); the draft argmax runs
11616 // over the draft vocab and the winning index maps through d2t to a TARGET token id.
11617 // Everything downstream (verify/accept/commit) sees target ids only — exactness unchanged.
11618 let d_vocab = mtp
11619 .shared_head_head
11620 .as_ref()
11621 .unwrap_or(&self.output)
11622 .out_features();
11623 if !self.mtp_extra.is_empty() {
11624 if self.plan.draft_source != memra_gguf::model_plan::DraftSourcePlan::Embedded
11625 || self.plan.mtp_blocks.len() != self.mtp_head_count()
11626 {
11627 return Err(
11628 "multi-head MTP requires one embedded canonical block per loaded head".into(),
11629 );
11630 }
11631 // TRIMMED chains (2026-08-27): every head must carry the SAME d2t — the ranking is
11632 // token-frequency and head-independent, and every downstream remap (per-step argmax,
11633 // stream pack, sampled d2t_dev) reads head 0's map, so equality is what makes that
11634 // single map correct for the whole chain. Mixed trimmed/untrimmed is refused.
11635 for (offset, head) in self.mtp_extra.iter().enumerate() {
11636 if head.d2t != mtp.d2t
11637 || head
11638 .shared_head_head
11639 .as_ref()
11640 .unwrap_or(&self.output)
11641 .out_features()
11642 != d_vocab
11643 {
11644 return Err(format!(
11645 "embedded MTP head {} has incompatible draft vocabulary",
11646 offset + 1
11647 )
11648 .into());
11649 }
11650 }
11651 eprintln!(
11652 "[mtp-chain] heads={} policy=step-modulo prefix-replay kv=per-head",
11653 self.mtp_head_count()
11654 );
11655 }
11656 let n_embd = self.cfg.n_embd as usize;
11657 // SESSION MODE: reuse the live cache/scratch, prime only the suffix. `base` = tokens
11658 // already committed (their state is in the caches); 0 = fresh single-shot call.
11659 let session_mode = sess.is_some();
11660 let max_ctx = match sess.as_ref() {
11661 Some(s) => s.cache.max_ctx,
11662 None => prompt.len() + max_new + k + 8,
11663 };
11664 let mut own_cache;
11665 let mut own_scratch;
11666 // PREFIX-CACHE capture request threaded out of the session (lane/spec-prefix-cache):
11667 // (requested split, destination list). Single-shot per burst; fresh calls have none.
11668 let mut sess_capture: Option<(Option<usize>, &mut Vec<SpecBoundaryCapture>)> = None;
11669 // STABLE-BOUNDARY turn-checkpoint request (lane/frspec-multiturn-cache): ABSOLUTE
11670 // committed-length position; consumed one-shot like `capture_at`. None = legacy
11671 // prompt-end capture below.
11672 let mut ckpt_req: Option<usize> = None;
11673 // FAIL-SAFE bit threaded out of the session (see `SpecSession::capture_disabled`).
11674 let mut sess_capture_disabled = false;
11675 let (
11676 cache,
11677 scratch,
11678 mut sess_tail,
11679 mut sess_draft_slot,
11680 mut sess_pending_slot,
11681 sess_ckpt_slot,
11682 sess_telem,
11683 ): (
11684 &mut Cache,
11685 &mut MtpScratch,
11686 Option<(
11687 &mut Vec<u32>,
11688 &mut Option<CudaSlice<f32>>,
11689 &mut Option<u32>,
11690 &mut u32,
11691 &mut u32,
11692 )>,
11693 Option<&mut Option<DraftGraphCtx>>,
11694 Option<&mut Option<u32>>,
11695 Option<&mut Option<SpecCheckpoint>>,
11696 Option<&SpecTelemetryCounters>,
11697 ) = match sess.take() {
11698 Some(sr) => {
11699 let SpecSession {
11700 cache,
11701 scratch,
11702 committed,
11703 last_h,
11704 next_pred,
11705 sctr: s_sctr,
11706 uctr: s_uctr,
11707 draft_ctx,
11708 pending_tok,
11709 turn_ckpt,
11710 telem,
11711 capture_at,
11712 boundary_captures,
11713 ckpt_at,
11714 capture_disabled,
11715 } = sr;
11716 sess_capture_disabled = *capture_disabled;
11717 sess_capture = Some((capture_at.take(), boundary_captures));
11718 ckpt_req = ckpt_at.take();
11719 (
11720 cache,
11721 scratch,
11722 Some((committed, last_h, next_pred, s_sctr, s_uctr)),
11723 Some(draft_ctx),
11724 Some(pending_tok),
11725 Some(turn_ckpt),
11726 Some(telem),
11727 )
11728 }
11729 None => {
11730 // STAGE-OWNED KV (lane/pp2-spec 2026-08-06) — see `new_session`. Door shut =
11731 // `Cache::new` verbatim.
11732 own_cache = crate::pp::new_cache_planned(e, &self.cfg, &self.plan, max_ctx)?;
11733 // Persistent scratch = max_ctx rows (~2KB/token quantized).
11734 own_scratch = self.new_mtp_scratch(e, max_ctx)?;
11735 (
11736 &mut own_cache,
11737 &mut own_scratch,
11738 None,
11739 None,
11740 None,
11741 None,
11742 None,
11743 )
11744 }
11745 };
11746 cache.ensure_usable("generate_spec")?;
11747 if scratch.plane_count() != self.mtp_head_count() {
11748 return Err(format!(
11749 "MTP scratch/head count mismatch ({}/{})",
11750 scratch.plane_count(),
11751 self.mtp_head_count()
11752 )
11753 .into());
11754 }
11755 let base = cache.pos;
11756 // PENDING-CARRY consume (2026-08-01): a carried bonus reaches here only on the
11757 // empty-suffix GREEDY continuation path (generate_spec_session_sampled flushed every
11758 // other case). It enters the round loop as round-0's pending — verify col 0 — exactly
11759 // like a mid-burst full-accept boundary: no init feed, no tail commit pass.
11760 let carried_pending: Option<u32> = sess_pending_slot.as_mut().and_then(|s| s.take());
11761 // PERSISTENT DRAFT KV (the only mode since 2026-07-08 — the legacy round-local scratch,
11762 // MEMRA_SPEC_KVLOCAL, measured -35 acceptance pts on the 27B p3 sweep and was removed;
11763 // acceptance-only — exactness is verify's job either way).
11764 // HIDDEN-PAIRING CONVENTION (DEFAULT = predecessor-row, 2026-07-04 — the 27B acceptance
11765 // unlock, +16pts): the MTP head is TRAINED on rows pairing token x_p with the trunk
11766 // hidden of its PREDECESSOR h_{p-1} (the reference engine's mtp_update shifts the target
11767 // hiddens right by one; its draft step 0 feeds (id_last, TRUE hidden of the row id_last
11768 // was sampled from)). memra's historical convention paired SAME-ROW (x_p, h_p) in the fill
11769 // and seeded chain step 0 through an extra MTP pass on a duplicated token (the
11770 // pseudo-seed) — measured 27B p2 K=3 acceptance 0.569 vs 0.731, p3 0.445 vs 0.63+, and
11771 // the chain steps j>=1 were already predecessor-shaped, so ONLY the fill + step-0 seed
11772 // move. The fill shifts by one and the chain seeds from the predecessor's true hidden
11773 // DIRECTLY (vh_seed / vx[j-1]) — the pseudo pass disappears (one MTP-block pass saved
11774 // per round on top of the acceptance win). Draft-quality-only: exactness stays the
11775 // verify's job either way. (The legacy same-row pairing seam, MEMRA_SPEC_HSAME, and its
11776 // pseudo-seed passes were removed 2026-07-08 — predecessor pairing won by +16 acc pts;
11777 // the legacy round-local scratch, MEMRA_SPEC_KVLOCAL, went with it.)
11778 // REPLAY-FREE PARTIAL ACCEPT (default, 2026-07-03): partial rounds keep the verify's own
11779 // bit-identical committed-prefix state (KV truncate + recur rebuild from the VerifyCkpt)
11780 // and leave the bonus PENDING — no duplicate trunk pass (profiled ~0.54 extra full weight
11781 // reads/round at long ctx). MEMRA_SPEC_REPLAY=1 restores the legacy rollback+replay (A/B
11782 // + fallback seam).
11783 // Qwen35-MoE replay pin LIFTED (lane/draftcost-moe, 2026-08-20). The pin's stated
11784 // bar — the retained verify-state commit proven equivalent to sequential serving —
11785 // was waiting on this arch running the serving batched verify class, which the
11786 // t-parallel admission (this lane, increment 1) provided: the VerifyCkpt the
11787 // replay-free commit consumes is now produced by the SAME serving-class verify that
11788 // qualified dense qwen35 on 2026-08-15 (where the per-round duplicate replay
11789 // measured 69 -> 30 tok/s). Qualification receipts (run-spec K=1..8 both arms,
11790 // 8-prompt replay-vs-replay-free canary, long-prompt cell):
11791 // research/draftcost-moe-20260820/RECEIPTS.md. MEMRA_SPEC_REPLAY=1 stays the
11792 // rollback + A/B seam.
11793 let spec_replay = spec_replay_env_enabled();
11794 if constraint.is_some() && spec_replay {
11795 return Err(
11796 "constrained spec decode does not support MEMRA_SPEC_REPLAY=1 \
11797 (legacy replay commits an unmasked bonus)"
11798 .into(),
11799 );
11800 }
11801 // TRUE-HIDDEN REFRESH (default in persistent-draft-KV mode): every round overwrites the
11802 // committed positions' scratch entries from the verify's exact hiddens (mtp_kv_fill batch)
11803 // instead of keeping chain-approximate entries. MEMRA_SPEC_NOREFRESH=1 = legacy (A/B seam).
11804 let refresh = std::env::var("MEMRA_SPEC_NOREFRESH").is_err();
11805 if !refresh && !self.mtp_extra.is_empty() {
11806 return Err("multi-head MTP requires exact accepted-prefix refresh".into());
11807 }
11808
11809 // prime: BATCHED cache prime (prime_cache — the measured #1 e2e gap: tokenwise primed at
11810 // ~102/38 tok/s vs the engine's ~2000-5900 tok/s batched prefill). prime_cache returns the
11811 // full pre-output_norm hidden stack [T, n_embd], which IS prompt_h (the persistent-draft-KV
11812 // mtp_kv_fill input) — no per-token collection needed. Prompts below PRIME_MIN_T, and
11813 // MEMRA_PRIME_TOKENWISE=1, and frozen Hy3 CPU/GPU expert splits take the tokenwise
11814 // decode_step_h loop. The latter avoids transient GPU staging of the spilled expert bank.
11815 // EMPTY-SUFFIX CONTINUATION (serve bursts): a session turn with NO new tokens resumes
11816 // generation exactly where the last turn stopped — no prime at all. The stashed
11817 // `next_pred` plays prime_logits' role: it is the token produced from the logits after
11818 // committed.last() by the same rule this entry applies to a cold prime's last row —
11819 // an argmax when greedy, a `sample_boundary_token` draw when sampled (the burst tail,
11820 // or `spec_session_from_restored` for a converted prefix-cache hit, did the drawing
11821 // where the sampler and the session's Philox counters were live). `last_h` seeds the
11822 // predecessor pairing below. Fresh calls and non-empty suffixes take the normal path.
11823 let continuation = prompt.is_empty();
11824 if continuation {
11825 assert!(session_mode, "empty prompt requires a session");
11826 assert!(
11827 sess_tail
11828 .as_ref()
11829 .is_some_and(|(c, lh, np, _, _)| !c.is_empty()
11830 && lh.is_some()
11831 && (np.is_some() || carried_pending.is_some())),
11832 "empty-suffix continuation needs a primed session (committed + last_h + next_pred|pending)"
11833 );
11834 }
11835 let mut prime_logits;
11836 let mut prompt_h: Option<CudaSlice<f32>> = None;
11837 let t_prime = std::time::Instant::now();
11838 let batched_prime = !continuation
11839 && prompt.len() >= crate::hybrid_forward::PRIME_MIN_T
11840 && std::env::var("MEMRA_PRIME_TOKENWISE").is_err()
11841 && !e.frozen_cpu_experts_prefer_tokenwise_prime();
11842 let prime_split = prime_split.filter(|&split| split > 0 && split < prompt.len());
11843 if prime_split.is_some() && continuation {
11844 return Err("spec prime split requires a non-empty prime".into());
11845 }
11846 // STABLE-BOUNDARY TURN CHECKPOINT stop (lane/frspec-multiturn-cache, 2026-08-21):
11847 // the worker's `ckpt_at` request, ABSOLUTE -> prompt-relative. On WARM bursts
11848 // (base != 0, an affinity-rewound or pool-resumed session priming its own delta)
11849 // this is the only stop; on COLD bursts it usually coincides with `prime_split`
11850 // (both are the plain tier's stable pre-generation boundary). A boundary the prime
11851 // cannot honor (outside this prime's range) silently drops the capture — the
11852 // turn_ckpt convention: the next turn re-primes in full, never a wrong resume.
11853 let ckpt_rel = if continuation {
11854 None
11855 } else {
11856 ckpt_req
11857 .and_then(|abs| abs.checked_sub(base))
11858 .filter(|&r| r > 0 && r < prompt.len())
11859 };
11860 // Prime stops, ordered: each is a boundary the prime halts at so the in-place GDN
11861 // conv/ssm state can be snapshotted there (the only moment it exists). One stop =
11862 // the legacy single-split program, byte-for-byte.
11863 let mut stops: Vec<usize> = Vec::new();
11864 for b in [prime_split, ckpt_rel].into_iter().flatten() {
11865 if !stops.contains(&b) {
11866 stops.push(b);
11867 }
11868 }
11869 stops.sort_unstable();
11870 // Captured at the ckpt stop, installed into the session slot post-prime (replacing
11871 // the legacy prompt-end capture). Some(None) = capture attempted and failed -> the
11872 // slot is cleared (a stale checkpoint would rewind to the WRONG boundary).
11873 let mut ckpt_early: Option<Option<SpecCheckpoint>> = None;
11874 if continuation {
11875 prime_logits = Vec::new();
11876 } else if !stops.is_empty() {
11877 if let Some(&first) = stops.first()
11878 && prime_split == Some(first)
11879 && first < crate::hybrid_forward::PRIME_MIN_T
11880 {
11881 return Err(format!(
11882 "spec prime split {first} is below PRIME_MIN_T {}",
11883 crate::hybrid_forward::PRIME_MIN_T,
11884 )
11885 .into());
11886 }
11887 // Mirror the plain worker's boundary stops exactly. Each segment is a
11888 // request-level prime (`queued_after` keeps Step35 arm selection independent of
11889 // the stops — tick-seg law); a segment below PRIME_MIN_T (and the final tail
11890 // under MEMRA_PRIME_TOKENWISE) takes the same eager tokenwise continuation as
11891 // prefill_tick. Retain every hidden row so the draft scratch fill remains one
11892 // coherent prompt.
11893 let mut h_all = e.uninit(prompt.len() * n_embd)?;
11894 prime_logits = Vec::new();
11895 let mut prev = 0usize;
11896 for seg_end in stops.iter().copied().chain(std::iter::once(prompt.len())) {
11897 if seg_end <= prev {
11898 continue;
11899 }
11900 let seg = &prompt[prev..seg_end];
11901 let is_final = seg_end == prompt.len();
11902 let batched_seg = seg.len() >= crate::hybrid_forward::PRIME_MIN_T
11903 && (!is_final
11904 || (std::env::var("MEMRA_PRIME_TOKENWISE").is_err()
11905 && !e.frozen_cpu_experts_prefer_tokenwise_prime()));
11906 if batched_seg {
11907 let (l, _, h_seg) =
11908 self.prime_cache(e, seg, &mut *cache, prompt.len() - seg_end)?;
11909 e.copy_into(&mut h_all, prev * n_embd, &h_seg, seg.len() * n_embd)?;
11910 prime_logits = l;
11911 } else {
11912 for (i, &tok) in seg.iter().enumerate() {
11913 let (l, h) = self.decode_step_h(e, tok, &mut *cache)?;
11914 e.copy_into(&mut h_all, (prev + i) * n_embd, &h, n_embd)?;
11915 prime_logits = l;
11916 }
11917 }
11918 prev = seg_end;
11919 if is_final {
11920 break;
11921 }
11922 debug_assert_eq!(cache.pos, base + seg_end, "prime stop landed off boundary");
11923 // PREFIX-CACHE BOUNDARY CAPTURE (lane/spec-prefix-cache): the GDN conv/ssm
11924 // states are about to be advanced in place by the next segment, so this is
11925 // the ONLY moment the boundary's recurrent state exists. Capture iff the
11926 // worker requested exactly this stop (cold sessions only — `capture_at` is
11927 // never armed warm). A failed snapshot is silent (turn_ckpt convention) —
11928 // publication is an optimization, never a correctness dependency.
11929 if base == 0
11930 && let Some((requested, slot)) = sess_capture.as_mut()
11931 {
11932 // Publish at the requested miss-LCP stop (the shared-prefix class)
11933 // AND at the stable-boundary stop (the next-turn re-render class,
11934 // lane/frspec-multiturn-cache) — the same boundary set the plain
11935 // prefill tick learns. Without the second entry, the turn after a
11936 // cold re-park could only hit the OLDER lcp entry (the measured
11937 // one-turn transient: t3 restored 607 of 24122 while the plain arm
11938 // rewound to 15222). Dedupe is the worker sweep's has_key.
11939 if (*requested == Some(seg_end) || ckpt_rel == Some(seg_end))
11940 && let Ok(snap) = cache.snapshot(e)
11941 {
11942 slot.push(SpecBoundaryCapture {
11943 snap,
11944 pos: seg_end,
11945 logits: prime_logits.clone(),
11946 // rows [0..seg_end) of h_all are primed — the following
11947 // segments append, never overwrite.
11948 last_h: capture_boundary_hidden(e, &h_all, seg_end, n_embd),
11949 latent_tails: Vec::new(),
11950 });
11951 }
11952 }
11953 // SESSION-AFFINITY TURN CHECKPOINT at the STABLE boundary (see `ckpt_at`):
11954 // same snapshot mechanics, installed post-prime in place of the prompt-end
11955 // capture the re-render class always diverged below.
11956 if ckpt_rel == Some(seg_end) {
11957 let anchor: Result<CudaSlice<f32>, Box<dyn std::error::Error>> =
11958 e.uninit(n_embd).and_then(|mut a| {
11959 e.copy_view_into(
11960 &mut a,
11961 0,
11962 &h_all.slice((seg_end - 1) * n_embd..seg_end * n_embd),
11963 n_embd,
11964 )?;
11965 Ok(a)
11966 });
11967 ckpt_early = Some(match (cache.snapshot(e), anchor) {
11968 (Ok(snap), Ok(last_h)) => Some(SpecCheckpoint {
11969 snap,
11970 pos: base + seg_end,
11971 last_h,
11972 }),
11973 _ => None,
11974 });
11975 }
11976 }
11977 if std::env::var("MEMRA_SPEC_STATS").as_deref() == Ok("1") {
11978 eprintln!(
11979 "[spec-prime] stops={stops:?} tail={}",
11980 prompt.len() - stops.last().copied().unwrap_or(0)
11981 );
11982 }
11983 prompt_h = Some(h_all);
11984 } else if batched_prime {
11985 let (l, _h_seed, hiddens) = self.prime_cache(e, prompt, &mut *cache, 0)?;
11986 prime_logits = l;
11987 prompt_h = Some(hiddens);
11988 } else {
11989 prime_logits = Vec::new();
11990 prompt_h = Some(e.uninit(prompt.len() * n_embd)?);
11991 for (i, &tok) in prompt.iter().enumerate() {
11992 let (l, h) = self.spec_target_step_h(e, tok, &mut *cache)?;
11993 if let Some(ph) = prompt_h.as_mut() {
11994 e.copy_into(ph, i * n_embd, &h, n_embd)?;
11995 }
11996 prime_logits = l;
11997 }
11998 }
11999 e.stream().synchronize()?;
12000 // PREFIX-CACHE SEED CAPTURE (lane/spec-prefix-cache): boundary == prompt end (the seed
12001 // case — no shared-prefix split, publish the whole prompt). The prime just finished, so
12002 // cache.pos == base + prompt.len() and the recurrent state IS the boundary state;
12003 // prime_logits are the boundary logits. Cold sessions only (base == 0) — same law as
12004 // prime_split. The mid-prompt capture above already consumed the request if it matched.
12005 if !continuation
12006 && base == 0
12007 && let Some((requested, slot)) = sess_capture.as_mut()
12008 && *requested == Some(prompt.len())
12009 && slot.is_empty()
12010 {
12011 debug_assert_eq!(cache.pos, prompt.len(), "seed capture off prompt end");
12012 if let Ok(snap) = cache.snapshot(e) {
12013 slot.push(SpecBoundaryCapture {
12014 snap,
12015 pos: prompt.len(),
12016 logits: prime_logits.clone(),
12017 last_h: prompt_h
12018 .as_ref()
12019 .map(|ph| capture_boundary_hidden(e, ph, prompt.len(), n_embd))
12020 .unwrap_or_default(),
12021 latent_tails: Vec::new(),
12022 });
12023 }
12024 }
12025 // Harness timing contract (see crate::PRIME_NANOS): gen-only throughput without the
12026 // prime-subtraction hack.
12027 crate::PRIME_NANOS.store(
12028 t_prime.elapsed().as_nanos() as u64,
12029 std::sync::atomic::Ordering::Relaxed,
12030 );
12031
12032 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
12033 // Resident table is fastest when it fits. Large spill deployments can preserve that HBM
12034 // for expert-cache slots and gather only the exact rows needed by MTP/verify from host.
12035 let host_embd = spec_host_embd();
12036 let embd_gpu = if host_embd {
12037 None
12038 } else {
12039 Some(
12040 self.embd_gpu
12041 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
12042 )
12043 };
12044 let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
12045 if host_embd {
12046 eprintln!(
12047 "[spec] host-row embedding: {} bytes kept off HBM",
12048 self.embd.raw.len()
12049 );
12050 }
12051 let mut out: Vec<u32> = Vec::with_capacity(max_new);
12052 let mut total_drafted = 0usize;
12053 let mut total_accepted = 0usize;
12054
12055 // --- SAMPLER FIRST (lane/sampled-spec-quality, 2026-08-19) ---
12056 // The sampler config, the session's Philox counters and the penalty window are parsed
12057 // HERE, above the boundary-token selection, because the boundary token must be drawn
12058 // from the sampler the request asked for. Pre-lane this block sat ~50 lines BELOW the
12059 // selection, which is the whole mechanical reason the boundary token was an argmax:
12060 // the sampler state was not in scope yet. Nothing here depends on the round loop, so
12061 // moving it up is a pure reordering for greedy (`sampled == false` ⇒ every branch
12062 // below takes the argmax path it always took).
12063 // --- SAMPLED SPEC (MEMRA_SPEC_TEMP>0, research/sampled-spec-impl-map.md): rejection-
12064 // sampling verify (Leviathan/Chen) — accept draft x at u < p(x)/q(x), resample from
12065 // norm(max(0,p-q)) on reject, bonus sampled from p on full accept. Counter-based Philox
12066 // everywhere (seed, event) -> reproducible. temp==0/unset = the greedy path, untouched.
12067 let sp = sampling.unwrap_or_else(|| SpecSampling {
12068 temp: std::env::var("MEMRA_SPEC_TEMP")
12069 .ok()
12070 .and_then(|v| v.parse().ok())
12071 .unwrap_or(0.0),
12072 seed: std::env::var("MEMRA_SEED")
12073 .ok()
12074 .and_then(|v| v.parse().ok())
12075 .unwrap_or(42),
12076 top_k: std::env::var("MEMRA_TOP_K")
12077 .ok()
12078 .and_then(|v| v.parse().ok())
12079 .unwrap_or(0),
12080 top_p: std::env::var("MEMRA_TOP_P")
12081 .ok()
12082 .and_then(|v| v.parse().ok())
12083 .unwrap_or(1.0),
12084 min_p: std::env::var("MEMRA_MIN_P")
12085 .ok()
12086 .and_then(|v| v.parse().ok())
12087 .unwrap_or(0.0),
12088 penalty_last_n: std::env::var("MEMRA_PENALTY_LAST_N")
12089 .ok()
12090 .and_then(|v| v.parse().ok())
12091 .unwrap_or(0),
12092 penalty_repeat: std::env::var("MEMRA_PENALTY_REPEAT")
12093 .ok()
12094 .and_then(|v| v.parse().ok())
12095 .unwrap_or(1.0),
12096 penalty_freq: std::env::var("MEMRA_PENALTY_FREQ")
12097 .ok()
12098 .and_then(|v| v.parse().ok())
12099 .unwrap_or(0.0),
12100 penalty_present: std::env::var("MEMRA_PENALTY_PRESENT")
12101 .ok()
12102 .and_then(|v| v.parse().ok())
12103 .unwrap_or(0.0),
12104 });
12105 let (sp_temp, sp_seed) = (sp.temp, sp.seed);
12106 let sampled = sp_temp > 0.0;
12107 // Counters resume from the session (burst continuity: randomness must never repeat
12108 // across generate_spec_session calls); one-shot callers start at (0,0). Read through
12109 // sess_tail — `sess` was take()n into it above, so sess.as_ref() here is always None.
12110 let mut sctr: u32 = sess_tail.as_ref().map(|(_, _, _, s, _)| **s).unwrap_or(0);
12111 let mut uctr: u32 = sess_tail.as_ref().map(|(_, _, _, _, u)| **u).unwrap_or(0);
12112 // Penalties (v2.1): applied to COPIES of q rows and p columns symmetrically (exactness
12113 // for the penalized+filtered target). History = generated tokens, host-tracked window.
12114 let pen_on = sampled
12115 && sp.penalty_last_n > 0
12116 && (sp.penalty_repeat != 1.0 || sp.penalty_freq != 0.0 || sp.penalty_present != 0.0);
12117 // SESSION-SPANNING PENALTY WINDOW (Item 2). Pre-lane this was
12118 // `prompt.iter().rev().take(64).rev()` — the BURST's suffix slice — so a continuation
12119 // burst (the majority of a stream's tokens, and ALL of a converted cache hit's) started
12120 // with an EMPTY penalty history and the client's repetition/frequency/presence penalties
12121 // silently reset at every burst boundary. The window now spans `committed ++ prompt`,
12122 // which is what the API contract says and what the plain sampler's own `history` does.
12123 // Byte-identical to the pre-lane seed for a cold turn-1 burst at the default window.
12124 let mut pen_hist: Vec<u32> = if pen_on {
12125 let sess_hist: &[u32] = if spec_pen_session_on() {
12126 sess_tail
12127 .as_ref()
12128 .map(|(c, ..)| c.as_slice())
12129 .unwrap_or(&[])
12130 } else {
12131 &[] // MEMRA_SPEC_PEN_SESSION=0: pre-lane burst-local window
12132 };
12133 pen_window_seed(sess_hist, prompt, sp.penalty_last_n)
12134 } else {
12135 Vec::new()
12136 };
12137 // First generated token = the BOUNDARY token: greedy takes the argmax of the prompt's
12138 // last logits (== greedy's first token, byte-contract); SAMPLED draws it from the
12139 // request's own filtered/penalized target through the session's Philox stream
12140 // (`sample_boundary_token`, lane/sampled-spec-quality Item 1 — pre-lane this was an
12141 // argmax in both regimes, so ~1 token per burst of a sampled stream was greedy).
12142 // Emit it, then FEED it to establish the loop invariant below.
12143 // PENDING-CARRY: the carried bonus was already emitted by the LAST burst — it becomes
12144 // last_token WITHOUT re-emission, and round 0 consumes it as pending (no init feed).
12145 // CONSTRAINED entry rules: the first emitted token is the MASKED argmax of the
12146 // prompt's last logits (plain constrained-greedy identity); a continuation without
12147 // a carried pending would emit an UNMASKED stashed next_pred — refused loudly (the
12148 // worker never resumes constrained sessions from the pool, so this cannot fire).
12149 if let Some(c) = constraint.as_deref_mut() {
12150 if continuation && carried_pending.is_none() {
12151 return Err("constrained spec continuation requires a carried pending \
12152 (pool resume is unconstrained-only)"
12153 .into());
12154 }
12155 if !continuation {
12156 c.mask_logits(&mut prime_logits)
12157 .map_err(|e2| format!("constraint: {e2}"))?;
12158 }
12159 }
12160 let mut last_token = if let Some(b) = carried_pending {
12161 b
12162 } else if continuation {
12163 // A continuation's boundary token was DRAWN by the burst that stashed it (the
12164 // session tail below), or by `spec_session_from_restored` for a converted
12165 // prefix-cache hit — in both cases from the correct logits row with this same
12166 // session's Philox stream, which is why it can be consumed here as-is.
12167 sess_tail.as_ref().unwrap().2.unwrap()
12168 } else if sampled && constraint.is_none() && spec_sampled_boundary_on() {
12169 sample_boundary_token(e, &prime_logits, &sp, &pen_hist, &mut sctr, "cold-prime")?
12170 } else {
12171 // greedy (byte contract), the rollback door, or constrained (masked-argmax
12172 // identity — the worker routes sampled+constrained to the plain path, and this
12173 // function refuses the combination outright above).
12174 argmax(&prime_logits) as u32
12175 };
12176 if pen_on {
12177 // The boundary token is a GENERATED token: the plain sampler `accept()`s every
12178 // emitted token into its penalty history, and pre-lane the burst's first token
12179 // was invisible to penalties forever (never pushed, and never in `committed`
12180 // until this burst's tail). Covers the carry/continuation seeds too — neither is
12181 // in `committed` yet.
12182 pen_hist.push(last_token);
12183 }
12184 if carried_pending.is_none() {
12185 out.push(last_token);
12186 // grammar advances with every emitted token (carried pendings were consumed
12187 // by the burst that emitted them).
12188 if let Some(c) = constraint.as_deref_mut() {
12189 c.consume(last_token)
12190 .map_err(|e2| format!("constraint: {e2}"))?;
12191 }
12192 }
12193 if continuation {
12194 // draft-KV invariant: entries [0..base) are the session's exact fills; truncate any
12195 // overhang so the chain's first append lands at slot base (== committed.len()).
12196 scratch.set_len(e, base)?;
12197 }
12198 // sse-cadence: hand the caller every not-yet-flushed token (disjoint in-order slices
12199 // concatenating to the full `out`). Called after the prime's first token and after each
12200 // round commit — emission timing only, token bytes untouched. The slice may be EMPTY
12201 // (poll-only boundary: zero-round folds commit nothing new); returns the caller's
12202 // continue-verdict (admission yield, 2026-08-06) — false ends the burst at this round.
12203 #[allow(clippy::type_complexity)] // allow: one-shot composite type; naming it would hide the shape that matters at the call site
12204 fn flush_commit(
12205 cb: &mut Option<&mut dyn FnMut(&[u32]) -> bool>,
12206 out: &[u32],
12207 flushed: &mut usize,
12208 ) -> bool {
12209 if let Some(f) = cb.as_mut() {
12210 let keep = f(&out[*flushed..]);
12211 *flushed = out.len();
12212 keep
12213 } else {
12214 true
12215 }
12216 }
12217 keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
12218 // INVARIANT at loop top: `last_token` is the most-recently-committed/emitted token, its
12219 // KV+recur state IS in `cache` (cache.pos = position right AFTER last_token), `last_pred`
12220 // is the greedy ARGMAX of the logits that predict the token FOLLOWING last_token, and
12221 // `h_seed` = last_token's pre-output_norm hidden. Establish it by feeding last_token once
12222 // (mirrors plain greedy). DEVICE-ARGMAX lever: the accept walk only ever consumes the
12223 // argmax of those logits — never the full vector — so a host u32 replaces the Vec<f32>.
12224 // Trimmed heads: q lives on the trimmed vocab; accept gathers use the TRIMMED index and
12225 // the residual scatters q into target-id space (q=-inf off-trim — the head cannot propose
12226 // those, so their residual mass is p(x), correct by construction).
12227 let d2t_dev: Option<CudaSlice<u32>> = if sampled || crate::spec::spec_stream() {
12228 match &mtp.d2t {
12229 Some(map) => Some(e.htod_u32_v(map)?),
12230 None => None,
12231 }
12232 } else {
12233 None
12234 };
12235 let mut q_full_buf: Option<CudaSlice<f32>> = None;
12236 // host Philox4x32-10 accept-test uniforms: module fn `host_u01` (shared with the
12237 // dspark sampled-admission walk); byte-identical to the closure it replaces.
12238 let mut draft_logits: Vec<CudaSlice<f32>> = Vec::new(); // retained head logits (q), per slot
12239 let mut draft_stats: Vec<(f32, f32, f32)> = Vec::new(); // (row_max, th_e, z_e) per slot
12240 let mut perturb_buf: Option<CudaSlice<f32>> = None; // gumbel scratch (max(n_vocab,d_vocab))
12241 let mut sample_tok = e.alloc_u32_zeroed(1)?; // residual/bonus sample out
12242 let mut col_buf: Option<CudaSlice<f32>> = None; // materialized verify column
12243 let mut pen_hist_d: Option<CudaSlice<u32>> = None;
12244 let mut pcol_buf: Option<CudaSlice<f32>> = None; // penalized p-column scratch
12245 // MEMRA_SPEC_SETUP_TRACE=1 (diagnostics): per-call wall decomposition of the burst
12246 // SETUP + TAIL segments (the round loop's internals are MEMRA_SPEC_PHASE's job) —
12247 // built to pin the serve per-burst fixed cost (research/spec-serving-20260801).
12248 let setup_trace = std::env::var("MEMRA_SPEC_SETUP_TRACE").as_deref() == Ok("1");
12249 let t_ent = std::time::Instant::now();
12250
12251 // SESSION-AFFINITY TURN CHECKPOINT (lane/session-affinity, 2026-08-05): capture the
12252 // PROMPT-END boundary state so a LATER turn can rewind here and re-prime only its own
12253 // delta instead of the whole conversation. See `SpecCheckpoint` for why this boundary is
12254 // the one that matters (a history-rewriting client mutates what the session GENERATED,
12255 // so the next turn's prompt agrees with this one up to exactly here).
12256 //
12257 // WHERE — AND WHY THIS EXACT LINE. Right after the trunk prime, BEFORE the init feed
12258 // (`decode_step_h(last_token)`) and before round 0: the last instant at which the caches
12259 // hold exactly `base + prompt.len()` rows and nothing generated.
12260 //
12261 // This was WRONG in the first cut of this lane: the capture sat after the draft-KV fill,
12262 // which is also after the init feed, so `cache.pos` was `base + prompt.len() + 1` — the
12263 // boundary included the FIRST GENERATED TOKEN. That token is the first thing inside the
12264 // `<think>` block the client strips, so every later turn's diff diverged exactly one
12265 // token below the checkpoint and affinity declined 100% of the time. Measured on the
12266 // owner regime: "history diverged at 12233 of checkpoint 12234". The off-by-one made the
12267 // whole mechanism inert while looking, from the outside, like a working
12268 // correctness-declines-safely path — hence the decline log carries the offsets.
12269 //
12270 // The full-attn planes are `len`-truncatable so the snapshot copies only the GDN conv/ssm
12271 // state (the reason a spec session could not rewind before). The draft scratch needs no
12272 // copy: rows below the boundary are rewritten by the next turn's own fill.
12273 //
12274 // WHEN: non-empty prime only. An empty-suffix continuation burst adds no prompt boundary
12275 // (its "prompt end" IS the previous checkpoint's, already held), so it keeps the existing
12276 // checkpoint rather than replacing it with a strictly worse one.
12277 //
12278 // FAILURE IS SILENT BY DESIGN: on a VRAM-tight rig the snapshot alloc can fail. That
12279 // costs the NEXT turn its rewind (it re-primes fully, today's behavior) and must never
12280 // fail the burst that is already running — so the error is swallowed, loud only under
12281 // MEMRA_DEBUG_SPEC.
12282 //
12283 // STABLE-BOUNDARY OVERRIDE (lane/frspec-multiturn-cache, 2026-08-21): the prompt-end
12284 // posture above was DISPROVED for the think-posture template class — the prompt's own
12285 // tail is the live generation header (`<|im_start|>assistant\n<think>\n`) that the
12286 // next turn's re-render replaces, so the diff diverged a couple tokens BELOW the
12287 // checkpoint and affinity declined 100% of multi-turn agent traffic (the same class
12288 // the plain tier fixed on 2026-08-09 via `plain_checkpoint_boundary`; the port to the
12289 // spec tier is this lane). When the worker armed `ckpt_at`, the capture happened at
12290 // that stop inside the prime above (`ckpt_early`) and is installed here instead;
12291 // capture-attempted-but-failed clears the slot exactly like the legacy arm.
12292 if let Some(slot) = sess_ckpt_slot {
12293 if let Some(early) = ckpt_early {
12294 if early.is_none() && std::env::var("MEMRA_DEBUG_SPEC").is_ok() {
12295 eprintln!(
12296 "[spec] stable-boundary turn checkpoint skipped; \
12297 next turn re-primes in full"
12298 );
12299 }
12300 *slot = early;
12301 } else if !continuation {
12302 let pos = cache.pos;
12303 debug_assert_eq!(
12304 pos,
12305 base + prompt.len(),
12306 "turn checkpoint must sit at the prompt end, before the init feed"
12307 );
12308 let anchor: Result<CudaSlice<f32>, Box<dyn std::error::Error>> =
12309 if let Some(ph) = &prompt_h {
12310 // hidden of the LAST primed row = the predecessor anchor at this
12311 // boundary (exactly what a fresh prime of committed[..pos] leaves in
12312 // last_h, and what the next prime's fill reads for its first row).
12313 let np = prompt.len();
12314 e.uninit(n_embd).and_then(|mut a| {
12315 e.copy_view_into(
12316 &mut a,
12317 0,
12318 &ph.slice((np - 1) * n_embd..np * n_embd),
12319 n_embd,
12320 )?;
12321 Ok(a)
12322 })
12323 } else {
12324 Err("no prompt hiddens".into())
12325 };
12326 match (cache.snapshot(e), anchor) {
12327 (Ok(snap), Ok(last_h)) => {
12328 *slot = Some(SpecCheckpoint { snap, pos, last_h });
12329 }
12330 (s, a) => {
12331 *slot = None; // a stale checkpoint would rewind to the WRONG boundary
12332 if std::env::var("MEMRA_DEBUG_SPEC").is_ok() {
12333 let err = s
12334 .err()
12335 .map(|e| e.to_string())
12336 .or_else(|| a.err().map(|e| e.to_string()))
12337 .unwrap_or_default();
12338 eprintln!(
12339 "[spec] turn checkpoint skipped ({err}); \
12340 next turn re-primes in full"
12341 );
12342 }
12343 }
12344 }
12345 }
12346 }
12347 // INIT FEED — skipped on a pending carry: last_token (the carried bonus) is NOT in the
12348 // caches and must NOT be fed solo; round 0's batched verify commits it as col 0. Its
12349 // seed/anchor hidden is the carried last_h (copied below); last_pred is dead in the
12350 // pending path (t_pred reads verify col 0 — the accept walk overwrites it).
12351 let mut last_pred = 0u32;
12352 let mut last_col_logits: Option<CudaSlice<f32>> = None;
12353 // CONSTRAINED: the init feed's logits back the (n_acc==0, base==0) masked-argmax
12354 // recompute in the grammar-truncation walk — retained host-side, round 0 only.
12355 let mut init_logits_host: Option<Vec<f32>> = None;
12356 let h_seed0: CudaSlice<f32> = if carried_pending.is_none() {
12357 let (init_logits, h) = self.spec_target_step_h(e, last_token, &mut *cache)?;
12358 last_pred = argmax(&init_logits) as u32;
12359 if constraint.is_some() {
12360 init_logits_host = Some(init_logits.clone());
12361 }
12362 // sampled mode: p-distribution after last_token, for the j==0/base==0 accept test.
12363 if sampled {
12364 last_col_logits = Some(e.htod(&init_logits)?);
12365 }
12366 h
12367 } else {
12368 // predecessor-row anchor: hidden of the last COMMITTED row (the carry contract).
12369 let lh = sess_tail
12370 .as_ref()
12371 .unwrap()
12372 .1
12373 .as_ref()
12374 .expect("pending carry requires last_h");
12375 e.clone_dtod(lh)?
12376 };
12377 let t_init = t_ent.elapsed();
12378 let mut last_col_stats: Option<(f32, f32, f32)> = None;
12379 // PERSISTENT h_seed buffer (allocated BEFORE any graph capture so no captured scratch can
12380 // alias it): every path that updates the round seed copies INTO it — no per-round allocs,
12381 // stable pointer for the graph-draft round-start copy.
12382 let mut h_seed_buf = e.clone_dtod(&h_seed0)?;
12383 // Predecessor-pairing trackers: `fill_prev` = trunk hidden AT the last COMMITTED row (the
12384 // predecessor of the next verify's col 0 — the reference's carried pending-h analogue;
12385 // also the predecessor-row hidden for the round-0 legacy-replay seed). At round 0 that
12386 // row is last_token's own (h_seed0). The chain step-0 seed under the pairing default =
12387 // hidden of the row BEFORE last_token = the prompt's last row at round 0 (h_seed_buf
12388 // overwritten below).
12389 let mut fill_prev = e.clone_dtod(&h_seed0)?;
12390 {
12391 if let Some(ph) = &prompt_h {
12392 let np = prompt.len();
12393 e.copy_view_into(
12394 &mut h_seed_buf,
12395 0,
12396 &ph.slice((np - 1) * n_embd..np * n_embd),
12397 n_embd,
12398 )?;
12399 } else if continuation
12400 && let Some((_, lh, _, _, _)) = sess_tail.as_ref()
12401 && let Some(lh) = lh.as_ref()
12402 {
12403 e.copy_into(&mut h_seed_buf, 0, lh, n_embd)?;
12404 }
12405 }
12406 // Persistent device prediction slots for the accept walk (max k+1 verify columns).
12407 let mut preds_d = e.alloc_u32_zeroed(k + 2)?;
12408
12409 let debug_spec = std::env::var("MEMRA_DEBUG_SPEC").is_ok();
12410 let fork_mode = OptiForkGateMode::configured();
12411 // MEMRA_SPEC_STATS=1: per-slot accept histogram + draft-length histogram, printed once at
12412 // the end. Metric normalization vs the reference engine: BOTH engines count
12413 // accepted/drafted where the chain stopped at p-min and the sub-threshold token is
12414 // discarded uncounted — per-slot decay + chain-length mix are the extra dimensions.
12415 let spec_stats = std::env::var("MEMRA_SPEC_STATS").is_ok();
12416 let mut st_drafted = vec![0usize; k];
12417 let mut st_accepted = vec![0usize; k];
12418 let mut st_len_hist = vec![0usize; k + 1];
12419 let mut st_full = 0usize;
12420 // P-MIN CONFIDENCE GATE (MEMRA_SPEC_PMIN, the serve script's --spec-draft-p-min mechanism):
12421 // stop the draft chain early when the head's softmax confidence in its own pick drops
12422 // below p_min. Hoisted above the loop: the graph capture bakes the prob kernels iff on.
12423 static PMIN: std::sync::OnceLock<f32> = std::sync::OnceLock::new();
12424 let p_min = *PMIN.get_or_init(|| {
12425 std::env::var("MEMRA_SPEC_PMIN")
12426 .ok()
12427 .and_then(|v| v.parse().ok())
12428 .unwrap_or(0.0)
12429 });
12430 // ZERO-DRAFT ROUNDS (MEMRA_SPEC_PMIN0=1, vendored from llama.cpp's draft gating): let the
12431 // p-min gate apply at j==0 too, so a low-confidence round drafts NOTHING and the verify
12432 // batch is just the pending bonus (m=1 = a plain decode step). llama's 35B win rides
12433 // exactly this — draft acceptance 76% at mean len 2.5 because unpredictable stretches
12434 // never pay draft+verify overhead. Only legal when a pending bonus exists (an empty
12435 // verify batch is not); the j==0 exemption stays for pending-less rounds.
12436 let pmin0 = std::env::var("MEMRA_SPEC_PMIN0")
12437 .map(|v| v == "1")
12438 .unwrap_or(false);
12439
12440 // --- GRAPH DRAFT setup: persistent I/O buffers + ONE capture (2 warmups inside). The
12441 // warmups mutate scratch len_d / pos / tok / seed — all reset at every round start, so the
12442 // only restore needed is the scratch counter. Capture failure (e.g. a non-capturable
12443 // cuBLAS path in an exotic head) falls back to the eager draft chain.
12444 // PER-SESSION PERSISTENCE (2026-08-01): session calls reuse the DraftGraphCtx parked on
12445 // the SpecSession — the capture (2 warmup head forwards + instantiate) ran ONCE at the
12446 // session's first burst, not per burst (measured ~16ms/burst fixed cost on H100 q27,
12447 // research/spec-serving-20260801). Reuse is pointer-exact: the graph bakes the session's
12448 // own scratch KV (never realloc'd), the model's resident embedding, the OnceLock p_min,
12449 // and the g_* buffers carried in the ctx — replay dispatch is identical to a fresh
12450 // capture, so draft tokens are bit-identical (drafts never decide exactness anyway; the
12451 // verify arbitrates). Single-shot calls (sess=None) build a fresh ctx and drop it.
12452 let mut dctx: DraftGraphCtx = match sess_draft_slot.as_mut().and_then(|s| s.take()) {
12453 Some(c) => c,
12454 None => DraftGraphCtx::new(e, n_embd, if sampled { d_vocab } else { 1 })?,
12455 };
12456 // FAIL-SAFE (step-OOM park replay): pre-mark both fallback flags so no capture arm
12457 // below can fire — LOUD once per replayed session through the standard WARN line.
12458 if sess_capture_disabled {
12459 let reason =
12460 "session replayed after a step-OOM park; draft capture disabled (fail-safe)";
12461 let flip = dctx.failed.mark_greedy(reason);
12462 let flip_s = dctx.failed.mark_sampled(reason);
12463 if let Some(line) = flip.or(flip_s) {
12464 eprintln!("{line}");
12465 }
12466 }
12467 // A session that ran greedy bursts first sized g_q/g_perturb at 1; a sampled resume
12468 // needs d_vocab. Realloc is legal exactly while graph_s is None (nothing baked them).
12469 if sampled && dctx.g_q.len() < d_vocab {
12470 dctx.g_q = e.zeros(d_vocab)?;
12471 dctx.g_perturb = e.zeros(d_vocab)?;
12472 }
12473 // DRAFT-SIDE GRAMMAR MASK (lane/draft-mask, 2026-08-04): the drafter samples the
12474 // grammar's legal set, so proposals are legal BY CONSTRUCTION and the verify-side
12475 // truncation (the correctness backstop) stops cutting every tight-schema round.
12476 // The mask is one node inside the captured draft chain — presence is a CAPTURE-TIME
12477 // shape, so a parked graph of the other shape is dropped and recaptured.
12478 let dmask_on = constraint
12479 .as_deref()
12480 .is_some_and(|c| c.draft_mask_enabled());
12481 let dmask_words = if dmask_on { d_vocab.div_ceil(32) } else { 0 };
12482 if dmask_on && dctx.g_dmask.len() < dmask_words {
12483 dctx.g_dmask = e.alloc_u32_zeroed(dmask_words)?;
12484 dctx.graph = None; // the old capture baked the old (or no) mask pointer
12485 dctx.chain = None; // chain last-row graphs bake the same pointer
12486 dctx.failed.clear_greedy();
12487 dctx.keeper.clear();
12488 }
12489 if (dctx.graph.is_some() || dctx.chain.is_some()) && dctx.graph_masked != dmask_on {
12490 dctx.graph = None;
12491 dctx.chain = None;
12492 dctx.failed.clear_greedy();
12493 dctx.keeper.clear();
12494 }
12495 // MULTI-HEAD CHAIN mode (mtp_extra non-empty — step37's 3-head shipping shape): the
12496 // step-modulo prefix-replay chain captures PER-HEAD single-row graphs
12497 // (`DraftChainGraphs`) instead of the one self-feeding graph below; the single-head
12498 // capture arms are untouched and unreachable in this mode (the launch arms branch the
12499 // same way). This removes the historical `mtp_extra.is_empty()` capture exclusion —
12500 // and with it the silent no-attempt hole: a chain capture that FAILS now trips the
12501 // same LOUD draft-graph WARN as a single-head failure.
12502 let chain_mode = !self.mtp_extra.is_empty();
12503 // ---- PRE-CAPTURE VRAM RESERVE CHECK + PER-SESSION DRAFT-STATE MEASUREMENT ----
12504 // (lane/step37-vram-admission-20260830). `cap_eff0` opens the measurement bracket:
12505 // when any capture succeeds in THIS call, the effective-free delta across the whole
12506 // capture section is recorded as the model's per-session draft-state high-water
12507 // (admission charges it per spec-capable session — this state was charged at ZERO
12508 // before the lane). The reserve check runs BEFORE any capture arm can allocate: a
12509 // refused capture trips the same LOUD once-per-flip WARN class as a failed one, but
12510 // with the card's headroom still intact (the owner's single-session OOM was a capture
12511 // attempt walking the card to the edge and stranding the eager fallback at 5 MiB free).
12512 let cap_eff0 = e
12513 .ctx()
12514 .mem_get_info()
12515 .ok()
12516 .map(|(f, _)| f.saturating_add(e.pool_cached_bytes()));
12517 // Peak instrument for the same bracket: the CAPTURE-TIME peak (warmup transients +
12518 // instantiate scratch, alive together) dwarfs the parked delta — measured on the
12519 // owner shape: a capture whose PARKED state reads ~2.6GB walked a ~7GB-free card to
12520 // OOM mid-capture. Reset the pool watermark here; read it at bracket end.
12521 let _ = e.pool_high_water_reset();
12522 let cap_used0 = e.pool_reserved_used().1;
12523 let mut captured_now = false;
12524 let mut capture_oom_entry_eff: Option<usize> = None;
12525 let capture_need = {
12526 let observed = self.draft_session_admission_bytes();
12527 if observed > 0 {
12528 observed
12529 } else {
12530 draft_capture_bootstrap_estimate(
12531 if chain_mode { self.mtp_head_count() } else { 1 },
12532 k,
12533 d_vocab,
12534 n_embd,
12535 )
12536 }
12537 };
12538 if spec_capture_gate_on()
12539 && graph_draft
12540 && !sampled
12541 && !dctx.failed.greedy_failed()
12542 && ((chain_mode && dctx.chain.is_none() && mtp_chain_graph_on())
12543 || (!chain_mode && dctx.graph.is_none()))
12544 && let Some(reason) = capture_headroom_refusal(e, capture_need)
12545 && let Some(line) = dctx.failed.mark_greedy(&reason)
12546 {
12547 eprintln!("{line}");
12548 }
12549 if graph_draft
12550 && !sampled
12551 && chain_mode
12552 && dctx.chain.is_none()
12553 && !dctx.failed.greedy_failed()
12554 {
12555 if mtp_chain_graph_on() {
12556 let heads_n = self.mtp_head_count();
12557 let DraftGraphCtx {
12558 g_tok,
12559 g_pos,
12560 g_seed,
12561 g_p,
12562 g_dmask,
12563 ..
12564 } = &mut dctx;
12565 if dmask_on {
12566 e.htod_u32_into(g_dmask, &vec![u32::MAX; dmask_words])?;
12567 }
12568 let g_dmask_ro: &CudaSlice<u32> = &*g_dmask;
12569 let with_prob = p_min > 0.0;
12570 // CAPTURE-RETAIN (#68 fix): one keeper for the whole chain — every graph's
12571 // warmup transients stay pinned as long as any of them replays.
12572 let cap_res = (|| -> Result<DraftChainGraphs, Box<dyn std::error::Error>> {
12573 // dcw door: same warmup headroom pre-arm as the single-head capture
12574 // below — every plane, because each head's capture warmups append on
12575 // its OWN plane. INSIDE the fallible closure (vram-admission lane): an
12576 // OOM here used to `?` out of the whole burst as a step error; now it
12577 // is a capture failure — LOUD WARN, eager chain serves.
12578 if step35_draft_dcw_on() {
12579 scratch.ensure_dcw_headroom(e, k + 2)?;
12580 }
12581 let mut interior = Vec::with_capacity(heads_n);
12582 let mut last = Vec::with_capacity(heads_n);
12583 let mut keeper: Vec<Box<dyn std::any::Any + Send>> = Vec::new();
12584 for hi in 0..heads_n {
12585 let head = self.mtp_head_at(hi);
12586 // interior row: KV append + carrier only (`with_head=false` — the
12587 // eager chain discards interior logits too, so this is the same
12588 // consumed-byte program minus the dead full-vocab head matmul).
12589 let (g, keep) = e.capture_graph_retained(|e| {
12590 self.mtp_head_forward_cap(
12591 e,
12592 head,
12593 g_tok,
12594 g_pos,
12595 g_seed,
12596 g_p,
12597 &mut *scratch,
12598 hi,
12599 false,
12600 false,
12601 embd_gpu.expect("graph draft requires resident embedding"),
12602 embd_qt,
12603 embd_rb,
12604 d_vocab,
12605 None,
12606 None,
12607 None,
12608 )
12609 })?;
12610 // the warmups appended rows on plane hi; rewind before the next
12611 // capture so successive warmups never outrun the pre-armed headroom.
12612 scratch.set_plane_len(e, hi, base)?;
12613 interior.push(g);
12614 keeper.extend(keep);
12615 // last row: head matmul + greedy argmax tail (+ p when the policy
12616 // reads it, + the grammar-mask node when constrained).
12617 let (g2, keep2) = e.capture_graph_retained(|e| {
12618 self.mtp_head_forward_cap(
12619 e,
12620 head,
12621 g_tok,
12622 g_pos,
12623 g_seed,
12624 g_p,
12625 &mut *scratch,
12626 hi,
12627 with_prob,
12628 true,
12629 embd_gpu.expect("graph draft requires resident embedding"),
12630 embd_qt,
12631 embd_rb,
12632 d_vocab,
12633 None,
12634 None,
12635 if dmask_on {
12636 Some((g_dmask_ro, dmask_words))
12637 } else {
12638 None
12639 },
12640 )
12641 })?;
12642 scratch.set_plane_len(e, hi, base)?;
12643 last.push(g2);
12644 keeper.extend(keep2);
12645 }
12646 Ok(DraftChainGraphs {
12647 interior,
12648 last,
12649 _keeper: keeper,
12650 })
12651 })();
12652 match cap_res {
12653 Ok(cg) => {
12654 scratch.set_len(e, base)?;
12655 // POSITIVE engagement receipt (the 3a lesson: a WARN-free boot is
12656 // NOT evidence of capture — the captured state must name itself).
12657 eprintln!(
12658 "[mtp-chain-graph] captured mode=greedy heads={heads_n} \
12659 interior={heads_n} last={heads_n} masked={}",
12660 dmask_on as u8
12661 );
12662 dctx.chain = Some(cg);
12663 dctx.graph_masked = dmask_on;
12664 captured_now = true;
12665 }
12666 Err(err) => {
12667 scratch.set_len(e, base)?;
12668 // LOUD flip (audit Q2): a dropped draft graph is a coverage loss,
12669 // never silent — now including the multi-head shipping shape.
12670 // OOM RECOVERY (vram-admission lane): a failed attempt's freed
12671 // transients sit CACHED in the async pool where the driver cannot
12672 // see them; trim them back so the eager fallback (and any driver-
12673 // side allocation) actually has the headroom the free suggests.
12674 let mut reason = err.to_string();
12675 if capture_err_is_oom(&reason) {
12676 capture_oom_entry_eff = capture_oom_entry_eff.max(cap_eff0);
12677 let trimmed = e.pool_trim_to_zero();
12678 if trimmed > 0 {
12679 reason.push_str(&format!(
12680 "; pool trimmed {}MB back to the driver",
12681 trimmed / (1 << 20)
12682 ));
12683 }
12684 }
12685 if let Some(line) = dctx.failed.mark_greedy(&reason) {
12686 eprintln!("{line}");
12687 }
12688 }
12689 }
12690 } else {
12691 // Disarmed by MEMRA_MTP_CHAIN_GRAPH=0: say so once per process — the OFF arm
12692 // must be attributable in a boot log, never inferable from silence.
12693 static NOTE: std::sync::Once = std::sync::Once::new();
12694 NOTE.call_once(|| {
12695 eprintln!(
12696 "[spec] multi-head draft-chain capture disarmed \
12697 (MEMRA_MTP_CHAIN_GRAPH=0); eager chain serves this shape"
12698 );
12699 });
12700 }
12701 }
12702 if graph_draft
12703 && !sampled
12704 && !chain_mode
12705 && dctx.graph.is_none()
12706 && !dctx.failed.greedy_failed()
12707 {
12708 let DraftGraphCtx {
12709 g_tok,
12710 g_pos,
12711 g_seed,
12712 g_p,
12713 g_dmask,
12714 ..
12715 } = &mut dctx;
12716 // capture-time contents: ALL-ONES (ban nothing). A replay only ever runs after the
12717 // host uploads the position's real words, so the warmups stay grammar-free.
12718 if dmask_on {
12719 e.htod_u32_into(g_dmask, &vec![u32::MAX; dmask_words])?;
12720 }
12721 let g_dmask_ro: &CudaSlice<u32> = &*g_dmask;
12722 // CAPTURE-RETAIN (#68 fix): the warmup transients' pool addresses are baked into the
12723 // captured graph; the keeper pins them for the graph's lifetime. capture_graph (non-
12724 // retained) freed them at exit — safe for one-shot generate_spec (nothing else touches
12725 // the pool between replays) but WRONG for sessions: burst-boundary prime/fill/commit
12726 // passes (and, in serve, other sessions) recycle those addresses and the replay then
12727 // clobbers live buffers — the ST serve-spec corruption (research/serve-st-20260803).
12728 let cap_res = (|| {
12729 // dcw door: the capture warmups append device-counter rows the capture body
12730 // cannot rebase for; pre-arm ring headroom host-side (no-op on flat planes /
12731 // room-enough rings, and the door-off path is untouched). INSIDE the fallible
12732 // closure (vram-admission lane): an OOM here is a capture failure, not a
12733 // burst-killing step error.
12734 if step35_draft_dcw_on() {
12735 scratch.ensure_dcw_headroom(e, k + 2)?;
12736 }
12737 e.capture_graph_retained(|e| {
12738 self.mtp_head_forward_cap(
12739 e,
12740 mtp,
12741 g_tok,
12742 g_pos,
12743 g_seed,
12744 g_p,
12745 &mut *scratch,
12746 0,
12747 p_min > 0.0 || fork_mode == OptiForkGateMode::Controller,
12748 true,
12749 embd_gpu.expect("graph draft requires resident embedding"),
12750 embd_qt,
12751 embd_rb,
12752 d_vocab,
12753 None,
12754 None,
12755 if dmask_on {
12756 Some((g_dmask_ro, dmask_words))
12757 } else {
12758 None
12759 },
12760 )
12761 })
12762 })();
12763 match cap_res {
12764 Ok((g, keep)) => {
12765 scratch.set_len(e, base)?;
12766 dctx.graph = Some(g);
12767 dctx.graph_masked = dmask_on;
12768 dctx.keeper = keep;
12769 captured_now = true;
12770 }
12771 Err(err) => {
12772 scratch.set_len(e, base)?;
12773 // LOUD flip (audit Q2): a dropped draft graph is a coverage loss, never
12774 // silent. Once per flip — mark returns None on an already-failed ctx.
12775 let mut reason = err.to_string();
12776 if capture_err_is_oom(&reason) {
12777 capture_oom_entry_eff = capture_oom_entry_eff.max(cap_eff0);
12778 let trimmed = e.pool_trim_to_zero();
12779 if trimmed > 0 {
12780 reason.push_str(&format!(
12781 "; pool trimmed {}MB back to the driver",
12782 trimmed / (1 << 20)
12783 ));
12784 }
12785 }
12786 if let Some(line) = dctx.failed.mark_greedy(&reason) {
12787 eprintln!("{line}");
12788 }
12789 }
12790 }
12791 }
12792 // --- SAMPLED GRAPH DRAFT setup (step 3 of the sampled-spec arc): a SECOND capture, own
12793 // graph object, built only when sampled && graph-eligible — the greedy capture above is
12794 // untouched (and skipped when sampled: its graph would never be launched). Same head
12795 // forward, but the in-graph argmax reads GUMBEL-PERTURBED logits; the Philox event
12796 // counter lives in the persistent device g_ctr (bumped in-graph, host-seeded from sctr
12797 // once per round); the raw head logits land in the persistent g_q for the host's
12798 // per-replay async D2D into the round's q slot (q_slots, K x d_vocab, allocated once).
12799 // seed/temp are capture-time constants — baked into graph_s, so a pool-resumed request
12800 // with a different (seed, temp, k) drops the parked sampled graph and recaptures.
12801 // COST OF THE FRESH-SEED SERVE DEFAULT (dogfood F4, 2026-08-04): omitting `seed` on a
12802 // serve request now draws fresh per-request entropy (it used to default to a pinned 0),
12803 // so a seed-omitting request that RESUMES a parked spec session finds an s_key baked
12804 // with the PREVIOUS request's seed and pays one recapture. Bounded, and it does not
12805 // reopen the ~16ms/burst regression the persistent ctx exists to fix: a session's seed
12806 // is fixed for its whole lifetime (worker.rs reads s.sampler.seed() per burst), so
12807 // this compare misses at most ONCE per resumed request — the first burst recaptures
12808 // and every later burst in that request replays. A client that wants the parked graph
12809 // AND reproducibility supplies an explicit `seed`, honored exactly, which keeps s_key
12810 // stable across its whole conversation.
12811 // COMPOSITION RULE (fspec x gsd merge): the in-graph chain samples from the RAW
12812 // softmax — it can hold neither per-row filter stats nor the varying penalty history.
12813 // The sampled graph therefore engages only in the PURE-TEMP regime; filters/penalties
12814 // force the eager draft (which computes stats/penalties per row).
12815 // KEY THE WHOLE REGIME, not just the baked constants (lane/graph-s-key-exactness-
12816 // 20260819). `s_key` used to be `(seed, temp, k)`; the filters and penalties were left
12817 // out, so a filtered request resuming a session that parked a PURE-TEMP graph kept it —
12818 // and the launch site never re-asked `pure_temp`. See [`SampledGraphKey`] for what that
12819 // costs (an unconditional accept of out-of-head draft tokens, i.e. an exactness bug on
12820 // the request shape the vendor-default flip makes the majority).
12821 let s_key = SampledGraphKey::new(sp_seed, sp_temp, k, sp.top_k, sp.top_p, sp.min_p, pen_on);
12822 let pure_temp = s_key.pure_temp();
12823 // The regime the sampled graph may be captured/launched in: pure-temp always;
12824 // truncation-filtered when the filtered-capture door is on (the filter runs
12825 // IN-GRAPH — lane/step37-draft-graph-serving-20260830); penalties never.
12826 let s_capturable = s_key.graph_capturable();
12827 if sampled && dctx.s_key.is_some_and(|old| old != s_key) {
12828 dctx.graph_s = None;
12829 dctx.chain_s = None;
12830 dctx.failed.clear_sampled();
12831 dctx.s_key = None;
12832 dctx.q_slots.clear();
12833 dctx.keeper_s.clear();
12834 }
12835 // PRE-CAPTURE VRAM RESERVE CHECK, sampled arms (vram-admission lane): same contract
12836 // as the greedy check above — refuse BEFORE allocating, LOUD once, eager serves.
12837 if spec_capture_gate_on()
12838 && graph_draft
12839 && sampled
12840 && s_capturable
12841 && !dctx.failed.sampled_failed()
12842 && ((chain_mode && dctx.chain_s.is_none() && mtp_chain_graph_on())
12843 || (!chain_mode && dctx.graph_s.is_none()))
12844 && let Some(reason) = capture_headroom_refusal(e, capture_need)
12845 && let Some(line) = dctx.failed.mark_sampled(&reason)
12846 {
12847 eprintln!("{line}");
12848 }
12849 // FILTERED capture nodes need q slots sized d_vocab AND the stat slots; the pure-temp
12850 // body leaves g_th/g_z/g_mx untouched (they exist from ctx creation either way).
12851 if graph_draft
12852 && sampled
12853 && s_capturable
12854 && chain_mode
12855 && dctx.chain_s.is_none()
12856 && !dctx.failed.sampled_failed()
12857 {
12858 if mtp_chain_graph_on() {
12859 let heads_n = self.mtp_head_count();
12860 let filtered = s_key.filtered();
12861 let DraftGraphCtx {
12862 g_tok,
12863 g_pos,
12864 g_seed,
12865 g_p,
12866 g_ctr,
12867 g_perturb,
12868 g_q,
12869 g_rows0,
12870 g_th,
12871 g_z,
12872 g_mx,
12873 ..
12874 } = &mut dctx;
12875 let with_prob = p_min > 0.0;
12876 let cap_res = (|| -> Result<DraftChainGraphs, Box<dyn std::error::Error>> {
12877 // dcw pre-arm INSIDE the fallible closure (vram-admission lane): an OOM
12878 // here is a capture failure with the LOUD WARN, never a step error.
12879 if step35_draft_dcw_on() {
12880 scratch.ensure_dcw_headroom(e, k + 2)?;
12881 }
12882 let mut interior = Vec::with_capacity(heads_n);
12883 let mut last = Vec::with_capacity(heads_n);
12884 let mut keeper: Vec<Box<dyn std::any::Any + Send>> = Vec::new();
12885 for hi in 0..heads_n {
12886 let head = self.mtp_head_at(hi);
12887 // interior row: no head, no draw — shared shape with the greedy
12888 // chain's interior, captured per mode for keeper-lifetime hygiene.
12889 let (g, keep) = e.capture_graph_retained(|e| {
12890 self.mtp_head_forward_cap(
12891 e,
12892 head,
12893 g_tok,
12894 g_pos,
12895 g_seed,
12896 g_p,
12897 &mut *scratch,
12898 hi,
12899 false,
12900 false,
12901 embd_gpu.expect("graph draft requires resident embedding"),
12902 embd_qt,
12903 embd_rb,
12904 d_vocab,
12905 None,
12906 None,
12907 None,
12908 )
12909 })?;
12910 scratch.set_plane_len(e, hi, base)?;
12911 interior.push(g);
12912 keeper.extend(keep);
12913 // last row: head matmul + the in-graph categorical draw (filtered
12914 // nodes when the request carries filters).
12915 let (g2, keep2) = e.capture_graph_retained(|e| {
12916 self.mtp_head_forward_cap(
12917 e,
12918 head,
12919 g_tok,
12920 g_pos,
12921 g_seed,
12922 g_p,
12923 &mut *scratch,
12924 hi,
12925 with_prob,
12926 true,
12927 embd_gpu.expect("graph draft requires resident embedding"),
12928 embd_qt,
12929 embd_rb,
12930 d_vocab,
12931 Some(SampledCapArgs {
12932 ctr: &mut *g_ctr,
12933 perturb: &mut *g_perturb,
12934 q_out: &mut *g_q,
12935 seed: sp_seed,
12936 temp: sp_temp,
12937 filt: if filtered {
12938 Some(SampledCapFilter {
12939 rows0: &*g_rows0,
12940 th: &mut *g_th,
12941 z: &mut *g_z,
12942 mx: &mut *g_mx,
12943 top_k: sp.top_k,
12944 top_p: sp.top_p,
12945 min_p: sp.min_p,
12946 })
12947 } else {
12948 None
12949 },
12950 }),
12951 None,
12952 None, // constrained spec is greedy-only
12953 )
12954 })?;
12955 scratch.set_plane_len(e, hi, base)?;
12956 last.push(g2);
12957 keeper.extend(keep2);
12958 }
12959 Ok(DraftChainGraphs {
12960 interior,
12961 last,
12962 _keeper: keeper,
12963 })
12964 })();
12965 match cap_res {
12966 Ok(cg) => {
12967 scratch.set_len(e, base)?;
12968 // NO STRANDED PARTIAL STATE (vram-admission lane): the q-slot allocs
12969 // after a successful capture are themselves fallible on a tight card.
12970 // A mid-loop failure used to `?` out as a step error, leaving orphan
12971 // slots parked on the ctx (wrong count, stale contents) for the next
12972 // capture attempt to stack onto. Allocate all-or-nothing: on failure
12973 // drop the fresh graphs AND the partial slots, mark the LOUD fallback.
12974 dctx.q_slots.clear();
12975 let slots = (0..k)
12976 .map(|_| e.zeros(d_vocab))
12977 .collect::<Result<Vec<_>, _>>();
12978 match slots {
12979 Ok(slots) => {
12980 dctx.q_slots = slots;
12981 eprintln!(
12982 "[mtp-chain-graph] captured mode=sampled heads={heads_n} \
12983 interior={heads_n} last={heads_n} filtered={} key={s_key:?}",
12984 s_key.filtered() as u8
12985 );
12986 dctx.chain_s = Some(cg);
12987 dctx.s_key = Some(s_key);
12988 captured_now = true;
12989 }
12990 Err(err) => {
12991 drop(cg);
12992 dctx.q_slots.clear();
12993 let mut reason = format!("q-slot alloc failed: {err}");
12994 if capture_err_is_oom(&reason) {
12995 capture_oom_entry_eff = capture_oom_entry_eff.max(cap_eff0);
12996 let trimmed = e.pool_trim_to_zero();
12997 if trimmed > 0 {
12998 reason.push_str(&format!(
12999 "; pool trimmed {}MB back to the driver",
13000 trimmed / (1 << 20)
13001 ));
13002 }
13003 }
13004 if let Some(line) = dctx.failed.mark_sampled(&reason) {
13005 eprintln!("{line}");
13006 }
13007 }
13008 }
13009 }
13010 Err(err) => {
13011 scratch.set_len(e, base)?;
13012 let mut reason = err.to_string();
13013 if capture_err_is_oom(&reason) {
13014 capture_oom_entry_eff = capture_oom_entry_eff.max(cap_eff0);
13015 let trimmed = e.pool_trim_to_zero();
13016 if trimmed > 0 {
13017 reason.push_str(&format!(
13018 "; pool trimmed {}MB back to the driver",
13019 trimmed / (1 << 20)
13020 ));
13021 }
13022 }
13023 if let Some(line) = dctx.failed.mark_sampled(&reason) {
13024 eprintln!("{line}");
13025 }
13026 }
13027 }
13028 } else {
13029 static NOTE_S: std::sync::Once = std::sync::Once::new();
13030 NOTE_S.call_once(|| {
13031 eprintln!(
13032 "[spec] multi-head draft-chain capture disarmed \
13033 (MEMRA_MTP_CHAIN_GRAPH=0); eager chain serves this shape"
13034 );
13035 });
13036 }
13037 }
13038 if graph_draft
13039 && sampled
13040 && s_capturable
13041 && !chain_mode
13042 && dctx.graph_s.is_none()
13043 && !dctx.failed.sampled_failed()
13044 {
13045 let filtered = s_key.filtered();
13046 let DraftGraphCtx {
13047 g_tok,
13048 g_pos,
13049 g_seed,
13050 g_p,
13051 g_ctr,
13052 g_perturb,
13053 g_q,
13054 g_rows0,
13055 g_th,
13056 g_z,
13057 g_mx,
13058 ..
13059 } = &mut dctx;
13060 // CAPTURE-RETAIN (#68 fix): same keeper contract as the greedy capture above.
13061 let cap_res = (|| {
13062 // dcw pre-arm INSIDE the fallible closure (vram-admission lane): an OOM
13063 // here is a capture failure with the LOUD WARN, never a step error.
13064 if step35_draft_dcw_on() {
13065 scratch.ensure_dcw_headroom(e, k + 2)?;
13066 }
13067 e.capture_graph_retained(|e| {
13068 self.mtp_head_forward_cap(
13069 e,
13070 mtp,
13071 g_tok,
13072 g_pos,
13073 g_seed,
13074 g_p,
13075 &mut *scratch,
13076 0,
13077 p_min > 0.0,
13078 true,
13079 embd_gpu.expect("graph draft requires resident embedding"),
13080 embd_qt,
13081 embd_rb,
13082 d_vocab,
13083 Some(SampledCapArgs {
13084 ctr: &mut *g_ctr,
13085 perturb: &mut *g_perturb,
13086 q_out: &mut *g_q,
13087 seed: sp_seed,
13088 temp: sp_temp,
13089 filt: if filtered {
13090 Some(SampledCapFilter {
13091 rows0: &*g_rows0,
13092 th: &mut *g_th,
13093 z: &mut *g_z,
13094 mx: &mut *g_mx,
13095 top_k: sp.top_k,
13096 top_p: sp.top_p,
13097 min_p: sp.min_p,
13098 })
13099 } else {
13100 None
13101 },
13102 }),
13103 None,
13104 None, // constrained spec is greedy-only — sampled never carries a hook
13105 )
13106 })
13107 })();
13108 match cap_res {
13109 Ok((g, keep)) => {
13110 scratch.set_len(e, base)?;
13111 // NO STRANDED PARTIAL STATE: all-or-nothing q slots, same contract as
13112 // the chain arm above.
13113 dctx.q_slots.clear();
13114 let slots = (0..k)
13115 .map(|_| e.zeros(d_vocab))
13116 .collect::<Result<Vec<_>, _>>();
13117 match slots {
13118 Ok(slots) => {
13119 dctx.q_slots = slots;
13120 dctx.graph_s = Some(g);
13121 dctx.s_key = Some(s_key);
13122 dctx.keeper_s = keep;
13123 captured_now = true;
13124 }
13125 Err(err) => {
13126 drop(g);
13127 drop(keep);
13128 dctx.q_slots.clear();
13129 let mut reason = format!("q-slot alloc failed: {err}");
13130 if capture_err_is_oom(&reason) {
13131 capture_oom_entry_eff = capture_oom_entry_eff.max(cap_eff0);
13132 let trimmed = e.pool_trim_to_zero();
13133 if trimmed > 0 {
13134 reason.push_str(&format!(
13135 "; pool trimmed {}MB back to the driver",
13136 trimmed / (1 << 20)
13137 ));
13138 }
13139 }
13140 if let Some(line) = dctx.failed.mark_sampled(&reason) {
13141 eprintln!("{line}");
13142 }
13143 }
13144 }
13145 }
13146 Err(err) => {
13147 scratch.set_len(e, base)?;
13148 // LOUD flip (audit Q2): same contract as the greedy capture above.
13149 let mut reason = err.to_string();
13150 if capture_err_is_oom(&reason) {
13151 capture_oom_entry_eff = capture_oom_entry_eff.max(cap_eff0);
13152 let trimmed = e.pool_trim_to_zero();
13153 if trimmed > 0 {
13154 reason.push_str(&format!(
13155 "; pool trimmed {}MB back to the driver",
13156 trimmed / (1 << 20)
13157 ));
13158 }
13159 }
13160 if let Some(line) = dctx.failed.mark_sampled(&reason) {
13161 eprintln!("{line}");
13162 }
13163 }
13164 }
13165 }
13166 // ---- PER-SESSION DRAFT-STATE MEASUREMENT bracket end (vram-admission lane): when a
13167 // capture landed in THIS call, the effective-free delta across the capture section is
13168 // this session's parked draft-graph state (keepers + q slots + instantiated graphs'
13169 // backing). Recorded as a model-owned high-water; admission charges it per
13170 // spec-capable session (see `draft_session_admission_bytes`).
13171 if captured_now
13172 && let Some(eff0) = cap_eff0
13173 && let Ok((f1, _)) = e.ctx().mem_get_info()
13174 {
13175 let eff1 = f1.saturating_add(e.pool_cached_bytes());
13176 let parked_delta = eff0.saturating_sub(eff1);
13177 let (_res_high, used_high) = e.pool_high_water_reset();
13178 let peak_delta = used_high.saturating_sub(cap_used0);
13179 let observed = parked_delta.max(peak_delta);
13180 if observed > 0
13181 && let Some(hw) = self.record_draft_state_bytes(observed)
13182 {
13183 eprintln!(
13184 "[spec] draft-session state high-water: {}MB (max of parked delta {}MB \
13185 and capture-time pool peak {}MB; charged per spec admission and gating \
13186 future captures)",
13187 hw / (1 << 20),
13188 parked_delta / (1 << 20),
13189 peak_delta / (1 << 20),
13190 );
13191 }
13192 }
13193 // FAILURE IS AN OBSERVATION TOO: a capture that OOM'd at entry-effective E proved
13194 // the capture-time peak exceeds E. Feed E into the gauge so every future gate
13195 // refuses at or below the headroom that just failed (self-healing even when the
13196 // boot probe is disarmed and the bootstrap estimate was blind).
13197 if let Some(entry_eff) = capture_oom_entry_eff
13198 && let Some(hw) = self.record_draft_state_bytes(entry_eff)
13199 {
13200 eprintln!(
13201 "[spec] draft-session capture appetite floor raised to {}MB: a capture \
13202 attempt OOM'd with that much effective free (failure-observed bound)",
13203 hw / (1 << 20)
13204 );
13205 }
13206 // ---- EXACTNESS GUARD, the enforceable half (lane/graph-s-key-exactness-20260819,
13207 // widened by lane/step37-draft-graph-serving-20260830) ----
13208 // With the filters and penalties in `s_key`, a graph that SURVIVED the drop above was
13209 // captured under THIS request's exact regime, and capture requires `graph_capturable`
13210 // (pure-temp, or filtered with the in-graph filter nodes; never penalties) — so a
13211 // parked graph implies both. That implication is the whole exactness argument for the
13212 // graph arm, so it is asserted here rather than assumed: a future change that widens
13213 // the capture condition, narrows the key, or copies a `DraftGraphCtx` across regimes
13214 // fails LOUDLY at this line instead of silently drafting from a distribution the
13215 // verify never reconstructs. Release builds refuse the graph (drop it, draft eager)
13216 // rather than launching it; the launch site re-tests the regime independently.
13217 if sampled
13218 && (dctx.graph_s.is_some() || dctx.chain_s.is_some())
13219 && (!s_capturable || dctx.s_key != Some(s_key))
13220 {
13221 debug_assert!(
13222 false,
13223 "sampled draft graph parked under {:?} survived into a request outside its \
13224 capture regime (top_k={} top_p={} min_p={} pen_on={} capturable={}): the \
13225 in-graph draw and the verify's accept test would see different distributions",
13226 dctx.s_key, sp.top_k, sp.top_p, sp.min_p, pen_on, s_capturable,
13227 );
13228 eprintln!(
13229 "[spec] BUG: dropping a parked sampled draft graph that outlived its capture \
13230 regime (s_key={:?}, request top_k={} top_p={} min_p={} pen_on={} \
13231 capturable={}); drafting EAGER — the key must carry every field that shapes q",
13232 dctx.s_key, sp.top_k, sp.top_p, sp.min_p, pen_on, s_capturable,
13233 );
13234 dctx.graph_s = None;
13235 dctx.chain_s = None;
13236 dctx.s_key = None;
13237 dctx.q_slots.clear();
13238 dctx.keeper_s.clear();
13239 }
13240 // SKEY PROBE (MEMRA_SKEY_PROBE=1): the burst-entry facts the reachability question turns
13241 // on — is this request sampled, is it in a regime the sampled graph is legal in, and is
13242 // a graph PARKED from an earlier request of the same session? The launch arms below
13243 // print which chain actually ran, so the probe never restates the condition.
13244 if skey_probe() {
13245 eprintln!(
13246 "[skey] burst sampled={} pure_temp={} capturable={} temp={} top_k={} top_p={} \
13247 min_p={} pen_on={} k={} graph_draft={} graph_s_parked={} chain_s_parked={} \
13248 s_key_parked={:?}",
13249 sampled as u8,
13250 pure_temp as u8,
13251 s_capturable as u8,
13252 sp_temp,
13253 sp.top_k,
13254 sp.top_p,
13255 sp.min_p,
13256 pen_on as u8,
13257 k,
13258 graph_draft as u8,
13259 dctx.graph_s.is_some() as u8,
13260 dctx.chain_s.is_some() as u8,
13261 dctx.s_key,
13262 );
13263 }
13264 let t_cap = t_ent.elapsed();
13265 // PERSISTENT DRAFT KV: fill the MTP block's K/V for every prompt position from the exact
13266 // trunk hiddens collected during prime — ONE batched K/V-only pass (overwrites any
13267 // capture-warmup garbage; capture left len at 0). last_token (the init feed) needs no
13268 // fill: the first chain step processes it and appends its entry at slot prompt.len().
13269 if let Some(ph) = &prompt_h {
13270 // SESSION: rows [0..base) are the previous turns' exact fills (refresh overwrote them
13271 // with true verify hiddens) — truncate any draft overhang, fill ONLY the suffix at
13272 // global positions [base..base+tp). Fresh call: base==0, identical to before.
13273 scratch.set_len(e, base)?;
13274 // CHUNKED FILL (long-ctx OOM fix, 2026-07-05): mtp_kv_fill's transients scale with its
13275 // T (concat = T*2*n_embd*4B — 1.5GB at 40k) and its concat loop is 2*T launches. The
13276 // fill is a pure sequential append, so chunking is exact: each chunk appends its rows
13277 // at pos0=base+start with the identical per-row math. Same knob as the trunk prime.
13278 let tp = prompt.len();
13279 let fill_chunk: usize = if crate::cache::swa_ring_on() {
13280 crate::hybrid_forward::prime_chunk_tokens(tp, self.layers.len())
13281 } else {
13282 // Preserve the flag-OFF schedule byte-for-byte, including the legacy zero value
13283 // meaning one monolithic fill.
13284 std::env::var("MEMRA_PRIME_CHUNK")
13285 .ok()
13286 .and_then(|v| v.parse().ok())
13287 .unwrap_or(4096)
13288 };
13289 let fill_chunk = if fill_chunk == 0 { tp } else { fill_chunk };
13290 // CUDA launch wall (same class as the trunk prime's PRIME_CHUNK_LAUNCH_CAP):
13291 // a fill call's matmuls can land on the grid.y=m dp4a family, and grid.y caps
13292 // at 65,535. This loop has no tail fold, so the raw limit is exact:
13293 // tp <= 65,535 keeps the legacy schedule (monolithic included) byte-for-byte,
13294 // and larger fills — unreachable before the trunk prime's own cap fix — chunk.
13295 let fill_chunk = fill_chunk.min(crate::hybrid_forward::CUDA_GRID_YZ_MAX);
13296 let mut start = 0usize;
13297 while start < tp {
13298 let end = (start + fill_chunk).min(tp);
13299 let tc = end - start;
13300 {
13301 // PREDECESSOR pairing: row i gets h[i-1]; global row 0 a zeros row (the
13302 // reference engine's initial pending-h is zeroed too); a session turn's row 0
13303 // gets the PREVIOUS turn's last committed hidden (sess.last_h). Per chunk:
13304 // rows start..end read h[start-1..end-1] — one dtod into a chunk buffer.
13305 let mut phs = e.zeros(tc * n_embd)?;
13306 let (src_lo, dst_off) = if start == 0 {
13307 (0, n_embd)
13308 } else {
13309 ((start - 1) * n_embd, 0)
13310 };
13311 let n_copy = if start == 0 {
13312 (tc - 1) * n_embd
13313 } else {
13314 tc * n_embd
13315 };
13316 if start == 0
13317 && let Some((_, lh, _, _, _)) = sess_tail.as_ref()
13318 && let Some(lh) = lh.as_ref()
13319 {
13320 e.copy_into(&mut phs, 0, lh, n_embd)?;
13321 }
13322 if n_copy > 0 {
13323 e.copy_view_into(
13324 &mut phs,
13325 dst_off,
13326 &ph.slice(src_lo..src_lo + n_copy),
13327 n_copy,
13328 )?;
13329 }
13330 self.mtp_kv_fill_all(
13331 e,
13332 &prompt[start..end],
13333 &phs,
13334 base + start,
13335 &mut *scratch,
13336 embd_dev,
13337 )?;
13338 }
13339 start = end;
13340 }
13341 }
13342 // MEMRA_PROFILE_SPEC=2: profiler capture starts HERE — after the prime, so an
13343 // `nsys -c cudaProfilerApi` capture contains ONLY the round loop (draft/verify/commit).
13344 // (=1 brackets the whole call in run_spec.rs, prime included.)
13345 if std::env::var("MEMRA_PROFILE_SPEC").as_deref() == Ok("2") {
13346 unsafe extern "C" {
13347 fn cudaProfilerStart() -> i32;
13348 }
13349 unsafe {
13350 cudaProfilerStart();
13351 }
13352 }
13353 // ROUND-STREAM stage (c) 4 (MEMRA_SPEC_STREAM=1, experimental): pre-issued M-round
13354 // bursts with ZERO per-round host readbacks — the accept/seed/rollback/ring kernels
13355 // consume each other's device outputs; the host drains the ring every M rounds. v1
13356 // constraints: greedy, !spec_replay, single-shot, batched-linear layers, no refresh
13357 // fills (acceptance effect A/B-arbitrated), enters from round 1 (pending guaranteed).
13358 // NOTE: not gated on the caller's graph_draft (its trunk_dense conjunct turns the 35B
13359 // MoE off) — the stream capture encloses ONLY the dense MTP head; the head-dense /
13360 // full-prec / k gates are re-derived here and a failed capture degrades to stream-off.
13361 let stream_on = crate::spec::spec_stream()
13362 && !sampled
13363 && !spec_replay
13364 && self.mtp_extra.is_empty()
13365 && constraint.is_none()
13366 && !session_mode
13367 && embd_gpu.is_some()
13368 && !crate::model::full_prec_enabled()
13369 && k + 2 < 96;
13370 let mut stream_graph: Option<cudarc::driver::CudaGraph> = None;
13371 let mut g_tokp2k = e.alloc_u32_zeroed(2 * k.max(1))?;
13372 if stream_on {
13373 let cap = e.capture_graph(|e| {
13374 for j in 0..k.max(1) {
13375 self.mtp_head_forward_cap(
13376 e,
13377 mtp,
13378 &mut dctx.g_tok,
13379 &mut dctx.g_pos,
13380 &mut dctx.g_seed,
13381 &mut dctx.g_p,
13382 &mut *scratch,
13383 0,
13384 true,
13385 true,
13386 embd_gpu.expect("round stream requires resident embedding"),
13387 embd_qt,
13388 embd_rb,
13389 d_vocab,
13390 None,
13391 Some((&mut g_tokp2k, j, d2t_dev.as_ref())),
13392 None, // round-stream requires constraint.is_none() (see stream_on)
13393 )?;
13394 }
13395 Ok(())
13396 });
13397 match cap {
13398 Ok(g) => {
13399 scratch.set_len(e, 0)?;
13400 stream_graph = Some(g);
13401 }
13402 Err(err) => {
13403 scratch.set_len(e, 0)?;
13404 if debug_spec {
13405 eprintln!("[spec] stream-graph capture failed ({err}); stream off");
13406 }
13407 }
13408 }
13409 }
13410 let stream_active = stream_on && stream_graph.is_some();
13411 if debug_spec {
13412 eprintln!(
13413 "[spec] stream_on={stream_on} env={} samp={sampled} dg={} captured={} active={stream_active} session={session_mode} replay={spec_replay}",
13414 crate::spec::spec_stream(),
13415 dctx.graph.is_some(),
13416 stream_graph.is_some()
13417 );
13418 }
13419 let t_v_s = k + 1;
13420 // ROUND-STREAM buffers + ptr tables now live in the model-generic round_stream
13421 // module (extracted 2026-07-12; the gemma burst reuses them).
13422 let sb = crate::round_stream::StreamBufs::new(e, k, crate::spec::spec_stream_m())?;
13423 let crate::round_stream::StreamBufs {
13424 mut vtok_d,
13425 mut brk_d,
13426 mut pend_d,
13427 last_pred_d,
13428 mut pos_ctr,
13429 mut pos_start_d,
13430 mut ring_d,
13431 acc_d: mut stream_acc,
13432 m_rounds,
13433 k: _,
13434 } = sb;
13435 let stream_ptrs: Option<CudaSlice<u64>> = if stream_active {
13436 Some(crate::round_stream::kv_len_ptr_table(
13437 e,
13438 cache,
13439 Some(&pos_ctr),
13440 )?)
13441 } else {
13442 None
13443 };
13444
13445 let t_fill = t_ent.elapsed();
13446 let mut round = 0usize;
13447 // ADAPTIVE DRAFT LENGTH (MEMRA_SPEC_ADAPT=1, opt-in — the gemma_spec accepted-run law,
13448 // ported 2026-08-01): next round's draft depth = last round's accepted run + 1, clamped
13449 // to [floor(pos), k_cap] — a miss shrinks the next draft to the miss point + 1,
13450 // full-accept streaks re-deepen one step per round. NOT the 2026-07-07 acceptance-EMA
13451 // (that arm measured an HONEST LOSS to static per-class optima — 115.0/85.8/73.4 vs
13452 // 121.6/92.7/75.6, EMA lag — and was removed 2026-07-08; rig5090.jsonl has the record).
13453 // The gemma law has no lag class: it reacts within one round, and was worth +7-20% on
13454 // the gemma cells at unchanged exactness (2026-07-10 flip; floor sweep 2026-07-25;
13455 // position key 2026-07-26). Signal = n_acc from the round's EXISTING accept readback —
13456 // zero new syncs; the draft graph is a SINGLE-STEP capture replayed per drafted token,
13457 // so a per-round depth needs no re-capture (unlike gemma's whole-chain graphs). qwen's
13458 // in-round p-min cut already shortens chains mid-round, so gemma's one-round-late p-min
13459 // fold into kc is unnecessary here — the accepted-run law sees the cut via n_acc.
13460 // Exactness is the verify's job at ANY depth (same contract as p-min variable rounds).
13461 // DEFAULT OFF on the qwen path until its cells gate a flip (gemma's is default-on).
13462 // MEASURED 2026-08-01 (H100 GPU-3, interleaved x3, NGEN=256, same-invocation plain
13463 // denominators; research/qwen-adaptive-k-20260801/): REFUTED on the tuned qwen configs.
13464 // q27 K=3+HPOST+PMIN=0.3: short +0.8% (noise; law ~idles, len_hist identical), board
13465 // -1.9%, agentic -0.5%; board PMIN=0 -2.1% (not p-min shadowing — the law itself);
13466 // floor=1 -2.8% (gemma's floor-collapse, reproduced). q35 K=2 board: -6.4% (52/136
13467 // rounds shrink to depth 1; no depth to reclaim at K=2). The gemma direction DOES
13468 // appear at untuned depth-K — q27 K=6 floor=4 +1.5% over fixed K=6 — but stays -3.7%
13469 // below fixed K=3: same verdict class as the retired EMA arm (honest loss to static
13470 // per-class optima). Acceptance-rate rises under the law while tokens/round falls —
13471 // it buys accept-% by adding rounds, and a round's fixed draft+verify cost wins.
13472 // K=1..8 self-consistency PASS both models with the law ON (exactness held).
13473 let adapt = std::env::var("MEMRA_SPEC_ADAPT").as_deref() == Ok("1");
13474 // floor: per-model default keyed on n_embd (gemma's tiering — models with an expensive
13475 // verify keep deep drafts after a miss); MEMRA_SPEC_ADAPT_FLOOR pins it everywhere.
13476 let adapt_floor_env: Option<usize> = std::env::var("MEMRA_SPEC_ADAPT_FLOOR")
13477 .ok()
13478 .and_then(|v| v.parse().ok());
13479 let adapt_floor_default: usize = if self.cfg.n_embd as usize >= 3500 {
13480 4
13481 } else if self.cfg.n_embd as usize >= 2500 {
13482 2
13483 } else {
13484 1
13485 };
13486 let adapt_floor: usize = adapt_floor_env.unwrap_or(adapt_floor_default);
13487 // position key: past floor_ctx a HIGH floor (>=4) relaxes to 1 — forced-deep drafts
13488 // turn net-negative at depth (gemma 31B d1736 evidence); MEMRA_SPEC_FLOOR_CTX moves
13489 // the boundary, an explicit MEMRA_SPEC_ADAPT_FLOOR pins the floor everywhere.
13490 let floor_ctx: usize = std::env::var("MEMRA_SPEC_FLOOR_CTX")
13491 .ok()
13492 .and_then(|v| v.parse().ok())
13493 .unwrap_or(1024);
13494 let floor_at = |pos: usize| -> usize {
13495 if adapt_floor_env.is_some() || pos < floor_ctx {
13496 adapt_floor
13497 } else if adapt_floor >= 4 {
13498 1
13499 } else {
13500 adapt_floor
13501 }
13502 };
13503 // cap: MEMRA_SPEC_CAPMAX (gemma semantics, default 7). Binds only under adapt — the
13504 // fixed-K default path is untouched by this whole block.
13505 let cap_max: usize = std::env::var("MEMRA_SPEC_CAPMAX")
13506 .ok()
13507 .and_then(|v| v.parse().ok())
13508 .unwrap_or(7);
13509 let k_cap = k.min(cap_max).max(1);
13510 let mut kc = k_cap;
13511 let mut opti_fork: Option<OptiForkState> = None;
13512 let mut _opti_walk: Option<crate::pp::PpWalkLease> = None;
13513 let mut _opti_walk_borrow: Option<crate::pp::PpWalkBorrowGuard> = None;
13514 let mut fork_snapshot: Option<crate::cache::CacheSnapshot> = None;
13515 if fork_mode != OptiForkGateMode::Disabled {
13516 let fence = crate::pp::pp_cuts(self.layers.len());
13517 let refusal = if !session_mode {
13518 Some("not-session")
13519 } else if k != 1 || adapt {
13520 Some("requires-fixed-k1")
13521 } else if sampled || constraint.is_some() || spec_replay {
13522 Some("sampled-constrained-or-replay")
13523 } else if pipe.is_some() {
13524 Some("two-session-pipeline")
13525 } else if !spec_devacc() {
13526 Some("requires-device-accept")
13527 } else if stream_active || crate::spec::spec_stream() {
13528 Some("round-stream")
13529 } else if !self.mtp_extra.is_empty() {
13530 Some("multi-head-mtp")
13531 } else if crate::cache::swa_ring_on() || cache.has_swa_ring() {
13532 Some("swa-ring")
13533 } else if crate::pp::pp_host_bounce_active() {
13534 Some("host-bounce")
13535 } else if fork_mode == OptiForkGateMode::Controller
13536 && cache.recur.iter().any(Option::is_some)
13537 {
13538 Some("controller-requires-zero-recurrent-state")
13539 } else if fence.as_ref().is_none_or(|f| f.len() != 3) {
13540 Some("requires-pp2")
13541 } else {
13542 None
13543 };
13544 if let Some(reason) = refusal {
13545 OPTI_FORK_REFUSALS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13546 eprintln!("[opti-fork] refused reason={reason}");
13547 } else {
13548 let fence = fence.expect("validated PP-2 fence");
13549 let rt = crate::pp::PpNRt::get(e)?;
13550 let primary_stage0 = rt.engine(0, e).ctx().ordinal() == e.ctx().ordinal();
13551 let primary_stage1 = rt.engine(1, e).ctx().ordinal() == e.ctx().ordinal();
13552 let primary_supported =
13553 primary_stage0 || (fork_mode == OptiForkGateMode::Controller && primary_stage1);
13554 if !rt.cross_device() || !primary_supported {
13555 OPTI_FORK_REFUSALS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13556 eprintln!("[opti-fork] refused reason=requires-supported-primary-cross-device");
13557 } else {
13558 // The optimistic controller can keep two boundary tickets in flight. Give
13559 // every nested verify an explicit borrow of one whole-walk generation; no
13560 // `pp_pipe` boolean is allowed to bypass ownership on its own.
13561 let walk = rt.acquire_walk("opti_fork_coordinator")?;
13562 let permit = rt.walk_permit(&walk, "opti_fork_coordinator")?;
13563 let borrow = rt.borrow_walk(&permit, "opti_fork_coordinator")?;
13564 // Both recurrent snapshots and both seed generations are allocated before
13565 // the first fork, each through its owning PP stage. Allocation failure
13566 // therefore happens before any optimistic state mutation can occur.
13567 let current_snapshot = opti_snapshot_stage_owned(e, cache, rt, &fence)?;
13568 let alternate_snapshot = opti_snapshot_stage_owned(e, cache, rt, &fence)?;
13569 let fork = OptiForkState::new(
13570 e,
13571 cache,
13572 fork_mode,
13573 alternate_snapshot,
13574 &h_seed_buf,
13575 &fill_prev,
13576 rt,
13577 fence[1],
13578 self.layers.len(),
13579 )?;
13580 eprintln!(
13581 "[opti-fork] armed mode={fork_mode:?} snapshots=2 seeds=2 split={} \
13582 payload_dev0={} payload_dev1={} q_threshold={:.3}",
13583 fence[1],
13584 fork.logical_payload_bytes[0],
13585 fork.logical_payload_bytes[1],
13586 fork.controller.map_or(0.0, |policy| policy.threshold),
13587 );
13588 fork_snapshot = Some(current_snapshot);
13589 opti_fork = Some(fork);
13590 _opti_walk = Some(walk);
13591 _opti_walk_borrow = Some(borrow);
13592 }
13593 }
13594 }
13595 // Persistent snapshot buffers are allocated once and refreshed in place. The fork arm
13596 // uses stage-owned snapshots; refused/disabled arms retain the existing generic helper.
13597 let mut snap = match fork_snapshot {
13598 Some(snapshot) => snapshot,
13599 None => cache.snapshot(e)?,
13600 };
13601 let mut carried_opti: Option<OptiControllerTicket> = None;
13602 // ROUND-STREAM stage (b) 3a: device table of per-layer kvl.len_d pointers (stable — the
13603 // cache never reallocates len_d; see cache.rs "stable pointer" note). 0 = no KV layer.
13604 let kv_len_ptrs: Option<CudaSlice<u64>> = if spec_devacc() && !spec_replay {
13605 Some(crate::round_stream::kv_len_ptr_table(e, cache, None)?)
13606 } else {
13607 None
13608 };
13609 // BONUS FOLD (2026-07-04): after a FULL accept the bonus token is NOT committed with a
13610 // separate T=1 trunk pass (a full weight read per round). It stays PENDING and rides as
13611 // column 0 of the NEXT round's verify batch. Under predecessor pairing the next chain
13612 // seeds from the bonus's predecessor's TRUE verify hidden (free — no extra
13613 // pass of any kind). Verify still
13614 // checks every emitted token against the target -> exactness holds by construction; only
13615 // DRAFT QUALITY can shift, which the acceptance numbers arbitrate.
13616 // bonus emitted but not yet committed to cache. A carried pending (see SpecSession::
13617 // pending_tok) enters round 0 directly — the burst boundary becomes a plain round edge.
13618 let mut pending: Option<u32> = carried_pending;
13619 // MEMRA_SPEC_PHASE=1: per-round wall decomposition (draft / verify / accept+commit) —
13620 // no tracing, no extra syncs (each phase is naturally sync-bounded: draft readbacks,
13621 // the verify accept readback). Printed once at loop end via spec-stats.
13622 let anatomy_on = std::env::var("MEMRA_SPEC_PP_ANATOMY").as_deref() == Ok("1");
13623 let phase_on = anatomy_on || std::env::var("MEMRA_SPEC_PHASE").as_deref() == Ok("1");
13624 // MEMRA_SPEC_PHASE_SYNC=1 — reads the phase split correctly, and proves it. `ph_mark` is a
13625 // bare Instant, so `verify-issue` is the host QUEUEING the walk (the GPU is already running
13626 // under it) and `verify-wait` is only the residual drain at the accept readback: one
13627 // overlapped interval cut at the first blocking call, NOT "GPU time" beside "host time".
13628 // Syncing right after the walk is issued moves the whole GPU wall into `verify-issue`. If
13629 // the walk's GPU total is really issue+wait, then with this on verify-issue jumps to that
13630 // sum, verify-wait collapses to the readback alone, and the ROUND WALL DOES NOT MOVE —
13631 // which is what says the queueing time was hidden and is not a target. Diagnostic only.
13632 let phase_sync = std::env::var("MEMRA_SPEC_PHASE_SYNC").as_deref() == Ok("1");
13633 // DRAFT-MASK receipt (lane/draft-mask): speculative-clone wall + rounds, printed with
13634 // spec-stats. The clone is the one cost the design adds per round — measured, not assumed.
13635 let (mut dm_clone_ns, mut dm_rounds) = (0u128, 0usize);
13636 // grammar-truncation counters: how many rounds the verify-side cut fired and how many
13637 // already-verified tokens it threw away. THIS is the quantity draft masking targets.
13638 let (mut dm_cuts, mut dm_cut_tokens) = (0usize, 0usize);
13639 let (mut ph_draft, mut ph_verify, mut ph_rest) = (0f64, 0f64, 0f64);
13640 let mut ph_wait = 0f64;
13641 let mut ph_commit = 0f64;
13642 let mut ph_t = std::time::Instant::now();
13643 let mut ph_mark = |acc: &mut f64, on: bool| {
13644 if on {
13645 let now = std::time::Instant::now();
13646 *acc += (now - ph_t).as_secs_f64();
13647 ph_t = now;
13648 }
13649 };
13650 // MTP-ROUTE VERIFY GRAPHS (`MEMRA_SPEC_VERIFY_GRAPH`, see the flag doc): the
13651 // model-owned capture pool, locked for the whole burst exactly as the dspark serve
13652 // arm holds it — the slab stash is live verify -> commit inside a round, and the
13653 // worker drives rounds from one scheduler thread. PERSISTENT across generations on
13654 // the model (rebuilding per call re-captures the pool per prompt, which is the
13655 // measured way to lose more than the launches cost); the captured bodies are
13656 // cache-independent, every state read going through per-round refreshed pointer
13657 // tables. None = the eager walk, byte-identical.
13658 //
13659 // Never armed together with ROUND-STREAM: the tparallel verify refuses that pair
13660 // loudly, and `stream_active` owns the burst arm above, so the door stays shut
13661 // whenever the stream is live rather than relying on that refusal.
13662 // The lock is taken ONLY when the door is armed: with the flag off this whole block
13663 // is inert, so the default path cannot serialize two spec generations behind a mutex
13664 // it never reads.
13665 let vg_armed =
13666 crate::spec::spec_verify_graph_env().unwrap_or_else(|| self.vgraph_family_default());
13667 let mut vg_guard = if vg_armed && !stream_active {
13668 let mut g = self.dspark_vgraphs.lock().unwrap();
13669 if g.is_none() {
13670 // Size by the WIDEST verify this run can present, which is k+1 and NOT
13671 // k_cap+1: the sampled arm's own window is `t_v_s = k + 1`, so a pool built
13672 // from a smaller adaptive cap gets sliced past its stash rows (a `slice_mut`
13673 // panic in the sampled ON arm, measured before this line said k+1).
13674 let vt_cap = (k.max(k_cap) + 1).max(2);
13675 *g = DsparkVerifyGraphs::new(e, cache, vt_cap, n_embd)?;
13676 if g.is_some() {
13677 // Engagement receipt (the dead-arm lesson): prove the door is LIVE rather
13678 // than trusting that a flag set means a pool built.
13679 eprintln!("[spec-vg] MTP verify-graph pool ENGAGED (vt_cap={vt_cap})");
13680 } else {
13681 eprintln!(
13682 "[spec-vg] MTP verify-graph pool declined (no linear layers, \
13683 non-uniform state, or vt_cap < 2) — eager walk"
13684 );
13685 }
13686 }
13687 Some(g)
13688 } else {
13689 None
13690 };
13691 // Capacity fail-safe: a round wider than the pool was built for must take the eager
13692 // walk, not slice the stash past its rows. The sizing above already covers every
13693 // round this run can present; this keeps a future caller (or a k that grows behind
13694 // the pool's back) on the byte-identical fallback instead of a panic.
13695 let vg_t_cap = vg_guard
13696 .as_ref()
13697 .and_then(|g| g.as_ref())
13698 .map(|g| g.t_capacity())
13699 .unwrap_or(0);
13700 if let Some(p) = pipe {
13701 p.setup_end();
13702 }
13703 drop(pipe_setup_walk);
13704 let mut graph_guard_noted = false;
13705 while keep_going && out.len() < max_new {
13706 // GRAPH-LAUNCH HEADROOM GUARD (see GRAPH_LAUNCH_MIN_FREE): below the floor,
13707 // every captured-graph arm in this round yields to its byte-identical eager
13708 // twin instead of feeding cuGraphLaunch a card it segfaults on.
13709 let graph_round_ok = graph_launch_headroom_ok(e);
13710 if !graph_round_ok && !graph_guard_noted {
13711 graph_guard_noted = true;
13712 eprintln!(
13713 "[spec] graph replay suspended: driver free below the {}MB launch floor \
13714 (eager arms serve; cuGraphLaunch segfaults into an exhausted card)",
13715 GRAPH_LAUNCH_MIN_FREE / (1 << 20)
13716 );
13717 }
13718 // MEMRA_SPEC_ROUND_PROF=1: wall of the WHOLE round against the pieces we already
13719 // instrument. Needed because the parts do not add up: the draft step measures 1.27 ms
13720 // ([spec-anatomy] glue 92 / attn 280 / ffn 222 / head 670 us) and the t=2 verify walk
13721 // 25.6 ms ([tcol-prof] attn 10.1 + ffn 15.3), yet a K=1 round takes 177 ms on the
13722 // step37 TP2 stack. This prints where the other ~150 ms lives.
13723 let round_prof = ROUND_PROF
13724 .get_or_init(|| std::env::var("MEMRA_SPEC_ROUND_PROF").as_deref() == Ok("1"));
13725 let round_t0 = round_prof.then(std::time::Instant::now);
13726 // ROUND-STREAM BURST: from round 1 (pending guaranteed by every non-replay arm),
13727 // issue M rounds with zero readbacks, then drain the ring + reconcile mirrors.
13728 if let (true, Some(sg), Some(ptrs)) = (
13729 stream_active && round >= 1 && pending.is_some() && graph_round_ok,
13730 &stream_graph,
13731 &stream_ptrs,
13732 ) {
13733 if debug_spec {
13734 static ONCE: std::sync::Once = std::sync::Once::new();
13735 ONCE.call_once(|| {
13736 eprintln!("[memra] ROUND-STREAM burst engaged (M={m_rounds} k={k})")
13737 });
13738 }
13739 e.set_i32_one(&mut pos_ctr, cache.pos as i32)?;
13740 e.set_u32_one(&mut pend_d, pending.unwrap())?;
13741 e.set_u32_one(&mut ring_d, 0)?; // ring count = 0 (writes element 0)
13742 for _mi in 0..m_rounds {
13743 e.i32_copy_add(&pos_ctr, &mut pos_start_d, 0)?;
13744 cache.snapshot_into(e, &mut snap)?; // device D2Ds, stream-ordered
13745 e.i32_copy_add(&pos_ctr, &mut scratch.kv.len_d, 0)?; // draft-KV rollback
13746 e.i32_copy_add(&pos_ctr, &mut dctx.g_pos, 1)?; // rope pos = pos + base
13747 e.u32_copy(&pend_d, &mut dctx.g_tok)?;
13748 e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
13749 sg.launch()?;
13750 e.spec_assemble_verify(
13751 &g_tokp2k,
13752 &pend_d,
13753 d2t_dev.as_ref(),
13754 &mut vtok_d,
13755 &mut brk_d,
13756 p_min,
13757 k,
13758 pmin0,
13759 )?;
13760 let mut ck = VerifyCkpt::new(self.layers.len());
13761 let dummy = vec![0u32; t_v_s];
13762 let (tl_d, vx) = self.decode_step_t_core_stream(
13763 e,
13764 &dummy,
13765 0,
13766 &mut *cache,
13767 embd_dev,
13768 Some(&mut ck),
13769 Some((&vtok_d, &pos_ctr)),
13770 None,
13771 None,
13772 None,
13773 )?;
13774 for j in 0..t_v_s {
13775 e.argmax_token_device_col(&tl_d, j, n_vocab, &mut preds_d, j)?;
13776 }
13777 e.spec_accept_greedy_dc(
13778 &preds_d,
13779 &vtok_d,
13780 &last_pred_d,
13781 &brk_d,
13782 &mut stream_acc,
13783 )?;
13784 e.spec_seed_gather(&vx, &fill_prev, &stream_acc, &mut h_seed_buf, 1, n_embd)?;
13785 e.copy_into(&mut fill_prev, 0, &h_seed_buf, n_embd)?;
13786 self.commit_verified_prefix_stream(
13787 e,
13788 &mut *cache,
13789 &snap,
13790 &ck,
13791 &stream_acc,
13792 1,
13793 t_v_s,
13794 )?;
13795 e.spec_rollback_stream(
13796 ptrs,
13797 &pos_start_d,
13798 &stream_acc,
13799 1,
13800 self.layers.len() + 1,
13801 )?;
13802 e.spec_ring_commit(&vtok_d, &stream_acc, &brk_d, &mut ring_d, &mut pend_d)?;
13803 }
13804 e.stream().synchronize()?;
13805 let ring_h = e.dtoh_u32(&ring_d)?;
13806 let cnt = ring_h[0] as usize;
13807 for i in 0..cnt {
13808 if out.len() < max_new {
13809 out.push(ring_h[1 + i]);
13810 }
13811 }
13812 let pos_h = e.dtoh_i32(&pos_ctr)?[0] as usize;
13813 for il in 0..self.layers.len() {
13814 if let Some(kvl) = cache.kv[il].as_mut() {
13815 kvl.len = pos_h;
13816 }
13817 }
13818 cache.pos = pos_h;
13819 scratch.kv.len = pos_h;
13820 pending = Some(ring_h[cnt]); // last drained token = the live bonus
13821 last_token = ring_h[cnt];
13822 total_drafted += k * m_rounds; // upper bound (p-min breaks uncounted)
13823 total_accepted += cnt.saturating_sub(m_rounds);
13824 if let Some(t) = sess_telem {
13825 // totals only — the burst's per-round accept counts stayed on device
13826 // (that is the point of the round-stream arm). pos_* untouched.
13827 t.record_totals(m_rounds, k * m_rounds, cnt.saturating_sub(m_rounds));
13828 }
13829 round += m_rounds;
13830 // sse-cadence: the drained ring is committed — flush it at burst-drain cadence.
13831 keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
13832 continue;
13833 }
13834 let pipe_draft = match pipe {
13835 Some(p) => Some(p.draft_begin(round)?),
13836 None => None,
13837 };
13838 let pos = cache.pos; // #tokens committed (EXCLUDES a pending bonus)
13839 let mut current_opti = carried_opti.take();
13840 let mut fork_generation = if current_opti.is_none() && pending.is_some() {
13841 match opti_fork.as_mut() {
13842 Some(fork) if fork.mode.is_forced() => Some(fork.reserve(&mut snap)?),
13843 None => None,
13844 Some(_) => None,
13845 }
13846 } else {
13847 None
13848 };
13849 if current_opti.is_none() {
13850 if let Some(fork) = opti_fork.as_ref() {
13851 opti_snapshot_stage_owned_into(e, cache, fork.rt, &fork.fence, &mut snap)?;
13852 } else {
13853 cache.snapshot_into(e, &mut snap)?;
13854 }
13855 } else if snap.pos != pos {
13856 return Err(format!(
13857 "optipipe carried snapshot pos {} != current pos {pos}",
13858 snap.pos
13859 )
13860 .into());
13861 } // §C: snapshot BEFORE draft+verify (already retained for a carried successor)
13862 ph_mark(&mut ph_rest, phase_on);
13863
13864 // --- 1. DRAFT k tokens with the NextN head (autoregressive, T=1 each) ---
13865 // p-min semantics (both paths): stop the chain early when the head's confidence in
13866 // its own pick drops below p_min — the just-drafted token is DISCARDED, but its
13867 // scratch append stands (identical to the eager chain's ordering). j==0 always drafts.
13868 let base0 = if pending.is_some() { 1usize } else { 0usize };
13869 // fixed draft length by default; MEMRA_SPEC_ADAPT=1 drafts at last round's
13870 // accepted run + 1 (the gemma law — see the setup block above the loop).
13871 let k_this = if adapt { kc } else { k };
13872 let mut draft: Vec<u32> = Vec::with_capacity(k);
13873 let mut draft_idx: Vec<u32> = Vec::with_capacity(k); // trimmed-vocab ids (== draft when untrimmed)
13874 let mut controller_draft_prob: Option<f32> = None;
13875 let mut controller_eager_state: Option<(u32, CudaSlice<f32>)> = None;
13876 if let Some(ticket) = current_opti.as_mut() {
13877 let carried_pending = pending.ok_or("optipipe carried successor lost pending")?;
13878 if ticket.verify_tokens[0] != carried_pending {
13879 return Err(format!(
13880 "optipipe carried pending mismatch: ticket={} live={carried_pending}",
13881 ticket.verify_tokens[0],
13882 )
13883 .into());
13884 }
13885 draft.push(ticket.verify_tokens[1]);
13886 controller_draft_prob = Some(ticket.draft_prob);
13887 controller_eager_state = ticket
13888 .take_eager_seed()
13889 .map(|seed| (ticket.verify_tokens[1], seed));
13890 } else {
13891 // Round-start draft-KV sync (BOTH paths). Persistent: truncate/align to the committed
13892 // history — slots 0..P hold entries for the tokens before last_token@P (P = pos +
13893 // base0 - 1); this single set_len IS the draft-side rollback (drops last round's
13894 // rejected drafts and p-min extras via the len mechanism).
13895 scratch.set_len(e, pos + base0 - 1)?;
13896 // dcw door: a captured chain appends k_this device-counter rows (plus the
13897 // pseudo-seed replay) with no host intervention; any ring rebase those appends
13898 // could need happens HERE, host-side, before the replays. The eager arm keeps
13899 // its own per-step prepare, so this is graph-path-only work.
13900 if step35_draft_dcw_on()
13901 && (dctx.graph.is_some()
13902 || dctx.graph_s.is_some()
13903 || dctx.chain.is_some()
13904 || dctx.chain_s.is_some())
13905 {
13906 scratch.ensure_dcw_headroom(e, k_this + 2)?;
13907 }
13908 if pen_on {
13909 // PEN_WINDOW_MAX also bounds the per-round upload and the O(n_hist^2)
13910 // device dedup: the serve window is already PEN_WINDOW_MAX, and this
13911 // defensive min also bounds non-server callers.
13912 let win = sp.penalty_last_n.min(PEN_WINDOW_MAX);
13913 let w0 = pen_hist.len().saturating_sub(win);
13914 pen_hist_d = Some(e.htod_u32_v(&pen_hist[w0..])?);
13915 }
13916 if sampled {
13917 draft_logits.clear();
13918 draft_stats.clear();
13919 }
13920 // DRAFT-SIDE GRAMMAR MASK: clone the committed grammar state ONCE per round; each
13921 // position's mask is computed on that clone and advanced by the PROPOSED token. The
13922 // real state moves only on emission (verify's job), so the emitted stream is
13923 // unchanged — the mask only removes tokens the verify would have truncated anyway.
13924 let mut dmask_live = dmask_on;
13925 if dmask_live {
13926 let t_c = std::time::Instant::now();
13927 constraint
13928 .as_deref_mut()
13929 .unwrap()
13930 .draft_begin()
13931 .map_err(|e2| format!("constraint: {e2}"))?;
13932 dm_clone_ns += t_c.elapsed().as_nanos();
13933 dm_rounds += 1;
13934 }
13935 if let (false, Some(cg)) = (sampled || pen_on || !graph_round_ok, &dctx.chain) {
13936 // GREEDY CHAIN GRAPH (lane/step37-draft-graph-serving-20260830): the
13937 // eager multi-head chain's EXACT launch order — step j rewinds head
13938 // (j % heads)'s plane to the committed length and replays rows 0..=j —
13939 // with each row's whole head-forward as ONE graph launch. The chain
13940 // POLICY (head choice, prefix length, stored-seed feed) is host-side,
13941 // identical to `mtp_chain_forward_dev`, so graph-vs-eager drafts are
13942 // bit-identical by construction (same launcher, same bucket — the dcw
13943 // parity contract). Interior rows launch the head-less graph: their
13944 // logits are dead in the eager chain too, so the consumed bytes match.
13945 let heads_n = self.mtp_head_count();
13946 let committed = pos + base0 - 1;
13947 let mut chain_tokens: Vec<u32> = vec![last_token];
13948 let mut chain_seed_bufs: Vec<CudaSlice<f32>> = vec![e.clone_dtod(&h_seed_buf)?];
13949 for j in 0..k_this {
13950 let index = mtp_chain_head_index(j, heads_n);
13951 if debug_spec {
13952 eprintln!(
13953 "[mtp-chain-step] round={round} j={j} head={index} \
13954 replay_rows={} arm=graph",
13955 chain_tokens.len(),
13956 );
13957 }
13958 scratch.set_plane_len(e, index, committed)?;
13959 e.set_i32_one(&mut dctx.g_pos, (committed + 1) as i32)?;
13960 for row in 0..=j {
13961 e.set_u32_one(&mut dctx.g_tok, chain_tokens[row])?;
13962 e.copy_into(&mut dctx.g_seed, 0, &chain_seed_bufs[row], n_embd)?;
13963 if row < j {
13964 cg.interior[index].launch()?;
13965 } else {
13966 // per-position mask upload before the LAST row only — the
13967 // eager chain applies the mask on is_last exactly the same.
13968 if dmask_live
13969 && !upload_draft_mask(
13970 e,
13971 constraint.as_deref_mut().unwrap(),
13972 &mut dctx.g_dmask,
13973 mtp.d2t.as_ref(),
13974 d_vocab,
13975 dmask_words,
13976 )?
13977 {
13978 e.htod_u32_into(
13979 &mut dctx.g_dmask,
13980 &vec![u32::MAX; dmask_words],
13981 )?;
13982 dmask_live = false;
13983 }
13984 cg.last[index].launch()?;
13985 }
13986 // host mirror (len_d advanced in-graph by the dcw append)
13987 scratch.plane_mut(index).0.len += 1;
13988 }
13989 let idx = e.dtoh_u32_one(&dctx.g_tok)?;
13990 // #87 SENTINEL TRAP (see the single-head graph arm below).
13991 if (idx as usize) >= d_vocab {
13992 let seed_h = e.dtoh(&dctx.g_seed)?;
13993 let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
13994 return Err(format!(
13995 "draft(chain-graph) argmax sentinel 0x{idx:08x} >= d_vocab \
13996 {d_vocab} at round {round} j={j} head={index} pos={pos}: \
13997 head-out NaN {seed_nan}/{n_embd} — refusing to dereference \
13998 the embed row (#87 trap)"
13999 )
14000 .into());
14001 }
14002 // multi-head MTP forbids a trimmed head (validated at entry), so the
14003 // draft index IS the target id; keep the map for uniformity.
14004 let d = match &mtp.d2t {
14005 Some(map) => map[idx as usize],
14006 None => idx,
14007 };
14008 let draft_p = if p_min > 0.0 {
14009 Some(e.dtoh(&dctx.g_p)?[0])
14010 } else {
14011 None
14012 };
14013 if j == 0 {
14014 controller_draft_prob = draft_p;
14015 }
14016 if let Some(p) = draft_p.filter(|_| p_min > 0.0)
14017 && p < p_min
14018 && (j > 0 || (pmin0 && base0 == 1))
14019 {
14020 break;
14021 }
14022 draft.push(d);
14023 chain_tokens.push(d);
14024 // step j's h_nextn: the last-row graph self-fed it into g_seed —
14025 // snapshot it as the chain history seed for row j+1 (stream-ordered
14026 // after the launch, exactly the eager chain's chain_seeds push).
14027 chain_seed_bufs.push(e.clone_dtod(&dctx.g_seed)?);
14028 // speculative grammar advance (see the single-head graph arm).
14029 if dmask_live
14030 && !constraint
14031 .as_deref_mut()
14032 .unwrap()
14033 .draft_advance(d)
14034 .map_err(|e2| format!("constraint: {e2}"))?
14035 {
14036 e.htod_u32_into(&mut dctx.g_dmask, &vec![u32::MAX; dmask_words])?;
14037 break;
14038 }
14039 }
14040 } else if let (true, Some(cg)) = (
14041 sampled && s_capturable && dctx.s_key == Some(s_key) && graph_round_ok,
14042 &dctx.chain_s,
14043 ) {
14044 if skey_probe() {
14045 eprintln!(
14046 "[skey] chain=graph_chain_s round={round} capturable={} top_k={} \
14047 top_p={} min_p={} s_key_parked={:?}",
14048 s_capturable as u8, sp.top_k, sp.top_p, sp.min_p, dctx.s_key,
14049 );
14050 }
14051 // SAMPLED CHAIN GRAPH: the greedy chain arm's launch order with the
14052 // sampled last-row graphs — in-graph counter bump + (filtered) gumbel
14053 // draw + argmax; q retained per step into q_slots exactly like the
14054 // single-head sampled graph arm. Counter continuity: g_ctr host-seeded
14055 // to sctr-1 once per ROUND; each step's last-row graph bumps it BEFORE
14056 // the perturb, so step j consumes counter sctr+j — the eager Philox
14057 // stream (interior rows never draw, never bump).
14058 let heads_n = self.mtp_head_count();
14059 let committed = pos + base0 - 1;
14060 let filtered_stats_in_graph = s_key.filtered();
14061 let mut chain_tokens: Vec<u32> = vec![last_token];
14062 let mut chain_seed_bufs: Vec<CudaSlice<f32>> = vec![e.clone_dtod(&h_seed_buf)?];
14063 e.set_u32_one(&mut dctx.g_ctr, sctr.wrapping_sub(1))?;
14064 for j in 0..k_this {
14065 let index = mtp_chain_head_index(j, heads_n);
14066 if debug_spec {
14067 eprintln!(
14068 "[mtp-chain-step] round={round} j={j} head={index} \
14069 replay_rows={} arm=graph_s",
14070 chain_tokens.len(),
14071 );
14072 }
14073 scratch.set_plane_len(e, index, committed)?;
14074 e.set_i32_one(&mut dctx.g_pos, (committed + 1) as i32)?;
14075 for row in 0..=j {
14076 e.set_u32_one(&mut dctx.g_tok, chain_tokens[row])?;
14077 e.copy_into(&mut dctx.g_seed, 0, &chain_seed_bufs[row], n_embd)?;
14078 if row < j {
14079 cg.interior[index].launch()?;
14080 } else {
14081 cg.last[index].launch()?;
14082 }
14083 scratch.plane_mut(index).0.len += 1;
14084 }
14085 sctr += 1; // mirrors the in-graph g_ctr bump (eager parity:
14086 // counts the p-min-discarded token too)
14087 // q retention: ONE async D2D of the persistent head-logits buffer
14088 // into this round's slot j (stream-ordered after the replay).
14089 e.copy_into(&mut dctx.q_slots[j], 0, &dctx.g_q, d_vocab)?;
14090 // FILTERED capture: read the in-graph filter_stats scalars back per
14091 // replay instead of a second full-vocab filter_stats per slot post-
14092 // chain — bit-exact (the values the in-graph perturb consumed) and
14093 // measured worth ~5% of vendor-default serving tok/s at K=3. Before
14094 // the p-min break so the discarded slot's stats land too.
14095 if filtered_stats_in_graph {
14096 draft_stats.push((
14097 e.dtoh(&dctx.g_mx)?[0],
14098 e.dtoh(&dctx.g_th)?[0],
14099 e.dtoh(&dctx.g_z)?[0],
14100 ));
14101 }
14102 let idx = e.dtoh_u32_one(&dctx.g_tok)?;
14103 // #87 SENTINEL TRAP (see the single-head graph arms).
14104 if (idx as usize) >= d_vocab {
14105 let seed_h = e.dtoh(&dctx.g_seed)?;
14106 let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
14107 return Err(format!(
14108 "draft(chain-graph-sampled) argmax sentinel 0x{idx:08x} >= \
14109 d_vocab {d_vocab} at round {round} j={j} head={index} pos={pos}: \
14110 head-out NaN {seed_nan}/{n_embd} — refusing to dereference the \
14111 embed row (#87 trap)"
14112 )
14113 .into());
14114 }
14115 let d = match &mtp.d2t {
14116 Some(map) => map[idx as usize],
14117 None => idx,
14118 };
14119 draft_idx.push(idx);
14120 if p_min > 0.0 {
14121 let p = e.dtoh(&dctx.g_p)?[0];
14122 if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
14123 break;
14124 }
14125 }
14126 draft.push(d);
14127 chain_tokens.push(d);
14128 chain_seed_bufs.push(e.clone_dtod(&dctx.g_seed)?);
14129 }
14130 // PURE-TEMP accept path: stats per used slot recomputed from the RETAINED
14131 // q with the SAME filter_stats program the eager arm runs (deployment-
14132 // keyed coop/plain choice, same input bits). The FILTERED graph read its
14133 // stats back per replay above.
14134 if !filtered_stats_in_graph {
14135 for j in 0..draft.len().max(draft_idx.len()) {
14136 let rows0 = e.htod_i32(&[0])?;
14137 let (mut th_d, mut z_d, mut mx_d) =
14138 (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
14139 e.filter_stats(
14140 &dctx.q_slots[j],
14141 d_vocab,
14142 &rows0,
14143 &mut th_d,
14144 &mut z_d,
14145 &mut mx_d,
14146 d_vocab,
14147 1,
14148 sp_temp,
14149 sp.top_k,
14150 sp.top_p,
14151 sp.min_p,
14152 )?;
14153 draft_stats.push((
14154 e.dtoh(&mx_d)?[0],
14155 e.dtoh(&th_d)?[0],
14156 e.dtoh(&z_d)?[0],
14157 ));
14158 }
14159 }
14160 } else if let (false, Some(gr)) =
14161 (sampled || pen_on || !graph_round_ok, &dctx.graph)
14162 {
14163 // GRAPH DRAFT: one dispatch per drafted token. The chain feeds itself on-device
14164 // (in-graph argmax -> tok_d -> next replay's embed; h_nextn -> h_seed_d; pos_d
14165 // inc'd in-graph); the host only reads 4B token (+4B p) and decides the break.
14166 e.set_i32_one(&mut dctx.g_pos, (pos + base0) as i32)?;
14167 e.set_u32_one(&mut dctx.g_tok, last_token)?;
14168 e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
14169 for j in 0..k_this {
14170 // per-position mask upload (contents only — the graph's baked pointer is
14171 // dctx.g_dmask). All-ones once masking goes dead mid-chain, so the captured
14172 // mask node degrades to a no-op ban instead of needing a second graph.
14173 if dmask_live
14174 && !upload_draft_mask(
14175 e,
14176 constraint.as_deref_mut().unwrap(),
14177 &mut dctx.g_dmask,
14178 mtp.d2t.as_ref(),
14179 d_vocab,
14180 dmask_words,
14181 )?
14182 {
14183 // no draft-vocab row is grammar-legal here (a trimmed FR-Spec head can
14184 // genuinely miss the legal set): neutralize the captured mask node and
14185 // finish the chain UNMASKED — exactly pre-lane behaviour, never worse.
14186 e.htod_u32_into(&mut dctx.g_dmask, &vec![u32::MAX; dmask_words])?;
14187 dmask_live = false;
14188 }
14189 gr.launch()?;
14190 scratch.kv.len += 1; // host mirror (len_d advanced in-graph)
14191 let idx = e.dtoh_u32_one(&dctx.g_tok)?;
14192 // #87 SENTINEL TRAP: an all-NaN head-logits row leaves the device argmax's
14193 // init sentinel (0x7FFFFFFF) in g_tok — feeding it onward dereferences
14194 // embed_row(sentinel) = table + ~4.6TB (never mapped) inside the NEXT graph
14195 // replay's embed node, and the MMU fault kills the CUDA context for the
14196 // whole process (research/pp2spec-crash-20260807: 3 coredumps, byte-exact
14197 // VA arithmetic). Refuse loudly instead; the diagnostics name the first-NaN
14198 // buffer (g_seed = the verify-side handoff vs head-side compute).
14199 if (idx as usize) >= d_vocab {
14200 // g_seed is SELF-FED (the replay writes h_nextn back into it), so it
14201 // reads as the head's OUTPUT at j; h_seed_buf is the round's INPUT
14202 // seed, untouched since the round-start copy — the pair discriminates
14203 // "seed arrived poisoned" from "head forward produced NaN".
14204 let seed_h = e.dtoh(&dctx.g_seed)?;
14205 let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
14206 let in_h = e.dtoh(&h_seed_buf)?;
14207 let in_nan = in_h.iter().filter(|v| v.is_nan()).count();
14208 return Err(format!(
14209 "draft(graph) argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab} at \
14210 round {round} j={j} pos={pos}: head-out NaN {seed_nan}/{n_embd}, \
14211 round-input-seed NaN {in_nan}/{n_embd} — refusing to dereference \
14212 the embed row (#87 trap)"
14213 )
14214 .into());
14215 }
14216 // trimmed draft vocab -> target token id (identity when no d2t map)
14217 let d = match &mtp.d2t {
14218 Some(map) => map[idx as usize],
14219 None => idx,
14220 };
14221 let draft_p = if p_min > 0.0
14222 || opti_fork
14223 .as_ref()
14224 .is_some_and(|fork| fork.controller.is_some())
14225 {
14226 Some(e.dtoh(&dctx.g_p)?[0])
14227 } else {
14228 None
14229 };
14230 if j == 0 {
14231 controller_draft_prob = draft_p;
14232 }
14233 if let Some(p) = draft_p.filter(|_| p_min > 0.0)
14234 && p < p_min
14235 && (j > 0 || (pmin0 && base0 == 1))
14236 {
14237 break;
14238 }
14239 draft.push(d);
14240 // with a trimmed head the NEXT embed must read the TARGET id, not the draft
14241 // index the argmax wrote — patch the persistent token buffer (4B htod).
14242 if d != idx {
14243 e.set_u32_one(&mut dctx.g_tok, d)?;
14244 }
14245 // advance the SPECULATIVE state with the proposal; a dead chain drops to
14246 // unmasked drafting for the remaining positions (verify still arbitrates).
14247 // speculative advance; a chain the grammar can no longer follow (EOS
14248 // proposed) ends here. The captured mask node always runs, so a dead chain
14249 // leaves the buffer NEUTRAL (all-ones = ban nothing) before it exits.
14250 if dmask_live
14251 && !constraint
14252 .as_deref_mut()
14253 .unwrap()
14254 .draft_advance(d)
14255 .map_err(|e2| format!("constraint: {e2}"))?
14256 {
14257 e.htod_u32_into(&mut dctx.g_dmask, &vec![u32::MAX; dmask_words])?;
14258 break;
14259 }
14260 }
14261 // REGIME RE-TEST (lane/graph-s-key-exactness-20260819, widened by
14262 // lane/step37-draft-graph-serving-20260830): the sampled graph is legal ONLY
14263 // in the regime it was captured in. The condition used to read
14264 // `(sampled, &dctx.graph_s)` and trusted `s_key` to have dropped anything
14265 // else — which it could not, because the key omitted the filters. Both
14266 // halves are enforced: the key drops a stale graph, and this site refuses to
14267 // launch one whose key differs or whose regime is uncapturable (penalties).
14268 } else if let (true, Some(gr)) = (
14269 sampled && s_capturable && dctx.s_key == Some(s_key) && graph_round_ok,
14270 &dctx.graph_s,
14271 ) {
14272 if skey_probe() {
14273 eprintln!(
14274 "[skey] chain=graph_s round={round} pure_temp={} capturable={} \
14275 top_k={} top_p={} min_p={} s_key_parked={:?}",
14276 pure_temp as u8,
14277 s_capturable as u8,
14278 sp.top_k,
14279 sp.top_p,
14280 sp.min_p,
14281 dctx.s_key,
14282 );
14283 }
14284 // SAMPLED GRAPH DRAFT: one replay per drafted token — head forward + gumbel +
14285 // argmax in ONE dispatch; the host reads 4B token (+4B p), D2Ds q into slot j,
14286 // and decides the break. Event-counter continuity: g_ctr is host-seeded to
14287 // sctr-1 ONCE per round (outside the graph); the in-graph bump runs BEFORE the
14288 // perturb, so replay j consumes counter sctr+j — exactly the eager arm's Philox
14289 // stream. Host sctr advances in lockstep (computed, no readback needed).
14290 e.set_i32_one(&mut dctx.g_pos, (pos + base0) as i32)?;
14291 e.set_u32_one(&mut dctx.g_tok, last_token)?;
14292 e.copy_into(&mut dctx.g_seed, 0, &h_seed_buf, n_embd)?;
14293 e.set_u32_one(&mut dctx.g_ctr, sctr.wrapping_sub(1))?;
14294 let filtered_stats_in_graph = s_key.filtered();
14295 for j in 0..k_this {
14296 gr.launch()?;
14297 scratch.kv.len += 1; // host mirror (len_d advanced in-graph)
14298 sctr += 1; // mirrors the in-graph g_ctr bump (eager parity:
14299 // counts the p-min-discarded token too)
14300 // q retention: ONE async D2D of the persistent head-logits buffer into this
14301 // round's slot j (stream-ordered after the replay, before the next one).
14302 e.copy_into(&mut dctx.q_slots[j], 0, &dctx.g_q, d_vocab)?;
14303 // FILTERED capture: the replay's own filter_stats node already computed
14304 // (th, z, mx) — read the three scalars back instead of paying a SECOND
14305 // full-vocab filter_stats per slot post-chain (measured ~5% of vendor-
14306 // default serving tok/s at K=3). Bit-exact by construction: these are
14307 // the very values the in-graph perturb consumed. Read BEFORE the p-min
14308 // break so the discarded slot's stats land too (accept-path indexing).
14309 if filtered_stats_in_graph {
14310 draft_stats.push((
14311 e.dtoh(&dctx.g_mx)?[0],
14312 e.dtoh(&dctx.g_th)?[0],
14313 e.dtoh(&dctx.g_z)?[0],
14314 ));
14315 }
14316 let idx = e.dtoh_u32_one(&dctx.g_tok)?;
14317 // #87 SENTINEL TRAP (see the greedy graph arm above).
14318 if (idx as usize) >= d_vocab {
14319 let seed_h = e.dtoh(&dctx.g_seed)?;
14320 let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
14321 return Err(format!(
14322 "draft(graph-sampled) argmax sentinel 0x{idx:08x} >= d_vocab \
14323 {d_vocab} at round {round} j={j} pos={pos}: round-seed NaN \
14324 {seed_nan}/{n_embd} — refusing to dereference the embed row \
14325 (#87 trap)"
14326 )
14327 .into());
14328 }
14329 let d = match &mtp.d2t {
14330 Some(map) => map[idx as usize],
14331 None => idx,
14332 };
14333 draft_idx.push(idx);
14334 if p_min > 0.0 {
14335 let p = e.dtoh(&dctx.g_p)?[0];
14336 if p < p_min && (j > 0 || (pmin0 && base0 == 1)) {
14337 break;
14338 }
14339 }
14340 draft.push(d);
14341 // trimmed head: the NEXT embed must read the TARGET id (see the greedy arm).
14342 if d != idx {
14343 e.set_u32_one(&mut dctx.g_tok, d)?;
14344 }
14345 }
14346 // PURE-TEMP accept path: fill draft_stats per used slot post-chain (the
14347 // stats degenerate to th=0 / full-Z; one filter_stats launch per slot).
14348 // The FILTERED graph read its stats back per replay above.
14349 if !filtered_stats_in_graph {
14350 for j in 0..draft.len().max(draft_idx.len()) {
14351 let rows0 = e.htod_i32(&[0])?;
14352 let (mut th_d, mut z_d, mut mx_d) =
14353 (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
14354 e.filter_stats(
14355 &dctx.q_slots[j],
14356 d_vocab,
14357 &rows0,
14358 &mut th_d,
14359 &mut z_d,
14360 &mut mx_d,
14361 d_vocab,
14362 1,
14363 sp_temp,
14364 sp.top_k,
14365 sp.top_p,
14366 sp.min_p,
14367 )?;
14368 draft_stats.push((
14369 e.dtoh(&mx_d)?[0],
14370 e.dtoh(&th_d)?[0],
14371 e.dtoh(&z_d)?[0],
14372 ));
14373 }
14374 }
14375 } else {
14376 if skey_probe() && sampled {
14377 eprintln!(
14378 "[skey] chain=eager round={round} pure_temp={} top_k={} \
14379 top_p={} min_p={} s_key_parked={:?}",
14380 pure_temp as u8, sp.top_k, sp.top_p, sp.min_p, dctx.s_key,
14381 );
14382 }
14383 // EAGER DRAFT (fallback: MoE head/trunk, huge k, MEMRA_SPEC_NOGRAPH, capture fail).
14384 let chain_heads = !self.mtp_extra.is_empty();
14385 let mut e_tok = last_token;
14386 let mut d_seed = e.clone_dtod(&h_seed_buf)?;
14387 let mut chain_tokens = if chain_heads {
14388 vec![last_token]
14389 } else {
14390 Vec::new()
14391 };
14392 let mut chain_seeds = if chain_heads {
14393 vec![e.clone_dtod(&h_seed_buf)?]
14394 } else {
14395 Vec::new()
14396 };
14397 for j in 0..k_this {
14398 // GPU-ARGMAX DRAFT (2026-07-03): device logits + device argmax + 4-byte token
14399 // read instead of the ~600KB full-vocab dtoh + host argmax per draft token.
14400 let mtp_pos = pos + base0 + j;
14401 // draft-side grammar mask (eager twin of the graph arm's in-graph node).
14402 // A position with no legal draft-vocab row drops to unmasked drafting for
14403 // the rest of the chain (pre-lane behaviour; verify still arbitrates).
14404 if dmask_live {
14405 dmask_live = upload_draft_mask(
14406 e,
14407 constraint.as_deref_mut().unwrap(),
14408 &mut dctx.g_dmask,
14409 mtp.d2t.as_ref(),
14410 d_vocab,
14411 dmask_words,
14412 )?;
14413 }
14414 let mask = if dmask_live {
14415 Some((&dctx.g_dmask, dmask_words))
14416 } else {
14417 None
14418 };
14419 let (dl_d, h_nextn) = if chain_heads {
14420 if debug_spec {
14421 eprintln!(
14422 "[mtp-chain-step] round={round} j={j} head={} replay_rows={}",
14423 mtp_chain_head_index(j, self.mtp_head_count()),
14424 chain_tokens.len(),
14425 );
14426 }
14427 self.mtp_chain_forward_dev(
14428 e,
14429 &chain_tokens,
14430 &chain_seeds,
14431 &mut *scratch,
14432 pos + base0 - 1,
14433 embd_dev,
14434 mask,
14435 )?
14436 } else {
14437 self.mtp_head_forward_dev(
14438 e,
14439 mtp,
14440 e_tok,
14441 &d_seed,
14442 &mut *scratch,
14443 mtp_pos,
14444 embd_dev,
14445 mask,
14446 )?
14447 };
14448 let tok_d = if sampled {
14449 // FILTERED Gumbel-max: stats -> masked perturb -> argmax = one draw from
14450 // the filtered softmax (filters off => th=0, exact v1 semantics).
14451 if perturb_buf.is_none() {
14452 perturb_buf = Some(e.zeros(d_vocab.max(n_vocab))?);
14453 }
14454 let mut q_row = e.clone_dtod(&dl_d)?; // retained q (penalized when on)
14455 if pen_on {
14456 let h = pen_hist_d.as_ref().unwrap();
14457 let nh = h.len();
14458 e.penalize_logits(
14459 &mut q_row,
14460 h,
14461 nh,
14462 sp.penalty_repeat,
14463 sp.penalty_freq,
14464 sp.penalty_present,
14465 d_vocab,
14466 )?;
14467 }
14468 let rows0 = e.htod_i32(&[0])?;
14469 let (mut th_d, mut z_d, mut mx_d) =
14470 (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
14471 e.filter_stats(
14472 &q_row, d_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, d_vocab,
14473 1, sp_temp, sp.top_k, sp.top_p, sp.min_p,
14474 )?;
14475 let (th, z, mx) =
14476 (e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0], e.dtoh(&mx_d)?[0]);
14477 let pb = perturb_buf.as_mut().unwrap();
14478 e.gumbel_perturb_filtered(
14479 &q_row, pb, d_vocab, sp_seed, sctr, sp_temp, mx, th,
14480 )?;
14481 sctr += 1;
14482 draft_logits.push(q_row);
14483 draft_stats.push((mx, th, z));
14484 e.argmax_token_device(pb, d_vocab)?
14485 } else {
14486 e.argmax_token_device(&dl_d, d_vocab)?
14487 };
14488 let idx = e.dtoh_u32_one(&tok_d)?;
14489 // #87 SENTINEL TRAP (eager twin — see the graph arm). Extra diagnostics
14490 // here because the eager chain's operands are all readable: dl_d (the head
14491 // logits row) and d_seed (this step's h_seed) name the first-NaN buffer.
14492 if (idx as usize) >= d_vocab {
14493 let dl_h = e.dtoh(&dl_d)?;
14494 let dl_nan = dl_h.iter().filter(|v| v.is_nan()).count();
14495 let seed_h = if chain_heads {
14496 e.dtoh(chain_seeds.last().unwrap())?
14497 } else {
14498 e.dtoh(&d_seed)?
14499 };
14500 let seed_nan = seed_h.iter().filter(|v| v.is_nan()).count();
14501 return Err(format!(
14502 "draft(eager) argmax sentinel 0x{idx:08x} >= d_vocab {d_vocab} at \
14503 round {round} j={j} pos={pos}: head-logits NaN {dl_nan}/{d_vocab}, \
14504 step-seed NaN {seed_nan}/{n_embd} — refusing to dereference the \
14505 embed row (#87 trap)"
14506 )
14507 .into());
14508 }
14509 let d = match &mtp.d2t {
14510 Some(map) => map[idx as usize],
14511 None => idx,
14512 };
14513 if sampled {
14514 draft_idx.push(idx);
14515 }
14516 let draft_p = if p_min > 0.0
14517 || opti_fork
14518 .as_ref()
14519 .is_some_and(|fork| fork.controller.is_some())
14520 {
14521 let p_d = e.prob_of_token_device(&dl_d, &tok_d, d_vocab)?;
14522 Some(e.dtoh(&p_d)?[0])
14523 } else {
14524 None
14525 };
14526 if j == 0 {
14527 controller_draft_prob = draft_p;
14528 }
14529 if let Some(p) = draft_p.filter(|_| p_min > 0.0)
14530 && p < p_min
14531 && (j > 0 || (pmin0 && base0 == 1))
14532 {
14533 break;
14534 }
14535 draft.push(d);
14536 if chain_heads {
14537 chain_tokens.push(d);
14538 chain_seeds.push(h_nextn);
14539 } else {
14540 e_tok = d;
14541 d_seed = h_nextn;
14542 }
14543 // speculative advance; a chain the grammar can no longer follow (EOS
14544 // proposed) ends here — the prefix already proposed still rides verify.
14545 if dmask_live
14546 && !constraint
14547 .as_deref_mut()
14548 .unwrap()
14549 .draft_advance(d)
14550 .map_err(|e2| format!("constraint: {e2}"))?
14551 {
14552 break;
14553 }
14554 }
14555 if !chain_heads
14556 && opti_fork
14557 .as_ref()
14558 .is_some_and(|fork| fork.controller.is_some())
14559 {
14560 controller_eager_state = Some((e_tok, d_seed));
14561 }
14562 }
14563 }
14564 let k_round = draft.len();
14565 if let Some(p) = pipe {
14566 p.draft_end(round);
14567 }
14568 drop(pipe_draft);
14569
14570 ph_mark(&mut ph_draft, phase_on);
14571 // --- 2. VERIFY: one batched target forward. With a pending bonus, it rides as col 0
14572 // (committing its KV/recur inside the SAME weight read); drafts follow. ---
14573 let verify_tokens: Vec<u32> = match pending {
14574 Some(b) => {
14575 let mut v = Vec::with_capacity(k_round + 1);
14576 v.push(b);
14577 v.extend_from_slice(&draft);
14578 v
14579 }
14580 None => draft.clone(),
14581 };
14582 let base = if pending.is_some() { 1 } else { 0 };
14583 // ckpt (REPLAY-FREE partial accept): retain per-layer state-rebuild inputs alongside
14584 // the verify. Pure buffer keep-alives + dtod clones — kernel work is unchanged.
14585 let mut ckpt = if let Some(ticket) = current_opti.as_mut() {
14586 Some(ticket.take_ckpt())
14587 } else if spec_replay {
14588 None
14589 } else {
14590 Some(VerifyCkpt::new(self.layers.len()))
14591 };
14592 let controller_can_probe = base == 1
14593 && k_round == 1
14594 && out.len().saturating_add(2) < max_new
14595 && controller_draft_prob.is_some()
14596 && opti_fork
14597 .as_ref()
14598 .and_then(|fork| fork.controller.as_ref())
14599 .is_some_and(|policy| !policy.breaker_tripped);
14600 let mut successor_attempt: Option<OptiControllerTicket> = None;
14601 let mut rejected_probe: Option<(f32, u32)> = None;
14602 let mut controller_prepared: Option<OptiControllerPrepared> = None;
14603 if controller_can_probe {
14604 // Prepare d2/q and, on admission, d3 before either current verify half is
14605 // issued. N stage 0 can then be followed immediately by N+1 stage 0; once N's
14606 // boundary fires, those dev0 launches overlap N stage 1 on dev1. Preparing on
14607 // the primary stream after N stage 1 would serialize the supposed pipeline.
14608 let eager_pos = scratch.kv.len + 1;
14609 let (optimistic_pending, pending_probability) = self.opti_controller_draft_step(
14610 e,
14611 mtp,
14612 &mut dctx,
14613 &mut *scratch,
14614 d_vocab,
14615 &mut controller_eager_state,
14616 eager_pos,
14617 embd_dev,
14618 graph_round_ok,
14619 )?;
14620 let first_probability = controller_draft_prob
14621 .ok_or("optipipe controller probe lost first-token probability")?;
14622 let q_proxy = first_probability * pending_probability;
14623 OPTI_GATE_CHECKS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14624 OPTI_SHADOW_DRAFT_TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14625 let admitted = opti_fork
14626 .as_ref()
14627 .and_then(|fork| fork.controller.as_ref())
14628 .ok_or("optipipe controller policy disappeared")?
14629 .admit(q_proxy);
14630 if admitted {
14631 OPTI_GATE_ADMITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14632 let eager_pos = scratch.kv.len + 1;
14633 let (optimistic_draft, optimistic_draft_probability) = self
14634 .opti_controller_draft_step(
14635 e,
14636 mtp,
14637 &mut dctx,
14638 &mut *scratch,
14639 d_vocab,
14640 &mut controller_eager_state,
14641 eager_pos,
14642 embd_dev,
14643 graph_round_ok,
14644 )?;
14645 OPTI_SHADOW_DRAFT_TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14646 let eager_seed = controller_eager_state.take().map(|(token, seed)| {
14647 debug_assert_eq!(token, optimistic_draft);
14648 seed
14649 });
14650 controller_prepared = Some(OptiControllerPrepared {
14651 verify_tokens: [optimistic_pending, optimistic_draft],
14652 draft_prob: optimistic_draft_probability,
14653 eager_seed,
14654 q_proxy,
14655 scratch_len: scratch.kv.len,
14656 });
14657 } else {
14658 OPTI_GATE_REJECTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14659 OPTI_WASTED_DRAFT_TOKENS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14660 rejected_probe = Some((q_proxy, optimistic_pending));
14661 eprintln!(
14662 "[opti-controller] reject q={q_proxy:.6} threshold={:.3}",
14663 opti_fork
14664 .as_ref()
14665 .and_then(|fork| fork.controller.as_ref())
14666 .expect("controller policy")
14667 .threshold,
14668 );
14669 }
14670 }
14671 let fork_attempt = match fork_generation.take() {
14672 Some(generation) if base == 1 && k_round == 1 => Some(generation),
14673 Some(generation) => {
14674 opti_fork
14675 .as_mut()
14676 .expect("fork generation without fork state")
14677 .retire(generation)?;
14678 None
14679 }
14680 None => None,
14681 };
14682 let (tlogits_d, vx) = if let Some(p) = pipe {
14683 self.decode_step_t_core_pipelined(
14684 e,
14685 &verify_tokens,
14686 pos,
14687 &mut *cache,
14688 embd_dev,
14689 ckpt.as_mut(),
14690 p,
14691 round,
14692 )?
14693 } else if controller_can_probe {
14694 let fence = opti_fork
14695 .as_ref()
14696 .ok_or("optipipe controller probe lost fork state")?
14697 .fence;
14698 let boundary = match current_opti.as_mut() {
14699 Some(ticket) => ticket.take_boundary(),
14700 None => self.verify_stage0_issue(
14701 e,
14702 &verify_tokens,
14703 pos,
14704 &mut *cache,
14705 embd_dev,
14706 ckpt.as_mut(),
14707 None,
14708 &fence,
14709 Some(true),
14710 None,
14711 )?,
14712 };
14713 if let Some(prepared) = controller_prepared.take() {
14714 let generation = {
14715 let fork = opti_fork
14716 .as_mut()
14717 .ok_or("optipipe controller admission lost fork state")?;
14718 let generation = fork.reserve_successor()?;
14719 let rt = fork.rt;
14720 let snapshot_fence = fork.fence;
14721 opti_snapshot_one_stage_owned_into(
14722 e,
14723 cache,
14724 rt,
14725 &snapshot_fence,
14726 0,
14727 fork.successor_snapshot_mut(),
14728 )?;
14729 generation
14730 };
14731 let mut successor_ckpt = VerifyCkpt::new(self.layers.len());
14732 let successor_boundary = self.verify_stage0_issue(
14733 e,
14734 &prepared.verify_tokens,
14735 pos + verify_tokens.len(),
14736 &mut *cache,
14737 embd_dev,
14738 Some(&mut successor_ckpt),
14739 None,
14740 &fence,
14741 Some(false),
14742 None,
14743 )?;
14744 OPTI_FORK_ATTEMPTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14745 let fork = opti_fork
14746 .as_ref()
14747 .ok_or("optipipe controller ticket lost fork state")?;
14748 successor_attempt = Some(fork.controller_ticket(
14749 generation,
14750 successor_boundary,
14751 successor_ckpt,
14752 prepared.verify_tokens,
14753 prepared.draft_prob,
14754 prepared.eager_seed,
14755 prepared.q_proxy,
14756 prepared.scratch_len,
14757 ));
14758 eprintln!(
14759 "[opti-controller] issue generation={} q={:.6} threshold={:.3} \
14760 verify={:?}",
14761 generation.id,
14762 prepared.q_proxy,
14763 fork.controller.expect("controller policy").threshold,
14764 prepared.verify_tokens,
14765 );
14766 }
14767 let result = self.verify_stage1_finish(
14768 e,
14769 boundary,
14770 &mut *cache,
14771 ckpt.as_mut(),
14772 None,
14773 &fence,
14774 successor_attempt.is_none(),
14775 )?;
14776 if let Some(ticket) = current_opti.as_mut() {
14777 ticket.settle();
14778 }
14779 if successor_attempt.is_some() {
14780 let fork = opti_fork
14781 .as_mut()
14782 .ok_or("optipipe successor snapshot lost fork state")?;
14783 let rt = fork.rt;
14784 let snapshot_fence = fork.fence;
14785 opti_snapshot_one_stage_owned_into(
14786 e,
14787 cache,
14788 rt,
14789 &snapshot_fence,
14790 1,
14791 fork.successor_snapshot_mut(),
14792 )?;
14793 // Publish N only after both independent successor-state queues are complete.
14794 fork.rt.publish_to(1, &e.stream())?;
14795 }
14796 result
14797 } else if let Some(ticket) = current_opti.as_mut() {
14798 let fork = opti_fork
14799 .as_mut()
14800 .ok_or("optipipe carried controller ticket lost fork state")?;
14801 let boundary = ticket.take_boundary();
14802 let result = self.verify_stage1_finish(
14803 e,
14804 boundary,
14805 &mut *cache,
14806 ckpt.as_mut(),
14807 None,
14808 &fork.fence,
14809 true,
14810 )?;
14811 ticket.settle();
14812 result
14813 } else if let Some(generation) = fork_attempt {
14814 let fork = opti_fork
14815 .as_mut()
14816 .expect("fork generation without fork state");
14817 fork.capture_seed(e, generation, &h_seed_buf, &fill_prev, scratch.kv.len)?;
14818 let action = fork.mode.action(generation.id);
14819 let boundary = self.verify_stage0_issue(
14820 e,
14821 &verify_tokens,
14822 pos,
14823 &mut *cache,
14824 embd_dev,
14825 ckpt.as_mut(),
14826 None,
14827 &fork.fence,
14828 Some(true),
14829 None,
14830 )?;
14831 OPTI_FORK_ATTEMPTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14832 let mut ticket = fork.ticket(generation, boundary);
14833 if action == OptiForkAction::Abort {
14834 return Err(format!(
14835 "optipipe forced abort with generation {} stage0 in flight",
14836 generation.id,
14837 )
14838 .into());
14839 }
14840 fork.reconcile(
14841 e,
14842 &mut *cache,
14843 &mut *scratch,
14844 &snap,
14845 &mut h_seed_buf,
14846 &mut fill_prev,
14847 generation,
14848 action,
14849 verify_tokens[0],
14850 )?;
14851 let result = if action == OptiForkAction::Hit {
14852 let boundary = ticket.take_boundary();
14853 self.verify_stage1_finish(
14854 e,
14855 boundary,
14856 &mut *cache,
14857 ckpt.as_mut(),
14858 None,
14859 &fork.fence,
14860 true,
14861 )?
14862 } else {
14863 // The optimistic boundary slot has no reader. Re-run the unchanged serial
14864 // verify only after E_restart published the restored stage-0 state.
14865 self.decode_step_t_core(
14866 e,
14867 &verify_tokens,
14868 pos,
14869 &mut *cache,
14870 embd_dev,
14871 ckpt.as_mut(),
14872 )?
14873 };
14874 ticket.settle();
14875 debug_assert_eq!(ticket.generation, generation);
14876 fork.retire(generation)?;
14877 result
14878 } else {
14879 // The serial verify every non-fork round takes — the MTP route's
14880 // verify-graph door. The pool is None unless MEMRA_SPEC_VERIFY_GRAPH armed
14881 // a pool above, and then the walk replays the captured trunk instead of
14882 // re-issuing it launch by launch. `graph_round_ok` is the round's
14883 // headroom snapshot (see GRAPH_LAUNCH_MIN_FREE): below the floor the
14884 // round declines the pool exactly like an over-cap round and rides the
14885 // byte-identical eager walk — the `[spec]` suspension line above
14886 // already named the round.
14887 let vg_round = if verify_tokens.len() <= vg_t_cap && graph_round_ok {
14888 vg_guard.as_mut().and_then(|g| g.as_mut())
14889 } else {
14890 if let Some(g) = vg_guard.as_mut().and_then(|g| g.as_mut()) {
14891 // The commit reads this flag to pick its arm; a round that declines
14892 // the pool must not inherit a stale `true` from the round before it.
14893 g.round_slab = false;
14894 }
14895 None
14896 };
14897 self.decode_step_t_core_vg(
14898 e,
14899 &verify_tokens,
14900 pos,
14901 &mut *cache,
14902 embd_dev,
14903 ckpt.as_mut(),
14904 vg_round,
14905 )?
14906 };
14907 let pipe_accept = match pipe {
14908 Some(p) => Some(p.accept_begin(round)?),
14909 None => None,
14910 };
14911
14912 if phase_sync {
14913 e.stream().synchronize()?;
14914 }
14915 ph_mark(&mut ph_verify, phase_on);
14916 // --- 3. GREEDY ACCEPT (walk prefix, stop at first mismatch) ---
14917 // DEVICE-ARGMAX ACCEPT: argmax every verify column ON DEVICE (same 2-pass kernels +
14918 // smallest-index tie-break as host argmax, argmax_gate-validated) and read back ONE
14919 // [T] u32 — replaces the T x n_vocab f32 dtoh + T host argmaxes per round.
14920 // t_pred[j] = target's greedy prediction for the slot after draft[j-1] (j>=1) or after
14921 // last_token (j==0). With a pending bonus, col 0 IS the prediction after last_token
14922 // (== the bonus), so every index shifts by `base` and last_pred is unused.
14923 let t_v = verify_tokens.len();
14924 let mut preds: Vec<u32> = Vec::new();
14925 if !sampled {
14926 for j in 0..t_v {
14927 e.argmax_token_device_col(&tlogits_d, j, n_vocab, &mut preds_d, j)?;
14928 }
14929 preds = e.dtoh_u32(&preds_d)?; // <- the verify-GPU wait lands here
14930 // #87 SENTINEL TRAP, verify side: a sentinel pred becomes the round's bonus =
14931 // next round's last_token = the next chain's embed lookup. Catch it at the
14932 // source with the column named — an all-NaN VERIFY column implicates the
14933 // stage-split trunk (decode_step_t_core_ppn), not the draft head.
14934 if let Some(bad) = preds[..t_v].iter().position(|&p| (p as usize) >= n_vocab) {
14935 let col = &tlogits_d.slice(bad * n_vocab..(bad + 1) * n_vocab);
14936 let mut probe = e.zeros(n_vocab)?;
14937 e.copy_view_into(&mut probe, 0, col, n_vocab)?;
14938 let col_h = e.dtoh(&probe)?;
14939 let col_nan = col_h.iter().filter(|v| v.is_nan()).count();
14940 return Err(format!(
14941 "verify argmax sentinel 0x{:08x} >= n_vocab {n_vocab} at round {round} \
14942 col {bad}/{t_v} pos={pos}: verify-logits col NaN {col_nan}/{n_vocab} \
14943 — the verify TRUNK produced a poisoned column (#87 trap). Run \
14944 MEMRA_SPEC_NAN_SCAN=1 to name the layer that creates it (=2 to split \
14945 that layer into attention and routed MoE). NOT the draft head, and NOT \
14946 the PP stage split this message used to name: pp_cuts() returns None \
14947 without MEMRA_PP_STAGES, so decode_step_t_core_ppn never runs unless \
14948 that variable is set.",
14949 preds[bad]
14950 )
14951 .into());
14952 }
14953 }
14954 ph_mark(&mut ph_wait, phase_on);
14955 let t_pred = |j: usize| -> u32 {
14956 if j == 0 && base == 0 {
14957 last_pred
14958 } else {
14959 // GREEDY-ONLY: `preds` is filled under `if !sampled` above. The debug print
14960 // used to call this from the sampled arm and panicked the worker; it now goes
14961 // through `debug_t_pred0`. Keep the strict index here — in the greedy walk an
14962 // out-of-range pred is a real bug, not something to paper over.
14963 debug_assert!(
14964 !sampled,
14965 "t_pred is greedy-only: `preds` is empty in the sampled arm"
14966 );
14967 preds[base + j - 1]
14968 }
14969 };
14970 let mut devacc_seeded = false;
14971 let mut devacc_acc: Option<CudaSlice<u32>> = None;
14972 let (n_acc, bonus) = if !sampled {
14973 // ROUND-STREAM stage (a) (MEMRA_SPEC_DEVACC=1 opt-in): the walk runs ON DEVICE
14974 // (spec_accept_greedy, verbatim rule) and the host reads back 8B (n_acc, bonus)
14975 // instead of the [T] preds. Same sync count — machinery for stages (b)/(c),
14976 // gated on token identity vs the host walk (the arms below are bit-equal rules).
14977 if crate::spec::spec_devacc() && k_round > 0 && !spec_replay && constraint.is_none()
14978 {
14979 let draft_d = e.htod_u32_v(&draft)?;
14980 let mut acc_out = e.alloc_u32_zeroed(2)?;
14981 e.spec_accept_greedy(
14982 &preds_d,
14983 &draft_d,
14984 last_pred,
14985 base,
14986 k_round,
14987 &mut acc_out,
14988 )?;
14989 devacc_acc = Some(acc_out.clone());
14990 // stage (b): next-round seed gathered ON DEVICE from acc_out before the host
14991 // ever reads n_acc (j=base+n_acc -> vx col j-1; j==0 -> fill_prev). The three
14992 // non-replay commit arms skip their host-offset seed copies (guarded below);
14993 // the legacy spec_replay arm keeps its own rx-based seeding (excluded here).
14994 // NOTE: fill_prev is NOT updated here — the commit arms' TRUE-HIDDEN
14995 // REFRESH reads the OLD fill_prev (predecessor of this round's verify batch);
14996 // the update lands after the arms (devacc_seeded guard below).
14997 e.spec_seed_gather(&vx, &fill_prev, &acc_out, &mut h_seed_buf, base, n_embd)?;
14998 // 3a: KV lens roll back on device (len = saved + base + n_acc, all arms'
14999 // unified rule; full accept rewrites the verify-left value). Host mirrors
15000 // update after the readback; commit_verified_prefix skips its len_d writes.
15001 if let Some(successor) = successor_attempt.as_ref() {
15002 opti_fork
15003 .as_mut()
15004 .ok_or("optipipe successor reconcile lost fork state")?
15005 .queue_actual_reconcile(
15006 e,
15007 &snap,
15008 &acc_out,
15009 successor.verify_tokens[0],
15010 base,
15011 )?;
15012 } else if let Some(ptrs) = &kv_len_ptrs {
15013 let saved: Vec<i32> = (0..self.layers.len())
15014 .map(|il| snap.kv_len[il].map(|v| v as i32).unwrap_or(0))
15015 .collect();
15016 let saved_d = e.htod_i32(&saved)?;
15017 e.spec_rollback_kv(ptrs, &saved_d, &acc_out, base, self.layers.len())?;
15018 }
15019 devacc_seeded = true;
15020 let ab = e.dtoh_u32(&acc_out)?;
15021 (ab[0] as usize, ab[1])
15022 } else {
15023 let mut n_acc = 0usize;
15024 #[allow(clippy::needless_range_loop)]
15025 // allow: the explicit index loop keeps the offset arithmetic visible and aligned with the device-side indexing
15026 for j in 0..k_round {
15027 if t_pred(j) == draft[j] {
15028 n_acc += 1;
15029 } else {
15030 break;
15031 }
15032 }
15033 // bonus = target's own token at the first non-accepted slot. n_acc in 0..=k; t_pred
15034 // is defined for j in 0..=k (j==0 -> last_logits, j>=1 -> col j-1, last col = k-1).
15035 (n_acc, t_pred(n_acc))
15036 }
15037 } else {
15038 // --- SAMPLED ACCEPT (rejection sampling): u_j < p_j(x_j)/q_j(x_j) walk ---
15039 if col_buf.is_none() {
15040 col_buf = Some(e.zeros(n_vocab)?);
15041 }
15042 // FILTERED p_j: per-verify-col stats (one batched filter_stats call), then the
15043 // filtered gather. j==0&&base==0 reads last_col (its own stats row appended).
15044 let mut pj = vec![0f32; k_round.max(1)];
15045 let mut col_stats: Vec<(f32, f32, f32)> = Vec::new(); // (max, th, z) per verify col used
15046 if k_round > 0 {
15047 let mut ids: Vec<u32> = Vec::new();
15048 let mut rows: Vec<i32> = Vec::new();
15049 #[allow(clippy::needless_range_loop)]
15050 // allow: the explicit index loop keeps the offset arithmetic visible and aligned with the device-side indexing
15051 for j in 0..k_round {
15052 if j > 0 || base == 1 {
15053 ids.push(draft[j]);
15054 rows.push((base + j) as i32 - 1);
15055 }
15056 }
15057 if !ids.is_empty() {
15058 let nr = rows.len();
15059 // penalties: materialize the used columns into one contiguous penalized
15060 // buffer (rows remapped 0..nr) so stats+gathers see the penalized p.
15061 // penalties: materialize used columns contiguously, penalize all rows in
15062 // one launch, and point stats+gathers at the penalized buffer (rows 0..nr).
15063 let p_rows: Vec<i32> = if pen_on {
15064 (0..nr as i32).collect()
15065 } else {
15066 rows.clone()
15067 };
15068 if pen_on {
15069 if pcol_buf.as_ref().map(|b| b.len()).unwrap_or(0) < nr * n_vocab {
15070 pcol_buf = Some(e.zeros(nr * n_vocab)?);
15071 }
15072 let pc = pcol_buf.as_mut().unwrap();
15073 for (i2, &r) in rows.iter().enumerate() {
15074 let c = r as usize;
15075 e.copy_view_into(
15076 pc,
15077 i2 * n_vocab,
15078 &tlogits_d.slice(c * n_vocab..(c + 1) * n_vocab),
15079 n_vocab,
15080 )?;
15081 }
15082 let h = pen_hist_d.as_ref().unwrap();
15083 let nh = h.len();
15084 e.penalize_logits_rows(
15085 pc,
15086 h,
15087 nh,
15088 sp.penalty_repeat,
15089 sp.penalty_freq,
15090 sp.penalty_present,
15091 n_vocab,
15092 nr,
15093 )?;
15094 }
15095 let p_src: &CudaSlice<f32> = if pen_on {
15096 pcol_buf.as_ref().unwrap()
15097 } else {
15098 &tlogits_d
15099 };
15100 let rowsd = e.htod_i32(&p_rows)?;
15101 let (mut th_d, mut z_d, mut mx_d) =
15102 (e.zeros(nr)?, e.zeros(nr)?, e.zeros(nr)?);
15103 e.filter_stats(
15104 p_src, n_vocab, &rowsd, &mut th_d, &mut z_d, &mut mx_d, n_vocab, nr,
15105 sp_temp, sp.top_k, sp.top_p, sp.min_p,
15106 )?;
15107 let idsd = e.htod_u32_v(&ids)?;
15108 let mut outd = e.zeros(nr)?;
15109 e.softmax_gather_filtered(
15110 p_src, n_vocab, &idsd, &rowsd, &th_d, &z_d, &mut outd, n_vocab, nr,
15111 sp_temp,
15112 )?;
15113 let outv = e.dtoh(&outd)?;
15114 let (thv, zv, mxv) = (e.dtoh(&th_d)?, e.dtoh(&z_d)?, e.dtoh(&mx_d)?);
15115 let mut oi = 0usize;
15116 #[allow(clippy::needless_range_loop)]
15117 // allow: the explicit index loop keeps the offset arithmetic visible and aligned with the device-side indexing
15118 for j in 0..k_round {
15119 if j > 0 || base == 1 {
15120 pj[j] = outv[oi];
15121 oi += 1;
15122 }
15123 }
15124 col_stats = (0..nr).map(|i| (mxv[i], thv[i], zv[i])).collect();
15125 }
15126 if base == 0 {
15127 let lc: &CudaSlice<f32> = if pen_on {
15128 if col_buf.is_none() {
15129 col_buf = Some(e.zeros(n_vocab)?);
15130 }
15131 let cb = col_buf.as_mut().unwrap();
15132 e.copy_into(
15133 cb,
15134 0,
15135 last_col_logits
15136 .as_ref()
15137 .expect("sampled: last_col_logits unset"),
15138 n_vocab,
15139 )?;
15140 let h = pen_hist_d.as_ref().unwrap();
15141 let nh = h.len();
15142 e.penalize_logits(
15143 cb,
15144 h,
15145 nh,
15146 sp.penalty_repeat,
15147 sp.penalty_freq,
15148 sp.penalty_present,
15149 n_vocab,
15150 )?;
15151 col_buf.as_ref().unwrap()
15152 } else {
15153 last_col_logits
15154 .as_ref()
15155 .expect("sampled: last_col_logits unset")
15156 };
15157 let rows0 = e.htod_i32(&[0])?;
15158 let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
15159 e.filter_stats(
15160 lc, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1,
15161 sp_temp, sp.top_k, sp.top_p, sp.min_p,
15162 )?;
15163 let idsd = e.htod_u32_v(&[draft[0]])?;
15164 let mut outd = e.zeros(1)?;
15165 e.softmax_gather_filtered(
15166 lc, n_vocab, &idsd, &rows0, &th_d, &z_d, &mut outd, n_vocab, 1, sp_temp,
15167 )?;
15168 pj[0] = e.dtoh(&outd)?[0];
15169 last_col_stats =
15170 Some((e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0], e.dtoh(&z_d)?[0]));
15171 }
15172 }
15173 // q source: the graph arms (single-head AND chain) retained the head logits
15174 // in the persistent q_slots; the eager arm in per-round draft_logits clones.
15175 // Same raw-logit values either way. FILTERED q_j: stats from draft_stats
15176 // (eager pushes in-chain; the graph arms compute them post-replay from the
15177 // retained q with the same filter_stats program — bit-identical to the
15178 // in-graph stats that shaped the draw, keeping ONE accept path).
15179 let q_bufs: &[CudaSlice<f32>] = if dctx.graph_s.is_some() || dctx.chain_s.is_some()
15180 {
15181 &dctx.q_slots
15182 } else {
15183 &draft_logits
15184 };
15185 let mut n_acc = 0usize;
15186 for j in 0..k_round {
15187 let (qmx, qth, qz) = draft_stats[j];
15188 let idsd = e.htod_u32_v(&[draft_idx[j]])?;
15189 let rowsd = e.htod_i32(&[0])?;
15190 let thd = e.htod(&[qth])?;
15191 let zd = e.htod(&[qz])?;
15192 let _ = qmx;
15193 let mut outd = e.zeros(1)?;
15194 e.softmax_gather_filtered(
15195 &q_bufs[j], d_vocab, &idsd, &rowsd, &thd, &zd, &mut outd, d_vocab, 1,
15196 sp_temp,
15197 )?;
15198 let qj = e.dtoh(&outd)?[0];
15199 let u = host_u01(sp_seed, uctr);
15200 uctr += 1;
15201 let accept = (u as f64) * (qj as f64) < pj[j] as f64;
15202 // SKEY PROBE: q == 0 for the token the draft actually proposed is the
15203 // exactness signature (see `skey_probe`). Impossible when the draft was
15204 // drawn from the same filtered distribution the verify reconstructs here;
15205 // `u * 0 < p` makes it an UNCONDITIONAL accept whenever p > 0.
15206 if skey_probe() && qj == 0.0 {
15207 eprintln!(
15208 "[skey] EXACTNESS q=0 round={round} j={j} draft_tok={} \
15209 draft_idx={} p={:e} u={u} accepted={} th_z={:?}",
15210 draft[j], draft_idx[j], pj[j], accept as u8, draft_stats[j],
15211 );
15212 }
15213 if accept {
15214 n_acc += 1;
15215 } else {
15216 break;
15217 }
15218 }
15219 let bonus = if n_acc == k_round {
15220 // FULL ACCEPT: bonus ~ FILTERED softmax at the last verify column.
15221 let col = base + k_round - 1;
15222 let cb = col_buf.as_mut().unwrap();
15223 e.copy_view_into(
15224 cb,
15225 0,
15226 &tlogits_d.slice(col * n_vocab..(col + 1) * n_vocab),
15227 n_vocab,
15228 )?;
15229 if pen_on {
15230 let h = pen_hist_d.as_ref().unwrap();
15231 let nh = h.len();
15232 e.penalize_logits(
15233 cb,
15234 h,
15235 nh,
15236 sp.penalty_repeat,
15237 sp.penalty_freq,
15238 sp.penalty_present,
15239 n_vocab,
15240 )?;
15241 }
15242 if perturb_buf.is_none() {
15243 perturb_buf = Some(e.zeros(d_vocab.max(n_vocab))?);
15244 }
15245 // STATS MUST COME FROM THIS COLUMN (bug fix 2026-08-05, lane/sampler-
15246 // truncation-fix; receipts research/sampfix-20260805/). The old code reused
15247 // `col_stats.last()` here, which is ALWAYS the wrong row: the gathered set
15248 // covers verify columns 0..=(base+k_round-2) (rows pushed as base+j-1), while
15249 // the full-accept bonus samples column base+k_round-1 — exactly ONE PAST the
15250 // last gathered column, in both base arms. `th` is a threshold in e-units of
15251 // its OWN row's max, so feeding a neighbour's (row_max, th) into
15252 // gumbel_perturb_filtered mis-scales every e0 = exp((x-row_max)/T). When the
15253 // donor column's peak is higher by more than T*ln(1/th), EVERY id fails
15254 // `e0 >= th`, the whole perturbed row becomes -3.4e38, and the 2-pass argmax
15255 // falls through to its smallest-index tie-break => token id 0 ("!") spliced
15256 // mid-word. Fragility is ordered by how large th is: min_p pins th = min_p
15257 // (0.05 => trigger at delta > 2.4 at T=0.8, fires constantly), top_p's
15258 // mass-boundary th is smaller, top_k's k-th-largest th smaller still — which
15259 // is why the head-to-head matrix saw min_p and top_p corrupt while top_k-only
15260 // stayed clean. The pure-temp default regime is immune (th == 0 masks nothing,
15261 // and row_max is unused once nothing is masked), so this fix is a byte-level
15262 // no-op for the untruncated serve default. One extra one-block filter_stats
15263 // per full-accept round is the whole cost.
15264 let (mx, th) = {
15265 let rows0 = e.htod_i32(&[0])?;
15266 let (mut th_d, mut z_d, mut mx_d) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
15267 let cb0 = col_buf.as_ref().unwrap();
15268 e.filter_stats(
15269 cb0, n_vocab, &rows0, &mut th_d, &mut z_d, &mut mx_d, n_vocab, 1,
15270 sp_temp, sp.top_k, sp.top_p, sp.min_p,
15271 )?;
15272 (e.dtoh(&mx_d)?[0], e.dtoh(&th_d)?[0])
15273 };
15274 let pb = perturb_buf.as_mut().unwrap();
15275 let cb2 = col_buf.as_ref().unwrap();
15276 e.gumbel_perturb_filtered(cb2, pb, n_vocab, sp_seed, sctr, sp_temp, mx, th)?;
15277 sctr += 1;
15278 let td = e.argmax_token_device(pb, n_vocab)?;
15279 e.dtoh_u32_one(&td)?
15280 } else {
15281 // REJECT at n_acc: bonus ~ norm(max(0, softmax_T(p) - softmax_T(q))).
15282 let cb = col_buf.as_mut().unwrap();
15283 if n_acc > 0 || base == 1 {
15284 let col = base + n_acc - 1;
15285 e.copy_view_into(
15286 cb,
15287 0,
15288 &tlogits_d.slice(col * n_vocab..(col + 1) * n_vocab),
15289 n_vocab,
15290 )?;
15291 } else {
15292 let lc = last_col_logits.as_ref().unwrap();
15293 e.copy_into(cb, 0, lc, n_vocab)?;
15294 }
15295 if pen_on {
15296 let h = pen_hist_d.as_ref().unwrap();
15297 let nh = h.len();
15298 e.penalize_logits(
15299 cb,
15300 h,
15301 nh,
15302 sp.penalty_repeat,
15303 sp.penalty_freq,
15304 sp.penalty_present,
15305 n_vocab,
15306 )?;
15307 }
15308 let cb2 = col_buf.as_ref().unwrap();
15309 let sc = sctr;
15310 sctr += 1;
15311 // p-stats for the reject column: from col_stats when the col was gathered,
15312 // else (j==0&&base==0) from last_col_stats.
15313 let p_stats = if n_acc > 0 || base == 1 {
15314 // col index within the gathered set == number of gathered cols before n_acc
15315 let gi = if base == 1 { n_acc } else { n_acc - 1 };
15316 col_stats.get(gi).copied().unwrap_or({
15317 (0.0, 0.0, 1.0) // unreachable: gathered cols always cover the reject slot
15318 })
15319 } else {
15320 last_col_stats.expect("sampled: last_col_stats unset at reject")
15321 };
15322 let q_stats = draft_stats[n_acc];
15323 if let Some(map) = &d2t_dev {
15324 if q_full_buf.is_none() {
15325 q_full_buf = Some(e.zeros(n_vocab)?);
15326 }
15327 let qf = q_full_buf.as_mut().unwrap();
15328 e.scatter_trim_logits(&q_bufs[n_acc], map, qf, d_vocab, n_vocab)?;
15329 let qf2 = q_full_buf.as_ref().unwrap();
15330 e.residual_sample_filtered(
15331 cb2,
15332 Some(qf2),
15333 n_vocab,
15334 sp_temp,
15335 sp_seed,
15336 sc,
15337 p_stats,
15338 q_stats,
15339 &mut sample_tok,
15340 )?;
15341 } else {
15342 e.residual_sample_filtered(
15343 cb2,
15344 Some(&q_bufs[n_acc]),
15345 n_vocab,
15346 sp_temp,
15347 sp_seed,
15348 sc,
15349 p_stats,
15350 q_stats,
15351 &mut sample_tok,
15352 )?;
15353 }
15354 e.dtoh_u32(&sample_tok)?[0]
15355 };
15356 (
15357 n_acc,
15358 guard_vocab_token(
15359 bonus,
15360 n_vocab,
15361 &format!("sampled verify bonus at round {round} pos={pos} n_acc={n_acc}"),
15362 )?,
15363 )
15364 };
15365 // --- 3b. GRAMMAR TRUNCATION (constrained spec, 2026-08-03): the grammar is
15366 // an extra rejection rule AFTER the exactness verify (the batched-verify-twins
15367 // ordering). Walk the accepted drafts through the grammar in commit order; the
15368 // first illegal token truncates acceptance at its slot, and that slot's emission
15369 // is recomputed as the MASKED argmax of the target's own verify column — token-
15370 // identical to constrained plain greedy decode (an unmasked argmax that is
15371 // grammar-legal IS the masked argmax: masking only removes competitors). The
15372 // column D2H (~1MB) is paid only when a cut fires — the tight-grammar cost,
15373 // measured in acceptance numbers, never hidden.
15374 let (n_acc, bonus) = match constraint.as_deref_mut() {
15375 None => (n_acc, bonus),
15376 Some(c) => {
15377 fn ce(e2: String) -> Box<dyn std::error::Error> {
15378 format!("constraint: {e2}").into()
15379 }
15380 let mut na = n_acc;
15381 let mut cut = false;
15382 for (j, &d) in draft.iter().enumerate().take(n_acc) {
15383 if c.is_allowed(d).map_err(ce)? {
15384 c.consume(d).map_err(ce)?;
15385 } else {
15386 na = j;
15387 cut = true;
15388 dm_cut_tokens += n_acc - j;
15389 break;
15390 }
15391 }
15392 if cut {
15393 dm_cuts += 1;
15394 }
15395 let mut bo = bonus;
15396 if cut || !c.is_allowed(bo).map_err(ce)? {
15397 let mut row = if na == 0 && base == 0 {
15398 init_logits_host
15399 .clone()
15400 .ok_or("constraint: init logits missing (round-0 cut)")?
15401 } else {
15402 e.dtoh_view(
15403 &tlogits_d.slice((base + na - 1) * n_vocab..(base + na) * n_vocab),
15404 )?
15405 };
15406 c.mask_logits(&mut row).map_err(ce)?;
15407 bo = argmax(&row) as u32;
15408 }
15409 c.consume(bo).map_err(ce)?;
15410 (na, bo)
15411 }
15412 };
15413 let mut successor_valid = false;
15414 if let Some((q_proxy, expected_d2)) = rejected_probe {
15415 let v_n = n_acc == 1 && bonus == expected_d2;
15416 eprintln!(
15417 "[opti-controller] shadow q={q_proxy:.6} admitted=false v_n={v_n} \
15418 expected_d2={expected_d2} n_acc={n_acc} bonus={bonus}",
15419 );
15420 }
15421 if let Some(successor) = successor_attempt.as_ref() {
15422 successor_valid = n_acc == 1 && bonus == successor.verify_tokens[0];
15423 let generation = successor.generation;
15424 let q_proxy = successor.q_proxy;
15425 let expected_pending = successor.verify_tokens[0];
15426 let resolution_ms = successor.issued_at.elapsed().as_secs_f64() * 1e3;
15427 let fork = opti_fork
15428 .as_mut()
15429 .ok_or("optipipe successor resolution lost fork state")?;
15430 fork.finish_actual_reconcile(e, &mut *cache, &snap, n_acc, base, successor_valid)?;
15431 if successor_valid {
15432 OPTI_FORK_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15433 } else {
15434 OPTI_FORK_MISSES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15435 OPTI_RECONCILES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15436 OPTI_WASTED_DRAFT_TOKENS.fetch_add(2, std::sync::atomic::Ordering::Relaxed);
15437 }
15438 let breaker_tripped = fork
15439 .controller
15440 .as_mut()
15441 .expect("controller policy")
15442 .resolve(successor_valid);
15443 if breaker_tripped {
15444 OPTI_BREAKER_TRIPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
15445 }
15446 eprintln!(
15447 "[opti-controller] resolve generation={} hit={} q={q_proxy:.6} \
15448 expected_pending={expected_pending} n_acc={n_acc} bonus={bonus} \
15449 resolution_ms={resolution_ms:.3} reconcile={} breaker={}",
15450 generation.id, successor_valid, !successor_valid, breaker_tripped,
15451 );
15452 if !successor_valid {
15453 let mut successor = successor_attempt
15454 .take()
15455 .expect("controller successor disappeared on miss");
15456 successor.settle();
15457 fork.retire(generation)?;
15458 }
15459 }
15460 total_drafted += k_round;
15461 total_accepted += n_acc;
15462 if let Some(t) = sess_telem {
15463 // Greedy, rejection-sampling, and grammar truncation all converge here after
15464 // the accept decision is already on host. Fixed-size relaxed atomics only.
15465 t.record_round(k_round, n_acc);
15466 }
15467 if spec_stats {
15468 st_len_hist[k_round] += 1;
15469 #[allow(clippy::needless_range_loop)]
15470 // allow: the explicit index loop keeps the offset arithmetic visible and aligned with the device-side indexing
15471 for j in 0..k_round {
15472 st_drafted[j] += 1;
15473 }
15474 #[allow(clippy::needless_range_loop)]
15475 // allow: the explicit index loop keeps the offset arithmetic visible and aligned with the device-side indexing
15476 for j in 0..n_acc {
15477 st_accepted[j] += 1;
15478 }
15479 if n_acc == k_round {
15480 st_full += 1;
15481 }
15482 }
15483
15484 if debug_spec {
15485 eprintln!(
15486 "[R{round}] pos={pos} out_len={} last_tok={last_token} draft={draft:?} n_acc={n_acc} bonus={bonus} t_pred0={}",
15487 out.len(),
15488 // NOT `t_pred(0)`: `preds` is filled only under `if !sampled` above, so on a
15489 // sampled request round >= 1 (base == 1) indexed an EMPTY vector and PANICKED
15490 // the GPU worker thread — a debug flag that killed the exact regime you would
15491 // set it to investigate. See `debug_t_pred0`.
15492 debug_t_pred0(sampled, base, last_pred, &preds)
15493 );
15494 }
15495
15496 // --- 4. COMMIT: draft[0..n_acc] then bonus (n_acc + 1 tokens) ---
15497 let commit_started = std::time::Instant::now();
15498 // SESSION MODE: every accepted column is already in the CACHE — `out` must carry all
15499 // of them (overshoot past max_new included) or `committed` under-counts the cache rows
15500 // and the next turn's continuation seeds one token off (gate-caught 2026-07-05). The
15501 // single-shot path keeps the cap (its caller truncates + drops the cache anyway).
15502 #[allow(clippy::needless_range_loop)]
15503 // allow: the explicit index loop keeps the offset arithmetic visible and aligned with the device-side indexing
15504 for j in 0..n_acc {
15505 if !session_mode && out.len() >= max_new {
15506 break;
15507 }
15508 out.push(draft[j]);
15509 }
15510 if pen_on {
15511 pen_hist.extend_from_slice(&draft[0..n_acc]);
15512 pen_hist.push(bonus);
15513 }
15514 let bonus_emitted = session_mode || out.len() < max_new;
15515 if bonus_emitted {
15516 out.push(bonus);
15517 }
15518 last_token = bonus;
15519
15520 // --- 5. ROLLBACK + advance (§C) ---
15521 if n_acc == k_round && !spec_replay {
15522 // FULL ACCEPT, BONUS FOLD: all verify columns (pending? + drafts) are committed in
15523 // cache; the NEW bonus stays PENDING for the next round's verify batch — NO extra
15524 // T=1 trunk pass. The next draft chain seeds from the MTP block's h_nextn at the
15525 // bonus position: one MTP-block pass (~1/33 trunk cost) replaces the trunk read.
15526 // last_pred is dead in the pending path (t_pred reads verify col 0).
15527 //
15528 // PERSISTENT DRAFT KV, full-accept fill: the chain covered last_token +
15529 // draft[0..k_round-2] as INPUTS (slots P..P'-2); draft[k_round-1] (slot P'-1) was
15530 // only ever an output, so its entry is MISSING. Fill it from vh_seed — its EXACT
15531 // trunk hidden (the last verify column). set_len first: a p-min break may have
15532 // left one extra chain append at that slot. Partial accepts need NO fill (the
15533 // chain already covered every accepted position; round-start set_len truncates).
15534 let mut vh_seed = e.zeros(n_embd)?;
15535 e.copy_view_into(
15536 &mut vh_seed,
15537 0,
15538 &vx.slice((t_v - 1) * n_embd..t_v * n_embd),
15539 n_embd,
15540 )?;
15541 if refresh {
15542 // TRUE-HIDDEN REFRESH (2026-07-03, the HANDOVER-listed acceptance lever):
15543 // overwrite ALL committed positions' scratch entries with K/V from their EXACT
15544 // verify hiddens — the reference engine's mtp_update fills from true hiddens;
15545 // the full stack (vx) is already resident from the verify. Replaces both the
15546 // chain-approximate entries AND the old last-token-only fill. Acceptance-only
15547 // (draft attention quality); exactness stays the verify's job.
15548 scratch.set_len(e, pos)?;
15549 // PREDECESSOR pairing: row i gets vx[i-1]; row 0 the carried fill_prev
15550 // (hidden of the last committed row before this verify batch).
15551 let mut vxs = e.zeros(t_v * n_embd)?;
15552 e.copy_into(&mut vxs, 0, &fill_prev, n_embd)?;
15553 if t_v > 1 {
15554 e.copy_view_into(
15555 &mut vxs,
15556 n_embd,
15557 &vx.slice(0..(t_v - 1) * n_embd),
15558 (t_v - 1) * n_embd,
15559 )?;
15560 }
15561 self.mtp_kv_fill_all(e, &verify_tokens, &vxs, pos, &mut *scratch, embd_dev)?;
15562 } else {
15563 scratch.set_len(e, pos + base + k_round - 1)?;
15564 // predecessor of the last draft = verify col t_v-2 (or fill_prev at t_v==1)
15565 let mut hp = e.zeros(n_embd)?;
15566 if t_v >= 2 {
15567 e.copy_view_into(
15568 &mut hp,
15569 0,
15570 &vx.slice((t_v - 2) * n_embd..(t_v - 1) * n_embd),
15571 n_embd,
15572 )?;
15573 } else {
15574 e.copy_into(&mut hp, 0, &fill_prev, n_embd)?;
15575 }
15576 self.mtp_kv_fill_all(
15577 e,
15578 &[draft[k_round - 1]],
15579 &hp,
15580 pos + base + k_round - 1,
15581 &mut *scratch,
15582 embd_dev,
15583 )?;
15584 }
15585 // REFERENCE SEEDING: no pseudo pass — the next chain's step 0 IS the
15586 // reference's (id_last, h_prev) draft row; it appends the bonus's scratch
15587 // entry itself. Seed = TRUE hidden of the bonus's predecessor (last verify
15588 // col). Saves one MTP-block pass per round on top of the pairing fix.
15589 if !devacc_seeded {
15590 e.copy_into(&mut h_seed_buf, 0, &vh_seed, n_embd)?;
15591 e.copy_into(&mut fill_prev, 0, &vh_seed, n_embd)?;
15592 }
15593 pending = Some(bonus);
15594 if debug_spec {
15595 eprintln!(" -> FULL ACCEPT (bonus pending, prev-h seed)");
15596 }
15597 } else if !spec_replay && base + n_acc >= 1 {
15598 // PARTIAL ACCEPT, REPLAY-FREE (2026-07-03 — the profiled #1 long-ctx spec cost):
15599 // the verify's first j = base+n_acc columns ARE the committed sequence, computed
15600 // bit-identically to eager (decode-exact contract) — so KEEP them: KV truncates to
15601 // pos+j, recurrent state rebuilds from the VerifyCkpt (same-kernel gdn prefix
15602 // re-run / pure state-clone restore), and the bonus stays PENDING exactly like the
15603 // full-accept path — the legacy duplicate trunk replay is gone. The next chain
15604 // seeds from the MTP pseudo-hidden of the bonus, whose seed = the TRUE verify
15605 // hidden of its predecessor (col j-1) — same one-hop pseudo structure as full
15606 // accept (never compounds: the next verify recomputes true hiddens for all
15607 // committed columns).
15608 let j = base + n_acc;
15609 // VERIFY-GRAPH SLAB COMMIT: when the captured trunk ran, the linear layers'
15610 // column stash was written into the graphs ctx's persistent slabs as in-graph
15611 // memcpy nodes, NOT into the per-column VerifyCkpt the cols arm reads — so the
15612 // commit must take the slab twin (same semantics, slab-addressed sources). The
15613 // ctx states which of the two this round produced via `round_slab`; trusting the
15614 // flag rather than the env keeps a round that fell back to the eager walk (a
15615 // capture that declined, a t the pool never captured) on the cols arm.
15616 let slab_commit = vg_guard
15617 .as_ref()
15618 .and_then(|g| g.as_ref())
15619 .map(|g| g.round_slab)
15620 .unwrap_or(false);
15621 if slab_commit {
15622 self.dspark_commit_prefix_slab(
15623 e,
15624 &mut *cache,
15625 &snap,
15626 vg_guard
15627 .as_ref()
15628 .and_then(|g| g.as_ref())
15629 .expect("slab_commit implies a graphs ctx"),
15630 j,
15631 )?;
15632 } else {
15633 self.commit_verified_prefix(
15634 e,
15635 &mut *cache,
15636 &snap,
15637 ckpt.as_ref().unwrap(),
15638 j,
15639 devacc_seeded,
15640 if devacc_seeded {
15641 devacc_acc.as_ref().map(|a| (a, base, t_v))
15642 } else {
15643 None
15644 },
15645 )?;
15646 }
15647 let mut seed = e.zeros(n_embd)?;
15648 e.copy_view_into(
15649 &mut seed,
15650 0,
15651 &vx.slice((j - 1) * n_embd..j * n_embd),
15652 n_embd,
15653 )?;
15654 // Draft scratch: TRUE-HIDDEN REFRESH of the committed prefix (see the full-accept
15655 // branch); without it the chain entries stand and only the tail truncates. Either
15656 // way len ends at pos+j so the pseudo append lands at the bonus's slot pos+j
15657 // (persistent mode), rope pos+j+1 (chain convention).
15658 if refresh {
15659 scratch.set_len(e, pos)?;
15660 let mut vxs = e.zeros(j * n_embd)?;
15661 e.copy_into(&mut vxs, 0, &fill_prev, n_embd)?;
15662 if j > 1 {
15663 e.copy_view_into(
15664 &mut vxs,
15665 n_embd,
15666 &vx.slice(0..(j - 1) * n_embd),
15667 (j - 1) * n_embd,
15668 )?;
15669 }
15670 self.mtp_kv_fill_all(
15671 e,
15672 &verify_tokens[0..j],
15673 &vxs,
15674 pos,
15675 &mut *scratch,
15676 embd_dev,
15677 )?;
15678 } else {
15679 scratch.set_len(e, pos + j)?;
15680 }
15681 // REFERENCE SEEDING (see the full-accept branch): seed = TRUE hidden of the
15682 // bonus's predecessor (verify col j-1); no pseudo pass.
15683 if !devacc_seeded {
15684 e.copy_into(&mut h_seed_buf, 0, &seed, n_embd)?;
15685 e.copy_into(&mut fill_prev, 0, &seed, n_embd)?;
15686 }
15687 pending = Some(bonus);
15688 if debug_spec {
15689 eprintln!(" -> PARTIAL(replay-free j={j}, bonus pending, prev-h seed)");
15690 }
15691 } else if !spec_replay {
15692 // ZERO ROUND FOLD (2026-07-10, verify-cost target #3): base+n_acc == 0 — a
15693 // pending-less round where nothing was accepted (PMIN0 zero-draft chains after a
15694 // replay/commit, or plain 0-accept rounds at round 0). The old path replayed
15695 // [bonus] through a FULL m=1 trunk+head forward (the 489us full-vocab head pass
15696 // measured at ~0.75/round on PMIN0 configs). Instead: restore the pre-round
15697 // snapshot and let the bonus ride the NEXT round's verify as col 0 — the existing
15698 // base=1 pending machinery, bit-identical by the decode-exact verify contract.
15699 // Seed: the bonus's predecessor is the last COMMITTED token, whose hidden
15700 // fill_prev already carries (same seeding as the 1-token-replay case it replaces).
15701 cache.rollback(e, &snap, 0)?;
15702 scratch.set_len(e, pos)?;
15703 e.copy_into(&mut h_seed_buf, 0, &fill_prev, n_embd)?;
15704 pending = Some(bonus);
15705 if debug_spec {
15706 eprintln!(" -> ZERO-ROUND FOLD (bonus pending, fill_prev seed)");
15707 }
15708 } else {
15709 // PARTIAL ACCEPT, LEGACY REPLAY (seam MEMRA_SPEC_REPLAY=1 — or j==0: nothing of
15710 // this round survives, only possible before the first pending exists, ~round 0):
15711 // restore EVERYTHING to the pre-round snapshot (KV truncate to pos + recur
15712 // restore), then replay the committed prefix pending? ++ draft[0..n_acc] ++
15713 // [bonus] as ONE batched T forward — single weight read, bit-identical to greedy
15714 // (the verify-all-columns path is the same math). Commits the bonus with a TRUE
15715 // trunk hidden.
15716 cache.rollback(e, &snap, 0)?; // accept_len=0: KV len = pos, recur = snapshot
15717 let mut replay: Vec<u32> = Vec::with_capacity(base + n_acc + 1);
15718 if let Some(b) = pending.take() {
15719 replay.push(b);
15720 }
15721 replay.extend_from_slice(&draft[0..n_acc]);
15722 replay.push(bonus);
15723 // Full-stack forward (decode_step_t_core = decode_step_t_h_emb_dev's body):
15724 // Predecessor pairing seeds from the PREDECESSOR row (col len-2) — the same-row path takes the
15725 // last col exactly as before (byte-identical to the old _h_emb_dev call).
15726 let (rl_d, rx) = if self.batched_serving_numeric_class() {
15727 let mut logits = Vec::with_capacity(replay.len() * n_vocab);
15728 let mut hidden = e.uninit(replay.len() * n_embd)?;
15729 for (row, &token) in replay.iter().enumerate() {
15730 let (row_logits, row_hidden) =
15731 self.spec_target_step_h(e, token, &mut *cache)?;
15732 logits.extend_from_slice(&row_logits);
15733 e.dtod_copy_into(&row_hidden, &mut hidden, row * n_embd)?;
15734 }
15735 (e.htod(&logits)?, hidden)
15736 } else {
15737 self.decode_step_t_core(e, &replay, pos, &mut *cache, embd_dev, None)?
15738 };
15739 // last_pred = argmax of the LAST column's logits (predicts the token after `bonus`)
15740 // — device argmax + one 4-byte read instead of the full-vocab column dtoh.
15741 e.argmax_token_device_col(&rl_d, replay.len() - 1, n_vocab, &mut preds_d, 0)?;
15742 last_pred = guard_vocab_token(
15743 e.dtoh_u32(&preds_d)?[0],
15744 n_vocab,
15745 &format!("replay last_pred at round {round} pos={pos}"),
15746 )?;
15747 if sampled {
15748 let lr0 = replay.len();
15749 let lc = last_col_logits
15750 .as_mut()
15751 .expect("sampled: last_col_logits unset");
15752 e.copy_view_into(
15753 lc,
15754 0,
15755 &rl_d.slice((lr0 - 1) * n_vocab..lr0 * n_vocab),
15756 n_vocab,
15757 )?;
15758 }
15759 let lr = replay.len();
15760 if lr >= 2 {
15761 e.copy_view_into(
15762 &mut h_seed_buf,
15763 0,
15764 &rx.slice((lr - 2) * n_embd..(lr - 1) * n_embd),
15765 n_embd,
15766 )?;
15767 } else {
15768 // 1-token replay (round-0 miss): the bonus's predecessor is the OLD
15769 // last_token, whose own-row hidden fill_prev still holds.
15770 e.copy_into(&mut h_seed_buf, 0, &fill_prev, n_embd)?;
15771 }
15772 // the bonus is COMMITTED here — it becomes the last committed row.
15773 let mut rh_last = e.zeros(n_embd)?;
15774 e.copy_view_into(
15775 &mut rh_last,
15776 0,
15777 &rx.slice((lr - 1) * n_embd..lr * n_embd),
15778 n_embd,
15779 )?;
15780 e.copy_into(&mut fill_prev, 0, &rh_last, n_embd)?;
15781 if debug_spec {
15782 eprintln!(" -> PARTIAL(replay={replay:?}), next_pred={last_pred}");
15783 }
15784 }
15785 if devacc_seeded {
15786 // stage (b) epilogue: fill_prev takes the gathered seed AFTER the refresh fills
15787 // consumed the old value (both slots carry the same value in every non-replay arm).
15788 e.copy_into(&mut fill_prev, 0, &h_seed_buf, n_embd)?;
15789 }
15790 if successor_valid {
15791 let optimistic_scratch_len = successor_attempt
15792 .as_ref()
15793 .expect("valid controller successor disappeared")
15794 .scratch_len;
15795 // The normal current-round commit refreshed/truncated the logical scratch tail.
15796 // Its optimistic successor row was already written physically, so restoring only
15797 // the retained logical length makes that row live for the carried round.
15798 scratch.set_len(e, optimistic_scratch_len)?;
15799 }
15800 if let Some(current) = current_opti.take() {
15801 opti_fork
15802 .as_mut()
15803 .ok_or("optipipe current retirement lost fork state")?
15804 .retire(current.generation)?;
15805 }
15806 if successor_valid {
15807 let successor = successor_attempt
15808 .take()
15809 .expect("valid controller successor disappeared before promotion");
15810 let generation = successor.generation;
15811 opti_fork
15812 .as_mut()
15813 .ok_or("optipipe successor promotion lost fork state")?
15814 .promote_successor_snapshot(&mut snap, generation);
15815 carried_opti = Some(successor);
15816 }
15817 if anatomy_on {
15818 // Commit/rollback is normally asynchronous on the primary/head stream. Bound it
15819 // only for this diagnostic so it does not disappear into the following draft's
15820 // first token readback.
15821 e.stream().synchronize()?;
15822 ph_commit += commit_started.elapsed().as_secs_f64();
15823 }
15824 // adaptive-K update (host math, zero syncs): next round drafts accepted-run + 1,
15825 // clamped to [floor(pos), k_cap]. cache.pos is post-rollback here (the round's
15826 // final position — the floor's position key reads the committed depth). Burst
15827 // rounds (`continue` above) draft the captured fixed depth and skip this, exactly
15828 // like gemma's burst arm.
15829 if adapt {
15830 let fl_now = floor_at(cache.pos);
15831 kc = (n_acc + 1).clamp(fl_now.min(k_cap), k_cap);
15832 }
15833 ph_mark(&mut ph_rest, phase_on);
15834 if let Some(p) = pipe {
15835 p.accept_end(round);
15836 }
15837 drop(pipe_accept);
15838 if let Some(t0) = round_t0 {
15839 let ms = t0.elapsed().as_secs_f64() * 1e3;
15840 ROUND_MS.fetch_add((ms * 1e3) as u64, std::sync::atomic::Ordering::Relaxed);
15841 let n = ROUND_N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
15842 if n.is_multiple_of(32) {
15843 eprintln!(
15844 "[spec-round] rounds={n} avg round wall={:.2} ms (emitted={} drafted so far)",
15845 ROUND_MS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e3 / n as f64,
15846 out.len()
15847 );
15848 }
15849 }
15850 round += 1;
15851 // sse-cadence: this round's accepted drafts + bonus are committed (out is
15852 // append-only past step 4) — flush at round cadence.
15853 keep_going = flush_commit(&mut on_commit, &out, &mut flushed);
15854 }
15855 if let Some(mut ticket) = carried_opti.take() {
15856 opti_fork
15857 .as_mut()
15858 .ok_or("optipipe tail drain lost fork state")?
15859 .cancel_controller_ticket(e, &mut *cache, &mut *scratch, &snap, &mut ticket)?;
15860 }
15861 // sse-cadence: nothing below appends to `out`; flush any remainder (defensive).
15862 // (verdict ignored — the burst is over either way; the session tail runs unchanged.)
15863 let _ = flush_commit(&mut on_commit, &out, &mut flushed);
15864
15865 if spec_stats {
15866 let per_slot: Vec<String> = (0..k)
15867 .map(|j| {
15868 if st_drafted[j] > 0 {
15869 format!(
15870 "{}/{}={:.3}",
15871 st_accepted[j],
15872 st_drafted[j],
15873 st_accepted[j] as f64 / st_drafted[j] as f64
15874 )
15875 } else {
15876 "0/0".into()
15877 }
15878 })
15879 .collect();
15880 let acc = if total_drafted > 0 {
15881 total_accepted as f64 / total_drafted as f64
15882 } else {
15883 0.0
15884 };
15885 eprintln!(
15886 "[spec-stats] rounds={round} full_accept={st_full} len_hist={st_len_hist:?} \
15887 per_slot=[{}] total={total_accepted}/{total_drafted}={acc:.3} \
15888 tok_per_round={:.3}",
15889 per_slot.join(" "),
15890 (total_accepted + round) as f64 / round.max(1) as f64
15891 );
15892 }
15893 if constraint.is_some() {
15894 eprintln!(
15895 "[draft-mask] mask_rounds={dm_rounds} clone_total={:.3}ms \
15896 clone_per_round={:.4}ms gram_cuts={dm_cuts}/{round} cut_tokens={dm_cut_tokens}",
15897 dm_clone_ns as f64 / 1e6,
15898 dm_clone_ns as f64 / 1e6 / dm_rounds.max(1) as f64
15899 );
15900 }
15901 if phase_on {
15902 let tot = ph_draft + ph_verify + ph_wait + ph_rest;
15903 eprintln!(
15904 "[spec-phase] draft={:.1}ms ({:.1}%) verify-issue={:.1}ms ({:.1}%) verify-wait={:.1}ms ({:.1}%) commit-host={:.1}ms ({:.1}%) rounds={round}",
15905 ph_draft * 1e3,
15906 ph_draft / tot * 100.0,
15907 ph_verify * 1e3,
15908 ph_verify / tot * 100.0,
15909 ph_wait * 1e3,
15910 ph_wait / tot * 100.0,
15911 ph_rest * 1e3,
15912 ph_rest / tot * 100.0
15913 );
15914 }
15915 if anatomy_on {
15916 let rounds_f = round.max(1) as f64;
15917 let other = (ph_rest - ph_commit).max(0.0);
15918 eprintln!(
15919 "[spec-anatomy] per-round draft={:.3}ms pp-verify={:.3}ms \
15920 verify-accept={:.3}ms commit-rollback={:.3}ms other={:.3}ms rounds={round}",
15921 ph_draft * 1e3 / rounds_f,
15922 ph_verify * 1e3 / rounds_f,
15923 ph_wait * 1e3 / rounds_f,
15924 ph_commit * 1e3 / rounds_f,
15925 other * 1e3 / rounds_f,
15926 );
15927 }
15928 let _pipe_tail = pipe.map(|p| p.primary()).transpose()?;
15929 // SESSION TAIL: leave the session in the exact invariant the next turn's suffix prime
15930 // expects — every row in `committed` has trunk KV/recur state AND an exact draft-KV row.
15931 // Park the draft-graph ctx back on the session (the serve-burst fixed-cost fix): the next
15932 // burst replays instead of recapturing. Error paths (`?` above) drop it — recaptured then.
15933 if let Some(slot) = sess_draft_slot.take() {
15934 *slot = Some(dctx);
15935 }
15936 let t_rounds = t_ent.elapsed();
15937 if let Some((committed, last_h, next_pred_slot, sctr_slot, uctr_slot)) = sess_tail.take() {
15938 // NEXT BURST'S BOUNDARY TOKEN (lane/sampled-spec-quality, Item 1). Greedy stashes
15939 // the argmax `last_pred` exactly as before (byte contract). SAMPLED draws the token
15940 // HERE, where the sampler, the session Philox counters and the penalty window are
15941 // all live and the boundary logits row still exists — that is the "make the state
15942 // available" half of the fix; the consuming burst then just emits it. `sctr` is
15943 // written to the session BELOW the draws so the advance is never lost.
15944 *next_pred_slot = Some(last_pred);
15945 let sample_boundary = sampled && constraint.is_none() && spec_sampled_boundary_on();
15946 let mut stashed_pending = false;
15947 if let Some(b) = pending.take() {
15948 if !sampled {
15949 // PENDING-CARRY (2026-08-01): stash the bonus on the session instead of
15950 // committing it with a solo T=1 pass — the next empty-suffix greedy burst
15951 // consumes it as round-0 verify col 0 (a plain round edge; the old tail
15952 // commit + next burst's init feed were 11.6+11.5ms solo trunk passes per
15953 // burst on H100 q27, [spec-setup] trace). b stays in `out` (emitted) but
15954 // OUT of `committed` (cache rows == committed); the consuming call
15955 // prepends it once its verify commits the row. next_pred is unknowable
15956 // without the commit pass — None; callers gate on pending_tok too.
15957 debug_assert_eq!(out.last(), Some(&b), "pending must be the last emitted");
15958 if let Some(slot) = sess_pending_slot.take() {
15959 *slot = Some(b);
15960 }
15961 *next_pred_slot = None;
15962 // fill_prev = hidden of the last COMMITTED row (b's predecessor) — the
15963 // exact chain-seed/fill anchor the consuming burst (or a flush) needs.
15964 *last_h = Some(e.clone_dtod(&fill_prev)?);
15965 stashed_pending = true;
15966 } else {
15967 // SAMPLED tail (unchanged): commit the bonus (one T=1 pass) + draft fill —
15968 // the sampled round-0 accept needs this pass's logits (last_col_logits).
15969 let pos_b = cache.pos;
15970 scratch.set_len(e, pos_b)?;
15971 let (lg_b, hb) = self.spec_target_step_h(e, b, &mut *cache)?;
15972 // after a FULL-accept exit `last_pred` is STALE (it predicted the bonus
15973 // itself — the prediction AFTER the bonus never materialized; it would have
15974 // been the next round's verify col 0). The commit's logits ARE that
15975 // prediction — so they are also the row the next burst's boundary token
15976 // comes off, and (lane/sampled-spec-quality) it is DRAWN from them here.
15977 *next_pred_slot = Some(if sample_boundary {
15978 sample_boundary_token(
15979 e,
15980 &lg_b,
15981 &sp,
15982 &pen_hist,
15983 &mut sctr,
15984 "burst-tail-commit",
15985 )?
15986 } else {
15987 argmax(&lg_b) as u32
15988 });
15989 self.mtp_kv_fill_all(e, &[b], &fill_prev, pos_b, &mut *scratch, embd_dev)?;
15990 *last_h = Some(hb);
15991 }
15992 } else {
15993 // fill_prev tracks the hidden of the last COMMITTED row throughout the loop.
15994 *last_h = Some(e.clone_dtod(&fill_prev)?);
15995 if sample_boundary {
15996 // No pending to commit, so the boundary row is the one `last_pred` was
15997 // argmaxed from and the sampled path keeps it on device: the init feed's
15998 // logits when the burst ran zero rounds, else the legacy-replay path's
15999 // last verify column (both predict the token AFTER the last committed
16000 // row). It is retained precisely because round 0's accept test needs it,
16001 // so the draw costs no extra D2H of the [n_vocab] row.
16002 match last_col_logits.as_ref() {
16003 Some(lc) => {
16004 *next_pred_slot = Some(sample_boundary_token_dev(
16005 e,
16006 lc,
16007 n_vocab,
16008 &sp,
16009 &pen_hist,
16010 &mut sctr,
16011 "burst-tail-nopending",
16012 )?);
16013 }
16014 // NAME THE FALLBACK (house standard): unreachable today — a sampled
16015 // burst always feeds or replays, so the row exists — but if it ever
16016 // is, the stream takes a greedy token and SAYS so rather than
16017 // silently regressing to the pre-lane behaviour.
16018 None => eprintln!(
16019 "[spec-boundary] sampled tail kept the ARGMAX boundary token \
16020 (reason: no retained boundary logits row)"
16021 ),
16022 }
16023 }
16024 }
16025 *sctr_slot = sctr;
16026 *uctr_slot = uctr;
16027 committed.extend_from_slice(prompt);
16028 if let Some(cb) = carried_pending {
16029 // the consumed carry's cache row landed in round 0's verify (every pending
16030 // round commits col 0) — it joins `committed` here, in sequence order.
16031 committed.push(cb);
16032 }
16033 if stashed_pending {
16034 // ZERO-EMIT BURST (2026-08-06 c=8 serve panic, pre-existing since b4aea184):
16035 // `out.len() - 1` underflowed on an EMPTY `out` — "range end index
16036 // 18446744073709551615 out of range for slice of length 0", killing the
16037 // memra-gpu-worker and failing 31 of 32 concurrent requests with "worker closed
16038 // stream". Reachable because `pending` starts as `carried_pending` (a bonus
16039 // stashed by the PREVIOUS burst) while `out` starts empty, and the carry is
16040 // deliberately NOT pushed to `out` (line ~3239: the burst that emitted it already
16041 // did). So a burst that stashes a pending without emitting anything of its own —
16042 // the round loop exits before a push, e.g. the ring drain's `out.len() < max_new`
16043 // guard skipping every token under a tight budget — arrives here with
16044 // out.len() == 0 and stashed_pending == true.
16045 //
16046 // The invariant is unchanged: `committed` gets every emitted token EXCEPT the
16047 // stashed bonus. With nothing emitted, that is nothing — and the carry pushed
16048 // just above is already accounted. Saturating, not a min/assert: an empty `out`
16049 // here is a legitimate burst shape, not a corrupt state.
16050 let emitted = out.len().saturating_sub(1);
16051 committed.extend_from_slice(&out[..emitted]);
16052 } else {
16053 committed.extend_from_slice(&out); // FULL out incl. overshoot — all committed
16054 }
16055 debug_assert_eq!(
16056 cache.pos,
16057 committed.len(),
16058 "session invariant: cache rows == committed tokens"
16059 );
16060 if setup_trace {
16061 e.stream().synchronize()?; // bound the async tail fill in the trace
16062 let t_tail = t_ent.elapsed();
16063 eprintln!(
16064 "[spec-setup] init={:.2}ms cap={:.2}ms fill={:.2}ms rounds={:.2}ms tail={:.2}ms total={:.2}ms out={} cont={}",
16065 t_init.as_secs_f64() * 1e3,
16066 (t_cap - t_init).as_secs_f64() * 1e3,
16067 (t_fill - t_cap).as_secs_f64() * 1e3,
16068 (t_rounds - t_fill).as_secs_f64() * 1e3,
16069 (t_tail - t_rounds).as_secs_f64() * 1e3,
16070 t_tail.as_secs_f64() * 1e3,
16071 out.len(),
16072 continuation
16073 );
16074 }
16075 return Ok((out, total_drafted, total_accepted));
16076 }
16077 out.truncate(max_new);
16078 Ok((out, total_drafted, total_accepted))
16079 }
16080
16081 /// Anchor-bounded DSpark target extraction. The trunk sees the exact generated token tape;
16082 /// only requested hidden rows and target-logit rows cross PCIe. An anchor token at p pairs
16083 /// with the pre-output-norm h[p-1] carrier, exactly as the existing replay/NextN path does.
16084 #[allow(clippy::too_many_arguments)] // allow: the parameter list mirrors the kernel/FFI/call contract; bundling into a struct is a refactor, not a lint fix
16085 pub fn extract_dspark_anchors(
16086 &self,
16087 e: &Engine,
16088 tokens: &[u32],
16089 anchor_positions: &[usize],
16090 gamma: usize,
16091 top_k: usize,
16092 chunk: usize,
16093 temperature: f32,
16094 ) -> Result<Vec<DsparkAnchorRecord>, Box<dyn std::error::Error>> {
16095 if tokens.len() < gamma + 2 || gamma == 0 || chunk < 2 {
16096 return Err("DSpark extraction token tape/gamma/chunk is invalid".into());
16097 }
16098 if anchor_positions.windows(2).any(|pair| pair[0] >= pair[1]) {
16099 return Err("DSpark anchor positions must be sorted and unique".into());
16100 }
16101 for &position in anchor_positions {
16102 if position == 0 || position + gamma >= tokens.len() {
16103 return Err(format!(
16104 "DSpark anchor {position} has no predecessor or cannot cover gamma={gamma} in {} tokens",
16105 tokens.len()
16106 )
16107 .into());
16108 }
16109 }
16110
16111 let n_vocab = self.output.out_features();
16112 let n_embd = self.cfg.n_embd as usize;
16113 let mut cache =
16114 crate::pp::new_cache_planned(e, &self.cfg, &self.plan, tokens.len() + gamma + 8)?;
16115 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
16116 let embd_gpu = if spec_host_embd() {
16117 None
16118 } else {
16119 Some(
16120 self.embd_gpu
16121 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
16122 )
16123 };
16124 let embd_dev = embd_gpu.map(|gpu| (gpu, embd_qt, embd_rb));
16125
16126 struct PendingRecord {
16127 position: usize,
16128 hidden: Option<Vec<f32>>,
16129 tokens: Vec<u32>,
16130 target_top_ids: Vec<Option<Vec<u32>>>,
16131 target_top_logits: Vec<Option<Vec<f32>>>,
16132 target_top_probs: Vec<Option<Vec<f32>>>,
16133 target_tail_probs: Vec<Option<f32>>,
16134 }
16135
16136 let mut pending: Vec<PendingRecord> = anchor_positions
16137 .iter()
16138 .map(|&position| PendingRecord {
16139 position,
16140 hidden: None,
16141 tokens: tokens[position..=position + gamma].to_vec(),
16142 target_top_ids: vec![None; gamma],
16143 target_top_logits: vec![None; gamma],
16144 target_top_probs: vec![None; gamma],
16145 target_tail_probs: vec![None; gamma],
16146 })
16147 .collect();
16148
16149 let mut start = 0usize;
16150 while start < tokens.len() {
16151 let end = (start + chunk).min(tokens.len());
16152 let chunk_tokens = &tokens[start..end];
16153 let (target_logits, hidden_rows) =
16154 self.decode_step_t_core(e, chunk_tokens, start, &mut cache, embd_dev, None)?;
16155 for record in &mut pending {
16156 let hidden_position = record.position - 1;
16157 if hidden_position >= start && hidden_position < end {
16158 let local = hidden_position - start;
16159 record.hidden = Some(
16160 e.dtoh_view(&hidden_rows.slice(local * n_embd..(local + 1) * n_embd))?,
16161 );
16162 }
16163 for slot in 0..gamma {
16164 let target_row = record.position + slot;
16165 if target_row < start || target_row >= end {
16166 continue;
16167 }
16168 let local = target_row - start;
16169 let logits =
16170 e.dtoh_view(&target_logits.slice(local * n_vocab..(local + 1) * n_vocab))?;
16171 let (ids, top_logits, probs, tail) =
16172 dspark_sparse_softmax_topk(&logits, top_k, temperature)?;
16173 record.target_top_ids[slot] = Some(ids);
16174 record.target_top_logits[slot] = Some(top_logits);
16175 record.target_top_probs[slot] = Some(probs);
16176 record.target_tail_probs[slot] = Some(tail);
16177 }
16178 }
16179 start = end;
16180 }
16181
16182 pending
16183 .into_iter()
16184 .map(|record| {
16185 let hidden = record
16186 .hidden
16187 .ok_or_else(|| format!("missing DSpark hidden at {}", record.position))?;
16188 let target_top_ids =
16189 flatten_dspark_rows(record.target_top_ids, record.position, "target ids")?;
16190 let target_top_logits = flatten_dspark_rows(
16191 record.target_top_logits,
16192 record.position,
16193 "target logits",
16194 )?;
16195 let target_top_probs =
16196 flatten_dspark_rows(record.target_top_probs, record.position, "target probs")?;
16197 let target_tail_probs = record
16198 .target_tail_probs
16199 .into_iter()
16200 .enumerate()
16201 .map(|(slot, value)| {
16202 value.ok_or_else(|| {
16203 format!("missing DSpark tail at {} slot {slot}", record.position)
16204 })
16205 })
16206 .collect::<Result<Vec<_>, _>>()?;
16207 Ok(DsparkAnchorRecord {
16208 position: record.position,
16209 hidden,
16210 tokens: record.tokens,
16211 target_top_ids,
16212 target_top_logits,
16213 target_top_probs,
16214 target_tail_probs,
16215 })
16216 })
16217 .collect()
16218 }
16219
16220 /// TEACHER-FORCED REPLAY ACCEPTANCE (hqmtp MTP-heal protocol): walk a FIXED token
16221 /// sequence and, at sampled positions, compare the MTP head's K-token draft chain against
16222 /// the trunk's own teacher-forced greedy predictions. Nothing is generated — the context is
16223 /// the corpus text itself, so (a) degenerate self-generated loops cannot inflate acceptance
16224 /// and (b) two arms (bf16 ceiling vs NVFP4) score on IDENTICAL contexts, isolating the
16225 /// quant-induced head/hidden-state mismatch from text drift.
16226 ///
16227 /// Per eval position p (context = tokens[0..=p], predecessor pairing as in spec decode):
16228 /// draft_j = chain token j from (tokens[p], h_{p-1}), then its own drafts — the exact
16229 /// eager spec-decode chain (same mtp_head_forward_dev, same rope positions).
16230 /// target_j = teacher-forced greedy pick for position p+1+j (argmax of the trunk logits
16231 /// at forced context tokens[0..p+j]). For j==0 this equals live spec
16232 /// acceptance; for j>=1 live verify would condition on the drafts, here it
16233 /// conditions on the corpus — deterministic and arm-comparable by design.
16234 ///
16235 /// Returns (rows, bg): one (p, drafts[k], targets[k]) row per eval position (ascending p),
16236 /// plus the full teacher-forced greedy track bg (bg[i] = greedy pick for position i, i>=1)
16237 /// so harnesses can cross-check runs (e.g. different chunk sizes must give identical bg).
16238 ///
16239 /// `hdump`: when Some, every position's pre-output_norm trunk hidden (the exact rows the
16240 /// draft-KV fill pairs from) streams to the file as little-endian f32 [t_total, n_embd] —
16241 /// the head-distillation extraction (hqmtp): the ENGINE is the source of truth for trunk
16242 /// hiddens (HF torch reproductions of the hybrid trunk measured only ~0.5 greedy
16243 /// agreement vs this path — not usable as a training-data source).
16244 #[allow(clippy::type_complexity)] // allow: one-shot composite type; naming it would hide the shape that matters at the call site
16245 pub fn replay_acceptance(
16246 &self,
16247 e: &Engine,
16248 tokens: &[u32],
16249 k: usize,
16250 stride: usize,
16251 chunk: usize,
16252 mut hdump: Option<&mut std::fs::File>,
16253 ) -> Result<(Vec<(usize, Vec<u32>, Vec<u32>)>, Vec<u32>), Box<dyn std::error::Error>> {
16254 assert!(k >= 1 && stride >= 1 && chunk >= 2);
16255 let mtp = self
16256 .mtp
16257 .as_ref()
16258 .expect("replay_acceptance requires an MTP head");
16259 let n_vocab = self.output.out_features();
16260 let d_vocab = mtp
16261 .shared_head_head
16262 .as_ref()
16263 .unwrap_or(&self.output)
16264 .out_features();
16265 let n_embd = self.cfg.n_embd as usize;
16266 let t_total = tokens.len();
16267 assert!(t_total >= 8, "corpus too short ({t_total} tokens)");
16268 // STAGE-OWNED KV (lane/pp2-spec 2026-08-06) — see `new_session`. Door shut = `Cache::new`.
16269 let mut cache = crate::pp::new_cache_planned(e, &self.cfg, &self.plan, t_total + k + 8)?;
16270 let mut scratch = self.new_mtp_scratch(e, t_total + k + 8)?;
16271 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
16272 let embd_gpu = if spec_host_embd() {
16273 None
16274 } else {
16275 Some(
16276 self.embd_gpu
16277 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
16278 )
16279 };
16280 let embd_dev = embd_gpu.map(|g| (g, embd_qt, embd_rb));
16281
16282 // bg[i] = the trunk's greedy pick for position i under the forced context (i >= 1).
16283 let mut bg: Vec<u32> = vec![0; t_total + 1];
16284 let mut rows: Vec<(usize, Vec<u32>, Vec<u32>)> = Vec::new();
16285 let mut prev_last_h = e.zeros(n_embd)?; // predecessor hidden entering the chunk
16286 let mut seed_buf = e.zeros(n_embd)?;
16287 let mut preds_d = e.alloc_u32_zeroed(chunk)?;
16288 let nll_on = std::env::var("MEMRA_REPLAY_NLL").as_deref() == Ok("1");
16289 let (mut nll_sum, mut nll_cnt) = (0f64, 0u64);
16290 let mut s = 0usize;
16291 while s < t_total {
16292 let cend = (s + chunk).min(t_total);
16293 let tc = cend - s;
16294 let ch = &tokens[s..cend];
16295 // 1. forced trunk pass — verify path (decode-exact contract): all-column logits +
16296 // the chunk's true hiddens.
16297 let (tl_d, vx) = self.decode_step_t_core(e, ch, s, &mut cache, embd_dev, None)?;
16298 for j in 0..tc {
16299 e.argmax_token_device_col(&tl_d, j, n_vocab, &mut preds_d, j)?;
16300 }
16301 let preds = e.dtoh_u32(&preds_d)?;
16302 for j in 0..tc {
16303 bg[s + j + 1] = preds[j];
16304 }
16305 // MEMRA_REPLAY_NLL=1: teacher-forced NLL/perplexity over the same forced pass — the
16306 // checkpoint-quality metric (position j's logits score the GOLD next token).
16307 if nll_on {
16308 let jmax = if cend < t_total { tc } else { tc - 1 }; // last pos has no gold next
16309 if jmax > 0 {
16310 let ids: Vec<u32> = (0..jmax).map(|j| tokens[s + j + 1]).collect();
16311 let rows: Vec<i32> = (0..jmax as i32).collect();
16312 let idsd = e.htod_u32_v(&ids)?;
16313 let rowsd = e.htod_i32(&rows)?;
16314 let mut outd = e.zeros(jmax)?;
16315 e.softmax_gather(&tl_d, n_vocab, &idsd, &rowsd, &mut outd, n_vocab, jmax, 1.0)?;
16316 for pr in e.dtoh(&outd)? {
16317 nll_sum += -((pr.max(1e-30)) as f64).ln();
16318 nll_cnt += 1;
16319 }
16320 }
16321 }
16322 if let Some(f) = hdump.as_deref_mut() {
16323 use std::io::Write;
16324 let host: Vec<f32> = e.dtoh(&vx)?;
16325 // bf16 round-to-nearest-even — f32 doubled the disk bill at bulk
16326 // extraction scale (20M tokens x 4096 = 320GB f32 vs 160GB bf16).
16327 let mut bytes = Vec::with_capacity(tc * n_embd * 2);
16328 for v in &host[..tc * n_embd] {
16329 let b = v.to_bits();
16330 let r = b.wrapping_add(0x7FFF + ((b >> 16) & 1));
16331 bytes.extend_from_slice(&((r >> 16) as u16).to_le_bytes());
16332 }
16333 f.write_all(&bytes)?;
16334 }
16335 // CHAINLESS extraction (stride > corpus, the bulk-hdump mode): no chunk ever
16336 // drafts, so the draft-KV fills are pure waste — skip them (2 MTP-block passes
16337 // per token saved; the forced trunk pass + hdump is all the mode needs).
16338 let chainless = stride > t_total;
16339 if chainless {
16340 e.copy_view_into(
16341 &mut prev_last_h,
16342 0,
16343 &vx.slice((tc - 1) * n_embd..tc * n_embd),
16344 n_embd,
16345 )?;
16346 s = cend;
16347 continue;
16348 }
16349 // 2. TRUE predecessor-paired draft-KV fill for the chunk (row i carries h_{i-1};
16350 // row s reads the previous chunk's last true hidden, zeros at corpus start).
16351 let mut vxs = e.zeros(tc * n_embd)?;
16352 e.copy_into(&mut vxs, 0, &prev_last_h, n_embd)?;
16353 if tc > 1 {
16354 e.copy_view_into(
16355 &mut vxs,
16356 n_embd,
16357 &vx.slice(0..(tc - 1) * n_embd),
16358 (tc - 1) * n_embd,
16359 )?;
16360 }
16361 scratch.set_len(e, s)?;
16362 self.mtp_kv_fill_all(e, ch, &vxs, s, &mut scratch, embd_dev)?;
16363 // 3. draft chains at sampled positions, DESCENDING: a chain reads only slots
16364 // [0..p) (true fills) and appends at >= p; the next (smaller-p) chain's set_len
16365 // truncates those approximate appends before they can ever be read.
16366 let ps: Vec<usize> = (s..cend)
16367 .filter(|p| *p >= 1 && *p % stride == 0 && *p + k <= t_total)
16368 .collect();
16369 for &p in ps.iter().rev() {
16370 scratch.set_len(e, p)?;
16371 if p == s {
16372 e.copy_into(&mut seed_buf, 0, &prev_last_h, n_embd)?;
16373 } else {
16374 e.copy_view_into(
16375 &mut seed_buf,
16376 0,
16377 &vx.slice((p - 1 - s) * n_embd..(p - s) * n_embd),
16378 n_embd,
16379 )?;
16380 }
16381 let mut e_tok = tokens[p];
16382 let mut d_seed = e.clone_dtod(&seed_buf)?;
16383 let chain_heads = !self.mtp_extra.is_empty();
16384 let mut chain_tokens = if chain_heads {
16385 vec![tokens[p]]
16386 } else {
16387 Vec::new()
16388 };
16389 let mut chain_seeds = if chain_heads {
16390 vec![e.clone_dtod(&seed_buf)?]
16391 } else {
16392 Vec::new()
16393 };
16394 let mut drafts: Vec<u32> = Vec::with_capacity(k);
16395 for j in 0..k {
16396 let (dl_d, h_nextn) = if chain_heads {
16397 self.mtp_chain_forward_dev(
16398 e,
16399 &chain_tokens,
16400 &chain_seeds,
16401 &mut scratch,
16402 p,
16403 embd_dev,
16404 None,
16405 )?
16406 } else {
16407 self.mtp_head_forward_dev(
16408 e,
16409 mtp,
16410 e_tok,
16411 &d_seed,
16412 &mut scratch,
16413 p + 1 + j,
16414 embd_dev,
16415 None,
16416 )?
16417 };
16418 let tok_d = e.argmax_token_device(&dl_d, d_vocab)?;
16419 let idx = e.dtoh_u32_one(&tok_d)?;
16420 let d = match &mtp.d2t {
16421 Some(map) => map[idx as usize],
16422 None => idx,
16423 };
16424 drafts.push(d);
16425 if chain_heads {
16426 chain_tokens.push(d);
16427 chain_seeds.push(h_nextn);
16428 } else {
16429 e_tok = d;
16430 d_seed = h_nextn;
16431 }
16432 }
16433 // targets may live in a LATER chunk's bg — resolved after the walk.
16434 rows.push((p, drafts, Vec::new()));
16435 }
16436 // 4. restore TRUE entries for the whole chunk (the next chunk's chains and fills
16437 // expect scratch.len == cend with exact rows).
16438 scratch.set_len(e, s)?;
16439 self.mtp_kv_fill_all(e, ch, &vxs, s, &mut scratch, embd_dev)?;
16440 e.copy_view_into(
16441 &mut prev_last_h,
16442 0,
16443 &vx.slice((tc - 1) * n_embd..tc * n_embd),
16444 n_embd,
16445 )?;
16446 s = cend;
16447 }
16448 for (p, drafts, targets) in rows.iter_mut() {
16449 for j in 0..drafts.len() {
16450 targets.push(bg[*p + 1 + j]);
16451 }
16452 }
16453 rows.sort_by_key(|r| r.0);
16454 if nll_cnt > 0 {
16455 let mean = nll_sum / nll_cnt as f64;
16456 println!(
16457 "[replay-nll] tokens={nll_cnt} nll/token={mean:.5} ppl={:.4}",
16458 mean.exp()
16459 );
16460 }
16461 Ok((rows, bg))
16462 }
16463}
16464
16465#[cfg(test)]
16466mod vg_debt_tests {
16467 use super::dspark_vg_debt_projection;
16468
16469 /// TOOTH for the verify-graph admission accounting: the pool's projected remaining
16470 /// growth must be charged (pre-fix, admission charged 0 for a pool measured at
16471 /// 8,852 MiB), the projection must price the MARGINAL cost of one more key rather than
16472 /// extrapolating the pool's one-time shared allocation, and the doors that make growth
16473 /// impossible must zero the debt.
16474 #[test]
16475 fn vg_debt_projects_remaining_growth_and_respects_the_freeze_valves() {
16476 const MIB: usize = 1 << 20;
16477 let d = dspark_vg_debt_projection;
16478 // cold pool: nothing observed, one capture fits inside SPEC_SHRINK_RESERVE.
16479 assert_eq!(d(0, 256, 0, None), 0);
16480 // freeze valve MEMRA_DSPARK_VG_MAX=0: the pool cannot grow.
16481 assert_eq!(d(10, 0, 500 * MIB, None), 0);
16482 // saturated pool: at/past the cap the pool FREEZES, nothing left to reserve.
16483 assert_eq!(d(256, 256, 8852 * MIB, None), 0);
16484 assert_eq!(d(300, 256, 8852 * MIB, None), 0);
16485
16486 // BOOTSTRAP (one observation, growth unmeasurable): at most one more pool's worth.
16487 // The pre-fix mean rule extrapolated 255x here — the measured 8.5 GB phantom.
16488 assert_eq!(d(1, 256, 33 * MIB, None), 33 * MIB);
16489
16490 // MARGINAL, flat pool (the box9 receipt: reserved stayed ~33.6 MiB across captures
16491 // 1..3, so an additional key costs ~nothing and the debt must collapse to ~0 —
16492 // NOT the 8,556/4,261/2,830 MB the mean rule printed).
16493 assert_eq!(d(3, 256, 33 * MIB, Some((1, 33 * MIB))), 0);
16494
16495 // MARGINAL, genuinely growing pool: 40 MiB per new key over 2 keys, 250 slots left.
16496 let debt = d(6, 256, 273 * MIB, Some((4, 193 * MIB)));
16497 assert_eq!(debt, 250 * (40 * MIB));
16498 assert!(
16499 debt > 3 * (1536 * MIB),
16500 "real growth must dwarf SPEC_SHRINK_RESERVE"
16501 );
16502
16503 // a shrinking/recycled reading never becomes a negative charge.
16504 assert_eq!(d(6, 256, 10 * MIB, Some((4, 99 * MIB))), 0);
16505 // a stale observation at the same capture count falls back to bootstrap.
16506 assert_eq!(d(4, 256, 80 * MIB, Some((4, 80 * MIB))), 80 * MIB);
16507 }
16508}
16509
16510#[cfg(test)]
16511mod capture_headroom_tests {
16512 use super::{
16513 CAPTURE_HEADROOM_FLOOR, capture_err_is_oom, capture_headroom_verdict,
16514 draft_capture_bootstrap_estimate,
16515 };
16516
16517 /// TOOTH for the pre-capture reserve check (lane/step37-vram-admission-20260830): a
16518 /// capture attempt must be refused BEFORE it allocates when the device cannot cover its
16519 /// appetite plus the post-capture floor — and pool-cached bytes count as headroom
16520 /// (driver `free` alone under-counts, the wrong direction for a gate that drops
16521 /// coverage).
16522 #[test]
16523 fn capture_reserve_check_refuses_short_devices_and_counts_pool_cache() {
16524 const MIB: usize = 1 << 20;
16525 let need = 900 * MIB;
16526 // Plenty of room: no refusal.
16527 assert_eq!(
16528 capture_headroom_verdict(8_000 * MIB, 0, need, CAPTURE_HEADROOM_FLOOR),
16529 None
16530 );
16531 // The owner's shape: capture appetite would walk the card to the edge — refused,
16532 // with the arithmetic surfaced for the WARN line.
16533 let (required, effective) =
16534 capture_headroom_verdict(1_200 * MIB, 0, need, CAPTURE_HEADROOM_FLOOR)
16535 .expect("short device must refuse");
16536 assert_eq!(required, need + CAPTURE_HEADROOM_FLOOR);
16537 assert_eq!(effective, 1_200 * MIB);
16538 // Pool-cached bytes are real headroom (the trim path makes them driver-visible).
16539 assert_eq!(
16540 capture_headroom_verdict(1_200 * MIB, 7_000 * MIB, need, CAPTURE_HEADROOM_FLOOR),
16541 None
16542 );
16543 // Boundary: exactly enough is enough (>=, never a fencepost refusal).
16544 assert_eq!(
16545 capture_headroom_verdict(
16546 need + CAPTURE_HEADROOM_FLOOR,
16547 0,
16548 need,
16549 CAPTURE_HEADROOM_FLOOR
16550 ),
16551 None
16552 );
16553 // POLICY at the call site (owner-shape receipts, escalated twice on-box): the
16554 // refusal fn is handed 2x the appetite plus TWO floors — a capture may take at
16555 // most half the discretionary headroom, so the card retains a whole capture's
16556 // worth of room after it lands. One floor of slack above one appetite (the shape
16557 // that step-OOM'd on the owner cell) must therefore REFUSE under the call-site
16558 // requirement.
16559 assert!(
16560 capture_headroom_verdict(
16561 need + CAPTURE_HEADROOM_FLOOR + (100 << 20),
16562 0,
16563 2 * need,
16564 CAPTURE_HEADROOM_FLOOR * 2
16565 )
16566 .is_some()
16567 );
16568 }
16569
16570 #[test]
16571 fn bootstrap_estimate_scales_with_heads_and_never_underflows() {
16572 // 3-head chain on a step37-shaped vocab must expect strictly more than one head.
16573 let one = draft_capture_bootstrap_estimate(1, 3, 128_896, 4_096);
16574 let three = draft_capture_bootstrap_estimate(3, 3, 128_896, 4_096);
16575 assert!(three > one);
16576 // Degenerate shapes keep a sane minimum (the estimate feeds a refusal gate; a
16577 // zero-need gate refuses nothing).
16578 assert!(draft_capture_bootstrap_estimate(0, 0, 0, 0) >= 64 << 20);
16579 }
16580
16581 #[test]
16582 fn capture_oom_predicate_matches_the_quoted_driver_text() {
16583 assert!(capture_err_is_oom(
16584 "DriverError(CUDA_ERROR_OUT_OF_MEMORY, \"out of memory\")"
16585 ));
16586 assert!(capture_err_is_oom("allocation failed: out of memory"));
16587 assert!(!capture_err_is_oom("capture produced no graph"));
16588 }
16589}
16590
16591#[cfg(test)]
16592mod mtp_chain_tests {
16593 use super::mtp_chain_head_index;
16594
16595 #[test]
16596 fn embedded_step_heads_cycle_in_declared_order() {
16597 let actual: Vec<usize> = (0..8).map(|step| mtp_chain_head_index(step, 3)).collect();
16598 assert_eq!(actual, [0, 1, 2, 0, 1, 2, 0, 1]);
16599 }
16600
16601 #[test]
16602 fn standalone_draft_remains_single_head() {
16603 assert!((0..8).all(|step| mtp_chain_head_index(step, 1) == 0));
16604 }
16605}
16606
16607#[cfg(test)]
16608mod tp_verified_prefix_tests {
16609 use super::rewind_tp_kv_verified_prefix;
16610 use crate::tp::ResidentTpKvCache;
16611
16612 fn cache_with_committed_len(committed: usize) -> ResidentTpKvCache {
16613 let mut cache = ResidentTpKvCache::new(Vec::new(), 1, 1, 1, 1, 8);
16614 let transaction = cache.begin_transaction().unwrap();
16615 let target = cache.append_target(transaction, committed).unwrap();
16616 cache.publish_append(transaction, target).unwrap();
16617 let target = cache.commit_target(transaction, committed).unwrap();
16618 cache.publish_finalize(transaction, target).unwrap();
16619 cache
16620 }
16621
16622 #[test]
16623 fn replay_free_prefix_rewinds_tp_visibility_to_snapshot_plus_accepts() {
16624 let mut layers = vec![Some(cache_with_committed_len(5)), None];
16625 rewind_tp_kv_verified_prefix(&mut layers, &[Some(2), None], 1).unwrap();
16626 let cache = layers[0].as_ref().unwrap();
16627 assert_eq!(cache.committed_len(), 3);
16628 assert_eq!(cache.staged_len(), 3);
16629 }
16630
16631 #[test]
16632 fn replay_free_prefix_rejects_a_changed_tp_cache_shape() {
16633 let mut layers = vec![Some(cache_with_committed_len(1))];
16634 let error = rewind_tp_kv_verified_prefix(&mut layers, &[None], 1)
16635 .unwrap_err()
16636 .to_string();
16637 assert!(error.contains("changed shape"), "unexpected error: {error}");
16638 }
16639}
16640
16641#[cfg(test)]
16642mod dspark_sparse_tests {
16643 use super::dspark_sparse_softmax_topk;
16644
16645 #[test]
16646 fn topk_keeps_full_softmax_mass_and_stable_ties() {
16647 let logits = [1.0f32, 3.0, 3.0, -2.0];
16648 let (ids, top_logits, probs, tail) = dspark_sparse_softmax_topk(&logits, 2, 1.0).unwrap();
16649 assert_eq!(ids, vec![1, 2]);
16650 assert_eq!(top_logits, vec![3.0, 3.0]);
16651 let denominator = logits.iter().map(|value| (value - 3.0).exp()).sum::<f32>();
16652 let expected = 1.0 / denominator;
16653 assert!((probs[0] - expected).abs() < 1.0e-6);
16654 assert!((probs[1] - expected).abs() < 1.0e-6);
16655 assert!((tail - (1.0 - 2.0 * expected)).abs() < 1.0e-6);
16656 assert!((probs.iter().sum::<f32>() + tail - 1.0).abs() < 1.0e-6);
16657 }
16658}
16659
16660#[cfg(test)]
16661mod spec_replay_env_tests {
16662 use super::spec_replay_env_on;
16663
16664 #[test]
16665 fn replay_requires_literal_one() {
16666 assert!(!spec_replay_env_on(None));
16667 assert!(!spec_replay_env_on(Some("")));
16668 assert!(!spec_replay_env_on(Some("0")));
16669 assert!(!spec_replay_env_on(Some("true")));
16670 assert!(!spec_replay_env_on(Some("2")));
16671 assert!(spec_replay_env_on(Some("1")));
16672 }
16673}
16674
16675#[cfg(test)]
16676mod telem_tests {
16677 use super::{SPEC_TELEM_POS, SpecTelemetry, SpecTelemetryCounters};
16678
16679 #[test]
16680 fn synthetic_accept_masks_produce_tau_and_position_histogram() {
16681 let counters = SpecTelemetryCounters::default();
16682 for mask in [
16683 [true, true, true],
16684 [true, true, false],
16685 [true, false, false],
16686 [false, false, false],
16687 ] {
16688 let accepted = mask.iter().take_while(|&&value| value).count();
16689 counters.record_round(mask.len(), accepted);
16690 }
16691
16692 let snapshot = counters.snapshot();
16693 assert_eq!(
16694 (snapshot.rounds, snapshot.drafted, snapshot.accepted),
16695 (4, 12, 6)
16696 );
16697 assert_eq!(&snapshot.pos_drafted[..3], &[4, 4, 4]);
16698 assert_eq!(&snapshot.pos_accepted[..3], &[3, 2, 1]);
16699 assert_eq!(snapshot.tau(), 1.5);
16700 assert_eq!(snapshot.pos_drafted[3..], [0; SPEC_TELEM_POS - 3]);
16701 assert_eq!(snapshot.pos_accepted[3..], [0; SPEC_TELEM_POS - 3]);
16702 }
16703
16704 /// The worker's per-burst pattern: stash, accumulate, diff — the delta must isolate
16705 /// exactly the burst's contribution (pool-resumed sessions carry prior requests' counts).
16706 #[test]
16707 fn delta_isolates_burst_contribution() {
16708 let mut t = SpecTelemetry::default();
16709 // "previous request": 2 rounds of k=3, accepts 3 then 1.
16710 for (kr, na) in [(3usize, 3usize), (3, 1)] {
16711 t.rounds += 1;
16712 t.drafted += kr as u64;
16713 t.accepted += na as u64;
16714 for j in 0..kr {
16715 t.pos_drafted[j] += 1;
16716 }
16717 for j in 0..na {
16718 t.pos_accepted[j] += 1;
16719 }
16720 }
16721 let before = t;
16722 // "this burst": 1 round k=3, accepts 2.
16723 t.rounds += 1;
16724 t.drafted += 3;
16725 t.accepted += 2;
16726 for j in 0..3 {
16727 t.pos_drafted[j] += 1;
16728 }
16729 for j in 0..2 {
16730 t.pos_accepted[j] += 1;
16731 }
16732 let d = t.delta_since(&before);
16733 assert_eq!((d.rounds, d.drafted, d.accepted), (1, 3, 2));
16734 assert_eq!(&d.pos_drafted[..3], &[1, 1, 1]);
16735 assert_eq!(&d.pos_accepted[..3], &[1, 1, 0]);
16736 assert_eq!(d.pos_drafted[3..], [0; SPEC_TELEM_POS - 3]);
16737 }
16738
16739 /// merge(delta) then merge(delta2) equals accumulating both — the per-model /metrics
16740 /// aggregation invariant.
16741 #[test]
16742 fn merge_accumulates_fieldwise() {
16743 let mut agg = SpecTelemetry::default();
16744 let mut d1 = SpecTelemetry {
16745 rounds: 2,
16746 drafted: 6,
16747 accepted: 4,
16748 ..Default::default()
16749 };
16750 d1.pos_drafted[0] = 2;
16751 d1.pos_accepted[0] = 2;
16752 let mut d2 = SpecTelemetry {
16753 rounds: 1,
16754 drafted: 3,
16755 accepted: 1,
16756 ..Default::default()
16757 };
16758 d2.pos_drafted[0] = 1;
16759 d2.pos_accepted[0] = 1;
16760 d2.pos_drafted[1] = 1;
16761 agg.merge(&d1);
16762 agg.merge(&d2);
16763 assert_eq!((agg.rounds, agg.drafted, agg.accepted), (3, 9, 5));
16764 assert_eq!(agg.pos_drafted[0], 3);
16765 assert_eq!(agg.pos_accepted[0], 3);
16766 assert_eq!(agg.pos_drafted[1], 1);
16767 assert_eq!(agg.pos_accepted[1], 0);
16768 }
16769
16770 /// Wrong-snapshot diff saturates to zero instead of wrapping — the counters feed a
16771 /// public metrics surface and must never publish a u64-wrapped garbage value.
16772 #[test]
16773 fn delta_saturates_never_wraps() {
16774 let small = SpecTelemetry {
16775 rounds: 1,
16776 drafted: 2,
16777 accepted: 1,
16778 ..Default::default()
16779 };
16780 let big = SpecTelemetry {
16781 rounds: 5,
16782 drafted: 15,
16783 accepted: 9,
16784 ..Default::default()
16785 };
16786 let d = small.delta_since(&big);
16787 assert_eq!((d.rounds, d.drafted, d.accepted), (0, 0, 0));
16788 }
16789}
16790
16791#[cfg(test)]
16792mod opti_fork_tests {
16793 use super::{
16794 OptiControllerPolicy, OptiForkAction, OptiForkGateMode, OptiForkGenerationTracker,
16795 };
16796
16797 #[test]
16798 fn controller_threshold_and_three_miss_breaker_are_exact() {
16799 let mut policy = OptiControllerPolicy {
16800 threshold: 0.7,
16801 consecutive_misses: 0,
16802 breaker_tripped: false,
16803 };
16804 assert!(!policy.admit(0.699_999));
16805 assert!(policy.admit(0.7));
16806 assert!(!policy.resolve(false));
16807 assert!(!policy.resolve(false));
16808 assert!(policy.resolve(false));
16809 assert!(policy.breaker_tripped);
16810 assert!(!policy.admit(1.0));
16811 assert!(
16812 !policy.resolve(true),
16813 "a resolved hit cannot re-arm a tripped request"
16814 );
16815 assert!(policy.breaker_tripped);
16816 }
16817
16818 #[test]
16819 fn zero_threshold_is_the_true_unconditional_measurement_arm() {
16820 let mut policy = OptiControllerPolicy {
16821 threshold: 0.0,
16822 consecutive_misses: 0,
16823 breaker_tripped: false,
16824 };
16825 for _ in 0..16 {
16826 assert!(policy.admit(0.0));
16827 assert!(!policy.resolve(false));
16828 }
16829 for invalid in [f32::NAN, f32::INFINITY, -0.01, 1.01] {
16830 assert!(
16831 !policy.admit(invalid),
16832 "invalid q proxy must fail closed: {invalid}"
16833 );
16834 }
16835 assert!(!policy.breaker_tripped);
16836 assert_eq!(policy.consecutive_misses, 0);
16837 }
16838
16839 #[test]
16840 fn alternating_mode_flips_by_generation_not_round_parity() {
16841 assert_eq!(OptiForkGateMode::Alternate.action(0), OptiForkAction::Hit);
16842 assert_eq!(OptiForkGateMode::Alternate.action(1), OptiForkAction::Miss);
16843 assert_eq!(OptiForkGateMode::Alternate.action(8), OptiForkAction::Hit);
16844 assert_eq!(OptiForkGateMode::Alternate.action(9), OptiForkAction::Miss);
16845 }
16846
16847 #[test]
16848 fn live_generation_cannot_be_overwritten() {
16849 let mut tracker = OptiForkGenerationTracker::default();
16850 let g0 = tracker.reserve().unwrap();
16851 let g1 = tracker.reserve().unwrap();
16852 let err = tracker.reserve().unwrap_err().to_string();
16853 assert!(
16854 err.contains("still owns generation 0"),
16855 "unexpected error: {err}"
16856 );
16857 tracker.retire(g0).unwrap();
16858 let g2 = tracker.reserve().unwrap();
16859 assert_eq!((g2.id, g2.slot), (2, 0));
16860 tracker.retire(g1).unwrap();
16861 tracker.retire(g2).unwrap();
16862 }
16863
16864 #[test]
16865 fn teardown_rejects_a_stale_generation_tag() {
16866 let mut tracker = OptiForkGenerationTracker::default();
16867 let g0 = tracker.reserve().unwrap();
16868 tracker.retire(g0).unwrap();
16869 let err = tracker.retire(g0).unwrap_err().to_string();
16870 assert!(err.contains("teardown mismatch"), "unexpected error: {err}");
16871 }
16872}
16873
16874#[cfg(test)]
16875mod draft_graph_fallback_tests {
16876 use super::DraftGraphFallback;
16877
16878 /// The Q2 contract, part (a): a fallback flip is LOUD — exactly once per flip.
16879 #[test]
16880 fn flip_is_loud_once_and_memoized_after() {
16881 let mut f = DraftGraphFallback::default();
16882 let line = f
16883 .mark_greedy("out of memory")
16884 .expect("first flip must return the warn line");
16885 assert!(
16886 line.contains("WARN"),
16887 "flip line must be warn-level: {line}"
16888 );
16889 assert!(
16890 line.contains("out of memory"),
16891 "flip line must carry the reason: {line}"
16892 );
16893 assert!(f.greedy_failed());
16894 // re-marking an already-failed graph is the memoization: quiet, still failed.
16895 assert!(f.mark_greedy("out of memory").is_none());
16896 assert!(f.greedy_failed());
16897 // the two graphs' flags are independent (greedy flip leaves sampled capturable).
16898 assert!(!f.sampled_failed());
16899 let line_s = f
16900 .mark_sampled("capture unsupported")
16901 .expect("sampled flip is its own flip");
16902 assert!(
16903 line_s.contains("sampled"),
16904 "sampled flip names itself: {line_s}"
16905 );
16906 assert!(f.mark_sampled("capture unsupported").is_none());
16907 }
16908
16909 /// The Q2 contract, part (b): resume-from-pool RESETS both flags (fresh capture chance),
16910 /// and says so exactly when there was something to reset.
16911 #[test]
16912 fn reset_on_resume_clears_flags_and_logs_once() {
16913 let mut f = DraftGraphFallback::default();
16914 // clean session: resume is silent, nothing to reset.
16915 assert!(f.reset_on_resume().is_none());
16916 f.mark_greedy("oom").unwrap();
16917 f.mark_sampled("oom").unwrap();
16918 let note = f
16919 .reset_on_resume()
16920 .expect("a set flag must produce the reset note");
16921 assert!(
16922 note.contains("greedy+sampled"),
16923 "note names what was reset: {note}"
16924 );
16925 assert!(
16926 !f.greedy_failed() && !f.sampled_failed(),
16927 "both flags cleared"
16928 );
16929 // and the NEXT failure after a reset is a fresh flip — loud again.
16930 assert!(f.mark_greedy("oom again").is_some());
16931 let note2 = f.reset_on_resume().expect("greedy-only reset");
16932 assert!(note2.contains("(greedy)"), "single-flag note: {note2}");
16933 }
16934
16935 /// Shape-change clears (dmask realloc / mask-shape mismatch / s_key change) stay silent —
16936 /// they precede a fresh capture attempt whose own failure re-flips loudly.
16937 #[test]
16938 fn shape_change_clears_are_silent() {
16939 let mut f = DraftGraphFallback::default();
16940 f.mark_greedy("oom").unwrap();
16941 f.clear_greedy();
16942 assert!(!f.greedy_failed());
16943 f.mark_sampled("oom").unwrap();
16944 f.clear_sampled();
16945 assert!(!f.sampled_failed());
16946 // after a silent clear there is nothing left for resume to report.
16947 assert!(f.reset_on_resume().is_none());
16948 }
16949}
16950
16951/// SAMPLED DRAFT-GRAPH KEY (lane/graph-s-key-exactness-20260819).
16952///
16953/// These are the CPU teeth for an exactness bug whose live reproduction needs a GPU, a trunk, a
16954/// drafter and a two-turn session: the key itself. Every test below fails against the pre-fix key
16955/// `(seed, temp.to_bits(), k)` — `legacy_key` restates it so the collision is explicit rather
16956/// than remembered.
16957#[cfg(test)]
16958mod sampled_graph_key_tests {
16959 use super::{SampledGraphKey, debug_t_pred0};
16960
16961 /// The pre-fix key, verbatim: `let s_key = (sp_seed, sp_temp.to_bits(), k);`
16962 fn legacy_key(k: &SampledGraphKey) -> (u64, u32, usize) {
16963 (k.seed, k.temp_bits, k.k)
16964 }
16965
16966 fn pure_temp_key() -> SampledGraphKey {
16967 // temperature 1.0, filters off — today's serve default, the shape that parks a graph.
16968 SampledGraphKey::new(12345, 1.0, 3, 0, 1.0, 0.0, false)
16969 }
16970
16971 /// THE COLLISION. Two requests that differ ONLY in the truncation filters shared one key, so
16972 /// a parked pure-temp graph survived into a filtered request and the launch site launched it.
16973 #[test]
16974 fn vendor_filters_change_the_key() {
16975 let parked = pure_temp_key();
16976 // qwen3.8 generation_config.json — what the vendor-default flip makes the default shape.
16977 let vendor = SampledGraphKey::new(12345, 1.0, 3, 20, 0.95, 0.0, false);
16978 assert_eq!(
16979 legacy_key(&parked),
16980 legacy_key(&vendor),
16981 "pre-fix key collided: this is the bug, and the reason a test asserts on it",
16982 );
16983 assert_ne!(parked, vendor, "post-fix key must separate the two regimes");
16984 assert!(parked.pure_temp());
16985 assert!(!vendor.pure_temp());
16986 }
16987
16988 /// Each distribution-shaping field alone is enough to drop the parked graph.
16989 #[test]
16990 fn every_filter_field_is_keyed() {
16991 let base = pure_temp_key();
16992 for (what, other) in [
16993 (
16994 "top_k",
16995 SampledGraphKey::new(12345, 1.0, 3, 20, 1.0, 0.0, false),
16996 ),
16997 (
16998 "top_p",
16999 SampledGraphKey::new(12345, 1.0, 3, 0, 0.95, 0.0, false),
17000 ),
17001 (
17002 "min_p",
17003 SampledGraphKey::new(12345, 1.0, 3, 0, 1.0, 0.05, false),
17004 ),
17005 (
17006 "penalties",
17007 SampledGraphKey::new(12345, 1.0, 3, 0, 1.0, 0.0, true),
17008 ),
17009 ] {
17010 assert_ne!(base, other, "{what} must be part of the key");
17011 assert!(!other.pure_temp(), "{what} leaves the pure-temp regime");
17012 assert_eq!(
17013 legacy_key(&base),
17014 legacy_key(&other),
17015 "{what} was invisible to the pre-fix key",
17016 );
17017 }
17018 }
17019
17020 /// The baked constants stay keyed (this half was always right — regression cover for it).
17021 #[test]
17022 fn baked_constants_stay_keyed() {
17023 let base = pure_temp_key();
17024 assert_ne!(
17025 base,
17026 SampledGraphKey::new(999, 1.0, 3, 0, 1.0, 0.0, false),
17027 "seed"
17028 );
17029 assert_ne!(
17030 base,
17031 SampledGraphKey::new(12345, 0.7, 3, 0, 1.0, 0.0, false),
17032 "temp"
17033 );
17034 assert_ne!(
17035 base,
17036 SampledGraphKey::new(12345, 1.0, 4, 0, 1.0, 0.0, false),
17037 "k"
17038 );
17039 // bitwise on temperature: 0.7f32 vs the same value re-derived must NOT differ.
17040 assert_eq!(
17041 SampledGraphKey::new(1, 0.7, 3, 0, 1.0, 0.0, false),
17042 SampledGraphKey::new(1, 7.0 / 10.0, 3, 0, 1.0, 0.0, false),
17043 );
17044 }
17045
17046 /// THE LOAD-BEARING HALF OF THE SEED DECISION (lane/session-resume-sampler-predicate-
17047 /// 20260820). The whole-session resume predicate deliberately does NOT compare `seed`: an
17048 /// omitted serve `seed` draws fresh per-request entropy, so comparing it would refuse every
17049 /// seed-omitting sampled conversation. That is only sound because the one piece of parked state
17050 /// that BAKES the seed — this graph — is re-keyed on it, so a seed change drops and recaptures.
17051 ///
17052 /// This test is the other end of that argument, asserted here rather than remembered in a
17053 /// comment: if a future change dropped `seed` from the key, the resume predicate's exclusion
17054 /// would silently become the unsound thing it is documented not to be.
17055 /// (Paired with `seed_alone_does_not_refuse` in `memra-sampling`.)
17056 #[test]
17057 fn seed_alone_still_rekeys_the_draft_graph() {
17058 let parked = pure_temp_key();
17059 let reseeded = SampledGraphKey::new(999, 1.0, 3, 0, 1.0, 0.0, false);
17060 assert_ne!(
17061 parked, reseeded,
17062 "a seed-only change MUST drop the parked sampled graph — the resume predicate's \
17063 decision not to compare seed rests on exactly this",
17064 );
17065 // Same regime on both sides: the drop is a recapture, not a fall to the eager chain
17066 // because of a filter difference.
17067 assert!(parked.pure_temp() && reseeded.pure_temp());
17068 }
17069
17070 /// `pure_temp()` is the capture guard's predicate, computed from the key so the two cannot
17071 /// drift. The equality below is the invariant the launch-site guard asserts: identical keys
17072 /// agree on the regime, so a graph that survives the drop is legal to launch.
17073 #[test]
17074 fn equal_keys_agree_on_the_regime() {
17075 let a = SampledGraphKey::new(7, 0.8, 3, 20, 0.95, 0.0, false);
17076 let b = SampledGraphKey::new(7, 0.8, 3, 20, 0.95, 0.0, false);
17077 assert_eq!(a, b);
17078 assert_eq!(a.pure_temp(), b.pure_temp());
17079 // top_p slightly above 1.0 (a client sending 1.0 exactly, or an operator default) is
17080 // still the unfiltered regime, matching the original `sp.top_p >= 1.0` test.
17081 assert!(SampledGraphKey::new(7, 0.8, 3, 0, 1.0, 0.0, false).pure_temp());
17082 assert!(SampledGraphKey::new(7, 0.8, 3, 0, 1.5, -1.0, false).pure_temp());
17083 }
17084
17085 /// The WIDENED capture regime (lane/step37-draft-graph-serving-20260830): truncation-
17086 /// filtered shapes are capturable — the filter runs IN-GRAPH (`filter_stats` +
17087 /// `gumbel_perturb_filtered_ctr`), so the draft draws from the same filtered
17088 /// distribution the accept test reconstructs. Penalties never are: the per-round
17089 /// history cannot be baked. The step37 vendor-default shape (temp 0.5 / top_p 0.9) is
17090 /// exactly the previously-excluded regime this lane exists to capture.
17091 #[test]
17092 fn filtered_regimes_are_capturable_penalties_never() {
17093 let vendor = SampledGraphKey::new(12345, 0.5, 3, 0, 0.9, 0.0, false);
17094 assert!(!vendor.pure_temp());
17095 assert!(vendor.filtered());
17096 assert!(
17097 vendor.graph_capturable(),
17098 "the vendor-default filtered shape must be capturable (default door state)",
17099 );
17100 assert!(pure_temp_key().graph_capturable());
17101 assert!(
17102 !pure_temp_key().filtered(),
17103 "pure-temp takes the legacy (filterless) capture body",
17104 );
17105 let pen = SampledGraphKey::new(12345, 0.5, 3, 0, 0.9, 0.0, true);
17106 assert!(
17107 !pen.graph_capturable(),
17108 "penalty history varies per round and can never be baked into a graph",
17109 );
17110 }
17111
17112 /// MEMRA_DEBUG_SPEC on a SAMPLED spec request past round 0: the print must render without
17113 /// indexing the empty greedy `preds` vector (it panicked the GPU worker before this lane).
17114 #[test]
17115 fn debug_print_survives_the_sampled_arm() {
17116 // round >= 1 with a pending bonus == base 1, sampled == `preds` empty.
17117 assert_eq!(debug_t_pred0(true, 1, 4242, &[]), "n/a");
17118 assert_eq!(debug_t_pred0(true, 2, 4242, &[]), "n/a");
17119 // round 0 without a pending bonus still reports last_pred, in both arms.
17120 assert_eq!(debug_t_pred0(true, 0, 4242, &[]), "4242");
17121 assert_eq!(debug_t_pred0(false, 0, 4242, &[7, 8]), "4242");
17122 // greedy keeps the real prediction it always printed.
17123 assert_eq!(debug_t_pred0(false, 1, 4242, &[7, 8]), "7");
17124 assert_eq!(debug_t_pred0(false, 2, 4242, &[7, 8]), "8");
17125 }
17126}