memra_engine/dflash.rs
1//! DFlash block-diffusion drafter (DFLASH-BRINGUP-PLAN.md, 2026-07-13).
2//!
3//! 5-layer qwen3-class mini-transformer that drafts a 16-token block in ONE non-causal
4//! forward, conditioned on the TARGET's hidden states at 6 tapped layers (concatenated
5//! through `fc` + `hidden_norm`). No embed / lm_head of its own — the round reuses the
6//! target's. Reference: z-lab/dflash `dflash/model.py` (semantics frozen in the plan doc);
7//! oracle: tools/dflash_oracle.py -> /data/cache/dflash-oracle.npz.
8//!
9//! FIRST LIGHT = f32-resident weights + fresh full-context forward (no draft KV cache) —
10//! correctness vs the oracle, then the cache/quant/window arms land measurement-gated.
11
12use crate::Engine;
13use crate::model::GpuTensor;
14use cudarc::driver::CudaSlice;
15
16pub struct DflashCfg {
17 pub hidden: usize, // 5376
18 pub n_head: usize, // 64
19 pub n_kv: usize, // 8
20 pub head_dim: usize, // 128
21 pub n_ff: usize, // 10752
22 pub n_layer: usize, // 5
23 pub eps: f32, // 1e-6
24 pub rope_theta: f32, // 1e6
25 pub block_size: usize, // 16
26 pub mask_token_id: u32, // 4
27 pub target_layer_ids: Vec<usize>, // [1,12,23,35,46,57]
28 pub sliding_window: usize, // 2048
29 /// true = sliding_attention for that layer (4x true + 1x false on the 31B draft).
30 pub layer_sliding: Vec<bool>,
31 /// Checkpoint training-strategy census (`dspark_strategy_census` over the raw
32 /// config.json): true = a SpecForge DSPARK-strategy export (shifted labels, ALL rows
33 /// supervised — the q38 arm-a family). Keys the HARVEST DEFAULT strategy-keyed,
34 /// never env-keyed (owner-ratified 2026-08-20 after B1 confirmed H1 ×5;
35 /// DSPARK-POSTMORTEM-20260820.md B0 default-flip plan).
36 pub strategy_dspark: bool,
37 /// Explicit top-level `is_causal` from config.json (z-lab reference: an explicit
38 /// value OVERRIDES the per-layer-type default). The DFlash2 q38 checkpoint carries
39 /// `"is_causal": false` — every sliding layer is NON-causal with a symmetric
40 /// +/-2048 window (model.py `_attention_mask`). None = key absent (historical
41 /// exports; the windowless-assert arm keeps handling those byte-identically).
42 pub is_causal: Option<bool>,
43}
44
45pub struct DflashLayer {
46 pub wq: GpuTensor, // [nh*hd, hidden] row-major (out_f rows)
47 pub wk: GpuTensor, // [nkv*hd, hidden]
48 pub wv: GpuTensor, // [nkv*hd, hidden]
49 pub wo: GpuTensor, // [hidden, nh*hd]
50 pub w_gate: GpuTensor, // [n_ff, hidden]
51 pub w_up: GpuTensor, // [n_ff, hidden]
52 pub w_down: GpuTensor, // [hidden, n_ff]
53 pub ln_in: CudaSlice<f32>, // [hidden]
54 pub ln_post: CudaSlice<f32>, // [hidden]
55 pub q_norm: CudaSlice<f32>, // [hd]
56 pub k_norm: CudaSlice<f32>, // [hd]
57}
58
59pub struct DflashDraft {
60 pub cfg: DflashCfg,
61 pub layers: Vec<DflashLayer>,
62 pub fc: GpuTensor, // [hidden, n_taps*hidden]
63 pub hidden_norm: CudaSlice<f32>, // [hidden]
64 pub norm: CudaSlice<f32>, // [hidden]
65 /// DSpark semi-AR markov head (present in the repo-root checkpoint variant):
66 /// draft logits at position k get + W2(W1[prev_realized_token]) — left-to-right
67 /// within the block (the patch's _markov_semiar_sample_block semantics, greedy).
68 /// w1 = raw bf16 [V, rank] (row-gathered by device token id); w2 = q8_0 [rank->V].
69 pub markov: Option<MarkovHead>,
70 /// DSpark accept-rate head (trained with confidence loss). sglang's DSPARK planner
71 /// consumes it to SIZE VERIFY WINDOWS (cumprod survival — v0.5.16 headline; the
72 /// earlier "reference serving loop never consumes it" note matched SpecForge's
73 /// legacy spec_generate only). memra schedules with it under
74 /// `MEMRA_DSPARK_VT=confidence` (the H4 fix, DSPARK-POSTMORTEM-20260820.md:
75 /// per-round verify window from cumprod survival, `dspark_confidence_vt`) and
76 /// keeps it census+parity-only under the default ladder. Host-resident (5k floats).
77 pub confidence: Option<ConfidenceHead>,
78 /// YaRN rope (q38 arm-a inherits the target's rope_parameters: rope_type yarn,
79 /// factor 32, original 8192, beta 32/1). ff = per-dim divisors for rope_neox_ff
80 /// (effective inv_freq_j = base^(-2j/d)/ff[j] = the HF-yarn remapped frequency,
81 /// verified vs Qwen3RotaryEmbedding to 1.6e-7), mscale = attention_scaling
82 /// (0.1*ln(factor)+1) applied to q/k post-rope — cos/sin scaling distributes onto
83 /// the rotated vector exactly. None = plain rope (gemma/z-lab drafters).
84 pub rope_yarn: Option<(CudaSlice<f32>, f32)>,
85 /// DFlash2 head (z-lab `DFlash2DraftModel`, DFLASH2-EVAL-20260820.md): grouped
86 /// dynamic causal convs around EVERY sublayer + the candidate path selector that
87 /// replaces the markov chain. A DISTINCT semantic program from the DSpark head
88 /// (no-generic-support law): present iff config `architectures` names
89 /// `DFlash2DraftModel`, and then ALL 23 family tensors are REQUIRED — loading the
90 /// 58 backbone tensors alone computes an untrained model (the census trap).
91 pub dflash2: Option<Dflash2Head>,
92}
93
94/// One `GroupedDynamicCausalConv` module (reference model.py): a causal 2-tap
95/// depthwise conv over the BLOCK rows (block-local — row 0 zero-pads its missing
96/// predecessor; stateless across rounds), with per-position dynamic per-group
97/// coefficients projected from the module INPUT. `prepare` convolves the sublayer
98/// input with base_kernel[0] + dyn half 0; `finish` convolves the sublayer OUTPUT
99/// with base_kernel[1] + dyn half 1 (both dyn halves come from the SAME projection
100/// of the pre-conv input).
101pub struct Dflash2Conv {
102 /// base_kernel [2, k, hidden] flattened f32 (half-major: prepare then finish).
103 pub base: CudaSlice<f32>,
104 /// kernel_projection.weight [2*k*groups, hidden] (row layout = view(2, k, groups)).
105 pub proj: GpuTensor,
106}
107
108pub struct Dflash2Head {
109 pub attn_conv: Vec<Dflash2Conv>, // per layer
110 pub mlp_conv: Vec<Dflash2Conv>, // per layer
111 /// candidate_selector.hidden_projection.weight [rank, hidden].
112 pub hidden_proj: GpuTensor,
113 /// Codebooks [V, rank] raw bf16, HOST-resident: the walk gathers ~1+16 rows per
114 /// draft slot (~70KB/round) — host math beside the round's existing chain dtoh,
115 /// no device residency for 2x127MB tables. Checkpoint quirk: stored WITHOUT the
116 /// `.weight` suffix (reference from_pretrained installs a key_mapping).
117 pub pred_codebook: Vec<u8>,
118 pub succ_codebook: Vec<u8>,
119 pub rank: usize, // selector_rank 256
120 pub top_k: usize, // selector_top_k 16
121 pub conv_k: usize, // conv_kernel_size 2
122 pub group_size: usize, // conv_group_size 16
123 pub vocab: usize, // codebook rows (248320)
124}
125
126/// Resolve the named DFlash weight program. Keep this separate from loading so a typo cannot
127/// silently select q8 and invalidate a performance/default receipt.
128fn dflash_precision(raw: Option<&str>) -> Result<&str, String> {
129 let prec = raw.unwrap_or("q4");
130 match prec {
131 "q4" | "q8" | "mixed" | "bf16" | "fc" => Ok(prec),
132 other => Err(format!(
133 "MEMRA_DFLASH_PREC={other:?}: want q4, q8, mixed, bf16, or fc \
134 (q5 was measured defective and is not a serving mode)"
135 )),
136 }
137}
138
139/// One bf16 codebook row -> f32 (exact widening).
140fn cb_row(cb: &[u8], tok: usize, rank: usize) -> Vec<f32> {
141 bf16_to_f32(&cb[tok * rank * 2..(tok + 1) * rank * 2])
142}
143
144/// Greedy selector walk (reference `CandidateSelector.select` at T=0): per draft
145/// slot p, score(k) = unary[p,k] + <pred_codebook[prev] .* hidden_proj_row[p],
146/// succ_codebook[cand[p,k]]>, argmax over the top-k candidate set; the CHOSEN
147/// candidate seeds the next slot (sequential — the chain is the semantics, not an
148/// optimization). Host math (~nd*k*rank fused ops per round) over host-resident bf16
149/// codebooks; ties break to the LOWEST k (torch argmax convention). Pure so the
150/// selector semantics are CPU-gateable.
151///
152/// `unary`/`cand`: [nd, top_k] row-major; `hproj`: [nd, rank] row-major.
153#[allow(clippy::too_many_arguments)]
154pub fn dflash2_walk_greedy(
155 pred_codebook: &[u8],
156 succ_codebook: &[u8],
157 vocab: usize,
158 rank: usize,
159 top_k: usize,
160 unary: &[f32],
161 cand: &[u32],
162 hproj: &[f32],
163 anchor: u32,
164 nd: usize,
165) -> Vec<u32> {
166 let (kk, r) = (top_k, rank);
167 assert_eq!(unary.len(), nd * kk, "walk: unary shape");
168 assert_eq!(cand.len(), nd * kk, "walk: candidate shape");
169 assert_eq!(hproj.len(), nd * r, "walk: hidden-projection shape");
170 let mut path = Vec::with_capacity(nd);
171 let mut prev = anchor;
172 for p in 0..nd {
173 assert!(
174 (prev as usize) < vocab,
175 "walk: predecessor token {prev} outside codebook vocab {vocab}"
176 );
177 let pr = cb_row(pred_codebook, prev as usize, r);
178 let hp = &hproj[p * r..(p + 1) * r];
179 // gate = pred_row .* hidden_proj (shared across the candidate set)
180 let gate: Vec<f32> = pr.iter().zip(hp).map(|(a, b)| a * b).collect();
181 let (mut best, mut bi) = (f32::NEG_INFINITY, 0usize);
182 for k in 0..kk {
183 let c = cand[p * kk + k] as usize;
184 assert!(c < vocab, "walk: candidate {c} outside codebook vocab");
185 let sr = cb_row(succ_codebook, c, r);
186 let mut s = unary[p * kk + k];
187 for j in 0..r {
188 s += gate[j] * sr[j];
189 }
190 if s > best {
191 best = s;
192 bi = k;
193 }
194 }
195 prev = cand[p * kk + bi];
196 path.push(prev);
197 }
198 path
199}
200
201impl Dflash2Head {
202 /// Greedy selector walk over this head's codebooks — see `dflash2_walk_greedy`.
203 pub fn walk_greedy(
204 &self,
205 unary: &[f32],
206 cand: &[u32],
207 hproj: &[f32],
208 anchor: u32,
209 nd: usize,
210 ) -> Vec<u32> {
211 dflash2_walk_greedy(
212 &self.pred_codebook,
213 &self.succ_codebook,
214 self.vocab,
215 self.rank,
216 self.top_k,
217 unary,
218 cand,
219 hproj,
220 anchor,
221 nd,
222 )
223 }
224
225 /// Sampled (T>0) selector walk — see `dflash2_walk_sampled`.
226 #[allow(clippy::too_many_arguments)]
227 pub fn walk_sampled(
228 &self,
229 unary: &[f32],
230 cand: &[u32],
231 hproj: &[f32],
232 anchor: u32,
233 nd: usize,
234 temp: f32,
235 uniforms: &mut dyn FnMut() -> f32,
236 ) -> (Vec<u32>, Vec<f32>, Vec<f32>) {
237 dflash2_walk_sampled(
238 &self.pred_codebook,
239 &self.succ_codebook,
240 self.vocab,
241 self.rank,
242 self.top_k,
243 unary,
244 cand,
245 hproj,
246 anchor,
247 nd,
248 temp,
249 uniforms,
250 )
251 }
252}
253
254/// AcceptRatePredictor: raw linear proj over [hidden ; markov_prev_embedding(rank)]
255/// (with_markov=true on the q38 arm-a export) — output is the PRE-sigmoid scalar.
256pub struct ConfidenceHead {
257 pub w: Vec<f32>, // [in_dim]
258 pub b: f32,
259 pub in_dim: usize,
260 pub with_markov: bool,
261}
262
263impl ConfidenceHead {
264 /// Host dot: the PRE-sigmoid accept score for one draft slot. `hidden` = the
265 /// drafter output row the slot is harvested from (the same row its logits use);
266 /// `emb` = the markov `w1` row of the slot's PREVIOUS chain token (required iff
267 /// `with_markov`) — the exact input contract the parity gate pins (prev ids =
268 /// `[anchor, chain[..nd-1]]`, dspark_q38_parity.rs stage 5).
269 pub fn raw_score(&self, hidden: &[f32], emb: Option<&[f32]>) -> f32 {
270 let mut acc = self.b;
271 for (w, x) in self.w.iter().zip(hidden) {
272 acc += w * x;
273 }
274 if self.with_markov {
275 let emb = emb.expect("with_markov confidence head scored without the markov embedding");
276 debug_assert_eq!(hidden.len() + emb.len(), self.in_dim);
277 for (w, x) in self.w[hidden.len()..].iter().zip(emb) {
278 acc += w * x;
279 }
280 } else {
281 debug_assert_eq!(hidden.len(), self.in_dim);
282 }
283 acc
284 }
285}
286
287pub struct MarkovHead {
288 pub w1_bf16: CudaSlice<u8>, // [V, rank] bf16 raw
289 pub w2: GpuTensor, // [rank -> V] q8_0
290 pub rank: usize,
291 pub vocab: usize,
292}
293
294/// Draft-row harvest convention for DFlash-family block drafters
295/// (darklanes research/deepseek-flash-20260818/DSPARK-POSTMORTEM-20260820.md).
296///
297/// The DFlash and DSpark SpecForge training strategies supervise DIFFERENT rows of the
298/// same `[anchor, MASK x b-1]` block, so the row -> trunk-position mapping is a property
299/// of the CHECKPOINT's training strategy, not of the loader:
300///
301/// - **Dflash** (mask-fill; z-lab dflash / SpecForge `OnlineDFlashModel`): row k is
302/// trained to predict the token AT position anchor+k — "Labels: same-position
303/// prediction", `weight_mask *= (pos_in_block > 0)` excludes the anchor row
304/// (SpecForge `specforge/algorithms/common/dflash_family_model.py:453-472`).
305/// Drafts = rows 1..b-1; the anchor row's output is untrained.
306/// - **Dspark** (shifted; SpecForge `OnlineDSparkModel`, `training.strategy: dspark` —
307/// the q38 arm-a export): row k is trained to predict the token at anchor+k+1, ALL
308/// rows supervised INCLUDING the anchor row (`label_offsets = arange(1,
309/// block_size+1)`, `dflash_family_model.py:816`). sglang's DSPARK worker — the stack
310/// every arm-a bank number was measured on — harvests gamma = block_size drafts with
311/// the anchor row's output as draft 1 (verified on the v0.5.17 eval-pin tag:
312/// `dspark_components/dspark_draft.py:248,260,318`; `dspark_config.py:269`).
313///
314/// Mismatching the convention verifies every slot against a position the row was never
315/// trained for — the q38 accept collapse (2.9 -> 1.43) in the postmortem.
316#[derive(Clone, Copy, PartialEq, Eq, Debug)]
317pub enum DsparkHarvest {
318 /// mask-fill: drafts = rows 1..b-1, row k fills position anchor+k.
319 Dflash,
320 /// shifted: drafts = rows 0..b-1, row k predicts position anchor+k+1.
321 Dspark,
322}
323
324impl DsparkHarvest {
325 /// The served resolution: explicit `MEMRA_DSPARK_HARVEST={dflash|dspark}` wins
326 /// (unknown values REFUSE loudly — a typo silently reverting the convention would
327 /// re-open the postmortem's misalignment); UNSET defers to the CHECKPOINT's own
328 /// training-strategy census — the owner-ratified default flip (2026-08-20, after
329 /// B1 confirmed H1 interleaved ×5 on serving-class hardware: accept 1.38→2.41
330 /// agentic / 1.53→3.66 math, E2E ALL EXACT both arms). Strategy-keyed, not
331 /// env-keyed, per the B0 plan: a DSPARK-strategy export harvests shifted
332 /// (all-rows), a mask-fill export keeps the historical dflash arm byte-identical.
333 pub fn resolve(cfg: &DflashCfg) -> Self {
334 Self::resolve_value(
335 std::env::var("MEMRA_DSPARK_HARVEST").ok().as_deref(),
336 cfg.strategy_dspark,
337 )
338 }
339
340 pub fn resolve_value(v: Option<&str>, strategy_dspark: bool) -> Self {
341 match v {
342 None | Some("") => {
343 if strategy_dspark {
344 DsparkHarvest::Dspark
345 } else {
346 DsparkHarvest::Dflash
347 }
348 }
349 set => Self::from_env_value(set),
350 }
351 }
352
353 /// ENV-ONLY parser (no checkpoint census): unset = `Dflash`, the historical arm.
354 /// Kept for the explicit-value path of [`Self::resolve_value`] and the seam tests;
355 /// round arms resolve through [`Self::resolve`] so the default stays strategy-keyed.
356 pub fn from_env_value(v: Option<&str>) -> Self {
357 match v {
358 None | Some("") | Some("dflash") => DsparkHarvest::Dflash,
359 Some("dspark") => DsparkHarvest::Dspark,
360 Some(other) => panic!(
361 "MEMRA_DSPARK_HARVEST={other}: unknown harvest convention (dflash|dspark); \
362 refusing — a wrong convention verifies every draft slot against a position \
363 the drafter row was not trained for (DSPARK-POSTMORTEM-20260820.md)"
364 ),
365 }
366 }
367
368 /// Resolve the harvest convention for a LOADED drafter — FAMILY-keyed first, then
369 /// STRATEGY-keyed (v0.100 train merge of the two ratified keyings):
370 /// - DFlash2 is a mask-fill-family drafter by construction (reference
371 /// `dflash_generate` harvests rows `1-verify_size:`; the card says "block size 8
372 /// (7 draft tokens per verification step)" — DFLASH2-EVAL-20260820.md §3). An env
373 /// value that CONTRADICTS the census REFUSES rather than silently re-keying the
374 /// round.
375 /// - Every other checkpoint rides [`Self::resolve_value`]: explicit env wins (typos
376 /// refuse loudly), unset defers to the checkpoint's own training-strategy census
377 /// (the owner-ratified 2026-08-20 default flip).
378 pub fn for_draft(draft: &DflashDraft) -> Self {
379 Self::for_family_value(
380 draft.dflash2.is_some(),
381 std::env::var("MEMRA_DSPARK_HARVEST").ok().as_deref(),
382 draft.cfg.strategy_dspark,
383 )
384 }
385
386 pub fn for_family_value(is_dflash2: bool, env: Option<&str>, strategy_dspark: bool) -> Self {
387 if is_dflash2 {
388 if env == Some("dspark") {
389 panic!(
390 "MEMRA_DSPARK_HARVEST=dspark with a DFlash2 checkpoint: DFlash2 \
391 is mask-fill (b-1 drafts, anchor row is not a draft — reference \
392 dflash_generate rows 1-verify_size:); the shifted harvest would \
393 verify every slot one position early. Refusing (census-keyed, \
394 not env-keyed)."
395 );
396 }
397 return DsparkHarvest::Dflash;
398 }
399 Self::resolve_value(env, strategy_dspark)
400 }
401
402 /// Manifest/serialized name (the oracle geometry manifest's `harvest` field).
403 pub fn name(self) -> &'static str {
404 match self {
405 DsparkHarvest::Dflash => "dflash",
406 DsparkHarvest::Dspark => "dspark",
407 }
408 }
409
410 pub fn from_name(v: &str) -> Option<Self> {
411 match v {
412 "dflash" => Some(DsparkHarvest::Dflash),
413 "dspark" => Some(DsparkHarvest::Dspark),
414 _ => None,
415 }
416 }
417
418 /// First drafter OUTPUT row consumed as a draft candidate.
419 pub fn first_row(self) -> usize {
420 match self {
421 DsparkHarvest::Dflash => 1,
422 DsparkHarvest::Dspark => 0,
423 }
424 }
425
426 /// Drafted tokens harvested per round from a `b`-row block.
427 pub fn n_drafts(self, b: usize) -> usize {
428 match self {
429 DsparkHarvest::Dflash => b - 1,
430 DsparkHarvest::Dspark => b,
431 }
432 }
433
434 /// The position offset (relative to the round anchor at the block's row 0) that
435 /// drafter output row `row` is TRAINED to predict under this convention.
436 pub fn trained_offset_of_row(self, row: usize) -> usize {
437 match self {
438 DsparkHarvest::Dflash => row,
439 DsparkHarvest::Dspark => row + 1,
440 }
441 }
442}
443
444/// Checkpoint training-strategy census over the raw config.json text (the loader's
445/// minimal-extractor idiom — no json dep in-tree). TRUE iff the export declares the
446/// DSPARK strategy: `architectures` naming a DSpark model class (`Qwen3DSparkModel`,
447/// the SpecForge OnlineDSparkModel export form) or `dflash_config.projector_type ==
448/// "dspark"`. z-lab / OnlineDFlashModel mask-fill exports carry neither signal. Pure,
449/// so the census is testable against config fragments without files.
450pub fn dspark_strategy_census(txt: &str) -> bool {
451 let arch = txt
452 .find("\"architectures\"")
453 .and_then(|i| {
454 let rest = &txt[i..];
455 let a = rest.find('[')?;
456 let b = rest.find(']')?;
457 Some(rest[a..b].contains("DSpark"))
458 })
459 .unwrap_or(false);
460 let proj = txt
461 .find("\"projector_type\"")
462 .map(|i| {
463 let rest = &txt[i..];
464 let after = rest.find(':').map(|c| &rest[c + 1..]).unwrap_or("");
465 after.trim_start().starts_with("\"dspark\"")
466 })
467 .unwrap_or(false);
468 arch || proj
469}
470
471/// Accepted-prefix length of a round's candidates against the trunk's verify argmaxes:
472/// `cand[0]` = the round anchor (already decided), `cand[1..]` = the drafts;
473/// `vam[j]` = the trunk's argmax prediction for position anchor+j+1. Returns m =
474/// number of accepted drafts (`cand[1..=m]` committed, `vam[m]` becomes the next
475/// anchor). Pure so the harvest-alignment fixture can exercise it CPU-side.
476pub fn dspark_accept_prefix(cand: &[u32], vam: &[u32], vt: usize) -> usize {
477 let mut m = 0usize;
478 while m < vt - 1 && cand[m + 1] == vam[m] {
479 m += 1;
480 }
481 m
482}
483
484/// Verify-window policy for the dspark round (H4, DSPARK-POSTMORTEM-20260820.md §3).
485///
486/// B2 measured the structural fork: the fixed full-block window (vt=8) buys 95–100%
487/// of the sglang accept bank but LOSES wall speed to the reactive ladder everywhere
488/// except math — at 0.2–0.5 slot rates, full-block verify pays 5–6 empty rows per
489/// round. The confidence policy is the mechanism both leading engines schedule with
490/// (sglang v0.5.16 `dspark_planner.py` cumprod survival; vLLM #47808): size EACH
491/// round's window from the drafter's own trained accept-rate head, so windows open
492/// on confident streaks (math/code) and shrink on bursty text without a 4-round
493/// ladder climb.
494#[derive(Clone, Copy, PartialEq, Debug)]
495pub enum DsparkVtPolicy {
496 /// The shipped reactive ladder: `vt = (m+2).clamp(3, vt_cap)` per round
497 /// (`MEMRA_DFLASH_ADAPT=0` pins vt at `vt_cap` = the fixed-window arm).
498 Ladder,
499 /// `MEMRA_DSPARK_VT=confidence`: per-round window from cumprod survival of the
500 /// confidence head's sigmoid scores, thresholded at `tau`
501 /// (`MEMRA_DSPARK_VT_TAU`, default 0.5). Raw sigmoid — no STS sidecar
502 /// calibration exists for this export; the postmortem names this the starting
503 /// policy.
504 Confidence { tau: f32 },
505 /// `MEMRA_DSPARK_VT=confidence-slot` (owner directive, 2026-08-20: "take only
506 /// high confidence offers"): submit only the longest draft PREFIX whose every
507 /// slot clears `tau` on its own sigmoid — the low-confidence tail never enters
508 /// verify. Same tau env. vs `Confidence`: if the head's per-row score is the
509 /// MARGINAL accept probability (it already sinks with depth), cumprod survival
510 /// double-counts the decay and over-truncates; if it is the CONDITIONAL,
511 /// per-slot under-truncates. Which statistic the q38 head emits is empirical —
512 /// both arms ride the A/B.
513 ConfidenceSlot { tau: f32 },
514}
515
516impl DsparkVtPolicy {
517 /// The served resolution: explicit `MEMRA_DSPARK_VT={ladder|confidence|
518 /// confidence-slot}` wins (unknown values REFUSE loudly — a typo silently
519 /// reverting the window policy would invalidate an A/B without a trace); UNSET
520 /// defaults to **`confidence-slot` at τ = `MEMRA_DSPARK_VT_TAU` (default 0.5)** —
521 /// the owner-ratified H4 flip (2026-08-20; cell 2's 4-arm A/B ×5 + cell 3's tau
522 /// ladder put the knee at τ=.5 for the slot arm: 94–98% of the fixed-8 accept bank
523 /// at wall ≥ the reactive ladder, exactness 11/11 ALL EXACT). Census-keyed per the
524 /// capacity-keyed-defaults law: a checkpoint WITHOUT an accept-rate head has no
525 /// signal to schedule with, so unset-env resolves to the ladder there (loudly, at
526 /// load) instead of panicking on a default; `MEMRA_DFLASH_ADAPT=0` (an explicit
527 /// fixed-window request) also keeps the ladder-family arm.
528 pub fn resolve(has_confidence_head: bool) -> Self {
529 Self::resolve_value(
530 std::env::var("MEMRA_DSPARK_VT").ok().as_deref(),
531 std::env::var("MEMRA_DSPARK_VT_TAU").ok().as_deref(),
532 std::env::var("MEMRA_DFLASH_ADAPT").ok().as_deref(),
533 has_confidence_head,
534 )
535 }
536
537 pub fn resolve_value(
538 vt: Option<&str>,
539 tau: Option<&str>,
540 adapt: Option<&str>,
541 has_confidence_head: bool,
542 ) -> Self {
543 match vt {
544 None | Some("") => {
545 if adapt == Some("0") || !has_confidence_head {
546 DsparkVtPolicy::Ladder
547 } else {
548 // The ratified default rides the SAME tau parse as the explicit
549 // arm (a bad MEMRA_DSPARK_VT_TAU refuses, never silently ignored).
550 Self::from_env_value(Some("confidence-slot"), tau, adapt)
551 }
552 }
553 set => Self::from_env_value(set, tau, adapt),
554 }
555 }
556
557 /// ENV-ONLY parser (no head census): unset = `Ladder`. Kept for the explicit-value
558 /// path of [`Self::resolve_value`] and the policy-gate tests; round arms resolve
559 /// through [`Self::resolve`] so the default stays head-census-keyed.
560 pub fn from_env_value(vt: Option<&str>, tau: Option<&str>, adapt: Option<&str>) -> Self {
561 match vt {
562 None | Some("") | Some("ladder") => DsparkVtPolicy::Ladder,
563 Some(mode @ ("confidence" | "confidence-slot")) => {
564 if adapt == Some("0") {
565 panic!(
566 "MEMRA_DSPARK_VT={mode} together with MEMRA_DFLASH_ADAPT=0 is \
567 contradictory (a pinned fixed window vs a per-round confidence \
568 window); unset one — refuse-on-ambiguity"
569 );
570 }
571 let tau = tau
572 .map(|t| {
573 t.parse::<f32>()
574 .unwrap_or_else(|_| panic!("MEMRA_DSPARK_VT_TAU={t}: not a float"))
575 })
576 .unwrap_or(0.5);
577 assert!(
578 tau > 0.0 && tau < 1.0,
579 "MEMRA_DSPARK_VT_TAU={tau}: confidence threshold must be in (0,1)"
580 );
581 if mode == "confidence" {
582 DsparkVtPolicy::Confidence { tau }
583 } else {
584 DsparkVtPolicy::ConfidenceSlot { tau }
585 }
586 }
587 Some(other) => panic!(
588 "MEMRA_DSPARK_VT={other}: unknown verify-window policy \
589 (ladder|confidence|confidence-slot); refusing — a wrong policy \
590 silently reverts the H4 arm (DSPARK-POSTMORTEM-20260820.md)"
591 ),
592 }
593 }
594
595 /// True for every head-scheduled arm (the loops gate the head requirement and
596 /// the embedding stash on this).
597 pub fn is_confidence(&self) -> bool {
598 !matches!(self, DsparkVtPolicy::Ladder)
599 }
600
601 /// Size this round's verify window from the head's pre-sigmoid slot scores.
602 /// `None` under the ladder (the caller keeps its carried vt).
603 pub fn size_window(&self, raws: &[f32], vt_cap: usize) -> Option<usize> {
604 match *self {
605 DsparkVtPolicy::Ladder => None,
606 DsparkVtPolicy::Confidence { tau } => Some(dspark_confidence_vt(raws, tau, vt_cap)),
607 DsparkVtPolicy::ConfidenceSlot { tau } => {
608 Some(dspark_slot_confidence_vt(raws, tau, vt_cap))
609 }
610 }
611 }
612}
613
614/// H4 window sizing (the sglang-planner/vLLM-#47808 mechanism, thresholded): `raws[k]`
615/// = the accept-rate head's PRE-sigmoid score for draft slot k+1; survival
616/// `S_k = prod_{j<=k} sigmoid(raws[j])`; the window keeps leading slots while
617/// `S_k >= tau`. Returns `vt` = 1 (anchor) + kept drafts, clamped to `[2, vt_cap]`:
618/// the draft forward is already paid, so at least one draft rides every verify — one
619/// extra verify row costs less than a guaranteed empty round. Pure, so the policy's
620/// knee is testable CPU-side like `dspark_accept_prefix`.
621pub fn dspark_confidence_vt(raws: &[f32], tau: f32, vt_cap: usize) -> usize {
622 let mut surv = 1.0f32;
623 let mut kept = 0usize;
624 for &r in raws {
625 surv *= 1.0 / (1.0 + (-r).exp());
626 if surv < tau {
627 break;
628 }
629 kept += 1;
630 }
631 (1 + kept).clamp(2, vt_cap.max(2))
632}
633
634/// Owner-directive arm (2026-08-20, "take only high confidence offers"): keep the
635/// longest draft PREFIX whose EVERY slot clears `tau` on its own sigmoid — truncate
636/// at the first sub-threshold slot, so the low-confidence tail (B2 measured 0.2–0.5
637/// slot rates at depth) never enters verify. Prefix truncation is forced by the
638/// accept rule anyway (`dspark_accept_prefix` stops at the first miss — a kept slot
639/// after a dropped one could never commit); the policy fork vs `dspark_confidence_vt`
640/// is only the stopping statistic (per-slot marginal vs cumulative survival). Same
641/// floor/cap contract.
642pub fn dspark_slot_confidence_vt(raws: &[f32], tau: f32, vt_cap: usize) -> usize {
643 let mut kept = 0usize;
644 for &r in raws {
645 let p = 1.0 / (1.0 + (-r).exp());
646 if p < tau {
647 break;
648 }
649 kept += 1;
650 }
651 (1 + kept).clamp(2, vt_cap.max(2))
652}
653
654// ================= SAMPLED ADMISSION (T>0) — lane/dspark-sampled-admission-20260820 =====
655// True rejection sampling for the dspark route (mystery A of DSPARK-POSTMORTEM-20260820):
656// draft slot j is DRAWN from a recorded proposal distribution q_j, the trunk's verify column
657// arbitrates with the Leviathan/Chen rule (accept x_j while u_j*q_j(x_j) < p_j(x_j); on
658// reject resample from norm(max(0, p-q)); on full accept the bonus ~ p at the last column),
659// so the committed stream's distribution equals trunk-only sampling from the FILTERED target
660// p — the same contract the frspec/MTP route ships (spec.rs sampled accept walk; kernels
661// oracled by sample_check). T==0/None keeps every greedy path byte-identical (the exactness
662// instrument and the kill-switch are the same code).
663//
664// Two proposal families, each recording the TRUE distribution its drafts were drawn from:
665// - Rows (dspark/dflash strategy checkpoints): per-slot FILTERED softmax of the draft-logits
666// row — markov-corrected in place when the head is present (the sglang DSPARK worker's
667// "chain rejection sampling over markov-corrected draft probs"), plain rows otherwise
668// (the z-lab reference's independent-row T>0 arm).
669// - Selector (DFlash2): the candidate-path selector's per-slot softmax over its top-k
670// candidate set at temperature ONLY — the reference applies no top-k/top-p to selector
671// scores (z-lab model.py `CandidateSelector.select`: `_sampling_probs(scores, temperature)`
672// with default filters) — with the candidate-set residual (`scatter_add_` of -q, clamped).
673
674/// Rejection-sampling prefix walk: accept draft j while `u_j * q_j < p_j` (strict, f64 —
675/// byte-identical to the frspec accept test). `p`/`q` are the FILTERED target/proposal
676/// probabilities of the drafted tokens; `u` the per-slot uniforms. Pure so the composition
677/// gate can pin the rule on CPU.
678pub fn rejection_accept_len(p: &[f32], q: &[f32], u: &[f32]) -> usize {
679 assert!(
680 q.len() >= p.len() && u.len() >= p.len(),
681 "accept walk shape"
682 );
683 let mut m = 0usize;
684 while m < p.len() && (u[m] as f64) * (q[m] as f64) < p[m] as f64 {
685 m += 1;
686 }
687 m
688}
689
690/// Sampled selector walk (reference `CandidateSelector.select`, temperature>0 arm): per
691/// draft slot the pair scores over the top-k candidate set become a softmax at `temp`
692/// (temperature ONLY — the reference passes no top-k/top-p here), one uniform draws the
693/// candidate (fixed-order CDF walk), and the CHOSEN candidate seeds the next slot exactly
694/// like the greedy chain. Returns (path, q_chosen[nd], q_rows[nd*top_k]) — q_rows are the
695/// recorded per-slot candidate probabilities (the residual's `scatter_add_` input), and
696/// q_chosen[j] == q_rows[j*top_k + chosen_j] is the accept-test q. Pure (uniforms injected)
697/// so the T->0 limit, the chain conditioning, and the recorded-q contract are CPU-gateable.
698#[allow(clippy::too_many_arguments)]
699pub fn dflash2_walk_sampled(
700 pred_codebook: &[u8],
701 succ_codebook: &[u8],
702 vocab: usize,
703 rank: usize,
704 top_k: usize,
705 unary: &[f32],
706 cand: &[u32],
707 hproj: &[f32],
708 anchor: u32,
709 nd: usize,
710 temp: f32,
711 uniforms: &mut dyn FnMut() -> f32,
712) -> (Vec<u32>, Vec<f32>, Vec<f32>) {
713 assert!(
714 temp > 0.0,
715 "sampled walk is the T>0 arm; T=0 is walk_greedy"
716 );
717 let (kk, r) = (top_k, rank);
718 assert_eq!(unary.len(), nd * kk, "walk: unary shape");
719 assert_eq!(cand.len(), nd * kk, "walk: candidate shape");
720 assert_eq!(hproj.len(), nd * r, "walk: hidden-projection shape");
721 let mut path = Vec::with_capacity(nd);
722 let mut q_chosen = Vec::with_capacity(nd);
723 let mut q_rows = Vec::with_capacity(nd * kk);
724 let mut prev = anchor;
725 for p in 0..nd {
726 assert!(
727 (prev as usize) < vocab,
728 "walk: predecessor token {prev} outside codebook vocab {vocab}"
729 );
730 let pr = cb_row(pred_codebook, prev as usize, r);
731 let hp = &hproj[p * r..(p + 1) * r];
732 let gate: Vec<f32> = pr.iter().zip(hp).map(|(a, b)| a * b).collect();
733 let mut scores = vec![0f32; kk];
734 for (k, s) in scores.iter_mut().enumerate() {
735 let c = cand[p * kk + k] as usize;
736 assert!(c < vocab, "walk: candidate {c} outside codebook vocab");
737 let sr = cb_row(succ_codebook, c, r);
738 let mut acc = unary[p * kk + k];
739 for j in 0..r {
740 acc += gate[j] * sr[j];
741 }
742 *s = acc;
743 }
744 // softmax over the candidate set at temp (f64 internals; recorded probs are the
745 // f32 values the CDF walk actually samples from — recorded q IS the proposal).
746 let mx = scores.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
747 let mut z = 0f64;
748 let ex: Vec<f64> = scores
749 .iter()
750 .map(|&s| {
751 let e0 = (((s - mx) / temp) as f64).exp();
752 z += e0;
753 e0
754 })
755 .collect();
756 let probs: Vec<f32> = ex.iter().map(|&e0| (e0 / z) as f32).collect();
757 let u = uniforms() as f64;
758 let mut acc = 0f64;
759 // fp-residue fallback (u >= f32-accumulated mass, ~2^-24 events): the max-prob
760 // candidate — never a zero-prob one (host_u01's range includes 1.0 exactly).
761 let mut bi = probs
762 .iter()
763 .enumerate()
764 .max_by(|a, b| a.1.total_cmp(b.1))
765 .map(|(k, _)| k)
766 .unwrap_or(0);
767 for (k, &pk) in probs.iter().enumerate() {
768 acc += pk as f64;
769 if u < acc {
770 bi = k;
771 break;
772 }
773 }
774 prev = cand[p * kk + bi];
775 path.push(prev);
776 q_chosen.push(probs[bi]);
777 q_rows.extend_from_slice(&probs);
778 }
779 (path, q_chosen, q_rows)
780}
781
782/// `dflash2_propose_sampled`'s wire: (path, q_chosen, candidate ids, q_rows).
783pub(crate) type Dflash2SampledProposal = (Vec<u32>, Vec<f32>, Vec<u32>, Vec<f32>);
784
785/// Per-round proposal record for the sampled dspark round — everything the rejection
786/// walk needs to evaluate the TRUE per-slot proposal distribution q.
787pub(crate) enum DsparkDraftSample {
788 /// q lives in the round's draft-logits buffer `dl` (markov-biased in place when the
789 /// head is armed); per-slot FILTERED stats retained device-contiguous for the accept
790 /// gather + host-mirrored for the reject-slot residual.
791 Rows {
792 th: CudaSlice<f32>, // [nd] filter thresholds (e-units), slot-indexed
793 z: CudaSlice<f32>, // [nd] renorm masses
794 stats: Vec<(f32, f32, f32)>, // host (mx, th, z) per slot
795 },
796 /// DFlash2 candidate-path selector: q is the recorded candidate-set distribution.
797 Selector {
798 cand: Vec<u32>, // [nd*top_k] candidate ids
799 q_rows: Vec<f32>, // [nd*top_k] per-slot candidate probs
800 q_chosen: Vec<f32>, // [nd] prob of the drawn candidate (accept-test q)
801 top_k: usize,
802 },
803}
804
805/// The sampled round's verify+accept: filtered p gathered from the trunk's verify logits
806/// (row j arbitrates draft `cand[j+1]` — the position mapping the greedy prefix walk uses),
807/// the rejection walk over host uniforms, then `next` = bonus (full accept: filtered-Gumbel
808/// from the LAST verify row with its OWN fresh stats — the sampfix-20260805 law: that row is
809/// one past the gathered set) or the residual sample at the reject slot (family-keyed q:
810/// full-row logits for Rows, sparse candidate-set probs for Selector). Returns (m, next) —
811/// the exact (accepted-drafts, next-anchor) contract of the greedy `dspark_accept_prefix` +
812/// `vam[m]` pair, so both round bodies commit identically downstream.
813///
814/// PENALIZED SAMPLED (lane/dspark-penalized-sampled-20260821): when the request carries
815/// non-identity penalties, the vt verify columns are materialized ONCE into a penalized
816/// copy where row j's Keskar pass runs over `pen_win ++ cand[1..=j]` (window-capped) —
817/// the tokens committed before position j ON EVERY PATH WHERE ROW j IS CONSULTED,
818/// same-round accepts included (row j is only read when drafts 1..j were all accepted,
819/// i.e. exactly when `cand[1..=j]` is the committed prefix; the bonus row vt-1 is only
820/// read on full accept, when all nq drafts are committed). Every p read — the batched
821/// stats+gather, the bonus draw, the reject-slot residual column — points at that buffer,
822/// so p is the true penalized per-state target and the committed stream equals plain
823/// penalized sampling (the composition gate's penalty fixtures, self-hit included).
824/// q stays the RECORDED proposal the drafts were actually drawn from (unpenalized):
825/// rejection sampling is unbiased for ANY proposal with `u·q(x) < p(x)` + residual
826/// `norm(max(0, p−q))`; penalizing q would only buy acceptance overlap and would cost an
827/// evolving-history pass inside the sync-free device chain. `pen_win` is the caller's
828/// session window ALREADY trimmed to `min(penalty_last_n, PEN_WINDOW_MAX)` (empty when
829/// penalties are off — the unpenalized path is byte-untouched).
830#[allow(clippy::too_many_arguments)]
831pub(crate) fn dspark_accept_sampled(
832 e: &Engine,
833 tlogits: &CudaSlice<f32>,
834 cand: &[u32],
835 vt: usize,
836 n_vocab: usize,
837 dl: &CudaSlice<f32>,
838 prop: &DsparkDraftSample,
839 sp: &crate::spec::SpecSampling,
840 pen_win: &[u32],
841 sctr: &mut u32,
842 uctr: &mut u32,
843) -> Result<(usize, u32), Box<dyn std::error::Error>> {
844 let nq = vt - 1; // drafts under this round's verify window
845 debug_assert!(nq >= 1 && cand.len() > nq, "sampled accept shape");
846 // --- penalized verify columns (identity penalties: no copy, no launch, raw tlogits) ---
847 let pen_on = sp.pen_on();
848 let ptl: Option<CudaSlice<f32>> = if pen_on {
849 let win = sp.penalty_last_n.min(crate::spec::PEN_WINDOW_MAX);
850 debug_assert!(pen_win.len() <= win, "pen_win must arrive pre-trimmed");
851 let mut hist: Vec<u32> = Vec::with_capacity(pen_win.len() + nq);
852 hist.extend_from_slice(pen_win);
853 hist.extend_from_slice(&cand[1..=nq]); // drafted tokens: row j reads the first j
854 let hd = e.htod_u32_v(&hist)?;
855 let mut buf = e.clone_dtod(tlogits)?;
856 e.penalize_logits_rows_inc(
857 &mut buf,
858 &hd,
859 pen_win.len(),
860 sp.penalty_repeat,
861 sp.penalty_freq,
862 sp.penalty_present,
863 n_vocab,
864 vt,
865 win,
866 )?;
867 Some(buf)
868 } else {
869 None
870 };
871 let p_src: &CudaSlice<f32> = ptl.as_ref().unwrap_or(tlogits);
872 // --- filtered p at the drafted tokens (one batched stats + gather over rows 0..nq-1) ---
873 let rows: Vec<i32> = (0..nq as i32).collect();
874 let ids: Vec<u32> = cand[1..=nq].to_vec();
875 let rowsd = e.htod_i32(&rows)?;
876 let idsd = e.htod_u32_v(&ids)?;
877 let (mut pth, mut pz, mut pmx) = (e.zeros(nq)?, e.zeros(nq)?, e.zeros(nq)?);
878 e.filter_stats(
879 p_src, n_vocab, &rowsd, &mut pth, &mut pz, &mut pmx, n_vocab, nq, sp.temp, sp.top_k,
880 sp.top_p, sp.min_p,
881 )?;
882 let mut pj_d = e.zeros(nq)?;
883 e.softmax_gather_filtered(
884 p_src, n_vocab, &idsd, &rowsd, &pth, &pz, &mut pj_d, n_vocab, nq, sp.temp,
885 )?;
886 let pj = e.dtoh(&pj_d)?;
887 let (pthv, pzv, pmxv) = (e.dtoh(&pth)?, e.dtoh(&pz)?, e.dtoh(&pmx)?);
888 // --- q at the drafted tokens (the recorded proposal distribution) ---
889 let qj: Vec<f32> = match prop {
890 DsparkDraftSample::Rows { th, z, .. } => {
891 // dl row j is draft j's (bias-corrected) logits row; th/z are slot-indexed, and
892 // rows 0..nq-1 index both the buffer rows and the stat pairs.
893 let mut qd = e.zeros(nq)?;
894 e.softmax_gather_filtered(
895 dl, n_vocab, &idsd, &rowsd, th, z, &mut qd, n_vocab, nq, sp.temp,
896 )?;
897 e.dtoh(&qd)?
898 }
899 DsparkDraftSample::Selector { q_chosen, .. } => q_chosen[..nq].to_vec(),
900 };
901 // --- the rejection walk ---
902 let mut us = Vec::with_capacity(nq);
903 for _ in 0..nq {
904 us.push(crate::spec::host_u01(sp.seed, *uctr));
905 *uctr = uctr.wrapping_add(1);
906 }
907 let m = rejection_accept_len(&pj[..nq], &qj[..nq], &us);
908 // --- next anchor: bonus or residual ---
909 let next = if m == nq {
910 // FULL ACCEPT: bonus ~ filtered p at verify row vt-1 — fresh stats for THIS row.
911 // Under penalties p_src row vt-1 carries the FULL drafted block in its window
912 // (all nq drafts are committed on this path — the "drafted token penalizes its
913 // own successor" case the composition gate's self-hit fixture pins).
914 let rows_l = e.htod_i32(&[(vt - 1) as i32])?;
915 let (mut th1, mut z1, mut mx1) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
916 e.filter_stats(
917 p_src, n_vocab, &rows_l, &mut th1, &mut z1, &mut mx1, n_vocab, 1, sp.temp, sp.top_k,
918 sp.top_p, sp.min_p,
919 )?;
920 let mut pb = e.zeros(n_vocab)?;
921 e.gumbel_perturb_filtered_col(
922 p_src,
923 vt - 1,
924 &mut pb,
925 n_vocab,
926 sp.seed,
927 *sctr,
928 sp.temp,
929 &mx1,
930 &th1,
931 0,
932 )?;
933 *sctr = sctr.wrapping_add(1);
934 let td = e.argmax_token_device(&pb, n_vocab)?;
935 e.dtoh_u32_one(&td)?
936 } else {
937 // REJECT at slot m: token ~ norm(max(0, p_m - q_m)); p row m's stats come from the
938 // gathered set (rows 0..nq-1 cover every reject slot). Under penalties the column
939 // copy MUST come from p_src (the penalized buffer) — a raw-tlogits residual is the
940 // composition gate's "residual reads unpenalized p" tooth.
941 let mut col = e.zeros(n_vocab)?;
942 e.copy_view_into(
943 &mut col,
944 0,
945 &p_src.slice(m * n_vocab..(m + 1) * n_vocab),
946 n_vocab,
947 )?;
948 let p_stats = (pmxv[m], pthv[m], pzv[m]);
949 let mut tok_d = e.alloc_u32_zeroed(1)?;
950 let sc = *sctr;
951 *sctr = sctr.wrapping_add(1);
952 match prop {
953 DsparkDraftSample::Rows { stats, .. } => {
954 let mut qbuf = e.zeros(n_vocab)?;
955 e.copy_view_into(
956 &mut qbuf,
957 0,
958 &dl.slice(m * n_vocab..(m + 1) * n_vocab),
959 n_vocab,
960 )?;
961 e.residual_sample_filtered(
962 &col,
963 Some(&qbuf),
964 n_vocab,
965 sp.temp,
966 sp.seed,
967 sc,
968 p_stats,
969 stats[m],
970 &mut tok_d,
971 )?;
972 }
973 DsparkDraftSample::Selector {
974 cand: cids,
975 q_rows,
976 top_k,
977 ..
978 } => {
979 let k = *top_k;
980 let ids_m = e.htod_u32_v(&cids[m * k..(m + 1) * k])?;
981 let qs_m = e.htod(&q_rows[m * k..(m + 1) * k])?;
982 e.residual_sample_sparse_q(
983 &col, &ids_m, &qs_m, k, n_vocab, sp.temp, sp.seed, sc, p_stats, &mut tok_d,
984 )?;
985 }
986 }
987 e.dtoh_u32(&tok_d)?[0]
988 };
989 Ok((m, next))
990}
991
992/// Clip door for the DFlash2 windowed round attention (lane/dflash2-longctx, §10.6(c)).
993/// Default ON: the lo-clipped kernel — byte-identical output (kernel_check
994/// `sdpa_naive_w_lo`), O(window) key scan, and no T_kv*4-byte shared-mem launch bound, so
995/// the route survives past ~12k ctx (GATES-SMOKE-20260821 B2: DriverError(
996/// CUDA_ERROR_INVALID_VALUE) at ctx 16,571/30,157, last success 9,510).
997/// MEMRA_DFLASH2_SDPA_CLIP=0 = the legacy full-scan kernel byte-for-byte — the rollback
998/// seam and the long-ctx gate's crash-reproduction arm.
999fn dflash2_sdpa_clip_on() -> bool {
1000 std::env::var("MEMRA_DFLASH2_SDPA_CLIP")
1001 .map(|v| v != "0")
1002 .unwrap_or(true)
1003}
1004
1005/// The DFlash2 round attention over the non-causal symmetric window: one seam for both the
1006/// first-light (`forward_block`) and cached (`forward_round`) arms, dispatching the clipped
1007/// kernel unless the rollback door is thrown.
1008#[allow(clippy::too_many_arguments)]
1009fn d2_windowed_attn(
1010 e: &Engine,
1011 q: &CudaSlice<f32>,
1012 k: &CudaSlice<f32>,
1013 v: &CudaSlice<f32>,
1014 attn: &mut CudaSlice<f32>,
1015 hd: usize,
1016 nh: usize,
1017 nkv: usize,
1018 t: usize,
1019 t_kv: usize,
1020 scale: f32,
1021 c: &DflashCfg,
1022) -> Result<(), Box<dyn std::error::Error>> {
1023 if dflash2_sdpa_clip_on() {
1024 e.sdpa_naive_w_lo(
1025 q,
1026 k,
1027 v,
1028 attn,
1029 hd,
1030 nh,
1031 nkv,
1032 t,
1033 t_kv,
1034 scale,
1035 false,
1036 c.sliding_window,
1037 )
1038 } else {
1039 e.sdpa_naive_w(
1040 q,
1041 k,
1042 v,
1043 attn,
1044 hd,
1045 nh,
1046 nkv,
1047 t,
1048 t_kv,
1049 scale,
1050 false,
1051 c.sliding_window,
1052 )
1053 }
1054}
1055
1056fn bf16_to_f32(bytes: &[u8]) -> Vec<f32> {
1057 bytes
1058 .chunks_exact(2)
1059 .map(|c| f32::from_bits((u16::from_le_bytes([c[0], c[1]]) as u32) << 16))
1060 .collect()
1061}
1062
1063/// Host q8_0 encode (ggml block layout: [d f16][32 x i8] = 34B/32 vals). The drafter's
1064/// weights ride the dp4a fast path at 1.6GB resident (bf16 3.1GB + the 31B trunk OOM'd
1065/// 24GB; f32 6.2GB worse). Drafter quantization moves ACCEPTANCE only — verify exactness
1066/// is structural.
1067fn encode_q8_0(vals: &[f32]) -> Vec<u8> {
1068 let mut out = Vec::with_capacity(vals.len() / 32 * 34);
1069 for blk in vals.chunks_exact(32) {
1070 let amax = blk.iter().fold(0f32, |a, v| a.max(v.abs()));
1071 let d = amax / 127.0;
1072 let id = if d > 0.0 { 1.0 / d } else { 0.0 };
1073 let dh = half_from_f32(d);
1074 out.extend_from_slice(&dh.to_le_bytes());
1075 for &v in blk {
1076 out.push(((v * id).round().clamp(-127.0, 127.0)) as i8 as u8);
1077 }
1078 }
1079 out
1080}
1081
1082/// Host q4_0 encode (ggml: [d f16][16B packed nibbles] = 18B/32 vals; q = round(v/d)+8,
1083/// d = amax/-7 sign trick NOT used — plain amax/7? ggml uses d = max/-8 .. follow ggml:
1084/// d = amax / -8 when the max is negative-dominant; reference quantize_row_q4_0: d =
1085/// max(|v|)/-8 signed-max form). Implemented to match ggml quantize_row_q4_0_ref.
1086fn encode_q4_0(vals: &[f32]) -> Vec<u8> {
1087 let mut out = Vec::with_capacity(vals.len() / 32 * 18);
1088 for blk in vals.chunks_exact(32) {
1089 // ggml ref: pick the value with the LARGEST |v| (keeping sign), d = that / -8
1090 let mut amax = 0f32;
1091 let mut mx = 0f32;
1092 for &v in blk {
1093 if v.abs() > amax {
1094 amax = v.abs();
1095 mx = v;
1096 }
1097 }
1098 let d = mx / -8.0;
1099 let id = if d != 0.0 { 1.0 / d } else { 0.0 };
1100 out.extend_from_slice(&half_from_f32(d).to_le_bytes());
1101 for j in 0..16 {
1102 let x0 = (blk[j] * id + 8.5).clamp(0.0, 15.0) as u8;
1103 let x1 = (blk[j + 16] * id + 8.5).clamp(0.0, 15.0) as u8;
1104 out.push(x0 | (x1 << 4));
1105 }
1106 }
1107 out
1108}
1109
1110fn half_from_f32(v: f32) -> u16 {
1111 // f32 -> IEEE f16 (round-to-nearest-even; range of q8_0 d values is tame)
1112 let b = v.to_bits();
1113 let sign = ((b >> 16) & 0x8000) as u16;
1114 let exp = ((b >> 23) & 0xff) as i32 - 127 + 15;
1115 let man = b & 0x7fffff;
1116 if exp <= 0 {
1117 return sign;
1118 } // flush tiny d to zero
1119 if exp >= 31 {
1120 return sign | 0x7c00;
1121 } // inf (unreachable for sane d)
1122 let mut h = sign | ((exp as u16) << 10) | ((man >> 13) as u16);
1123 // round to nearest even on the truncated 13 bits
1124 let rem = man & 0x1fff;
1125 if rem > 0x1000 || (rem == 0x1000 && (h & 1) == 1) {
1126 h += 1;
1127 }
1128 h
1129}
1130
1131impl DflashDraft {
1132 /// Load the backbone-only checkpoint dir (config.json + model.safetensors, bf16).
1133 /// Config scalars ride a minimal extractor (no json dep in-tree — HfConfig precedent).
1134 pub fn load(e: &Engine, dir: &std::path::Path) -> Result<Self, Box<dyn std::error::Error>> {
1135 let txt = std::fs::read_to_string(dir.join("config.json"))?;
1136 fn num(txt: &str, key: &str) -> Option<f64> {
1137 let i = txt.find(&format!("\"{key}\""))?;
1138 let rest = &txt[i..];
1139 let colon = rest.find(':')?;
1140 let val: String = rest[colon + 1..]
1141 .trim_start()
1142 .chars()
1143 .take_while(|c| {
1144 c.is_ascii_digit()
1145 || *c == '.'
1146 || *c == '-'
1147 || *c == 'e'
1148 || *c == 'E'
1149 || *c == '+'
1150 })
1151 .collect();
1152 val.parse().ok()
1153 }
1154 fn num_list(txt: &str, key: &str) -> Vec<usize> {
1155 let Some(i) = txt.find(&format!("\"{key}\"")) else {
1156 return Vec::new();
1157 };
1158 let rest = &txt[i..];
1159 let (Some(a), Some(b)) = (rest.find('['), rest.find(']')) else {
1160 return Vec::new();
1161 };
1162 rest[a + 1..b]
1163 .split(',')
1164 .filter_map(|s| s.trim().parse().ok())
1165 .collect()
1166 }
1167 /// Substring of the JSON OBJECT value of a top-level key (brace-balanced) —
1168 /// the explicit scoped parse the DFlash2 census demands: `dflash_config` and
1169 /// `rope_parameters` are nested objects, and finding their keys by global
1170 /// `txt.find` is luck, not a contract (DFLASH2-EVAL-20260820.md §5.1).
1171 fn scope<'a>(txt: &'a str, key: &str) -> Option<&'a str> {
1172 let i = txt.find(&format!("\"{key}\""))?;
1173 let rest = &txt[i..];
1174 let open = rest.find('{')?;
1175 let mut depth = 0usize;
1176 for (j, ch) in rest[open..].char_indices() {
1177 match ch {
1178 '{' => depth += 1,
1179 '}' => {
1180 depth -= 1;
1181 if depth == 0 {
1182 return Some(&rest[open..open + j + 1]);
1183 }
1184 }
1185 _ => {}
1186 }
1187 }
1188 None
1189 }
1190 // Family detection is the ARCHITECTURES string, not tensor presence: a DFlash2
1191 // checkpoint whose new tensors were stripped must REFUSE, not degrade into the
1192 // 58-tensor untrained program (DFLASH2-EVAL-20260820.md §3).
1193 let is_dflash2 = {
1194 let arch = scope_list(&txt, "architectures");
1195 arch.contains("DFlash2DraftModel")
1196 };
1197 fn scope_list(txt: &str, key: &str) -> String {
1198 let Some(i) = txt.find(&format!("\"{key}\"")) else {
1199 return String::new();
1200 };
1201 let rest = &txt[i..];
1202 match (rest.find('['), rest.find(']')) {
1203 (Some(a), Some(b)) if a < b => rest[a + 1..b].to_string(),
1204 _ => String::new(),
1205 }
1206 }
1207 // DFlash2 scalars parse from their OWN scopes; other families keep the
1208 // historical global-find behavior byte-identically.
1209 let d2_cfg_txt: Option<&str> = if is_dflash2 {
1210 Some(scope(&txt, "dflash_config").unwrap_or_else(|| {
1211 panic!("DFlash2DraftModel config.json has no dflash_config object — refusing")
1212 }))
1213 } else {
1214 None
1215 };
1216 let g = |k: &str| num(&txt, k).unwrap_or_else(|| panic!("config missing {k}")) as usize;
1217 let g2 = |k: &str| -> usize {
1218 let t = d2_cfg_txt.expect("dflash2 scope");
1219 num(t, k).unwrap_or_else(|| panic!("dflash_config missing {k} — refusing")) as usize
1220 };
1221 // layer_types order: count entries, mark sliding ones
1222 let layer_sliding: Vec<bool> = {
1223 let i = txt.find("\"layer_types\"").expect("layer_types");
1224 let rest = &txt[i..];
1225 let (a, b) = (rest.find('[').unwrap(), rest.find(']').unwrap());
1226 rest[a + 1..b]
1227 .split(',')
1228 .map(|s| s.contains("sliding_attention"))
1229 .collect()
1230 };
1231 // sliding_window is null on all-full-attention exports (q38 arm-a); the window
1232 // only constrains rounds when a sliding layer exists (reference: resolve_dflash_
1233 // attention_layout returns None when no layer slides).
1234 let sliding_window = if layer_sliding.iter().any(|&s| s) {
1235 g("sliding_window")
1236 } else {
1237 num(&txt, "sliding_window")
1238 .map(|v| v as usize)
1239 .unwrap_or(usize::MAX)
1240 };
1241 // Explicit top-level is_causal (z-lab reference: overrides the layer-type
1242 // default). Parsed as a bare bool; absent = None (historical arms unchanged).
1243 let is_causal = txt
1244 .find("\"is_causal\"")
1245 .and_then(|i| txt[i..].find(':').map(|c| i + c + 1))
1246 .map(|v| txt[v..].trim_start().starts_with("true"));
1247 let cfg = DflashCfg {
1248 hidden: g("hidden_size"),
1249 n_head: g("num_attention_heads"),
1250 n_kv: g("num_key_value_heads"),
1251 head_dim: g("head_dim"),
1252 n_ff: g("intermediate_size"),
1253 n_layer: g("num_hidden_layers"),
1254 eps: num(&txt, "rms_norm_eps").expect("rms_norm_eps") as f32,
1255 // DFlash2 (transformers-5 style): rope_theta lives in the nested
1256 // rope_parameters object — parse it from its scope, not by global find.
1257 rope_theta: if is_dflash2 {
1258 let rp = scope(&txt, "rope_parameters")
1259 .unwrap_or_else(|| panic!("DFlash2 config has no rope_parameters — refusing"));
1260 assert!(
1261 rp.contains("\"default\""),
1262 "DFlash2 rope_parameters rope_type is not \"default\" — the port \
1263 implements plain neox rope only; refusing ({rp})"
1264 );
1265 num(rp, "rope_theta").expect("rope_parameters.rope_theta") as f32
1266 } else {
1267 num(&txt, "rope_theta").expect("rope_theta") as f32
1268 },
1269 block_size: if is_dflash2 {
1270 g2("block_size")
1271 } else {
1272 g("block_size")
1273 },
1274 mask_token_id: if is_dflash2 {
1275 g2("mask_token_id")
1276 } else {
1277 g("mask_token_id")
1278 } as u32,
1279 target_layer_ids: if is_dflash2 {
1280 num_list(d2_cfg_txt.expect("dflash2 scope"), "target_layer_ids")
1281 } else {
1282 num_list(&txt, "target_layer_ids")
1283 },
1284 sliding_window,
1285 layer_sliding,
1286 strategy_dspark: dspark_strategy_census(&txt),
1287 is_causal,
1288 };
1289 if is_dflash2 {
1290 // The windowed round arm implements the reference's NON-causal symmetric
1291 // window only (config `is_causal: false` on the q38 DFlash2 export). A
1292 // causal DFlash2 variant is a different mask program — refuse it rather
1293 // than run the wrong one fluently.
1294 assert_eq!(
1295 cfg.is_causal,
1296 Some(false),
1297 "DFlash2 port requires explicit config is_causal=false \
1298 (non-causal symmetric sliding window); got {is_causal:?} — refusing"
1299 );
1300 assert!(
1301 cfg.layer_sliding.iter().all(|&s| s),
1302 "DFlash2 port expects all layers sliding_attention (q38 export); \
1303 got {:?} — refusing (unverified mask program)",
1304 cfg.layer_sliding
1305 );
1306 assert!(
1307 cfg.block_size <= cfg.sliding_window,
1308 "DFlash2 block {} exceeds the sliding window {} — the windowed SDPA \
1309 omits the future-side mask because block rows stay within the window",
1310 cfg.block_size,
1311 cfg.sliding_window
1312 );
1313 }
1314 let st = memra_gguf::safetensors::StModel::open(&dir.join("model.safetensors"))?;
1315 // 1D norm weights ride raw slices; 2D matmul weights ride GpuTensor::Float
1316 // (cuBLASLt f32 arm — the Stage-A numeric class, right for oracle parity).
1317 let up = |name: &str| -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1318 let (_info, bytes) = st
1319 .raw(name)
1320 .ok_or_else(|| format!("missing tensor {name}"))?;
1321 Ok(e.htod(&bf16_to_f32(bytes))?)
1322 };
1323 // Precision policy (MEMRA_DFLASH_PREC seam): "q4" = all q4_0 (DEFAULT since
1324 // lane/dflash2-head-trim 2026-08-25, owner-ratified): measured on BOTH engaging
1325 // card classes at unchanged acceptance — RTX PRO 6000 dspark_q38_gate x3
1326 // interleaved 157.9 vs q8 152.4 spec tok/s (accept 0.662 vs 0.656, ALL EXACT;
1327 // darklanes research/dflash2-pro6000-20260824/prec-ladder + trim cells) and the
1328 // 5090 rig cell that shipped the arm (PR #41). "q8" = all q8_0 (1.6GB, the
1329 // pre-flip default = the rollback seam); "mixed" = bf16 attn+fc (the
1330 // ctx-conditioning path) + q8_0 ffn (~2.2GB — fits the ~2.8GB headroom beside
1331 // the 31B trunk); "bf16" = all bf16 (parity runs, no target). The asymmetric
1332 // "q5" arm was measured DEFECTIVE (acceptance 0.656 -> 0.424) and never landed.
1333 let prec_env = std::env::var("MEMRA_DFLASH_PREC").ok();
1334 let prec = match dflash_precision(prec_env.as_deref()) {
1335 Ok(prec) => prec,
1336 Err(err) => return Err(err.into()),
1337 };
1338 let upw = |name: &str| -> Result<GpuTensor, Box<dyn std::error::Error>> {
1339 let (info, bytes) = st
1340 .raw(name)
1341 .ok_or_else(|| format!("missing tensor {name}"))?;
1342 let shape = info.ne(); // ggml order: ne[0]=in_f, ne[1]=out_f
1343 let in_f = shape[0] as usize;
1344 let is_ffn = name.contains(".mlp.");
1345 let bf16 = prec == "bf16"
1346 || (prec == "mixed" && !is_ffn)
1347 || (prec == "fc" && name == "fc.weight");
1348 if bf16 {
1349 return Ok(GpuTensor::FloatBf16 {
1350 data: e.upload_u8(bytes)?,
1351 ne: shape.to_vec(),
1352 });
1353 }
1354 let f32s = bf16_to_f32(bytes);
1355 if prec == "q4" {
1356 let q = encode_q4_0(&f32s);
1357 return Ok(GpuTensor::Quant {
1358 bytes: e.upload_u8(&q)?,
1359 qtype: crate::QT_Q4_0,
1360 row_bytes: in_f / 32 * 18,
1361 ne: shape.to_vec(),
1362 scale: 1.0,
1363 rp: false,
1364 #[cfg(memra_cutlass)]
1365 cutlass: None,
1366 fp8: None,
1367 blk: None,
1368 rp4: None,
1369 f16: None,
1370 });
1371 }
1372 let q = encode_q8_0(&f32s);
1373 Ok(GpuTensor::Quant {
1374 bytes: e.upload_u8(&q)?,
1375 qtype: crate::QT_Q8_0,
1376 row_bytes: in_f / 32 * 34,
1377 ne: shape.to_vec(),
1378 scale: 1.0,
1379 rp: false,
1380 #[cfg(memra_cutlass)]
1381 cutlass: None,
1382 fp8: None,
1383 blk: None,
1384 rp4: None,
1385 f16: None,
1386 })
1387 };
1388 let mut layers = Vec::with_capacity(cfg.n_layer);
1389 for i in 0..cfg.n_layer {
1390 let p = |s: &str| format!("layers.{i}.{s}");
1391 layers.push(DflashLayer {
1392 wq: upw(&p("self_attn.q_proj.weight"))?,
1393 wk: upw(&p("self_attn.k_proj.weight"))?,
1394 wv: upw(&p("self_attn.v_proj.weight"))?,
1395 wo: upw(&p("self_attn.o_proj.weight"))?,
1396 w_gate: upw(&p("mlp.gate_proj.weight"))?,
1397 w_up: upw(&p("mlp.up_proj.weight"))?,
1398 w_down: upw(&p("mlp.down_proj.weight"))?,
1399 ln_in: up(&p("input_layernorm.weight"))?,
1400 ln_post: up(&p("post_attention_layernorm.weight"))?,
1401 q_norm: up(&p("self_attn.q_norm.weight"))?,
1402 k_norm: up(&p("self_attn.k_norm.weight"))?,
1403 });
1404 }
1405 let markov = if let Some((info, bytes)) = st.raw("markov_head.markov_w1.weight") {
1406 let sh = info.ne(); // [rank, vocab] in ggml order (safetensors [V, rank] reversed)
1407 let (rank, vocab) = (sh[0] as usize, sh[1] as usize);
1408 let (i2, b2) = st
1409 .raw("markov_head.markov_w2.weight")
1410 .ok_or("markov_w2 missing beside markov_w1")?;
1411 // w2 follows the precision seam: bf16 for parity runs (the q8_0 encode is a
1412 // serving-size choice and would put quant error inside the markov-logits gate),
1413 // q8_0 otherwise (acceptance-only impact, like the trunk weights).
1414 let w2 = if prec == "bf16" {
1415 GpuTensor::FloatBf16 {
1416 data: e.upload_u8(b2)?,
1417 ne: i2.ne().to_vec(),
1418 }
1419 } else {
1420 let w2f = bf16_to_f32(b2);
1421 let w2q = encode_q8_0(&w2f);
1422 GpuTensor::Quant {
1423 bytes: e.upload_u8(&w2q)?,
1424 qtype: crate::QT_Q8_0,
1425 row_bytes: rank / 32 * 34,
1426 ne: vec![rank as u64, vocab as u64],
1427 scale: 1.0,
1428 rp: false,
1429 #[cfg(memra_cutlass)]
1430 cutlass: None,
1431 fp8: None,
1432 blk: None,
1433 rp4: None,
1434 f16: None,
1435 }
1436 };
1437 Some(MarkovHead {
1438 w1_bf16: e.upload_u8(bytes)?,
1439 w2,
1440 rank,
1441 vocab,
1442 })
1443 } else {
1444 None
1445 };
1446 let confidence = if let Some((info, bytes)) = st.raw("confidence_head.proj.weight") {
1447 let sh = info.ne(); // ggml order: ne[0]=in_dim, ne[1]=1
1448 let in_dim = sh[0] as usize;
1449 let (_bi, bb) = st
1450 .raw("confidence_head.proj.bias")
1451 .ok_or("confidence bias missing beside weight")?;
1452 let with_markov = markov
1453 .as_ref()
1454 .map(|m| in_dim == cfg.hidden + m.rank)
1455 .unwrap_or(false);
1456 if !with_markov && in_dim != cfg.hidden {
1457 panic!(
1458 "confidence_head in_dim {in_dim} matches neither hidden {} nor hidden+rank",
1459 cfg.hidden
1460 );
1461 }
1462 Some(ConfidenceHead {
1463 w: bf16_to_f32(bytes),
1464 b: bf16_to_f32(bb)[0],
1465 in_dim,
1466 with_markov,
1467 })
1468 } else {
1469 None
1470 };
1471 // ---- DFlash2 family tensors (DFLASH2-EVAL-20260820.md §2): 10 conv modules
1472 // (base_kernel + kernel_projection around attention AND mlp in EVERY layer) +
1473 // the candidate path selector (hidden_projection + two codebooks). REQUIRED
1474 // when the arch says DFlash2DraftModel: a missing tensor is a refusal (`?`),
1475 // never a degraded program.
1476 let dflash2 = if is_dflash2 {
1477 assert!(
1478 markov.is_none() && confidence.is_none(),
1479 "DFlash2 checkpoint carries markov/confidence tensors — no such \
1480 variant exists in the family (census refuses the ambiguity)"
1481 );
1482 let rank = g2("selector_rank");
1483 let top_k = g2("selector_top_k");
1484 let conv_k = g2("conv_kernel_size");
1485 let group_size = g2("conv_group_size");
1486 let groups = cfg.hidden / group_size;
1487 let load_conv = |name: &str| -> Result<Dflash2Conv, Box<dyn std::error::Error>> {
1488 let (bi, bb) = st
1489 .raw(&format!("{name}.base_kernel"))
1490 .ok_or_else(|| format!("DFlash2 census: missing {name}.base_kernel"))?;
1491 // safetensors [2, k, hidden] -> ggml ne reversed [hidden, k, 2]
1492 let bne = bi.ne();
1493 assert_eq!(
1494 (bne[0] as usize, bne[1] as usize, bne[2] as usize),
1495 (cfg.hidden, conv_k, 2),
1496 "{name}.base_kernel shape != [2, conv_kernel_size, hidden]"
1497 );
1498 let pname = format!("{name}.kernel_projection.weight");
1499 let (pi, _pb) = st
1500 .raw(&pname)
1501 .ok_or_else(|| format!("DFlash2 census: missing {pname}"))?;
1502 let pne = pi.ne(); // ggml: [in_f=hidden, out_f=2*k*groups]
1503 assert_eq!(
1504 (pne[0] as usize, pne[1] as usize),
1505 (cfg.hidden, 2 * conv_k * groups),
1506 "{pname} shape != [2*conv_kernel_size*groups, hidden]"
1507 );
1508 Ok(Dflash2Conv {
1509 base: e.htod(&bf16_to_f32(bb))?,
1510 proj: upw(&pname)?,
1511 })
1512 };
1513 let mut attn_conv = Vec::with_capacity(cfg.n_layer);
1514 let mut mlp_conv = Vec::with_capacity(cfg.n_layer);
1515 for i in 0..cfg.n_layer {
1516 attn_conv.push(load_conv(&format!("layers.{i}.attention_conv"))?);
1517 mlp_conv.push(load_conv(&format!("layers.{i}.mlp_conv"))?);
1518 }
1519 // Codebooks: stored WITHOUT `.weight` (checkpoint quirk; reference
1520 // from_pretrained maps the keys). Host-resident raw bf16.
1521 let cb = |name: &str| -> Result<(Vec<u8>, usize), Box<dyn std::error::Error>> {
1522 let (ci, cbytes) = st
1523 .raw(&format!("candidate_selector.{name}"))
1524 .ok_or_else(|| format!("DFlash2 census: missing candidate_selector.{name}"))?;
1525 let ne = ci.ne(); // ggml: [rank, V]
1526 assert_eq!(ne[0] as usize, rank, "candidate_selector.{name} rank");
1527 Ok((cbytes.to_vec(), ne[1] as usize))
1528 };
1529 let (pred_codebook, v1) = cb("predecessor_codebook")?;
1530 let (succ_codebook, v2) = cb("successor_codebook")?;
1531 assert_eq!(v1, v2, "codebook vocab mismatch");
1532 let hp_name = "candidate_selector.hidden_projection.weight";
1533 let (hi, _hb) = st
1534 .raw(hp_name)
1535 .ok_or_else(|| format!("DFlash2 census: missing {hp_name}"))?;
1536 assert_eq!(
1537 (hi.ne()[0] as usize, hi.ne()[1] as usize),
1538 (cfg.hidden, rank),
1539 "{hp_name} shape != [rank, hidden]"
1540 );
1541 Some(Dflash2Head {
1542 attn_conv,
1543 mlp_conv,
1544 hidden_proj: upw(hp_name)?,
1545 pred_codebook,
1546 succ_codebook,
1547 rank,
1548 top_k,
1549 conv_k,
1550 group_size,
1551 vocab: v1,
1552 })
1553 } else {
1554 None
1555 };
1556 // CENSUS GATE: every tensor in the export must be consumed by the map above.
1557 // DSpark-class checkpoints (markov head present) and DFlash2 checkpoints
1558 // REFUSE on unrecognized names — an unmapped tensor is a semantic program we
1559 // would silently drop (house law). Plain dflash checkpoints keep the
1560 // historical warn-only behavior.
1561 {
1562 let mut consumed: std::collections::HashSet<String> = std::collections::HashSet::new();
1563 for i in 0..cfg.n_layer {
1564 for s in [
1565 "self_attn.q_proj.weight",
1566 "self_attn.k_proj.weight",
1567 "self_attn.v_proj.weight",
1568 "self_attn.o_proj.weight",
1569 "self_attn.q_norm.weight",
1570 "self_attn.k_norm.weight",
1571 "input_layernorm.weight",
1572 "post_attention_layernorm.weight",
1573 "mlp.gate_proj.weight",
1574 "mlp.up_proj.weight",
1575 "mlp.down_proj.weight",
1576 ] {
1577 consumed.insert(format!("layers.{i}.{s}"));
1578 }
1579 if dflash2.is_some() {
1580 for s in [
1581 "attention_conv.base_kernel",
1582 "attention_conv.kernel_projection.weight",
1583 "mlp_conv.base_kernel",
1584 "mlp_conv.kernel_projection.weight",
1585 ] {
1586 consumed.insert(format!("layers.{i}.{s}"));
1587 }
1588 }
1589 }
1590 for s in [
1591 "fc.weight",
1592 "hidden_norm.weight",
1593 "norm.weight",
1594 "markov_head.markov_w1.weight",
1595 "markov_head.markov_w2.weight",
1596 "confidence_head.proj.weight",
1597 "confidence_head.proj.bias",
1598 ] {
1599 consumed.insert(s.into());
1600 }
1601 if dflash2.is_some() {
1602 for s in [
1603 "candidate_selector.hidden_projection.weight",
1604 "candidate_selector.predecessor_codebook",
1605 "candidate_selector.successor_codebook",
1606 ] {
1607 consumed.insert(s.into());
1608 }
1609 }
1610 let leftovers: Vec<&String> = st.names().filter(|n| !consumed.contains(*n)).collect();
1611 if !leftovers.is_empty() {
1612 if markov.is_some() || dflash2.is_some() {
1613 panic!("dspark/dflash2 census: unrecognized tensors {leftovers:?}");
1614 }
1615 eprintln!("[dflash census] unmapped tensors (ignored): {leftovers:?}");
1616 }
1617 }
1618 // YaRN rope from config rope_parameters (HF _compute_yarn_parameters, verified
1619 // numerically vs Qwen3RotaryEmbedding on the arm-a export).
1620 let rope_yarn =
1621 if txt.contains("\"rope_type\": \"yarn\"") || txt.contains("\"rope_type\":\"yarn\"") {
1622 let factor = num(&txt, "factor").expect("yarn factor") as f64;
1623 let orig = num(&txt, "original_max_position_embeddings").expect("yarn orig");
1624 let beta_fast = num(&txt, "beta_fast").expect("beta_fast");
1625 let beta_slow = num(&txt, "beta_slow").expect("beta_slow");
1626 let base = cfg.rope_theta as f64;
1627 let d = cfg.head_dim as f64;
1628 let corr =
1629 |r: f64| d * (orig / (r * 2.0 * std::f64::consts::PI)).ln() / (2.0 * base.ln());
1630 let low = corr(beta_fast).floor().max(0.0);
1631 let high = corr(beta_slow).ceil().min(d - 1.0);
1632 let half = cfg.head_dim / 2;
1633 let mut ff = Vec::with_capacity(half);
1634 for j in 0..half {
1635 let base_inv = base.powf(-2.0 * j as f64 / d);
1636 let ramp = (((j as f64) - low) / (high - low)).clamp(0.0, 1.0);
1637 let ex = 1.0 - ramp; // extrapolation share
1638 let yarn_inv = (base_inv / factor) * (1.0 - ex) + base_inv * ex;
1639 ff.push((base_inv / yarn_inv) as f32);
1640 }
1641 let mscale = (0.1 * factor.ln() + 1.0) as f32;
1642 Some((e.htod(&ff)?, mscale))
1643 } else {
1644 None
1645 };
1646 let fc = upw("fc.weight")?;
1647 // Ratified-default receipts (capacity-keyed-defaults law: the active program is
1648 // NAMED at load, never inferred from silence). The boot output-sample gate greps
1649 // these lines; a run whose log lacks them did not load this code.
1650 eprintln!(
1651 "[dspark] precision={prec} (MEMRA_DFLASH_PREC {})",
1652 if prec_env.is_some() { "set" } else { "unset" },
1653 );
1654 eprintln!(
1655 "[dspark] harvest={} (checkpoint census dflash2={} strategy_dspark={}, \
1656 MEMRA_DSPARK_HARVEST {})",
1657 DsparkHarvest::for_family_value(
1658 dflash2.is_some(),
1659 std::env::var("MEMRA_DSPARK_HARVEST").ok().as_deref(),
1660 cfg.strategy_dspark,
1661 )
1662 .name(),
1663 dflash2.is_some(),
1664 cfg.strategy_dspark,
1665 match std::env::var("MEMRA_DSPARK_HARVEST") {
1666 Ok(v) if !v.is_empty() => "set",
1667 _ => "unset",
1668 },
1669 );
1670 eprintln!(
1671 "[dspark] verify-window={:?} (accept-rate head {}, MEMRA_DSPARK_VT {})",
1672 DsparkVtPolicy::resolve(confidence.is_some()),
1673 if confidence.is_some() {
1674 "present"
1675 } else {
1676 "ABSENT -> ladder"
1677 },
1678 match std::env::var("MEMRA_DSPARK_VT") {
1679 Ok(v) if !v.is_empty() => "set",
1680 _ => "unset",
1681 },
1682 );
1683 Ok(Self {
1684 fc,
1685 hidden_norm: up("hidden_norm.weight")?,
1686 norm: up("norm.weight")?,
1687 cfg,
1688 layers,
1689 markov,
1690 confidence,
1691 rope_yarn,
1692 dflash2,
1693 })
1694 }
1695
1696 /// Rope q or k rows in place: yarn (ff divisors + post-rope mscale) when the config
1697 /// carries it, plain neox otherwise. One primitive for all five drafter rope sites.
1698 fn rope_rows(
1699 &self,
1700 e: &Engine,
1701 x: &mut CudaSlice<f32>,
1702 pos_d: &CudaSlice<i32>,
1703 n_heads: usize,
1704 n_tokens: usize,
1705 ) -> Result<(), Box<dyn std::error::Error>> {
1706 let c = &self.cfg;
1707 match &self.rope_yarn {
1708 Some((ff, mscale)) => {
1709 e.rope_neox_ff(
1710 x,
1711 pos_d,
1712 c.head_dim,
1713 c.head_dim,
1714 n_heads,
1715 n_tokens,
1716 c.rope_theta,
1717 1.0,
1718 ff,
1719 )?;
1720 e.scale_inplace(x, *mscale, n_tokens * n_heads * c.head_dim)?;
1721 }
1722 None => {
1723 e.rope_neox(
1724 x,
1725 pos_d,
1726 c.head_dim,
1727 c.head_dim,
1728 n_heads,
1729 n_tokens,
1730 c.rope_theta,
1731 1.0,
1732 )?;
1733 }
1734 }
1735 Ok(())
1736 }
1737
1738 /// f32 GEMM helper via the engine Float arm (cuBLASLt): y[t, out_f].
1739 fn mm(
1740 &self,
1741 e: &Engine,
1742 w: &GpuTensor,
1743 x: &CudaSlice<f32>,
1744 t: usize,
1745 _in_f: usize,
1746 _out_f: usize,
1747 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1748 Ok(e.matmul(w, x, t)?)
1749 }
1750
1751 /// DFlash2 conv `prepare` (reference GroupedDynamicCausalConv.prepare): projects
1752 /// the pre-conv rows to BOTH dynamic kernels, convolves the rows with base half 0
1753 /// + dyn half 0, and returns (convolved rows, the dyn projection) — `finish`
1754 /// reuses the SAME projection's half 1. Block-local causal shift (row 0 zero-pads).
1755 pub fn d2_conv_prepare(
1756 &self,
1757 e: &Engine,
1758 conv: &Dflash2Conv,
1759 xn: &CudaSlice<f32>,
1760 rows: usize,
1761 ) -> Result<(CudaSlice<f32>, CudaSlice<f32>), Box<dyn std::error::Error>> {
1762 let d2 = self
1763 .dflash2
1764 .as_ref()
1765 .expect("d2_conv on a non-dflash2 draft");
1766 let h = self.cfg.hidden;
1767 let groups = h / d2.group_size;
1768 let dyn_ = self.mm(e, &conv.proj, xn, rows, h, 2 * d2.conv_k * groups)?;
1769 let mut out = e.uninit(rows * h)?;
1770 e.dflash2_dynconv(
1771 xn,
1772 &dyn_,
1773 &conv.base,
1774 &mut out,
1775 rows,
1776 h,
1777 d2.group_size,
1778 d2.conv_k,
1779 0,
1780 )?;
1781 Ok((out, dyn_))
1782 }
1783
1784 /// DFlash2 conv `finish`: convolves the sublayer OUTPUT rows with base half 1 +
1785 /// dyn half 1 (dyn from the matching `prepare`).
1786 pub fn d2_conv_finish(
1787 &self,
1788 e: &Engine,
1789 conv: &Dflash2Conv,
1790 y: &CudaSlice<f32>,
1791 dyn_: &CudaSlice<f32>,
1792 rows: usize,
1793 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
1794 let d2 = self
1795 .dflash2
1796 .as_ref()
1797 .expect("d2_conv on a non-dflash2 draft");
1798 let h = self.cfg.hidden;
1799 let mut out = e.uninit(rows * h)?;
1800 e.dflash2_dynconv(
1801 y,
1802 dyn_,
1803 &conv.base,
1804 &mut out,
1805 rows,
1806 h,
1807 d2.group_size,
1808 d2.conv_k,
1809 1,
1810 )?;
1811 Ok(out)
1812 }
1813
1814 /// DFlash2 proposal (reference `DFlash2DraftModel.propose`, greedy arm): device
1815 /// top-k over the draft logits + the rank-`r` hidden projection, ONE small dtoh
1816 /// (~nd*(2k+rank) floats — the same per-round sync slot the markov chain's token
1817 /// readback occupies), then the host codebook walk. Returns the nd drafted tokens
1818 /// (mask-fill rows 1..b-1; the anchor row is not a draft).
1819 pub fn dflash2_propose_greedy(
1820 &self,
1821 e: &Engine,
1822 dl: &CudaSlice<f32>,
1823 rows: &CudaSlice<f32>,
1824 nd: usize,
1825 n_vocab: usize,
1826 anchor: u32,
1827 d2t: Option<&[u32]>,
1828 ) -> Result<Vec<u32>, Box<dyn std::error::Error>> {
1829 let d2 = self
1830 .dflash2
1831 .as_ref()
1832 .expect("dflash2_propose on a non-dflash2 draft");
1833 assert!(
1834 n_vocab <= d2.vocab,
1835 "target head vocab {n_vocab} exceeds the selector codebooks ({})",
1836 d2.vocab
1837 );
1838 let (vals_d, idx_d) = e.topk_rows(dl, nd, n_vocab, d2.top_k)?;
1839 let hproj_d = e.matmul(&d2.hidden_proj, rows, nd)?;
1840 let unary = e.dtoh(&vals_d)?;
1841 let mut cand = e.dtoh_u32(&idx_d)?;
1842 // TRIMMED draft head (lane/dflash2-head-trim, 2026-08-25): `dl` was scored over the
1843 // FR-Spec-gathered rows, so candidate index i names trimmed row i — remap to the true
1844 // token id BEFORE the selector walk (the codebooks and the verify block index the full
1845 // vocabulary). Same permute-the-proposal law as the MTP arm's spec.rs d2t map; verify
1846 // stays full-vocab, so the trim moves acceptance only, never output.
1847 if let Some(map) = d2t {
1848 for c in cand.iter_mut() {
1849 *c = map[*c as usize];
1850 }
1851 }
1852 let hproj = e.dtoh(&hproj_d)?;
1853 Ok(d2.walk_greedy(&unary, &cand, &hproj, anchor, nd))
1854 }
1855
1856 /// DFlash2 proposal, SAMPLED arm (reference `DFlash2DraftModel.propose` at T>0): same
1857 /// device top-k + hidden projection + one dtoh as the greedy arm, then the host
1858 /// candidate-set softmax walk (`dflash2_walk_sampled`) drawing one host-Philox uniform
1859 /// per slot from the session's `uctr` stream. Returns (path, q_chosen, cand, q_rows).
1860 #[allow(clippy::too_many_arguments)]
1861 pub(crate) fn dflash2_propose_sampled(
1862 &self,
1863 e: &Engine,
1864 dl: &CudaSlice<f32>,
1865 rows: &CudaSlice<f32>,
1866 nd: usize,
1867 n_vocab: usize,
1868 anchor: u32,
1869 temp: f32,
1870 seed: u64,
1871 uctr: &mut u32,
1872 d2t: Option<&[u32]>,
1873 ) -> Result<Dflash2SampledProposal, Box<dyn std::error::Error>> {
1874 let d2 = self
1875 .dflash2
1876 .as_ref()
1877 .expect("dflash2_propose on a non-dflash2 draft");
1878 assert!(
1879 n_vocab <= d2.vocab,
1880 "target head vocab {n_vocab} exceeds the selector codebooks ({})",
1881 d2.vocab
1882 );
1883 let (vals_d, idx_d) = e.topk_rows(dl, nd, n_vocab, d2.top_k)?;
1884 let hproj_d = e.matmul(&d2.hidden_proj, rows, nd)?;
1885 let unary = e.dtoh(&vals_d)?;
1886 let mut cand = e.dtoh_u32(&idx_d)?;
1887 // Trimmed-head remap — see the greedy arm. The q the walk reports is the softmax
1888 // over the candidate SET it actually proposed (ids are labels, not indices into a
1889 // distribution), so the rejection-verify contract is unchanged by the remap.
1890 if let Some(map) = d2t {
1891 for c in cand.iter_mut() {
1892 *c = map[*c as usize];
1893 }
1894 }
1895 let hproj = e.dtoh(&hproj_d)?;
1896 let mut draw = || {
1897 let u = crate::spec::host_u01(seed, *uctr);
1898 *uctr = uctr.wrapping_add(1);
1899 u
1900 };
1901 let (path, q_chosen, q_rows) =
1902 d2.walk_sampled(&unary, &cand, &hproj, anchor, nd, temp, &mut draw);
1903 Ok((path, q_chosen, cand, q_rows))
1904 }
1905
1906 /// Sampled draft chain for the Rows families (T>0 twin of the greedy markov chain):
1907 /// slot k gets the markov bias of the PREVIOUS chain token added in place (when the
1908 /// head is armed — the sglang DSPARK worker's markov-corrected draft probs), then ONE
1909 /// draw from the row's FILTERED softmax (filter_stats -> device-stat gumbel perturb ->
1910 /// argmax into the chain buffer — the frspec eager-chain composition, stats kept on
1911 /// device so the chain stays sync-free like the greedy arm). Without a markov head the
1912 /// rows sample independently (the z-lab reference's T>0 arm for plain DFlash). `dl` is
1913 /// biased IN PLACE and retained by the caller: it is the accept walk's q source.
1914 #[allow(clippy::too_many_arguments)]
1915 pub(crate) fn dspark_chain_sampled(
1916 &self,
1917 e: &Engine,
1918 dl: &mut CudaSlice<f32>,
1919 nd: usize,
1920 n_vocab: usize,
1921 anchor: u32,
1922 sp: &crate::spec::SpecSampling,
1923 sctr: &mut u32,
1924 // H4 confidence-policy stash (v0.100 train merge): Some = copy each slot's
1925 // markov prev-token embedding (the exact `w1` row the chain gathers) into a
1926 // [nd, rank] buffer — the same d2d stash the greedy chain carries, so the
1927 // confidence window sizes identically at T>0.
1928 mut conf_emb: Option<&mut CudaSlice<f32>>,
1929 ) -> Result<(Vec<u32>, DsparkDraftSample), Box<dyn std::error::Error>> {
1930 let markov_on = std::env::var("MEMRA_DFLASH_MARKOV").as_deref() != Ok("0");
1931 let mut chain_d = e.stream().alloc_zeros::<u32>(nd + 1)?;
1932 e.set_u32_one(&mut chain_d, anchor)?;
1933 let mut th_all = e.zeros(nd)?;
1934 let mut z_all = e.zeros(nd)?;
1935 let mut mx_all = e.zeros(nd)?;
1936 let mut pb = e.zeros(n_vocab)?;
1937 for k in 0..nd {
1938 if let (Some(mk), true) = (&self.markov, markov_on) {
1939 let mut f = e.uninit(mk.rank)?;
1940 e.gather_row_bf16(&mk.w1_bf16, &chain_d, k, &mut f, mk.rank)?;
1941 if let Some(ce) = conf_emb.as_deref_mut() {
1942 let fv = e.view(&f, mk.rank);
1943 e.copy_view_into(ce, k * mk.rank, &fv, mk.rank)?;
1944 }
1945 let bias = e.matmul(&mk.w2, &f, 1)?;
1946 e.add_row_inplace(dl, &bias, n_vocab, k * n_vocab)?;
1947 } else if let (Some(ce), Some(mk)) = (conf_emb.as_deref_mut(), &self.markov) {
1948 // MARKOV=0 arm still stashes the embedding for the confidence head —
1949 // the greedy chain's exact behavior.
1950 let mut f = e.uninit(mk.rank)?;
1951 e.gather_row_bf16(&mk.w1_bf16, &chain_d, k, &mut f, mk.rank)?;
1952 let fv = e.view(&f, mk.rank);
1953 e.copy_view_into(ce, k * mk.rank, &fv, mk.rank)?;
1954 }
1955 let rows_k = e.htod_i32(&[k as i32])?;
1956 let (mut th1, mut z1, mut mx1) = (e.zeros(1)?, e.zeros(1)?, e.zeros(1)?);
1957 e.filter_stats(
1958 dl, n_vocab, &rows_k, &mut th1, &mut z1, &mut mx1, n_vocab, 1, sp.temp, sp.top_k,
1959 sp.top_p, sp.min_p,
1960 )?;
1961 e.gumbel_perturb_filtered_col(
1962 dl, k, &mut pb, n_vocab, sp.seed, *sctr, sp.temp, &mx1, &th1, 0,
1963 )?;
1964 *sctr = sctr.wrapping_add(1);
1965 e.argmax_token_device_col(&pb, 0, n_vocab, &mut chain_d, k + 1)?;
1966 e.copy_into(&mut th_all, k, &th1, 1)?;
1967 e.copy_into(&mut z_all, k, &z1, 1)?;
1968 e.copy_into(&mut mx_all, k, &mx1, 1)?;
1969 }
1970 let chain = e.dtoh_u32(&chain_d)?;
1971 let (thv, zv, mxv) = (e.dtoh(&th_all)?, e.dtoh(&z_all)?, e.dtoh(&mx_all)?);
1972 let stats = (0..nd).map(|i| (mxv[i], thv[i], zv[i])).collect();
1973 Ok((
1974 chain[1..].to_vec(),
1975 DsparkDraftSample::Rows {
1976 th: th_all,
1977 z: z_all,
1978 stats,
1979 },
1980 ))
1981 }
1982
1983 /// Family dispatch for the sampled proposal: Selector for DFlash2, Rows otherwise.
1984 /// Returns the drafted tokens (the round's `cand` tail) + the proposal record.
1985 #[allow(clippy::too_many_arguments)]
1986 pub(crate) fn dspark_propose_sampled(
1987 &self,
1988 e: &Engine,
1989 dl: &mut CudaSlice<f32>,
1990 rows: &CudaSlice<f32>,
1991 nd: usize,
1992 n_vocab: usize,
1993 anchor: u32,
1994 sp: &crate::spec::SpecSampling,
1995 sctr: &mut u32,
1996 uctr: &mut u32,
1997 conf_emb: Option<&mut CudaSlice<f32>>,
1998 d2t: Option<&[u32]>,
1999 ) -> Result<(Vec<u32>, DsparkDraftSample), Box<dyn std::error::Error>> {
2000 if let Some(d2) = self.dflash2.as_ref() {
2001 // The confidence stash is a markov-family program; DFlash2 has no
2002 // accept-rate head (the policy resolver never arms it for this family).
2003 debug_assert!(
2004 conf_emb.is_none(),
2005 "conf_emb stash requested on a DFlash2 selector proposal"
2006 );
2007 let (path, q_chosen, cand, q_rows) = self.dflash2_propose_sampled(
2008 e, dl, rows, nd, n_vocab, anchor, sp.temp, sp.seed, uctr, d2t,
2009 )?;
2010 Ok((
2011 path,
2012 DsparkDraftSample::Selector {
2013 cand,
2014 q_rows,
2015 q_chosen,
2016 top_k: d2.top_k,
2017 },
2018 ))
2019 } else {
2020 self.dspark_chain_sampled(e, dl, nd, n_vocab, anchor, sp, sctr, conf_emb)
2021 }
2022 }
2023
2024 /// FIRST-LIGHT forward (oracle contract): full non-causal attention over
2025 /// [ctx_features ; block], NO draft KV cache, NO sliding window (the oracle bypasses
2026 /// the reference mask machinery the same way — window/caching land in the round arm).
2027 ///
2028 /// `target_hidden`: [ctx, n_taps*hidden] (f32, device) — raw tapped states.
2029 /// `noise_emb`: [block, hidden] — target embed rows for [accepted, MASK x b-1].
2030 /// `pos`: absolute positions for ctx rows THEN block rows (ctx+block i32).
2031 /// Returns final normed hidden [block, hidden] (feed target lm_head for draft logits).
2032 /// ctx features for `t` tapped rows: hidden_norm(fc(taps)) — the drafter's context
2033 /// representation, cacheable across rounds (append-only in committed-token order).
2034 pub fn ctx_features(
2035 &self,
2036 e: &Engine,
2037 taps: &CudaSlice<f32>,
2038 t: usize,
2039 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2040 let c = &self.cfg;
2041 let n_taps = c.target_layer_ids.len();
2042 let fc_out = self.mm(e, &self.fc, taps, t, n_taps * c.hidden, c.hidden)?;
2043 let mut out = e.uninit(t * c.hidden)?;
2044 e.rms_norm(&fc_out, &self.hidden_norm, &mut out, c.hidden, t, c.eps)?;
2045 Ok(out)
2046 }
2047
2048 pub fn forward(
2049 &self,
2050 e: &Engine,
2051 target_hidden: &CudaSlice<f32>,
2052 noise_emb: &CudaSlice<f32>,
2053 pos: &[i32],
2054 ctx: usize,
2055 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2056 let ctx_f = self.ctx_features(e, target_hidden, ctx)?;
2057 if let Ok(dir) = std::env::var("MEMRA_DFLASH_DUMP") {
2058 let v = e.dtoh(&ctx_f)?;
2059 let bytes: Vec<u8> = v.iter().flat_map(|f| f.to_le_bytes()).collect();
2060 std::fs::write(format!("{dir}/memra-ctx_features.f32"), bytes)?;
2061 }
2062 self.forward_block(e, &ctx_f, noise_emb, pos, ctx)
2063 }
2064
2065 /// Block forward over PRECOMPUTED ctx features (the round arm's entry: features are
2066 /// cached across rounds; only the block work repeats).
2067 pub fn forward_block(
2068 &self,
2069 e: &Engine,
2070 ctx_f: &CudaSlice<f32>,
2071 noise_emb: &CudaSlice<f32>,
2072 pos: &[i32],
2073 ctx: usize,
2074 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2075 let c = &self.cfg;
2076 let (h, nh, nkv, hd) = (c.hidden, c.n_head, c.n_kv, c.head_dim);
2077 let b = c.block_size;
2078 assert_eq!(pos.len(), ctx + b, "pos covers ctx rows then block rows");
2079
2080 let pos_blk = e.htod_i32(&pos[ctx..])?;
2081
2082 let mut x = e.clone_dtod(noise_emb)?; // [b, hidden] residual stream
2083 for (li, l) in self.layers.iter().enumerate() {
2084 // input_layernorm on the block rows only (ctx features are norm-free per ref:
2085 // k/v project the SAME ctx_f every layer, un-layernormed).
2086 let mut xn = e.uninit(b * h)?;
2087 e.rms_norm(&x, &l.ln_in, &mut xn, h, b, c.eps)?;
2088 // DFlash2: dynamic conv WRAPS attention — q/k_noise/v_noise all project the
2089 // CONVOLVED block rows (reference decoder layer: prepare -> self_attn ->
2090 // finish, all inside the residual branch). ctx_f is never convolved.
2091 let mut attn_dyn: Option<CudaSlice<f32>> = None;
2092 if let Some(d2) = &self.dflash2 {
2093 let (xc, dyn_) = self.d2_conv_prepare(e, &d2.attn_conv[li], &xn, b)?;
2094 xn = xc;
2095 attn_dyn = Some(dyn_);
2096 }
2097
2098 // q from block; k/v from [ctx_f ; block-normed]
2099 let q0 = self.mm(e, &l.wq, &xn, b, h, nh * hd)?;
2100 let k0c = self.mm(e, &l.wk, ctx_f, ctx, h, nkv * hd)?;
2101 let v0c = self.mm(e, &l.wv, ctx_f, ctx, h, nkv * hd)?;
2102 let k0b = self.mm(e, &l.wk, &xn, b, h, nkv * hd)?;
2103 let v0b = self.mm(e, &l.wv, &xn, b, h, nkv * hd)?;
2104
2105 // per-head q/k rms norm (v passes through: ones weight trick not needed — the
2106 // qkv kernel norms rq+rk rows; concatenate k first).
2107 let mut k0 = e.uninit((ctx + b) * nkv * hd)?;
2108 e.copy_into(&mut k0, 0, &k0c, ctx * nkv * hd)?;
2109 e.copy_into(&mut k0, ctx * nkv * hd, &k0b, b * nkv * hd)?;
2110 let mut v = e.uninit((ctx + b) * nkv * hd)?;
2111 e.copy_into(&mut v, 0, &v0c, ctx * nkv * hd)?;
2112 e.copy_into(&mut v, ctx * nkv * hd, &v0b, b * nkv * hd)?;
2113
2114 if li == 0 {
2115 if let Ok(dir) = std::env::var("MEMRA_DFLASH_DUMP") {
2116 let v = e.dtoh(&q0)?;
2117 let bytes: Vec<u8> = v.iter().flat_map(|f| f.to_le_bytes()).collect();
2118 std::fs::write(format!("{dir}/memra-l0_q0.f32"), bytes)?;
2119 }
2120 }
2121 let mut q = e.uninit(b * nh * hd)?;
2122 let mut k = e.uninit((ctx + b) * nkv * hd)?;
2123 // rms over head_dim rows: q has b*nh rows, k has (ctx+b)*nkv rows.
2124 e.rms_norm(&q0, &l.q_norm, &mut q, hd, b * nh, c.eps)?;
2125 if li == 0 {
2126 if let Ok(dir) = std::env::var("MEMRA_DFLASH_DUMP") {
2127 let v = e.dtoh(&q)?;
2128 let bytes: Vec<u8> = v.iter().flat_map(|f| f.to_le_bytes()).collect();
2129 std::fs::write(format!("{dir}/memra-l0_qn.f32"), bytes)?;
2130 }
2131 }
2132 e.rms_norm(&k0, &l.k_norm, &mut k, hd, (ctx + b) * nkv, c.eps)?;
2133
2134 // rope: q at block positions, k at ctx-then-block positions (absolute).
2135 let norope = std::env::var("MEMRA_DFLASH_NOROPE").is_ok();
2136 if !norope {
2137 self.rope_rows(e, &mut q, &pos_blk, nh, b)?;
2138 }
2139 if li == 0 {
2140 if let Ok(dir) = std::env::var("MEMRA_DFLASH_DUMP") {
2141 let dump = |name: &str,
2142 t: &cudarc::driver::CudaSlice<f32>|
2143 -> Result<(), Box<dyn std::error::Error>> {
2144 let v = e.dtoh(t)?;
2145 let bytes: Vec<u8> = v.iter().flat_map(|f| f.to_le_bytes()).collect();
2146 std::fs::write(format!("{dir}/memra-l0_{name}.f32"), bytes)?;
2147 Ok(())
2148 };
2149 dump("xn", &xn)?;
2150 dump("q_prerope", &q)?;
2151 }
2152 }
2153 // k rows are laid out [row, nkv, hd] with row-major tokens — rope_neox expects
2154 // (n_heads, n_tokens); ctx and block ropes run as one call over ctx+b tokens.
2155 let pos_all = e.htod_i32(pos)?;
2156 if !norope {
2157 self.rope_rows(e, &mut k, &pos_all, nkv, ctx + b)?;
2158 }
2159
2160 // full non-causal attention: every block query sees all ctx+b keys.
2161 let mut attn = e.uninit(b * nh * hd)?;
2162 let scale = 1.0f32 / (hd as f32).sqrt();
2163 // NAIVE SDPA for first light: fa_prefill's NON-CAUSAL arm with T != T_kv is
2164 // BROKEN (attn maxdiff 0.34 vs the torch oracle; q/k inputs bit-close — no
2165 // existing caller exercises that shape class, jsonl 2026-07-13). The 16 x
2166 // (ctx+16) block attention is tiny; the fa arm returns behind this seam once
2167 // its kernel is fixed + parity-gated.
2168 if self.dflash2.is_some() && c.layer_sliding[li] {
2169 // DFlash2 non-causal symmetric window (config is_causal=false, all
2170 // layers sliding). The kernel masks only keys OLDER than
2171 // q_pos-(window-1); the future side (k - q < window) never binds
2172 // because keys reach at most q_pos + block <= q_pos + window
2173 // (asserted at load). Positions must be contiguous — q_pos is derived
2174 // in-kernel as (T_kv - T) + qt.
2175 debug_assert!(pos.windows(2).all(|w| w[1] == w[0] + 1));
2176 d2_windowed_attn(e, &q, &k, &v, &mut attn, hd, nh, nkv, b, ctx + b, scale, c)?;
2177 } else if std::env::var("MEMRA_DFLASH_FA").is_ok() {
2178 e.fa_prefill(&q, &k, &v, &mut attn, hd, nh, nkv, b, ctx + b, scale, false)?;
2179 } else {
2180 e.sdpa_naive(&q, &k, &v, &mut attn, hd, nh, nkv, b, ctx + b, scale, false)?;
2181 }
2182
2183 let mut o = self.mm(e, &l.wo, &attn, b, nh * hd, h)?;
2184 if let (Some(d2), Some(dyn_)) = (&self.dflash2, &attn_dyn) {
2185 o = self.d2_conv_finish(e, &d2.attn_conv[li], &o, dyn_, b)?;
2186 }
2187 let mut x1 = e.uninit(b * h)?;
2188 e.add(&o, &x, &mut x1, b * h)?;
2189 if li == 0 {
2190 if let Ok(dir) = std::env::var("MEMRA_DFLASH_DUMP") {
2191 let dump = |name: &str,
2192 t: &cudarc::driver::CudaSlice<f32>|
2193 -> Result<(), Box<dyn std::error::Error>> {
2194 let v = e.dtoh(t)?;
2195 let bytes: Vec<u8> = v.iter().flat_map(|f| f.to_le_bytes()).collect();
2196 std::fs::write(format!("{dir}/memra-l0_{name}.f32"), bytes)?;
2197 Ok(())
2198 };
2199 dump("q", &q)?;
2200 dump("k", &k)?;
2201 dump("attn", &attn)?;
2202 dump("x1", &x1)?;
2203 }
2204 }
2205
2206 // mlp (DFlash2: the same conv wrap — prepare on the post-ln rows, mlp on
2207 // the convolved rows, finish on the mlp output, then the residual add)
2208 let mut x1n = e.uninit(b * h)?;
2209 e.rms_norm(&x1, &l.ln_post, &mut x1n, h, b, c.eps)?;
2210 let mut mlp_dyn: Option<CudaSlice<f32>> = None;
2211 if let Some(d2) = &self.dflash2 {
2212 let (xc, dyn_) = self.d2_conv_prepare(e, &d2.mlp_conv[li], &x1n, b)?;
2213 x1n = xc;
2214 mlp_dyn = Some(dyn_);
2215 }
2216 let gate = self.mm(e, &l.w_gate, &x1n, b, h, c.n_ff)?;
2217 let up_ = self.mm(e, &l.w_up, &x1n, b, h, c.n_ff)?;
2218 let mut act = e.uninit(b * c.n_ff)?;
2219 e.silu_mul(&gate, &up_, &mut act, b * c.n_ff)?;
2220 let mut down = self.mm(e, &l.w_down, &act, b, c.n_ff, h)?;
2221 if let (Some(d2), Some(dyn_)) = (&self.dflash2, &mlp_dyn) {
2222 down = self.d2_conv_finish(e, &d2.mlp_conv[li], &down, dyn_, b)?;
2223 }
2224 let mut x2 = e.uninit(b * h)?;
2225 e.add(&down, &x1, &mut x2, b * h)?;
2226 x = x2;
2227 if let Ok(dir) = std::env::var("MEMRA_DFLASH_DUMP") {
2228 let v = e.dtoh(&x)?;
2229 let bytes: Vec<u8> = v.iter().flat_map(|f| f.to_le_bytes()).collect();
2230 std::fs::write(format!("{dir}/memra-layer{li}_out.f32"), bytes)?;
2231 }
2232 }
2233 let mut out = e.uninit(b * h)?;
2234 e.rms_norm(&x, &self.norm, &mut out, h, b, c.eps)?;
2235 Ok(out)
2236 }
2237}
2238
2239/// Draft KV cache (round-cost fix, 2026-07-13): per-layer normed+roped ctx K and raw ctx V,
2240/// append-only in committed order. Block K/V land TRANSIENTLY at [len..len+b] each round
2241/// (never committed — the reference crops them identically). Kills the per-round full-ctx
2242/// projection recompute (first light was O(ctx)/round -> 7 tok/s).
2243pub struct DflashKv {
2244 pub k: Vec<CudaSlice<f32>>, // per layer [cap + block, nkv*hd]
2245 pub v: Vec<CudaSlice<f32>>,
2246 pub len: usize,
2247 pub cap: usize,
2248 /// Trailing rows the drafter can still observe: `sliding_window + block_size`. Carried on
2249 /// the KV (not recomputed at call sites) so an export and an import cannot disagree about
2250 /// the geometry — see `DsparkSpecSession::draft_tail_rows`.
2251 window_rows: usize,
2252 /// `n_kv * head_dim * size_of::<f32>()` — the row unit for tail copies.
2253 row_bytes: usize,
2254}
2255
2256impl DflashKv {
2257 pub fn new(
2258 e: &Engine,
2259 cfg: &DflashCfg,
2260 cap: usize,
2261 ) -> Result<Self, Box<dyn std::error::Error>> {
2262 let rowsz = cfg.n_kv * cfg.head_dim;
2263 let mut k = Vec::with_capacity(cfg.n_layer);
2264 let mut v = Vec::with_capacity(cfg.n_layer);
2265 for _ in 0..cfg.n_layer {
2266 k.push(e.uninit((cap + cfg.block_size) * rowsz)?);
2267 v.push(e.uninit((cap + cfg.block_size) * rowsz)?);
2268 }
2269 Ok(Self {
2270 k,
2271 v,
2272 len: 0,
2273 cap,
2274 window_rows: cfg.sliding_window.saturating_add(cfg.block_size),
2275 row_bytes: rowsz * std::mem::size_of::<f32>(),
2276 })
2277 }
2278}
2279
2280impl DflashDraft {
2281 /// Ingest `t` NEW ctx-feature rows (committed order, absolute positions `pos_new`) into
2282 /// the draft KV: per layer k/v projections + k head-norm + rope, appended at kv.len.
2283 pub fn ingest_ctx(
2284 &self,
2285 e: &Engine,
2286 kv: &mut DflashKv,
2287 feats: &CudaSlice<f32>,
2288 pos_new: &[i32],
2289 t: usize,
2290 ) -> Result<(), Box<dyn std::error::Error>> {
2291 let c = &self.cfg;
2292 let (h, nkv, hd) = (c.hidden, c.n_kv, c.head_dim);
2293 assert!(kv.len + t <= kv.cap, "draft kv overflow");
2294 let pos_d = e.htod_i32(pos_new)?;
2295 for (li, l) in self.layers.iter().enumerate() {
2296 let k0 = self.mm(e, &l.wk, feats, t, h, nkv * hd)?;
2297 let v0 = self.mm(e, &l.wv, feats, t, h, nkv * hd)?;
2298 let mut kn = e.uninit(t * nkv * hd)?;
2299 e.rms_norm(&k0, &l.k_norm, &mut kn, hd, t * nkv, c.eps)?;
2300 self.rope_rows(e, &mut kn, &pos_d, nkv, t)?;
2301 e.copy_into(&mut kv.k[li], kv.len * nkv * hd, &kn, t * nkv * hd)?;
2302 e.copy_into(&mut kv.v[li], kv.len * nkv * hd, &v0, t * nkv * hd)?;
2303 }
2304 kv.len += t;
2305 Ok(())
2306 }
2307
2308 /// Block forward over the CACHED ctx KV: only the 16 block rows are projected per layer;
2309 /// block K/V land transiently at kv[len..len+b]. Bit-class-identical to forward_block
2310 /// (same kernels, same per-row programs; ONLY the ctx K/V recompute is cached).
2311 pub fn forward_round(
2312 &self,
2313 e: &Engine,
2314 kv: &mut DflashKv,
2315 noise_emb: &CudaSlice<f32>,
2316 pos_block: &[i32],
2317 ) -> Result<CudaSlice<f32>, Box<dyn std::error::Error>> {
2318 let c = &self.cfg;
2319 let (h, nh, nkv, hd) = (c.hidden, c.n_head, c.n_kv, c.head_dim);
2320 let b = c.block_size;
2321 assert_eq!(pos_block.len(), b);
2322 let ctx = kv.len;
2323 let pos_blk = e.htod_i32(pos_block)?;
2324 let mut x = e.clone_dtod(noise_emb)?;
2325 for (li, l) in self.layers.iter().enumerate() {
2326 let mut xn = e.uninit(b * h)?;
2327 e.rms_norm(&x, &l.ln_in, &mut xn, h, b, c.eps)?;
2328 // DFlash2: dynamic conv wraps attention (see forward_block).
2329 let mut attn_dyn: Option<CudaSlice<f32>> = None;
2330 if let Some(d2) = &self.dflash2 {
2331 let (xc, dyn_) = self.d2_conv_prepare(e, &d2.attn_conv[li], &xn, b)?;
2332 xn = xc;
2333 attn_dyn = Some(dyn_);
2334 }
2335 let q0 = self.mm(e, &l.wq, &xn, b, h, nh * hd)?;
2336 let k0b = self.mm(e, &l.wk, &xn, b, h, nkv * hd)?;
2337 let v0b = self.mm(e, &l.wv, &xn, b, h, nkv * hd)?;
2338 let mut q = e.uninit(b * nh * hd)?;
2339 let mut kb = e.uninit(b * nkv * hd)?;
2340 e.rms_norm(&q0, &l.q_norm, &mut q, hd, b * nh, c.eps)?;
2341 e.rms_norm(&k0b, &l.k_norm, &mut kb, hd, b * nkv, c.eps)?;
2342 self.rope_rows(e, &mut q, &pos_blk, nh, b)?;
2343 self.rope_rows(e, &mut kb, &pos_blk, nkv, b)?;
2344 e.copy_into(&mut kv.k[li], ctx * nkv * hd, &kb, b * nkv * hd)?;
2345 e.copy_into(&mut kv.v[li], ctx * nkv * hd, &v0b, b * nkv * hd)?;
2346 let mut attn = e.uninit(b * nh * hd)?;
2347 let scale = 1.0f32 / (hd as f32).sqrt();
2348 if self.dflash2.is_some() && c.layer_sliding[li] {
2349 // Non-causal symmetric window (config is_causal=false): kv row index
2350 // == absolute position for BOTH ctx rows (committed order) and the
2351 // transient block rows, so the kernel's q_pos = (T_kv - T) + qt is the
2352 // absolute position and the old-side mask is exact. The future side
2353 // never binds (block <= window, asserted at load).
2354 d2_windowed_attn(
2355 e,
2356 &q,
2357 &kv.k[li],
2358 &kv.v[li],
2359 &mut attn,
2360 hd,
2361 nh,
2362 nkv,
2363 b,
2364 ctx + b,
2365 scale,
2366 c,
2367 )?;
2368 } else if std::env::var("MEMRA_DFLASH_FA").is_ok() {
2369 e.fa_prefill(
2370 &q,
2371 &kv.k[li],
2372 &kv.v[li],
2373 &mut attn,
2374 hd,
2375 nh,
2376 nkv,
2377 b,
2378 ctx + b,
2379 scale,
2380 false,
2381 )?;
2382 } else {
2383 e.sdpa_naive(
2384 &q,
2385 &kv.k[li],
2386 &kv.v[li],
2387 &mut attn,
2388 hd,
2389 nh,
2390 nkv,
2391 b,
2392 ctx + b,
2393 scale,
2394 false,
2395 )?;
2396 }
2397 let mut o = self.mm(e, &l.wo, &attn, b, nh * hd, h)?;
2398 if let (Some(d2), Some(dyn_)) = (&self.dflash2, &attn_dyn) {
2399 o = self.d2_conv_finish(e, &d2.attn_conv[li], &o, dyn_, b)?;
2400 }
2401 let mut x1 = e.uninit(b * h)?;
2402 e.add(&o, &x, &mut x1, b * h)?;
2403 let mut x1n = e.uninit(b * h)?;
2404 e.rms_norm(&x1, &l.ln_post, &mut x1n, h, b, c.eps)?;
2405 let mut mlp_dyn: Option<CudaSlice<f32>> = None;
2406 if let Some(d2) = &self.dflash2 {
2407 let (xc, dyn_) = self.d2_conv_prepare(e, &d2.mlp_conv[li], &x1n, b)?;
2408 x1n = xc;
2409 mlp_dyn = Some(dyn_);
2410 }
2411 let gate = self.mm(e, &l.w_gate, &x1n, b, h, c.n_ff)?;
2412 let up_ = self.mm(e, &l.w_up, &x1n, b, h, c.n_ff)?;
2413 let mut act = e.uninit(b * c.n_ff)?;
2414 e.silu_mul(&gate, &up_, &mut act, b * c.n_ff)?;
2415 let mut down = self.mm(e, &l.w_down, &act, b, c.n_ff, h)?;
2416 if let (Some(d2), Some(dyn_)) = (&self.dflash2, &mlp_dyn) {
2417 down = self.d2_conv_finish(e, &d2.mlp_conv[li], &down, dyn_, b)?;
2418 }
2419 let mut x2 = e.uninit(b * h)?;
2420 e.add(&down, &x1, &mut x2, b * h)?;
2421 x = x2;
2422 }
2423 let mut out = e.uninit(b * h)?;
2424 e.rms_norm(&x, &self.norm, &mut out, h, b, c.eps)?;
2425 Ok(out)
2426 }
2427}
2428
2429/// Emit an accepted draft run under the `max_new` budget: check BEFORE each push — at
2430/// real acceptance the final round often accepts a draft at the boundary, and
2431/// push-then-check emitted max_new+1 tokens (plain emits exactly max_new; the E2E gate
2432/// read it as a length divergence at index max_new with the shared prefix
2433/// byte-identical). f8300340cd fixed generate_spec_dspark this way; generate_spec_dflash
2434/// kept the buggy shape until the hermes sweep (fixed 2026-08-23) — both now share this
2435/// one helper. Returns true when the caller must break (budget reached or EOS emitted).
2436fn emit_accepted_run(out: &mut Vec<u32>, accepted: &[u32], eos: &[u32], max_new: usize) -> bool {
2437 for &dt in accepted {
2438 if out.len() >= max_new {
2439 return true;
2440 }
2441 out.push(dt);
2442 if eos.contains(&dt) {
2443 return true;
2444 }
2445 }
2446 false
2447}
2448
2449#[cfg(test)]
2450mod emit_budget_tests {
2451 use super::emit_accepted_run;
2452
2453 #[test]
2454 fn accepted_run_never_exceeds_max_new() {
2455 // TOOTH (hermes finding, fixed 2026-08-23): the dflash accept loop pushed THEN
2456 // checked, emitting max_new+1 whenever the final round accepted at the boundary.
2457 let mut out = vec![1, 2, 3]; // 3 committed, budget 4: exactly ONE slot left
2458 let stop = emit_accepted_run(&mut out, &[10, 11, 12], &[], 4);
2459 assert!(stop, "hitting the budget must break the round loop");
2460 assert_eq!(
2461 out,
2462 vec![1, 2, 3, 10],
2463 "exactly max_new tokens, never max_new+1"
2464 );
2465 // EOS inside the run stops after emitting it (unchanged semantics).
2466 let mut out = vec![1];
2467 let stop = emit_accepted_run(&mut out, &[10, 99, 12], &[99], 8);
2468 assert!(stop);
2469 assert_eq!(out, vec![1, 10, 99]);
2470 // A run fitting the budget with no EOS lets the round continue.
2471 let mut out = vec![1];
2472 assert!(!emit_accepted_run(&mut out, &[10, 11], &[], 8));
2473 assert_eq!(out, vec![1, 10, 11]);
2474 }
2475}
2476
2477// ================= DFlash spec round (greedy, first light) =================
2478// Exact contract: identical output stream to plain greedy decode BY CONSTRUCTION — the
2479// target's batched verify argmax decides every committed token; the drafter only proposes.
2480// (Same verify+rewind pattern as generate_spec_gemma's eager round; t=16 verify rides the
2481// straddle-split-safe fa_decode_rows.)
2482impl crate::hybrid::HybridModel {
2483 pub fn generate_spec_dflash(
2484 &self,
2485 e: &Engine,
2486 draft: &DflashDraft,
2487 prompt: &[u32],
2488 max_new: usize,
2489 eos: &[u32],
2490 ) -> Result<Vec<u32>, Box<dyn std::error::Error>> {
2491 use crate::cache::{Cache, DflashTapSink};
2492 let n_embd = self.cfg.n_embd as usize;
2493 let c = &draft.cfg;
2494 assert!(
2495 draft.dflash2.is_none(),
2496 "DFlash2 drafters ride the qwen-hybrid dspark round (selector + windowed \
2497 attention); the gemma arm has no consumer for the family's ops"
2498 );
2499 assert_eq!(n_embd, c.hidden, "draft hidden must match target n_embd");
2500 let b = c.block_size;
2501 let n_taps = c.target_layer_ids.len();
2502 let max_ctx = prompt.len() + max_new + b + 8;
2503 // First light holds ctx <= sliding_window: the draft was trained with 4 sliding
2504 // layers (window 2048) and the first-light attention is windowless full — inside
2505 // the window the two are identical. The depth cell (1736 + 128) fits.
2506 assert!(
2507 max_ctx <= c.sliding_window,
2508 "first-light dflash round is windowless — ctx cap {} exceeds the draft window {}",
2509 max_ctx,
2510 c.sliding_window
2511 );
2512 let mut cache = Cache::new(e, &self.cfg, max_ctx)?;
2513
2514 // ---- prime with taps armed ----
2515 let tp = prompt.len();
2516 cache.dflash_taps = Some(DflashTapSink {
2517 layer_ids: c.target_layer_ids.clone(),
2518 buf: e.uninit(tp * n_taps * n_embd)?,
2519 hidden: n_embd,
2520 t: tp,
2521 base: 0,
2522 });
2523 let t_prime = std::time::Instant::now();
2524 let (logits, _h_seed, _hiddens) = self.prime_cache(e, prompt, &mut cache, 0)?;
2525 let mut last = crate::forward::argmax(&logits) as u32;
2526 // draft KV cache: ingest the prompt's ctx features once; per round only the kept
2527 // rows ingest + the block projects (round cost O(block), not O(ctx)).
2528 let mut dkv = DflashKv::new(e, &draft.cfg, max_ctx)?;
2529 {
2530 // CHUNKED ingest (depth OOM fix): the 1736-row prompt tap buffer is ~224MB f32;
2531 // running fc + 5-layer k/v projection over it in one shot stacks another
2532 // ~300MB of transients on the ~21.3GB trunk peak. 256-row windows bound the
2533 // transient set; identical values (row-independent ops).
2534 let taps = cache.dflash_taps.take().unwrap();
2535 let n_taps_h = n_taps * n_embd;
2536 let mut r0 = 0usize;
2537 while r0 < tp {
2538 let t_c = (tp - r0).min(256);
2539 let tv = e.view(&taps.buf, tp * n_taps_h);
2540 let win = tv.slice(r0 * n_taps_h..(r0 + t_c) * n_taps_h);
2541 let mut chunk = e.uninit(t_c * n_taps_h)?;
2542 e.copy_view_into(&mut chunk, 0, &win, t_c * n_taps_h)?;
2543 let f = draft.ctx_features(e, &chunk, t_c)?;
2544 let pos_c: Vec<i32> = ((r0 as i32)..(r0 + t_c) as i32).collect();
2545 draft.ingest_ctx(e, &mut dkv, &f, &pos_c, t_c)?;
2546 r0 += t_c;
2547 }
2548 }
2549 let mut ctx_len = tp;
2550 e.stream().synchronize()?;
2551 // published prime wall (the run-spec/gemma-gate timing contract subtracts it)
2552 crate::PRIME_NANOS.store(
2553 t_prime.elapsed().as_nanos() as u64,
2554 std::sync::atomic::Ordering::Relaxed,
2555 );
2556
2557 // embed-scale seam (MEMRA_DFLASH_EMB_SCALE): gemma trunks scale embeddings by
2558 // sqrt(n_embd) INSIDE the forward; whether the z-lab gemma4 training fed the
2559 // drafter scaled or raw embed rows is not visible from the reference (qwen path
2560 // uses raw embed_tokens). Acceptance arbitrates; default raw.
2561 let emb_scale = if std::env::var("MEMRA_DFLASH_EMB_SCALE").as_deref() == Ok("1") {
2562 (n_embd as f32).sqrt()
2563 } else {
2564 1.0
2565 };
2566
2567 let mut out = Vec::with_capacity(max_new);
2568 let n_vocab = self.output.out_features();
2569 // VERIFY WIDTH (MEMRA_DFLASH_VERIFY_T, default 8): the drafter always drafts a full
2570 // block (its trained mask pattern) but only the first vt rows go through the target
2571 // verify — the t=16 verify rides the untuned b16 tier at ~32% of the byte wall
2572 // (65ms/verify) while b8 rides the tuned r2 tier; with ~2.7 committed/round the
2573 // deep block positions almost never survive anyway. Exactness unaffected (verify
2574 // still decides every committed token).
2575 let vt_cap: usize = std::env::var("MEMRA_DFLASH_VERIFY_T")
2576 .ok()
2577 .and_then(|v| v.parse().ok())
2578 .unwrap_or(8)
2579 .clamp(2, b);
2580 // adaptive verify width (MEMRA_DFLASH_ADAPT!=0, MTP accepted+1 recipe): next round
2581 // verifies one past this round's accepted run, clamped [3, cap].
2582 let adapt = std::env::var("MEMRA_DFLASH_ADAPT").as_deref() != Ok("0");
2583 let mut vt = vt_cap;
2584 let mut attempted = 0usize;
2585 let mut accepted = 0usize;
2586 // The whole round runs in the decode-exact matmul scope: the m=16 draft mms were
2587 // otherwise falling into the prefill-GEMM class (770us/matmul, 17% of the depth
2588 // round). Prime (before this loop) keeps the prefill GEMM path. RAII: a `?` exit
2589 // anywhere in the loop restores the pre-scope value instead of latching exact ON
2590 // engine-wide (hermes finding, fixed 2026-08-23).
2591 let exact_scope = e.exact_scope(true);
2592 'outer: while out.len() < max_new {
2593 let start = cache.pos; // committed length
2594 // ---- draft: block = [last, MASK x b-1] ----
2595 let mut block: Vec<u32> = vec![c.mask_token_id; b];
2596 block[0] = last;
2597 let mut noise = e.htod(&self.embd.gather(n_embd, &block))?;
2598 if emb_scale != 1.0 {
2599 e.scale_inplace(&mut noise, emb_scale, b * n_embd)?;
2600 }
2601 if std::env::var("MEMRA_DFLASH_DEBUG").as_deref() == Ok("1") && start == cache.pos {
2602 let nv = e.dtoh(&noise)?;
2603 let r0: f32 = nv[..n_embd].iter().map(|x| x * x).sum::<f32>().sqrt();
2604 let r1: f32 = nv[n_embd..2 * n_embd]
2605 .iter()
2606 .map(|x| x * x)
2607 .sum::<f32>()
2608 .sqrt();
2609 eprintln!(
2610 "[dflash noise] |row0(last)|={r0:.3} |row1(MASK id {})|={r1:.3}",
2611 c.mask_token_id
2612 );
2613 }
2614 let pos_block: Vec<i32> = ((start as i32)..(start + b) as i32).collect();
2615 let dh = draft.forward_round(e, &mut dkv, &noise, &pos_block)?;
2616 // draft tokens = argmax(lm_head(h rows 1..b))
2617 let mut rows = e.uninit((b - 1) * n_embd)?;
2618 {
2619 let dv = e.view(&dh, b * n_embd);
2620 let tail = dv.slice(n_embd..b * n_embd);
2621 e.copy_view_into(&mut rows, 0, &tail, (b - 1) * n_embd)?;
2622 }
2623 let mut dl = e.matmul(&self.output, &rows, b - 1)?;
2624 // SEMI-AR MARKOV CHAIN (DSpark head, when present + MEMRA_DFLASH_MARKOV!=0):
2625 // left-to-right, logits_k += W2(W1[prev realized token]) — the whole chain
2626 // stays on-device (chain_d[0] = the pending token; argmax k writes
2627 // chain_d[k+1], the k+1 bias gathers from it). Greedy mirror of the patch's
2628 // _markov_semiar_sample_block.
2629 let markov_on = std::env::var("MEMRA_DFLASH_MARKOV").as_deref() != Ok("0");
2630 let mut chain_d = e.stream().alloc_zeros::<u32>(b)?;
2631 if let (Some(mk), true) = (&draft.markov, markov_on) {
2632 e.set_u32_one(&mut chain_d, last)?;
2633 for k in 0..(b - 1) {
2634 let mut f = e.uninit(mk.rank)?;
2635 e.gather_row_bf16(&mk.w1_bf16, &chain_d, k, &mut f, mk.rank)?;
2636 let bias = e.matmul(&mk.w2, &f, 1)?;
2637 e.add_row_inplace(&mut dl, &bias, n_vocab, k * n_vocab)?;
2638 e.argmax_token_device_col(&dl, k, n_vocab, &mut chain_d, k + 1)?;
2639 }
2640 } else {
2641 for i in 0..(b - 1) {
2642 e.argmax_token_device_col(&dl, i, n_vocab, &mut chain_d, i + 1)?;
2643 }
2644 }
2645 let chain = e.dtoh_u32(&chain_d)?;
2646 let dtoks = &chain[1..];
2647 for (i, &dt) in dtoks.iter().enumerate() {
2648 block[i + 1] = dt;
2649 }
2650 let dbg = std::env::var("MEMRA_DFLASH_DEBUG").as_deref() == Ok("1");
2651
2652 // ---- verify: one t=vt target forward with taps armed ----
2653 let vblock = &block[..vt];
2654 cache.dflash_taps = Some(DflashTapSink {
2655 layer_ids: c.target_layer_ids.clone(),
2656 buf: e.uninit(vt * n_taps * n_embd)?,
2657 hidden: n_embd,
2658 t: vt,
2659 base: 0,
2660 });
2661 let (vam, _vh) = self.gemma4_decode_step_t_am(e, vblock, start, &mut cache)?;
2662 let taps = cache.dflash_taps.take().unwrap();
2663 if dbg {
2664 eprintln!(
2665 "[dflash r] start={start} last={last}\n draft={:?}\n vam ={:?}",
2666 &block[1..],
2667 &vam
2668 );
2669 }
2670
2671 // ---- accept ----
2672 let mut m = 0usize;
2673 while m < vt - 1 && block[m + 1] as usize == vam[m] as usize {
2674 m += 1;
2675 }
2676 attempted += vt - 1;
2677 accepted += m;
2678 out.push(last);
2679 if eos.contains(&last) {
2680 break 'outer;
2681 }
2682 if emit_accepted_run(&mut out, &block[1..=m], eos, max_new) {
2683 break 'outer;
2684 }
2685 let next = vam[m] as u32;
2686
2687 // ---- commit/rollback: keep m+1 of the b appended rows ----
2688 let keep = m + 1;
2689 for kvl in cache.kv.iter_mut().flatten() {
2690 kvl.len -= vt - keep;
2691 e.set_i32_one(&mut kvl.len_d, kvl.len as i32)?;
2692 }
2693 cache.pos -= vt - keep;
2694
2695 // ---- ingest the kept rows' ctx features into the draft KV ----
2696 {
2697 let tv = e.view(&taps.buf, vt * n_taps * n_embd);
2698 let keep_view = tv.slice(0..keep * n_taps * n_embd);
2699 let mut kept = e.uninit(keep * n_taps * n_embd)?;
2700 e.copy_view_into(&mut kept, 0, &keep_view, keep * n_taps * n_embd)?;
2701 let f = draft.ctx_features(e, &kept, keep)?;
2702 let pos_k: Vec<i32> = ((ctx_len as i32)..(ctx_len + keep) as i32).collect();
2703 draft.ingest_ctx(e, &mut dkv, &f, &pos_k, keep)?;
2704 ctx_len += keep;
2705 }
2706 last = next;
2707 if adapt {
2708 vt = (m + 2).clamp(3, vt_cap);
2709 }
2710 }
2711 drop(exact_scope);
2712 if std::env::var("MEMRA_SPEC_STATS").as_deref() == Ok("1") {
2713 eprintln!(
2714 "[dflash] acceptance {accepted}/{attempted} = {:.3}",
2715 accepted as f64 / attempted.max(1) as f64
2716 );
2717 }
2718 Ok(out)
2719 }
2720}
2721
2722// ================= Engine-bundle slice 1: batched GDN state snapshot ====================
2723// DSF-ROUNDCOST-20260820 §1.1 measured the dspark round's `cache.snapshot(e)` at 0.67 ms
2724// native wall — 48 linear layers x {conv, ssm} x (alloc_zeros + memcpy_dtod) of pure
2725// dispatch serialization, zero kernels. This batcher holds ONE persistent CacheSnapshot
2726// (buffers allocated on round 1, reused every round — kills the per-round alloc/memset
2727// churn) plus device pointer tables, so a round's snap is one small H2D table refresh
2728// (the ssm handles ping-pong per verify row, so live pointers are re-read each round;
2729// conv handles are rolled in place and never move) + TWO `copy_batch_uniform_f32`
2730// launches. Bytes, buffers and stream order are identical to `Cache::snapshot`; only the
2731// dispatch count changes, so acceptance and streams stay bit-identical (E2E-gated).
2732// `MEMRA_STATE_COPY_BATCH=0` reverts to the legacy per-layer snapshot.
2733
2734pub(crate) struct DsparkSnapBatch {
2735 pub(crate) snap: crate::cache::CacheSnapshot,
2736 /// Linear-attention layer indices, in `conv_table`/`ssm_table` order.
2737 lin: Vec<usize>,
2738 /// [src_0..src_{n-1}, dst_0..dst_{n-1}] — live conv states -> snapshot conv buffers.
2739 conv_table: CudaSlice<u64>,
2740 ssm_table: CudaSlice<u64>,
2741 host_ssm: Vec<u64>,
2742 conv_words: usize,
2743 ssm_words: usize,
2744}
2745
2746impl DsparkSnapBatch {
2747 /// Build from a fresh full snapshot (this IS round 1's snap — the caller uses
2748 /// `self.snap` directly after `new`). Returns None when the cache has no linear
2749 /// layers or their state sizes are non-uniform (a future hybrid shape) — the caller
2750 /// then stays on the legacy per-layer snapshot rather than copying wrong byte counts.
2751 pub(crate) fn new(
2752 e: &Engine,
2753 cache: &crate::cache::Cache,
2754 ) -> Result<Option<Self>, Box<dyn std::error::Error>> {
2755 use cudarc::driver::DevicePtr;
2756 let snap = cache.snapshot(e)?;
2757 let lin: Vec<usize> = (0..cache.recur.len())
2758 .filter(|&il| cache.recur[il].is_some())
2759 .collect();
2760 if lin.is_empty() {
2761 return Ok(None);
2762 }
2763 let first = cache.recur[lin[0]].as_ref().unwrap();
2764 let (conv_words, ssm_words) = (first.conv_state.len(), first.ssm_state.len());
2765 for &il in &lin {
2766 let rl = cache.recur[il].as_ref().unwrap();
2767 if rl.conv_state.len() != conv_words || rl.ssm_state.len() != ssm_words {
2768 return Ok(None);
2769 }
2770 }
2771 let n = lin.len();
2772 let mut host_conv = vec![0u64; 2 * n];
2773 let mut host_ssm = vec![0u64; 2 * n];
2774 {
2775 let s = &e.gpu.stream();
2776 for (k, &il) in lin.iter().enumerate() {
2777 let rl = cache.recur[il].as_ref().unwrap();
2778 let (pc, _g0) = rl.conv_state.device_ptr(s);
2779 let (ps, _g1) = rl.ssm_state.device_ptr(s);
2780 let (dc, _g2) = snap.conv[il].as_ref().unwrap().device_ptr(s);
2781 let (ds, _g3) = snap.ssm[il].as_ref().unwrap().device_ptr(s);
2782 host_conv[k] = pc as u64;
2783 host_conv[n + k] = dc as u64;
2784 host_ssm[k] = ps as u64;
2785 host_ssm[n + k] = ds as u64;
2786 }
2787 }
2788 let conv_table = e.htod_u64(&host_conv)?;
2789 let ssm_table = e.htod_u64(&host_ssm)?;
2790 Ok(Some(Self {
2791 snap,
2792 lin,
2793 conv_table,
2794 ssm_table,
2795 host_ssm,
2796 conv_words,
2797 ssm_words,
2798 }))
2799 }
2800
2801 /// The per-round snap: refresh kv lens/pos host-side (as `snapshot_into` does),
2802 /// re-read the live ssm handles into the table (gdn ping-pong moves them; the conv
2803 /// handles and every snapshot dst are stable), then two batched-copy launches.
2804 pub(crate) fn refresh(
2805 &mut self,
2806 e: &Engine,
2807 cache: &crate::cache::Cache,
2808 ) -> Result<(), Box<dyn std::error::Error>> {
2809 use cudarc::driver::DevicePtr;
2810 for il in 0..cache.kv.len() {
2811 self.snap.kv_len[il] = cache.kv[il].as_ref().map(|kvl| kvl.len);
2812 }
2813 self.snap.pos = cache.pos;
2814 let n = self.lin.len();
2815 {
2816 let s = &e.gpu.stream();
2817 for (k, &il) in self.lin.iter().enumerate() {
2818 let rl = cache.recur[il].as_ref().unwrap();
2819 let (ps, _g) = rl.ssm_state.device_ptr(s);
2820 self.host_ssm[k] = ps as u64;
2821 }
2822 }
2823 e.htod_u64_into(&self.host_ssm, &mut self.ssm_table)?;
2824 e.copy_batch_uniform_f32(&self.conv_table, n, self.conv_words)?;
2825 e.copy_batch_uniform_f32(&self.ssm_table, n, self.ssm_words)?;
2826 Ok(())
2827 }
2828}
2829
2830// ================= DSpark spec round, QWEN-HYBRID target (lane/dspark-q38-recover) =====
2831// The q38 twin of generate_spec_dflash. Same drafter machinery (rounds, markov chain,
2832// draft KV, adaptive verify width); the TARGET side swaps gemma4's dense verify for the
2833// qwen serving-class verify funnel (dspark_verify_t_am) + snapshot/rollback, because the
2834// hybrid GDN conv/ssm state mutates in place — dense KV truncation cannot roll it back.
2835// Exactness contract unchanged: identical stream to plain greedy BY CONSTRUCTION (the
2836// target's verify argmax decides every committed token).
2837impl crate::hybrid::HybridModel {
2838 pub fn generate_spec_dspark(
2839 &self,
2840 e: &Engine,
2841 draft: &DflashDraft,
2842 prompt: &[u32],
2843 max_new: usize,
2844 eos: &[u32],
2845 sampling: Option<&crate::spec::SpecSampling>,
2846 ) -> Result<Vec<u32>, Box<dyn std::error::Error>> {
2847 use crate::cache::{Cache, DflashTapSink};
2848 assert!(
2849 !self.uses_gemma_program(),
2850 "gemma4 targets use generate_spec_dflash; this is the qwen-hybrid arm"
2851 );
2852 // SAMPLED ADMISSION (T>0, lane/dspark-sampled-admission-20260820): Some+temp>0
2853 // routes the round's proposal/accept through the rejection-sampling arms; None or
2854 // temp==0 keeps every greedy path byte-identical (the exactness instrument).
2855 let sp_on: Option<&crate::spec::SpecSampling> = sampling.filter(|s| s.temp > 0.0);
2856 // PENALTIES AT T==0 ARE A LOUD REFUSAL (lane/dspark-penalized-sampled-20260821):
2857 // the greedy walk argmaxes RAW verify columns, so a temp==0 config carrying
2858 // non-identity penalties would silently serve the UNPENALIZED greedy stream —
2859 // exactly the H-class silent-program-switch this route refuses everywhere else.
2860 // Penalized greedy stays on the plain path (worker admission owns the exclusion).
2861 if let Some(s) = sampling {
2862 if s.temp <= 0.0 && s.pen_on() {
2863 return Err(
2864 "dspark spec at temp==0 is the greedy route and would silently drop \
2865 the request's penalties; penalized greedy is served on the plain path"
2866 .into(),
2867 );
2868 }
2869 }
2870 // Penalized-sampled state: the session window (pen_window_seed — one definition
2871 // across both spec routes), extended with every committed token; each round's
2872 // accept receives the trimmed tail (min(penalty_last_n, PEN_WINDOW_MAX)).
2873 let pen_on = sp_on.is_some_and(|s| s.pen_on());
2874 let mut pen_hist: Vec<u32> = if pen_on {
2875 crate::spec::pen_window_seed(&[], prompt, sp_on.unwrap().penalty_last_n)
2876 } else {
2877 Vec::new()
2878 };
2879 let (mut sctr, mut uctr) = (0u32, 0u32);
2880 let n_embd = self.cfg.n_embd as usize;
2881 let c = &draft.cfg;
2882 assert_eq!(n_embd, c.hidden, "draft hidden must match target n_embd");
2883 let b = c.block_size;
2884 let n_taps = c.target_layer_ids.len();
2885 let max_ctx = prompt.len() + max_new + b + 8;
2886 // DFlash2 implements the reference's non-causal symmetric sliding window in
2887 // the round attention (sdpa_naive_w), so depth past the window is admitted;
2888 // other families keep the historical windowless contract.
2889 assert!(
2890 draft.dflash2.is_some() || max_ctx <= c.sliding_window,
2891 "dspark round is windowless — ctx cap {} exceeds the draft window {}",
2892 max_ctx,
2893 c.sliding_window
2894 );
2895 let mut cache = Cache::new(e, &self.cfg, max_ctx)?;
2896
2897 // ---- prime with taps armed (chunked prime writes at chunk offsets via sink.base) ----
2898 let tp = prompt.len();
2899 cache.dflash_taps = Some(DflashTapSink {
2900 layer_ids: c.target_layer_ids.clone(),
2901 buf: e.uninit(tp * n_taps * n_embd)?,
2902 hidden: n_embd,
2903 t: tp,
2904 base: 0,
2905 });
2906 let t_prime = std::time::Instant::now();
2907 let (logits, _h_seed, _hiddens) = self.prime_cache(e, prompt, &mut cache, 0)?;
2908 // Boundary token: greedy takes the argmax (byte contract); sampled draws it from
2909 // the request's own filtered target through the session Philox stream — the same
2910 // shipped composition the frspec route uses (sample_check arm 9 oracles it).
2911 let mut last = match sp_on {
2912 Some(sp) => crate::spec::sample_boundary_token(
2913 e,
2914 &logits,
2915 sp,
2916 &pen_hist,
2917 &mut sctr,
2918 "dspark-prime",
2919 )?,
2920 None => crate::forward::argmax(&logits) as u32,
2921 };
2922 let mut dkv = DflashKv::new(e, &draft.cfg, max_ctx)?;
2923 {
2924 let taps = cache.dflash_taps.take().unwrap();
2925 let n_taps_h = n_taps * n_embd;
2926 let mut r0 = 0usize;
2927 while r0 < tp {
2928 let t_c = (tp - r0).min(256);
2929 let tv = e.view(&taps.buf, tp * n_taps_h);
2930 let win = tv.slice(r0 * n_taps_h..(r0 + t_c) * n_taps_h);
2931 let mut chunk = e.uninit(t_c * n_taps_h)?;
2932 e.copy_view_into(&mut chunk, 0, &win, t_c * n_taps_h)?;
2933 let f = draft.ctx_features(e, &chunk, t_c)?;
2934 let pos_c: Vec<i32> = ((r0 as i32)..(r0 + t_c) as i32).collect();
2935 draft.ingest_ctx(e, &mut dkv, &f, &pos_c, t_c)?;
2936 r0 += t_c;
2937 }
2938 }
2939 let mut ctx_len = tp;
2940 e.stream().synchronize()?;
2941 crate::PRIME_NANOS.store(
2942 t_prime.elapsed().as_nanos() as u64,
2943 std::sync::atomic::Ordering::Relaxed,
2944 );
2945
2946 let mut out = Vec::with_capacity(max_new);
2947 let n_vocab = self.output.out_features();
2948 // Harvest convention (DSPARK-POSTMORTEM-20260820.md): which drafter output rows
2949 // become draft candidates. nd = drafts/round; verify carries [anchor, drafts]
2950 // = up to nd+1 rows. FAMILY-keyed for DFlash2 (mask-fill by construction),
2951 // else default = the CHECKPOINT's own strategy census (owner-ratified flip,
2952 // 2026-08-20); explicit env still wins (contradiction refuses).
2953 let harvest = DsparkHarvest::for_draft(draft);
2954 let nd = harvest.n_drafts(b);
2955 let r0 = harvest.first_row();
2956 let vt_cap: usize = std::env::var("MEMRA_DFLASH_VERIFY_T")
2957 .ok()
2958 .and_then(|v| v.parse().ok())
2959 .unwrap_or(nd + 1)
2960 .clamp(2, nd + 1);
2961 let adapt = std::env::var("MEMRA_DFLASH_ADAPT").as_deref() != Ok("0");
2962 // Verify-window policy (H4, DSPARK-POSTMORTEM-20260820.md): default =
2963 // confidence-slot tau=.5 when the checkpoint carries an accept-rate head
2964 // (owner-ratified flip 2026-08-20; cell-3 tau ladder knee) — each round's
2965 // window is sized from the head's own slot scores, post-draft pre-verify.
2966 // Head-less checkpoints and MEMRA_DFLASH_ADAPT=0 keep the reactive ladder.
2967 let vt_policy = DsparkVtPolicy::resolve(draft.confidence.is_some());
2968 if vt_policy.is_confidence() {
2969 assert!(
2970 draft.confidence.is_some(),
2971 "MEMRA_DSPARK_VT={vt_policy:?} needs a checkpoint with an accept-rate \
2972 head (confidence_head.* absent in this export)"
2973 );
2974 }
2975 let mut vt = vt_cap;
2976 let mut attempted = 0usize;
2977 let mut accepted = 0usize;
2978 // Engine-bundle slice 1: persistent batched snapshot (None until round 1; stays
2979 // None — legacy per-layer snapshot — under MEMRA_STATE_COPY_BATCH=0 or when the
2980 // batcher declines the cache shape).
2981 let mut snapb: Option<DsparkSnapBatch> = None;
2982 let mut snapb_off = !crate::spec::state_copy_batch_on();
2983 // Engine-bundle slice 2: deferred chain readback needs the resident embed table
2984 // (verify then embeds chain_d directly). Ladder/stash arms only — the confidence
2985 // policies size vt from a pre-verify head readback and keep the legacy order.
2986 let defer_rb = crate::spec::dspark_defer_readback_on() && !vt_policy.is_confidence();
2987 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
2988 let embd_gpu = if !defer_rb || crate::spec::spec_host_embd() {
2989 None
2990 } else {
2991 Some(
2992 self.embd_gpu
2993 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
2994 )
2995 };
2996 // Engine-bundle slice 3: per-(segment, vt) verify graphs for the linear-layer runs
2997 // (rides the slice-2 deferred path only — device tokens keep the whole verify off
2998 // the host). PERSISTENT across generations on the model (rebuilding per call
2999 // re-captured ~80 graphs per prompt — measured 97.8 -> 79.1 tok/s e2e); the
3000 // captured bodies are cache-independent: all state reads go through per-round
3001 // refreshed pointer tables and ctx-owned slabs. None = eager walk, byte-identical.
3002 let mut vg_guard = self.dspark_vgraphs.lock().unwrap();
3003 if vg_guard.is_none() && embd_gpu.is_some() && crate::spec::dspark_verify_graph_on() {
3004 *vg_guard = crate::spec::DsparkVerifyGraphs::new(e, &cache, vt_cap, n_embd)?;
3005 }
3006 let vgraphs: &mut Option<crate::spec::DsparkVerifyGraphs> = &mut vg_guard;
3007 // per-phase economics counters (ns) — the verify-toll dataset
3008 let (mut ns_draft, mut ns_snap, mut ns_verify, mut ns_roll, mut ns_ingest) =
3009 (0u64, 0u64, 0u64, 0u64, 0u64);
3010 let mut rounds = 0usize;
3011 let stats = std::env::var("MEMRA_SPEC_STATS").as_deref() == Ok("1");
3012 let clock = |on: bool, e: &Engine| -> std::time::Instant {
3013 if on {
3014 let _ = e.stream().synchronize();
3015 }
3016 std::time::Instant::now()
3017 };
3018 'outer: while out.len() < max_new {
3019 rounds += 1;
3020 let start = cache.pos; // committed length
3021 // ---- draft: block = [last, MASK x b-1] (decode-exact class for the m=b mms) ----
3022 let t0 = clock(stats, e);
3023 // RAII: a `?` exit restores the pre-scope value instead of latching exact
3024 // ON engine-wide (hermes finding, fixed 2026-08-23).
3025 let exact_scope = e.exact_scope(true);
3026 let mut block: Vec<u32> = vec![c.mask_token_id; b];
3027 block[0] = last;
3028 let noise = e.htod(&self.embd.gather(n_embd, &block))?;
3029 let pos_block: Vec<i32> = ((start as i32)..(start + b) as i32).collect();
3030 let dh = draft.forward_round(e, &mut dkv, &noise, &pos_block)?;
3031 // Harvest: logits over rows r0..r0+nd (Dflash: mask rows 1..b-1, fill
3032 // semantics; Dspark: ALL b rows, shifted semantics — row k predicts
3033 // anchor+k+1, so col k of `dl` is the draft for position start+k+1).
3034 let mut rows = e.uninit(nd * n_embd)?;
3035 {
3036 let dv = e.view(&dh, b * n_embd);
3037 let src = dv.slice(r0 * n_embd..(r0 + nd) * n_embd);
3038 e.copy_view_into(&mut rows, 0, &src, nd * n_embd)?;
3039 }
3040 // TRIMMED DRAFT HEAD (lane/dflash2-head-trim, 2026-08-25): DFlash2 family
3041 // only — the selector consumes (value, candidate-id) pairs, so a d2t remap
3042 // after top-k restores true ids; the markov/chain arms argmax dl columns
3043 // into token ids DIRECTLY and must keep the full head. Reuses the FR-Spec
3044 // self-trim the load path builds on the MTP struct (MEMRA_FRSPEC_TRIM):
3045 // gathered rows of the target's own head, zero requant. Verify stays
3046 // full-vocab, so the trim moves draft acceptance only, never output.
3047 let trim = if draft.dflash2.is_some() {
3048 self.mtp
3049 .as_ref()
3050 .filter(|m| m.d2t_from_target_head)
3051 .and_then(|m| m.shared_head_head.as_ref().zip(m.d2t.as_ref()))
3052 .filter(|(_, d2t)| !d2t.is_empty())
3053 } else {
3054 None
3055 };
3056 let (dl_head, dl_vocab) = match trim {
3057 Some((head, d2t)) => (head, d2t.len()),
3058 None => (&self.output, n_vocab),
3059 };
3060 let trim_d2t = trim.map(|(_, d2t)| d2t.as_slice());
3061 let mut dl = e.matmul(dl_head, &rows, nd)?;
3062 // Family/sampling-keyed proposal (v0.100 train merge of the port and H4/
3063 // engine-bundle stacks — BOTH programs preserved):
3064 // - SAMPLED (sp_on): rejection-sampling proposal, records the true per-slot
3065 // q (family-keyed inside: selector for DFlash2, markov-corrected rows
3066 // otherwise). Host CDF/readback syncs inside — slice-2 deferral N/A.
3067 // - DFlash2 greedy: the candidate path selector REPLACES the markov chain
3068 // (reference DFlash2DraftModel.propose — greedy arm).
3069 // - markov/plain greedy chain: the engine-bundle arm; slice-2 readback
3070 // deferral decided below (needs the ckpt arm reads).
3071 // Confidence policy: stash each slot's markov prev-token embedding (the
3072 // exact `w1` row the chain gathers) into a [nd, rank] buffer — d2d async,
3073 // read back beside `rows` in one host sync after the chain.
3074 let want_conf_emb = vt_policy.is_confidence()
3075 && draft.confidence.as_ref().is_some_and(|ch| ch.with_markov);
3076 let mut conf_emb: Option<CudaSlice<f32>> = match (&draft.markov, want_conf_emb) {
3077 (Some(mk), true) => Some(e.uninit(nd * mk.rank)?),
3078 (None, true) => unreachable!(
3079 "with_markov confidence head without a markov table — the loader forbids it"
3080 ),
3081 _ => None,
3082 };
3083 let mut cand: Vec<u32> = Vec::with_capacity(nd + 1);
3084 let mut prop: Option<DsparkDraftSample> = None;
3085 let mut chain_dev: Option<CudaSlice<u32>> = None;
3086 if let Some(sp) = sp_on {
3087 let (tail, ds) = draft.dspark_propose_sampled(
3088 e,
3089 &mut dl,
3090 &rows,
3091 nd,
3092 dl_vocab,
3093 last,
3094 sp,
3095 &mut sctr,
3096 &mut uctr,
3097 conf_emb.as_mut(),
3098 trim_d2t,
3099 )?;
3100 drop(exact_scope);
3101 cand.push(last);
3102 cand.extend_from_slice(&tail);
3103 prop = Some(ds);
3104 } else if draft.dflash2.is_some() {
3105 let path =
3106 draft.dflash2_propose_greedy(e, &dl, &rows, nd, dl_vocab, last, trim_d2t)?;
3107 drop(exact_scope);
3108 cand.push(last);
3109 cand.extend_from_slice(&path);
3110 } else {
3111 let markov_on = std::env::var("MEMRA_DFLASH_MARKOV").as_deref() != Ok("0");
3112 let mut chain_d = e.stream().alloc_zeros::<u32>(nd + 1)?;
3113 if let (Some(mk), true) = (&draft.markov, markov_on) {
3114 e.set_u32_one(&mut chain_d, last)?;
3115 for k in 0..nd {
3116 let mut f = e.uninit(mk.rank)?;
3117 e.gather_row_bf16(&mk.w1_bf16, &chain_d, k, &mut f, mk.rank)?;
3118 if let Some(ce) = conf_emb.as_mut() {
3119 let fv = e.view(&f, mk.rank);
3120 e.copy_view_into(ce, k * mk.rank, &fv, mk.rank)?;
3121 }
3122 let bias = e.matmul(&mk.w2, &f, 1)?;
3123 e.add_row_inplace(&mut dl, &bias, n_vocab, k * n_vocab)?;
3124 e.argmax_token_device_col(&dl, k, n_vocab, &mut chain_d, k + 1)?;
3125 }
3126 } else {
3127 if want_conf_emb {
3128 // chain_d[0] must carry the anchor — slot 0's prev token.
3129 e.set_u32_one(&mut chain_d, last)?;
3130 }
3131 for i in 0..nd {
3132 if let (Some(ce), Some(mk)) = (conf_emb.as_mut(), &draft.markov) {
3133 let mut f = e.uninit(mk.rank)?;
3134 e.gather_row_bf16(&mk.w1_bf16, &chain_d, i, &mut f, mk.rank)?;
3135 let fv = e.view(&f, mk.rank);
3136 e.copy_view_into(ce, i * mk.rank, &fv, mk.rank)?;
3137 }
3138 e.argmax_token_device_col(&dl, i, n_vocab, &mut chain_d, i + 1)?;
3139 }
3140 }
3141 drop(exact_scope);
3142 chain_dev = Some(chain_d);
3143 }
3144 // MEMRA_DSPARK_CKPT (default 1): verify with the MTP column-stash armed so a
3145 // partial accept restores state directly. =0 keeps the snapshot+replay arm
3146 // (the oracle the stash arm is gated against — MEMRA_DSPARK_CKPT_GATE=1 runs
3147 // BOTH per partial round and byte-compares the resulting cache state).
3148 // Read here (was at the verify site) — slice 2's deferral needs the arm
3149 // choice before deciding whether the chain readback can move past verify.
3150 let ckpt_on = std::env::var("MEMRA_DSPARK_CKPT").as_deref() != Ok("0");
3151 let ckpt_gate = std::env::var("MEMRA_DSPARK_CKPT_GATE").as_deref() == Ok("1");
3152 // SAMPLED x ckpt-gate refusal: the gate compares verify argmaxes across a
3153 // replay — a greedy-exactness instrument (port lane). Refuse loudly.
3154 if sp_on.is_some() && ckpt_gate {
3155 return Err(
3156 "MEMRA_DSPARK_CKPT_GATE compares verify argmaxes across a replay \
3157 — a greedy-exactness instrument; unset it for T>0 dspark rounds"
3158 .into(),
3159 );
3160 }
3161 // Slice 2: under the stash/gate arms with a resident embed table, the GREEDY
3162 // chain readback is DEFERRED past verify dispatch and merged with the argmax
3163 // readback into one sync. The replay arm (CKPT=0) verifies host tokens and
3164 // keeps the legacy order; the sampled and DFlash2 proposals already synced
3165 // at the walk (chain_dev is None there).
3166 let deferred = chain_dev.is_some() && embd_gpu.is_some() && (ckpt_on || ckpt_gate);
3167 // ---- H4 confidence window: size THIS round's verify from the head ----
3168 if vt_policy.is_confidence() {
3169 let ch = draft.confidence.as_ref().expect("asserted at loop entry");
3170 let (rows_h, emb_h) = match conf_emb.as_ref() {
3171 Some(ce) => {
3172 let (a, b2) = e.dtoh_pair(&rows, ce)?;
3173 (a, Some(b2))
3174 }
3175 None => (e.dtoh(&rows)?, None),
3176 };
3177 let rank = draft.markov.as_ref().map(|m| m.rank).unwrap_or(0);
3178 let mut raws = Vec::with_capacity(nd);
3179 for k in 0..nd {
3180 let hrow = &rows_h[k * n_embd..(k + 1) * n_embd];
3181 let emb = emb_h.as_ref().map(|eh| &eh[k * rank..(k + 1) * rank]);
3182 raws.push(ch.raw_score(hrow, emb));
3183 }
3184 vt = vt_policy
3185 .size_window(&raws, vt_cap)
3186 .expect("confidence policies always size the window");
3187 }
3188 // Verify candidates: [anchor, draft 1..nd]. Under Dflash this is the
3189 // historical `block` content; under Dspark it is one longer than the
3190 // drafter's input block (nd = b drafts + the anchor). The sampled/DFlash2
3191 // proposals built `cand` at the walk; deferred greedy rounds build it after
3192 // the merged readback — the bytes are identical (chain_d is written before
3193 // either sync).
3194 if let Some(chain_d) = chain_dev.as_ref() {
3195 if !deferred {
3196 let chain = e.dtoh_u32(chain_d)?;
3197 cand.push(last);
3198 cand.extend_from_slice(&chain[1..]);
3199 }
3200 }
3201 ns_draft += clock(stats, e).duration_since(t0).as_nanos() as u64;
3202
3203 // ---- snapshot (GDN conv/ssm state + KV lens), then verify t=vt ----
3204 let t1 = std::time::Instant::now();
3205 // Slice 1: batched snap (one table refresh + two copy launches) with the
3206 // legacy per-layer snapshot as the kill-switch / non-uniform fallback.
3207 let mut snap_legacy: Option<crate::cache::CacheSnapshot> = None;
3208 if !snapb_off && snapb.is_none() {
3209 snapb = DsparkSnapBatch::new(e, &cache)?;
3210 snapb_off = snapb.is_none();
3211 } else if let Some(sb) = snapb.as_mut() {
3212 sb.refresh(e, &cache)?;
3213 }
3214 let snap: &crate::cache::CacheSnapshot = match snapb.as_ref() {
3215 Some(sb) => &sb.snap,
3216 None => {
3217 snap_legacy = Some(cache.snapshot(e)?);
3218 snap_legacy.as_ref().unwrap()
3219 }
3220 };
3221 let _ = &snap_legacy;
3222 ns_snap += clock(stats, e).duration_since(t1).as_nanos() as u64;
3223 let t2 = std::time::Instant::now();
3224 // Slice 3: the tap-sink buffer is persistent per vt in the graphs ctx
3225 // (captured segments bake its address); fully rewritten by every verify.
3226 let tap_buf = match vgraphs.as_mut().and_then(|g| g.tap_bufs.remove(&vt)) {
3227 Some(buf) => buf,
3228 None => e.uninit(vt * n_taps * n_embd)?,
3229 };
3230 cache.dflash_taps = Some(DflashTapSink {
3231 layer_ids: c.target_layer_ids.clone(),
3232 buf: tap_buf,
3233 hidden: n_embd,
3234 t: vt,
3235 base: 0,
3236 });
3237 // The whole fallible verify window runs inside a closure so the Err path can
3238 // return the sink buffer to the ctx pool before propagating (v0.98 review
3239 // carry-over): five `?`s span the window, and an early return would drop
3240 // `cache.dflash_taps` — freeing the buffer whose ADDRESS the model-persistent
3241 // captured graphs bake, so the next generation's replayed tap copies would
3242 // write freed memory. The never-orphan invariant below now holds on EVERY
3243 // exit, not just the EOS/budget break.
3244 let verify_res = (|cache: &mut crate::cache::Cache,
3245 cand: &mut Vec<u32>,
3246 vgraphs: &mut Option<crate::spec::DsparkVerifyGraphs>|
3247 -> Result<
3248 (
3249 Vec<u32>,
3250 Option<CudaSlice<f32>>,
3251 Option<crate::spec::DsparkVerifyCkpt>,
3252 ),
3253 Box<dyn std::error::Error>,
3254 > {
3255 if sp_on.is_some() {
3256 // SAMPLED: keep the raw verify logits — the accept walk gathers
3257 // filtered p from them (argmaxes are the greedy arm's instrument,
3258 // not this one's).
3259 if ckpt_on {
3260 let (tl, vck) =
3261 self.dspark_verify_t_logits_ckpt(e, &cand[..vt], start, cache)?;
3262 Ok((Vec::new(), Some(tl), Some(vck)))
3263 } else {
3264 Ok((
3265 Vec::new(),
3266 Some(self.dspark_verify_t_logits(e, &cand[..vt], start, cache)?),
3267 None,
3268 ))
3269 }
3270 } else if deferred {
3271 // Slice 2: verify embeds the DEVICE chain (cand layout by construction:
3272 // chain_d[0] = anchor, chain_d[1..] = drafts), then ONE host sync reads
3273 // chain + verify argmaxes together — the host dispatched snap + all of
3274 // verify while the draft was still executing.
3275 let chain_d = chain_dev.as_ref().expect("deferred implies greedy chain");
3276 let g = embd_gpu.expect("deferred implies resident embed");
3277 let (am_d, vck) = self.dspark_verify_t_am_ckpt_dev(
3278 e,
3279 chain_d,
3280 vt,
3281 start,
3282 cache,
3283 (g, embd_qt, embd_rb),
3284 vgraphs.as_mut(),
3285 )?;
3286 let ch = e.stream().clone_dtoh(chain_d)?;
3287 let am = e.stream().clone_dtoh(&am_d)?;
3288 e.stream().synchronize()?;
3289 cand.push(last);
3290 cand.extend_from_slice(&ch[1..]);
3291 Ok((am, None, Some(vck)))
3292 } else if ckpt_on || ckpt_gate {
3293 let (vam, vck) = self.dspark_verify_t_am_ckpt(e, &cand[..vt], start, cache)?;
3294 Ok((vam, None, Some(vck)))
3295 } else {
3296 Ok((
3297 self.dspark_verify_t_am(e, &cand[..vt], start, cache)?,
3298 None,
3299 None,
3300 ))
3301 }
3302 })(&mut cache, &mut cand, vgraphs);
3303 let (vam, tl, vck) = match verify_res {
3304 Ok(v) => v,
3305 Err(err) => {
3306 if let (Some(g), Some(taps)) = (vgraphs.as_mut(), cache.dflash_taps.take()) {
3307 g.tap_bufs.insert(vt, taps.buf);
3308 }
3309 return Err(err);
3310 }
3311 };
3312 let taps = cache.dflash_taps.take().unwrap();
3313 // Return the tap buffer to the ctx pool IMMEDIATELY — an EOS/budget break
3314 // between accept and ingest must never orphan an address the captured
3315 // graphs bake (the next generation would alloc a fresh buffer and the
3316 // replayed tap copies would write freed memory). Ingest reads it borrowed.
3317 let tap_local: Option<CudaSlice<f32>> = match vgraphs.as_mut() {
3318 Some(g) => {
3319 g.tap_bufs.insert(vt, taps.buf);
3320 None
3321 }
3322 None => Some(taps.buf),
3323 };
3324 let tap_ref: &CudaSlice<f32> = match &tap_local {
3325 Some(b) => b,
3326 None => &vgraphs.as_ref().expect("ctx present above").tap_bufs[&vt],
3327 };
3328 ns_verify += clock(stats, e).duration_since(t2).as_nanos() as u64;
3329
3330 // ---- accept ----
3331 // Penalized-sampled: the anchor `last` is committed THIS round unconditionally
3332 // (the out.push below), so it joins the window before the accept walk — verify
3333 // row 0's state includes it. Accepted drafts extend the window after the walk;
3334 // `next` joins as the anchor of ITS round.
3335 if pen_on {
3336 pen_hist.push(last);
3337 }
3338 let (m, next) = match (sp_on, tl.as_ref()) {
3339 (Some(sp), Some(tl)) => {
3340 let w0 = pen_hist
3341 .len()
3342 .saturating_sub(sp.penalty_last_n.min(crate::spec::PEN_WINDOW_MAX));
3343 dspark_accept_sampled(
3344 e,
3345 tl,
3346 &cand,
3347 vt,
3348 n_vocab,
3349 &dl,
3350 prop.as_ref()
3351 .expect("sampled round without a proposal record"),
3352 sp,
3353 &pen_hist[w0..],
3354 &mut sctr,
3355 &mut uctr,
3356 )?
3357 }
3358 _ => {
3359 let m = dspark_accept_prefix(&cand, &vam, vt);
3360 (m, vam[m])
3361 }
3362 };
3363 if pen_on {
3364 pen_hist.extend_from_slice(&cand[1..=m]);
3365 }
3366 attempted += vt - 1;
3367 accepted += m;
3368 out.push(last);
3369 if eos.contains(&last) {
3370 break 'outer;
3371 }
3372 if emit_accepted_run(&mut out, &cand[1..=m], eos, max_new) {
3373 break 'outer;
3374 }
3375
3376 // ---- commit/rollback: hybrid state cannot truncate — restore + replay kept ----
3377 let keep = m + 1;
3378 let t3 = std::time::Instant::now();
3379 // Slice 3: rounds whose linear column stash lives in the graphs ctx's slabs
3380 // commit through the slab twin (same semantics, slab-addressed sources).
3381 let slab_commit = vgraphs.as_ref().map(|g| g.round_slab).unwrap_or(false);
3382 if keep < vt {
3383 if ckpt_gate {
3384 // GATE ARM: stash-restore, snapshot S1; then the replay oracle, snapshot
3385 // S2; the two cache states must match BIT-FOR-BIT (kv lens, pos, every
3386 // conv/ssm buffer). Continue from the replay state (proven identical).
3387 if slab_commit {
3388 self.dspark_commit_prefix_slab(
3389 e,
3390 &mut cache,
3391 snap,
3392 vgraphs.as_ref().expect("slab_commit implies ctx"),
3393 keep,
3394 )?;
3395 } else {
3396 let vck = vck.as_ref().expect("gate arm always fills the ckpt");
3397 self.dspark_commit_prefix(e, &mut cache, snap, vck, keep)?;
3398 }
3399 // host-side state capture (NO device snapshot copies — two extra
3400 // device snapshots per round OOM'd beside the 15GB trunk)
3401 let capture = |cache: &Cache| -> Result<
3402 (usize, Vec<Option<usize>>, Vec<(Vec<f32>, Vec<f32>)>),
3403 Box<dyn std::error::Error>,
3404 > {
3405 let mut lens = Vec::new();
3406 let mut states = Vec::new();
3407 for il in 0..cache.kv.len() {
3408 lens.push(cache.kv[il].as_ref().map(|k| k.len));
3409 if let Some(rl) = &cache.recur[il] {
3410 states.push((e.dtoh(&rl.conv_state)?, e.dtoh(&rl.ssm_state)?));
3411 }
3412 }
3413 Ok((cache.pos, lens, states))
3414 };
3415 let (p1, l1, st1) = capture(&cache)?;
3416 crate::pp::restore_cache_checkpoint(e, self, None, &mut cache, snap)?;
3417 let ram = self.dspark_verify_t_am(e, &cand[..keep], start, &mut cache)?;
3418 assert_eq!(
3419 &ram[..],
3420 &vam[..keep],
3421 "prefix replay must reproduce the verify argmaxes"
3422 );
3423 let (p2, l2, st2) = capture(&cache)?;
3424 assert_eq!(p1, p2, "ckpt-gate: pos mismatch");
3425 assert_eq!(l1, l2, "ckpt-gate: kv_len mismatch");
3426 for (il, ((c1, s1v), (c2, s2v))) in st1.iter().zip(&st2).enumerate() {
3427 let bits = |a: &[f32], b: &[f32]| {
3428 a.iter().zip(b).all(|(x, y)| x.to_bits() == y.to_bits())
3429 };
3430 assert!(
3431 bits(c1, c2),
3432 "ckpt-gate: linear layer {il} conv state differs"
3433 );
3434 assert!(
3435 bits(s1v, s2v),
3436 "ckpt-gate: linear layer {il} ssm state differs"
3437 );
3438 }
3439 } else if slab_commit {
3440 // STASH ARM, slab twin (slice 3): same restore, slab-addressed.
3441 self.dspark_commit_prefix_slab(
3442 e,
3443 &mut cache,
3444 snap,
3445 vgraphs.as_ref().expect("slab_commit implies ctx"),
3446 keep,
3447 )?;
3448 } else if let Some(vck) = vck.as_ref() {
3449 // STASH ARM (default): column-state restore, no replay forward.
3450 self.dspark_commit_prefix(e, &mut cache, snap, vck, keep)?;
3451 } else {
3452 // REPLAY ARM (MEMRA_DSPARK_CKPT=0): the original snapshot+replay oracle.
3453 crate::pp::restore_cache_checkpoint(e, self, None, &mut cache, snap)?;
3454 debug_assert_eq!(cache.pos, start, "rollback landed off the round start");
3455 let ram = self.dspark_verify_t_am(e, &cand[..keep], start, &mut cache)?;
3456 if sp_on.is_none() {
3457 // the argmax-reproduction oracle is greedy-only; the sampled arm
3458 // replays purely to rebuild the cache state.
3459 debug_assert_eq!(
3460 &ram[..],
3461 &vam[..keep],
3462 "prefix replay must reproduce the verify argmaxes"
3463 );
3464 }
3465 }
3466 }
3467 ns_roll += clock(stats, e).duration_since(t3).as_nanos() as u64;
3468
3469 // ---- ingest the kept rows' ctx features into the draft KV ----
3470 let t4 = std::time::Instant::now();
3471 {
3472 let tv = e.view(tap_ref, vt * n_taps * n_embd);
3473 let keep_view = tv.slice(0..keep * n_taps * n_embd);
3474 let mut kept = e.uninit(keep * n_taps * n_embd)?;
3475 e.copy_view_into(&mut kept, 0, &keep_view, keep * n_taps * n_embd)?;
3476 let f = draft.ctx_features(e, &kept, keep)?;
3477 let pos_k: Vec<i32> = ((ctx_len as i32)..(ctx_len + keep) as i32).collect();
3478 draft.ingest_ctx(e, &mut dkv, &f, &pos_k, keep)?;
3479 ctx_len += keep;
3480 }
3481 ns_ingest += clock(stats, e).duration_since(t4).as_nanos() as u64;
3482 last = next;
3483 // Ladder update only — under the confidence policies vt is recomputed
3484 // from the head every round, post-draft pre-verify.
3485 if !vt_policy.is_confidence() && adapt {
3486 vt = (m + 2).clamp(3, vt_cap);
3487 }
3488 }
3489 if stats {
3490 let ms = |n: u64| n as f64 / 1e6;
3491 eprintln!(
3492 "[dspark-q38] acceptance {accepted}/{attempted} = {:.3} rounds={rounds} \
3493 draft={:.1}ms snap={:.1}ms verify={:.1}ms rollback+replay={:.1}ms ingest={:.1}ms",
3494 accepted as f64 / attempted.max(1) as f64,
3495 ms(ns_draft),
3496 ms(ns_snap),
3497 ms(ns_verify),
3498 ms(ns_roll),
3499 ms(ns_ingest)
3500 );
3501 }
3502 Ok(out)
3503 }
3504}
3505
3506// ================= DSpark SERVING session (lane/dspark-q38-recover serve route) =========
3507// Burst-scoped state for the worker's dspark spec arm — the qwen-hybrid twin of
3508// GemmaSpecSession. Holds the trunk cache + draft KV + the round loop's carry state
3509// (`last`, ctx_len, adaptive vt) so the scheduler round-robins other sessions between
3510// bursts. The round body is generate_spec_dspark's loop, hoisted; that bin arm stays the
3511// banked oracle (E2E gate), and the serve-route smoke gates this twin byte-identical to
3512// a spec-off boot over the real HTTP surface. Exactness contract unchanged: the target's
3513// verify argmax decides every committed token, so the stream equals plain greedy BY
3514// CONSTRUCTION on every accept path (ckpt stash, gate, replay).
3515fn take_dspark_prefix_capture(
3516 slot: &mut Option<crate::spec::SpecBoundaryCapture>,
3517) -> Option<crate::spec::SpecBoundaryCapture> {
3518 slot.take()
3519}
3520
3521/// Deterministic preflight for the serving session's prompt-headroom requirement. Kept pure so
3522/// the worker can make the same decision before choosing whether to consume a prefix entry.
3523pub fn dspark_spec_prompt_fits(
3524 prompt_len: usize,
3525 ctx_cap: usize,
3526 block_size: usize,
3527 sliding_window: usize,
3528 is_dflash2: bool,
3529) -> bool {
3530 // PRIME FLOOR (incident 2026-08-25, second hit — the one that actually took prod down
3531 // twice). This predicate is the ONE admission gate the worker consumes for the dspark
3532 // route, and it only ever checked the ctx CEILING. A prompt shorter than
3533 // `PRIME_MIN_T` was therefore admitted and then panicked inside the cold prime, because
3534 // `prime_cache`'s batched arm asserts `T >= PRIME_MIN_T` and has no tokenwise twin that
3535 // fills the DFlash tap sink. A panic there is not a failed request: the GPU worker
3536 // exits 70 (poisoned-context contract) and every live session on the box dies, then the
3537 // guard relaunches into the same prompt — 20 panics and ~5 min of edge 502s on box10,
3538 // and a second loop on BOTH boxes when the route was redeployed. The trigger is
3539 // ordinary traffic: "Say OK." is 5 tokens, and our own watchdog sends that class.
3540 // Below the floor the route simply declines and the request serves on the plain path.
3541 if prompt_len < crate::hybrid_forward::PRIME_MIN_T {
3542 return false;
3543 }
3544 let max_ctx = if is_dflash2 {
3545 ctx_cap
3546 } else {
3547 ctx_cap.min(sliding_window)
3548 };
3549 prompt_len
3550 .checked_add(block_size)
3551 .and_then(|n| n.checked_add(8))
3552 .is_some_and(|need| need <= max_ctx)
3553}
3554
3555pub struct DsparkSpecSession {
3556 pub cache: crate::cache::Cache,
3557 /// One-shot prompt-end state for the worker's cross-request prefix cache. DFlash has no
3558 /// restorable draft plane, so this capture deliberately carries trunk snapshot + logits
3559 /// only; low-load DFlash requests ignore the resulting trunk-only entry while a later
3560 /// shed-to-plain request can consume it.
3561 prefix_capture: Option<crate::spec::SpecBoundaryCapture>,
3562 dkv: DflashKv,
3563 last: u32,
3564 ctx_len: usize,
3565 vt: usize,
3566 pub rounds: usize,
3567 max_ctx: usize,
3568 done: bool,
3569 /// Engine-bundle slice 1: persistent batched snapshot (buffers + pointer tables live
3570 /// with the session so bursts reuse them). None until the first round; stays None —
3571 /// legacy per-layer snapshot — when `snapb_off`.
3572 snapb: Option<DsparkSnapBatch>,
3573 snapb_off: bool,
3574 /// SAMPLED ADMISSION (T>0, lane/dspark-sampled-admission-20260820): the request's
3575 /// sampling config (None/temp==0 = the greedy route, byte-identical). Fixed for the
3576 /// session — the worker's admission owns the sampler identity.
3577 sampling: Option<crate::spec::SpecSampling>,
3578 /// Philox event counters, session-owned so randomness never repeats across bursts
3579 /// (the frspec session-continuity law): `sctr` = device sampling events (boundary,
3580 /// draft chain, bonus, residual), `uctr` = host uniforms (selector walk, accept tests).
3581 sctr: u32,
3582 uctr: u32,
3583 /// Penalized-sampled window (lane/dspark-penalized-sampled-20260821): seeded from
3584 /// the prompt tail (`pen_window_seed`), extended with every committed token, carried
3585 /// across bursts so a burst boundary never resets the stream the client asked us to
3586 /// penalize. Empty (and never touched) when the request carries no penalties.
3587 pen_hist: Vec<u32>,
3588}
3589
3590fn dspark_commit_limit(
3591 accepted_keep: usize,
3592 burst_out_len: usize,
3593 request_room: usize,
3594) -> (usize, bool) {
3595 let public_room = request_room.saturating_sub(burst_out_len);
3596 debug_assert!(public_room > 0);
3597 let keep = accepted_keep.min(public_room);
3598 (keep, keep < accepted_keep)
3599}
3600
3601impl DsparkSpecSession {
3602 /// How many trailing draft-KV rows a restore must carry for the drafter to be
3603 /// indistinguishable from one that cold-primed: the sliding window plus one block.
3604 ///
3605 /// WHY A TAIL IS SUFFICIENT, and why this is a fact about THIS export rather than a hope:
3606 /// every DFlash2 draft layer is `sliding_attention` (the port asserts
3607 /// `cfg.layer_sliding.iter().all(|&s| s)` at load and refuses otherwise), so the windowed
3608 /// SDPA never reads a key below the current block's window floor
3609 /// (`sdpa_naive_w_lo`, whose bit-identity at Tkv 4104 and legacy launch failure are both
3610 /// pinned by kernel_check). A round at context `pos` therefore reads rows
3611 /// `[pos - window + 1, pos + block)` and nothing older. Storing that tail is storing
3612 /// everything the drafter can observe.
3613 ///
3614 /// SIZE, the reason this is affordable at all: 5 layers x (2048 + 16) rows x 8 kv x 128
3615 /// dim x 4 B x 2 (k+v) is ~85 MB, against ~1,057 MB for the trunk planes of a
3616 /// 30k-token entry. Storing the FULL draft history instead would be ~1,229 MB — more than
3617 /// the trunk entry itself — which is what makes the tail the only viable form.
3618 pub fn draft_tail_rows(&self) -> usize {
3619 self.dkv.cfg_window_rows()
3620 }
3621
3622 /// The drafter's KV, for a worker publishing the tail into its cross-request prefix cache.
3623 pub fn draft_kv(&self) -> &DflashKv {
3624 &self.dkv
3625 }
3626}
3627
3628/// The tail-import refusal arms, PURE so they are testable without CUDA. These are the fence
3629/// in front of the deliberate uninitialised-rows-below-`base` design: rows the import does not
3630/// copy are unreadable ONLY if the tail actually covers the drafter's window ending exactly at
3631/// the logical length — every arm here is what makes that "only if" hold. A refusal that
3632/// silently stopped firing would let a session attend garbage without crashing, which is the
3633/// silent-quality-loss class, so each arm names itself.
3634#[allow(clippy::too_many_arguments)]
3635pub fn tail_geometry_ok(
3636 tail_layers: usize,
3637 tail_row_bytes: usize,
3638 tail_base: usize,
3639 tail_rows: usize,
3640 tail_len: usize,
3641 kv_layers: usize,
3642 kv_row_bytes: usize,
3643 kv_window_rows: usize,
3644 cap: usize,
3645) -> Result<(), &'static str> {
3646 if tail_layers != kv_layers {
3647 return Err("layer count differs from the live drafter");
3648 }
3649 if tail_row_bytes != kv_row_bytes {
3650 return Err("row geometry differs from the live drafter");
3651 }
3652 if tail_len > cap {
3653 return Err("logical length exceeds the session cap");
3654 }
3655 if tail_base + tail_rows != tail_len {
3656 return Err("tail does not end at its own logical length");
3657 }
3658 // The whole point of the tail: it must cover everything a round can read. A shorter
3659 // tail than the window is only acceptable when the tail IS the entire history.
3660 if tail_rows < kv_window_rows.min(tail_len) {
3661 return Err("tail shorter than the drafter's readable window");
3662 }
3663 Ok(())
3664}
3665
3666/// A DFlash draft-KV tail, per drafter layer, ready to ride a cross-request prefix-cache
3667/// entry: `(k, v)` f32 rows covering absolute positions `[base, base + rows)`.
3668///
3669/// Only the tail travels, and that is a fact about this export rather than an optimisation:
3670/// every DFlash2 draft layer is `sliding_attention` (the port asserts it at load), so a round
3671/// at context `pos` reads rows `[pos - window + 1, pos + block)` and nothing older. Storing
3672/// the whole history for a 30k-token prompt would be ~1,229 MB — MORE than the ~1,057 MB of
3673/// trunk planes it would ride with; the tail is ~85 MB.
3674pub struct DflashKvTail {
3675 pub layers: Vec<(CudaSlice<f32>, CudaSlice<f32>)>,
3676 /// Absolute position of the first stored row.
3677 pub base: usize,
3678 /// Rows stored per layer.
3679 pub rows: usize,
3680 /// Logical length the KV had when exported (`= pos`), so an import can restore the same
3681 /// absolute row addressing the rope positions were baked against.
3682 pub len: usize,
3683 /// Bytes per row per layer, carried so an import cannot disagree about the geometry.
3684 pub row_bytes: usize,
3685}
3686
3687impl DflashKvTail {
3688 pub fn bytes(&self) -> usize {
3689 self.layers.len() * self.rows * self.row_bytes * 2
3690 }
3691}
3692
3693impl DflashKv {
3694 /// Copy out the readable tail ending at `upto` (see `DflashKvTail`). `None` when there is
3695 /// nothing to publish or an allocation fails — publication is always optional.
3696 ///
3697 /// `upto` IS NOT `self.len`, and conflating them was the bug the first exactness-gate run
3698 /// caught: publication happens at the scheduler's drain sweep, by which time the session
3699 /// has committed generated rows, so `len` had run 35 rows past the capture boundary and
3700 /// every restore was refused with `draft KV len 30364 != prompt 30329`. The trunk planes
3701 /// are copied at the capture `pos` for the same reason; the tail must agree with them.
3702 pub fn export_tail(&self, e: &Engine, upto: usize) -> Option<DflashKvTail> {
3703 if upto == 0 || upto > self.len {
3704 return None;
3705 }
3706 let rowsz = self.row_bytes / std::mem::size_of::<f32>();
3707 let rows = self.window_rows.min(upto);
3708 let base = upto - rows;
3709 let mut layers = Vec::with_capacity(self.k.len());
3710 for li in 0..self.k.len() {
3711 let (Ok(mut k), Ok(mut v)) = (e.uninit(rows * rowsz), e.uninit(rows * rowsz)) else {
3712 return None;
3713 };
3714 if e.copy_range_into(&mut k, 0, &self.k[li], base * rowsz, rows * rowsz)
3715 .is_err()
3716 || e.copy_range_into(&mut v, 0, &self.v[li], base * rowsz, rows * rowsz)
3717 .is_err()
3718 {
3719 return None;
3720 }
3721 layers.push((k, v));
3722 }
3723 Some(DflashKvTail {
3724 layers,
3725 base,
3726 rows,
3727 len: upto,
3728 row_bytes: self.row_bytes,
3729 })
3730 }
3731
3732 /// Rebuild a draft KV from a published tail: a fresh allocation at `cap`, the tail copied
3733 /// back to the SAME absolute rows it came from, and `len` restored so the next round
3734 /// addresses positions exactly as a cold-primed session would.
3735 ///
3736 /// Rows below `tail.base` are ZEROED, not left uninitialised. The clipped SDPA never reads
3737 /// below the block's window floor, but the legacy full-scan kernel
3738 /// (`MEMRA_DFLASH2_SDPA_CLIP=0`, the rollback seam) scans EVERY row into the score and the
3739 /// output, relying on masked rows contributing exactly zero — an identity that holds only
3740 /// for finite data (`0.0 * NaN = NaN`, and an uninit K row can produce a NaN score that
3741 /// poisons the softmax sum). Zeros keep that identity on both kernel arms, so a clip
3742 /// rollback on a restore-armed box stays byte-exact instead of decoding silent garbage
3743 /// (review round 3). Rows above `tail.len` stay uninit — equally unwritten and unread in
3744 /// the cold path, so restored matches cold there.
3745 ///
3746 /// This function still REFUSES rather than trusts the window math — if the tail does not
3747 /// cover the window, the caller gets `None` and must cold-prime.
3748 pub fn from_tail(e: &Engine, cfg: &DflashCfg, cap: usize, tail: &DflashKvTail) -> Option<Self> {
3749 let mut kv = Self::new(e, cfg, cap).ok()?;
3750 if let Err(why) = tail_geometry_ok(
3751 tail.layers.len(),
3752 tail.row_bytes,
3753 tail.base,
3754 tail.rows,
3755 tail.len,
3756 kv.k.len(),
3757 kv.row_bytes,
3758 kv.window_rows,
3759 cap,
3760 ) {
3761 eprintln!("[dspark] tail import refused: {why}");
3762 return None;
3763 }
3764 let rowsz = kv.row_bytes / std::mem::size_of::<f32>();
3765 for li in 0..kv.k.len() {
3766 let (src_k, src_v) = &tail.layers[li];
3767 if tail.base > 0 {
3768 // Finite zeros below the tail: the legacy full-scan kernel reads these rows
3769 // (see the doc above); NaN in either K or V poisons the row's contribution.
3770 e.memset_zeros_view(&mut kv.k[li].slice_mut(0..tail.base * rowsz))
3771 .ok()?;
3772 e.memset_zeros_view(&mut kv.v[li].slice_mut(0..tail.base * rowsz))
3773 .ok()?;
3774 }
3775 e.copy_range_into(
3776 &mut kv.k[li],
3777 tail.base * rowsz,
3778 src_k,
3779 0,
3780 tail.rows * rowsz,
3781 )
3782 .ok()?;
3783 e.copy_range_into(
3784 &mut kv.v[li],
3785 tail.base * rowsz,
3786 src_v,
3787 0,
3788 tail.rows * rowsz,
3789 )
3790 .ok()?;
3791 }
3792 kv.len = tail.len;
3793 Some(kv)
3794 }
3795
3796 /// Rows a restore must carry (see `DsparkSpecSession::draft_tail_rows`). Stored here
3797 /// because `DflashKv` owns the row geometry; the value comes from the drafter cfg.
3798 pub fn cfg_window_rows(&self) -> usize {
3799 self.window_rows
3800 }
3801
3802 /// Bytes per row per layer (`n_kv * head_dim * 4`), the unit both the export and the
3803 /// import address rows in.
3804 pub fn row_bytes(&self) -> usize {
3805 self.row_bytes
3806 }
3807
3808 /// Number of draft layers, i.e. how many per-layer planes an export produces.
3809 pub fn n_layer(&self) -> usize {
3810 self.k.len()
3811 }
3812}
3813
3814impl DsparkSpecSession {
3815 pub fn cache_max_ctx(&self) -> usize {
3816 self.max_ctx
3817 }
3818 pub fn finished(&self) -> bool {
3819 self.done
3820 }
3821 pub fn pos(&self) -> usize {
3822 self.cache.pos
3823 }
3824 /// Drain the prompt-end prefix capture exactly once. Publication is worker-owned so it can
3825 /// apply namespace isolation, dedupe and the shared byte budget at the scheduler boundary.
3826 pub fn take_prefix_capture(&mut self) -> Option<crate::spec::SpecBoundaryCapture> {
3827 take_dspark_prefix_capture(&mut self.prefix_capture)
3828 }
3829 /// DEMOTION HANDOFF (lane/dspark-spec-gate-demote, 2026-08-24): consume this session and
3830 /// hand its trunk cache + next-token prediction to the plain batched-decode path — the
3831 /// dspark twin of [`crate::spec::SpecSession::into_demoted`].
3832 ///
3833 /// WHY THIS IS EXACT (greedy). The burst-boundary invariant is `cache.pos == prompt rows
3834 /// + emitted tokens`: each round commits exactly `m+1` trunk rows (anchor + accepted
3835 /// drafts) and emits exactly those `m+1` tokens, so every emitted token has its KV row
3836 /// and nothing else does. `last` is the verify argmax at the LAST committed row — and
3837 /// verify-column argmax equality with plain decode is the very property the dspark E2E
3838 /// byte-identity gate pins (`dspark_q38_gate`: ALL EXACT). Handing (cache, last) to the
3839 /// batched path therefore continues the stream from a state indistinguishable from one
3840 /// the batched path produced itself.
3841 ///
3842 /// Unlike the MTP twin there is no carried-pending shape: the round commits its bonus
3843 /// inside the burst, so a session at a burst boundary is ALWAYS in handoff shape. The
3844 /// caller still cross-checks `pos()` against its fed-token count (a budget-clamped
3845 /// overshoot leaves cache rows past the public stream — those sessions finish, never
3846 /// demote). The draft KV, snapshot buffers and philox counters are DROPPED here
3847 /// (freeing their VRAM): the batched path never drafts, and the handoff is one-way.
3848 ///
3849 /// Sampled sessions must not be demoted (the caller excludes them, mirroring the MTP
3850 /// gate): their committed stream depends on the session-owned philox counters, and the
3851 /// plain batched sampler is a different random program mid-request.
3852 pub fn into_demoted(self) -> (crate::cache::Cache, u32) {
3853 (self.cache, self.last)
3854 }
3855}
3856
3857impl crate::hybrid::HybridModel {
3858 /// Turn-1 prime: trunk prefill with taps armed + chunked ctx ingest into the draft KV.
3859 /// Mirrors generate_spec_dspark's prime block exactly (chunk offsets via sink.base are
3860 /// handled inside prime_cache's tick loop; the 256-row ingest chunks match the bin arm).
3861 pub fn dspark_spec_session_new(
3862 &self,
3863 e: &Engine,
3864 draft: &DflashDraft,
3865 prompt: &[u32],
3866 ctx_cap: usize,
3867 sampling: Option<crate::spec::SpecSampling>,
3868 capture_prefix: bool,
3869 ) -> Result<DsparkSpecSession, Box<dyn std::error::Error>> {
3870 use crate::cache::{Cache, DflashTapSink};
3871 assert!(
3872 !self.uses_gemma_program(),
3873 "gemma4 targets use the assistant-drafter route; dspark is the qwen-hybrid arm"
3874 );
3875 // Penalized SAMPLED requests are IN scope (lane/dspark-penalized-sampled-20260821:
3876 // p-side penalties over the true per-state window, q the recorded proposal — the
3877 // accept walk's penalty arm). Penalties at temp==0 stay a LOUD refusal: the greedy
3878 // walk argmaxes RAW columns and would silently drop them — penalized greedy is
3879 // served exactly on the plain path (worker admission owns that exclusion).
3880 if let Some(sp) = sampling.as_ref() {
3881 if sp.temp <= 0.0 && sp.pen_on() {
3882 return Err(
3883 "dspark spec at temp==0 is the greedy route and would silently drop \
3884 the request's penalties; penalized greedy is served on the plain path"
3885 .into(),
3886 );
3887 }
3888 }
3889 let n_embd = self.cfg.n_embd as usize;
3890 let c = &draft.cfg;
3891 assert_eq!(n_embd, c.hidden, "draft hidden must match target n_embd");
3892 let b = c.block_size;
3893 let n_taps = c.target_layer_ids.len();
3894 // The dspark round is windowless: every position the session will ever hold must
3895 // fit the draft window. Clamp the session ctx to it and refuse prompts that
3896 // cannot take even one round — admission falls back to the plain path.
3897 // DFlash2 rounds implement the reference's symmetric sliding window
3898 // (sdpa_naive_w), so its sessions take the full ctx cap.
3899 let is_dflash2 = draft.dflash2.is_some();
3900 let max_ctx = if is_dflash2 {
3901 ctx_cap
3902 } else {
3903 ctx_cap.min(c.sliding_window)
3904 };
3905 if !dspark_spec_prompt_fits(prompt.len(), ctx_cap, b, c.sliding_window, is_dflash2) {
3906 let need = prompt.len().saturating_add(b).saturating_add(8);
3907 return Err(format!(
3908 "dspark session needs {need} ctx (prompt {} + block {b} + 8), cap {max_ctx}",
3909 prompt.len()
3910 )
3911 .into());
3912 }
3913 let mut cache = Cache::new(e, &self.cfg, max_ctx)?;
3914 let tp = prompt.len();
3915 cache.dflash_taps = Some(DflashTapSink {
3916 layer_ids: c.target_layer_ids.clone(),
3917 buf: e.uninit(tp * n_taps * n_embd)?,
3918 hidden: n_embd,
3919 t: tp,
3920 base: 0,
3921 });
3922 let (logits, _h_seed, _hiddens) = self.prime_cache(e, prompt, &mut cache, 0)?;
3923 // Boundary token: greedy argmax (byte contract) or the request's own filtered
3924 // draw through the session Philox stream (the frspec boundary composition) —
3925 // penalized over the prompt window when the request carries penalties.
3926 let mut sctr0 = 0u32;
3927 let pen_hist: Vec<u32> = match sampling.as_ref().filter(|s| s.temp > 0.0 && s.pen_on()) {
3928 Some(sp) => crate::spec::pen_window_seed(&[], prompt, sp.penalty_last_n),
3929 None => Vec::new(),
3930 };
3931 let last = match sampling.as_ref().filter(|s| s.temp > 0.0) {
3932 Some(sp) => crate::spec::sample_boundary_token(
3933 e,
3934 &logits,
3935 sp,
3936 &pen_hist,
3937 &mut sctr0,
3938 "dspark-prime",
3939 )?,
3940 None => crate::forward::argmax(&logits) as u32,
3941 };
3942 let mut dkv = DflashKv::new(e, &draft.cfg, max_ctx)?;
3943 {
3944 let taps = cache.dflash_taps.take().unwrap();
3945 let n_taps_h = n_taps * n_embd;
3946 let mut r0 = 0usize;
3947 while r0 < tp {
3948 let t_c = (tp - r0).min(256);
3949 let tv = e.view(&taps.buf, tp * n_taps_h);
3950 let win = tv.slice(r0 * n_taps_h..(r0 + t_c) * n_taps_h);
3951 let mut chunk = e.uninit(t_c * n_taps_h)?;
3952 e.copy_view_into(&mut chunk, 0, &win, t_c * n_taps_h)?;
3953 let f = draft.ctx_features(e, &chunk, t_c)?;
3954 let pos_c: Vec<i32> = ((r0 as i32)..(r0 + t_c) as i32).collect();
3955 draft.ingest_ctx(e, &mut dkv, &f, &pos_c, t_c)?;
3956 r0 += t_c;
3957 }
3958 }
3959 e.stream().synchronize()?;
3960 // FULL-PROMPT ONLY. Unlike MTP, DFlash cannot restore its draft plane from a trunk
3961 // prefix, so there is no LCP/message-boundary split arm here. Mandatory draft-KV
3962 // allocation + ingest has already succeeded; the optional snapshot can no longer turn
3963 // a session that would have fit into a draft-allocation failure. Capture remains before
3964 // any speculative burst mutates the recurrent state.
3965 let prefix_capture = if capture_prefix {
3966 cache
3967 .snapshot(e)
3968 .ok()
3969 .map(|snap| crate::spec::SpecBoundaryCapture {
3970 snap,
3971 pos: tp,
3972 logits: logits.clone(),
3973 last_h: Vec::new(),
3974 })
3975 } else {
3976 None
3977 };
3978 // Verify carries [anchor, drafts] = up to n_drafts+1 rows (harvest-dependent;
3979 // DSPARK-POSTMORTEM-20260820.md; family-keyed for DFlash2, else checkpoint
3980 // strategy census).
3981 let nd = DsparkHarvest::for_draft(draft).n_drafts(b);
3982 let vt_cap: usize = std::env::var("MEMRA_DFLASH_VERIFY_T")
3983 .ok()
3984 .and_then(|v| v.parse().ok())
3985 .unwrap_or(nd + 1)
3986 .clamp(2, nd + 1);
3987 Ok(DsparkSpecSession {
3988 cache,
3989 prefix_capture,
3990 dkv,
3991 last,
3992 ctx_len: tp,
3993 vt: vt_cap,
3994 rounds: 0,
3995 max_ctx,
3996 done: false,
3997 snapb: None,
3998 snapb_off: !crate::spec::state_copy_batch_on(),
3999 sampling,
4000 sctr: sctr0,
4001 uctr: 0,
4002 pen_hist,
4003 })
4004 }
4005
4006 /// One scheduler burst: dspark rounds until >= `burst_target` tokens are committed,
4007 /// EOS lands, or the ctx cap is reached. `request_room` is the request's remaining
4008 /// public budget, which may be larger than the per-tick scheduler quantum. Returns
4009 /// (tokens, drafted, accepted) for this burst — mid-request quantum overshoot stays
4010 /// public, while only the true request boundary clamps the committed cache prefix.
4011 /// ADMISSION DEBT of this model's dspark verify-graph pool, in bytes (lane/
4012 /// hermes-perf-fixes, 2026-08-23): the projected remaining growth the serve admission
4013 /// gate must reserve so sessions admitted while the pool is cold do not overcommit VRAM
4014 /// the pool will hold (it grows monotonically to a measured multi-GiB high-water —
4015 /// 8,852 MiB on the q38 export — with no eviction by design; the 1.5 GiB
4016 /// SPEC_SHRINK_RESERVE never covered it). Projection contract and the self-measuring
4017 /// arithmetic live on [`crate::spec::dspark_vg_debt_projection`]; the observed bytes
4018 /// come from the device graph mem pool (`Engine::device_graph_mem_reserved`). 0 when
4019 /// the door is closed (`MEMRA_DSPARK_VERIFY_GRAPH=0`), frozen (`MEMRA_DSPARK_VG_MAX=0`),
4020 /// or the pool has not captured yet.
4021 pub fn dspark_vg_admission_debt(&self, e: &Engine) -> usize {
4022 if !crate::spec::dspark_verify_graph_serve_on() && !crate::spec::dspark_verify_graph_on() {
4023 return 0;
4024 }
4025 let reserved = e.device_graph_mem_reserved();
4026 self.dspark_vgraphs
4027 .lock()
4028 .unwrap()
4029 .as_mut()
4030 .map(|g| g.admission_debt(reserved))
4031 .unwrap_or(0)
4032 }
4033
4034 /// MULTI-TURN RESUME (lane/dflash2-session-reuse, 2026-08-25): continue a parked
4035 /// dspark session with the next turn's suffix — the dspark twin of the MTP pool
4036 /// resume. Trunk rows for the committed stream are already resident in `cache` and
4037 /// their ctx features in `dkv`, so turn N+1 primes ONLY its delta instead of
4038 /// re-priming the whole conversation (the route previously served every turn cold —
4039 /// a full-prompt prime whose cost grows with the conversation).
4040 ///
4041 /// EXACTNESS. The suffix prime is the same session-continuation `prime_cache` the
4042 /// serve path uses for split prompts and LCP restores (chunk N+1 attends chunk N's
4043 /// resident KV); the tap sink collects the suffix rows prompt-relative and the dkv
4044 /// ingest lands them at their absolute positions, exactly as the burst's per-round
4045 /// keep-ingest does. The boundary token re-derives as the cold prime does: greedy
4046 /// argmax of the suffix's last row, or the request's filtered draw through the
4047 /// SESSION's own Philox stream (`sctr` continues — the frspec session-continuity
4048 /// law), penalized over the session+suffix window. A resumed stream is therefore
4049 /// byte-identical to the stream a cold prime of the full concatenation produces —
4050 /// the verify arbitrates every committed token either way.
4051 ///
4052 /// EOS in the committed history is fine (a finished turn parks with EOS committed;
4053 /// the new user turn continues past it) — `done` resets here. Callers must pass a
4054 /// NON-EMPTY suffix for a `done` session (an empty-suffix continuation of a finished
4055 /// stream would re-emit from a terminal state); the worker's probe enforces it.
4056 /// Re-arm a dspark session from a RESTORED trunk cache plus a published draft tail —
4057 /// the long-answer half of lane/dspark-draft-plane-20260827.
4058 ///
4059 /// WHY THIS EXISTS. `dspark_spec_session_new` must prime the full prompt, because the draft
4060 /// KV derives from trunk hidden FEATURES the prime produces as a side effect. A cache hit
4061 /// returns trunk K/V, not features, so before this a speculating request had to discard even
4062 /// a full-prompt hit and re-prefill (~10 s at 30k tokens). With the drafter's readable tail
4063 /// travelling on the entry, both halves are restorable and the discard is unnecessary.
4064 ///
4065 /// WHY IT IS EQUIVALENT TO A COLD PRIME, field by field:
4066 /// * `cache` — the caller's restored trunk cache, already at `prompt.len()` with recurrent
4067 /// state, which is why only WHOLE-ENTRY hits are eligible (a GDN trunk cannot rebuild
4068 /// recurrent state mid-sequence, so there is no LCP arm here — same restriction as the
4069 /// cold path's full-prompt-only rule).
4070 /// * `dkv` — byte-copied from the tail into the SAME absolute rows, so rope positions and
4071 /// every row the windowed SDPA can read are identical to what the prime produced.
4072 /// * `last` — drawn from the entry's boundary logits with the request's own sampler, the
4073 /// same composition the cold path applies to its prime logits.
4074 /// * `pen_hist` / `sctr` / `uctr` — seeded exactly as a cold session's are: the penalty
4075 /// window from this prompt, the Philox counters fresh, because randomness is
4076 /// session-owned by the frspec continuity law and a restore is a NEW session.
4077 /// * `prefix_capture` — `None`: the entry this restored FROM already exists, so
4078 /// republishing the same key would be dropped by the worker's dedupe anyway.
4079 ///
4080 /// Refuses (rather than asserting) whenever the rebuilt draft KV and the cache disagree, so
4081 /// a caller that gets `Err` simply cold-primes.
4082 #[allow(clippy::too_many_arguments)]
4083 pub fn dspark_spec_session_from_restored(
4084 &self,
4085 e: &Engine,
4086 draft: &DflashDraft,
4087 cache: crate::cache::Cache,
4088 prompt: &[u32],
4089 // Draft KV ALREADY rebuilt from the entry's tail by the caller (`DflashKv::from_tail`)
4090 // while the prefix cache was borrowable. Taking the built KV rather than the tail is
4091 // what keeps the ~85 MB tail in the entry for other requests — `from_tail` copies OUT
4092 // of it, so no clone of the tail is ever needed.
4093 dkv: DflashKv,
4094 boundary_logits: &[f32],
4095 sampling: Option<crate::spec::SpecSampling>,
4096 ctx_cap: usize,
4097 ) -> Result<DsparkSpecSession, Box<dyn std::error::Error>> {
4098 assert!(
4099 !self.uses_gemma_program(),
4100 "gemma4 targets use the assistant-drafter route; dspark is the qwen-hybrid arm"
4101 );
4102 if let Some(sp) = sampling.as_ref() {
4103 if sp.temp <= 0.0 && sp.pen_on() {
4104 return Err("penalized greedy is served on the plain path".into());
4105 }
4106 }
4107 let c = &draft.cfg;
4108 let b = c.block_size;
4109 let is_dflash2 = draft.dflash2.is_some();
4110 let max_ctx = if is_dflash2 {
4111 ctx_cap
4112 } else {
4113 ctx_cap.min(c.sliding_window)
4114 };
4115 let tp = prompt.len();
4116 if !dspark_spec_prompt_fits(tp, ctx_cap, b, c.sliding_window, is_dflash2) {
4117 return Err(format!("restored dspark session does not fit ctx {max_ctx}").into());
4118 }
4119 if cache.pos != tp {
4120 return Err(format!(
4121 "restored dspark session needs a whole-entry trunk cache: cache.pos {} != prompt {tp}",
4122 cache.pos
4123 )
4124 .into());
4125 }
4126 if dkv.len != tp {
4127 return Err(format!("restored draft KV len {} != prompt {tp}", dkv.len).into());
4128 }
4129 if dkv.cap != max_ctx {
4130 return Err(
4131 format!("restored draft KV cap {} != session ctx {max_ctx}", dkv.cap).into(),
4132 );
4133 }
4134 if boundary_logits.is_empty() {
4135 return Err("restored dspark session needs the entry's boundary logits".into());
4136 }
4137 let mut sctr0 = 0u32;
4138 let pen_hist: Vec<u32> = match sampling.as_ref().filter(|s| s.temp > 0.0 && s.pen_on()) {
4139 Some(sp) => crate::spec::pen_window_seed(&[], prompt, sp.penalty_last_n),
4140 None => Vec::new(),
4141 };
4142 let last = match sampling.as_ref().filter(|s| s.temp > 0.0) {
4143 Some(sp) => crate::spec::sample_boundary_token(
4144 e,
4145 boundary_logits,
4146 sp,
4147 &pen_hist,
4148 &mut sctr0,
4149 "dspark-restore",
4150 )?,
4151 None => crate::forward::argmax(boundary_logits) as u32,
4152 };
4153 let nd = DsparkHarvest::for_draft(draft).n_drafts(b);
4154 let vt_cap: usize = std::env::var("MEMRA_DFLASH_VERIFY_T")
4155 .ok()
4156 .and_then(|v| v.parse().ok())
4157 .unwrap_or(nd + 1)
4158 .clamp(2, nd + 1);
4159 Ok(DsparkSpecSession {
4160 cache,
4161 prefix_capture: None,
4162 dkv,
4163 last,
4164 ctx_len: tp,
4165 vt: vt_cap,
4166 rounds: 0,
4167 max_ctx,
4168 done: false,
4169 snapb: None,
4170 snapb_off: !crate::spec::state_copy_batch_on(),
4171 sampling,
4172 sctr: sctr0,
4173 uctr: 0,
4174 pen_hist,
4175 })
4176 }
4177
4178 pub fn dspark_spec_session_resume(
4179 &self,
4180 e: &Engine,
4181 draft: &DflashDraft,
4182 sess: &mut DsparkSpecSession,
4183 suffix: &[u32],
4184 ) -> Result<(), Box<dyn std::error::Error>> {
4185 use crate::cache::DflashTapSink;
4186 let n_embd = self.cfg.n_embd as usize;
4187 let c = &draft.cfg;
4188 let b = c.block_size;
4189 let n_taps = c.target_layer_ids.len();
4190 let pos0 = sess.cache.pos;
4191 debug_assert_eq!(
4192 sess.ctx_len, pos0,
4193 "dspark resume: draft KV rows != trunk cache rows"
4194 );
4195 if suffix.is_empty() {
4196 return Err(
4197 "dspark resume needs a non-empty suffix (worker probe owns the \
4198 empty-suffix exact-continuation case)"
4199 .into(),
4200 );
4201 }
4202 // SHORT-SUFFIX FLOOR (incident 2026-08-25, box10 crash loop). The suffix prime goes
4203 // through `prime_cache`, which asserts `T >= PRIME_MIN_T` — the batched prefill arm
4204 // has no tokenwise twin that also fills the DFlash tap sink. A resumed turn shorter
4205 // than that floor (the watchdog's "Say OK." class, and any brief agent follow-up)
4206 // therefore PANICKED the GPU worker, which exits 70 and takes every session on the
4207 // box with it: 20 panics and ~5 minutes of 502s on box10 before MEMRA_REUSE_POOL=0
4208 // stopped it. The worker probe declines these before it ever gets here (its own
4209 // guard is the one that keeps the request on the cold path, which is exactly the
4210 // pre-lane behavior); this is the engine-side backstop so no future caller can
4211 // reintroduce the panic, and it is a refusal rather than an assert because a
4212 // too-short turn is ordinary traffic, not a bug.
4213 if suffix.len() < crate::hybrid_forward::PRIME_MIN_T {
4214 return Err(format!(
4215 "dspark resume suffix {} < PRIME_MIN_T {} (prime_cache has no tokenwise \
4216 tap-filling twin); serve this turn cold",
4217 suffix.len(),
4218 crate::hybrid_forward::PRIME_MIN_T
4219 )
4220 .into());
4221 }
4222 let need = pos0
4223 .saturating_add(suffix.len())
4224 .saturating_add(b)
4225 .saturating_add(8);
4226 if need > sess.max_ctx {
4227 return Err(format!(
4228 "dspark resume needs {need} ctx (resident {pos0} + suffix {} + block {b} + 8), \
4229 cap {}",
4230 suffix.len(),
4231 sess.max_ctx
4232 )
4233 .into());
4234 }
4235 let tp = suffix.len();
4236 sess.cache.dflash_taps = Some(DflashTapSink {
4237 layer_ids: c.target_layer_ids.clone(),
4238 buf: e.uninit(tp * n_taps * n_embd)?,
4239 hidden: n_embd,
4240 t: tp,
4241 base: 0,
4242 });
4243 let (logits, _h_seed, _hiddens) = self.prime_cache(e, suffix, &mut sess.cache, 0)?;
4244 let sp_pen = sess.sampling.filter(|s| s.temp > 0.0 && s.pen_on());
4245 if sp_pen.is_some() {
4246 let sp = sp_pen.as_ref().unwrap();
4247 sess.pen_hist = crate::spec::pen_window_seed(&sess.pen_hist, suffix, sp.penalty_last_n);
4248 }
4249 let last = match sess.sampling.filter(|s| s.temp > 0.0) {
4250 Some(sp) => crate::spec::sample_boundary_token(
4251 e,
4252 &logits,
4253 &sp,
4254 &sess.pen_hist,
4255 &mut sess.sctr,
4256 "dspark-resume",
4257 )?,
4258 None => crate::forward::argmax(&logits) as u32,
4259 };
4260 {
4261 let taps = sess.cache.dflash_taps.take().unwrap();
4262 let n_taps_h = n_taps * n_embd;
4263 let mut r0 = 0usize;
4264 while r0 < tp {
4265 let t_c = (tp - r0).min(256);
4266 let tv = e.view(&taps.buf, tp * n_taps_h);
4267 let win = tv.slice(r0 * n_taps_h..(r0 + t_c) * n_taps_h);
4268 let mut chunk = e.uninit(t_c * n_taps_h)?;
4269 e.copy_view_into(&mut chunk, 0, &win, t_c * n_taps_h)?;
4270 let f = draft.ctx_features(e, &chunk, t_c)?;
4271 let pos_c: Vec<i32> = (((pos0 + r0) as i32)..((pos0 + r0 + t_c) as i32)).collect();
4272 draft.ingest_ctx(e, &mut sess.dkv, &f, &pos_c, t_c)?;
4273 r0 += t_c;
4274 }
4275 }
4276 e.stream().synchronize()?;
4277 sess.ctx_len += tp;
4278 sess.last = last;
4279 sess.done = false;
4280 Ok(())
4281 }
4282
4283 pub fn dspark_spec_session_burst(
4284 &self,
4285 e: &Engine,
4286 draft: &DflashDraft,
4287 sess: &mut DsparkSpecSession,
4288 burst_target: usize,
4289 request_room: usize,
4290 eos: &[u32],
4291 ) -> Result<(Vec<u32>, usize, usize), Box<dyn std::error::Error>> {
4292 use crate::cache::DflashTapSink;
4293 let n_embd = self.cfg.n_embd as usize;
4294 let c = &draft.cfg;
4295 let b = c.block_size;
4296 let n_taps = c.target_layer_ids.len();
4297 let n_vocab = self.output.out_features();
4298 // Harvest convention (DSPARK-POSTMORTEM-20260820.md) — identical to the bin arm
4299 // (family-keyed for DFlash2, else checkpoint strategy census; owner-ratified
4300 // flip 2026-08-20).
4301 let harvest = DsparkHarvest::for_draft(draft);
4302 let nd = harvest.n_drafts(b);
4303 let r0 = harvest.first_row();
4304 let vt_cap: usize = std::env::var("MEMRA_DFLASH_VERIFY_T")
4305 .ok()
4306 .and_then(|v| v.parse().ok())
4307 .unwrap_or(nd + 1)
4308 .clamp(2, nd + 1);
4309 let adapt = std::env::var("MEMRA_DFLASH_ADAPT").as_deref() != Ok("0");
4310 // Verify-window policy (H4, DSPARK-POSTMORTEM-20260820.md) — identical to the
4311 // bin arm: default = confidence-slot tau=.5 on a head-carrying checkpoint
4312 // (owner-ratified flip 2026-08-20); head-less (incl. the DFlash2 family) and
4313 // ADAPT=0 keep the ladder.
4314 let vt_policy = DsparkVtPolicy::resolve(draft.confidence.is_some());
4315 if vt_policy.is_confidence() {
4316 assert!(
4317 draft.confidence.is_some(),
4318 "MEMRA_DSPARK_VT={vt_policy:?} needs a checkpoint with an accept-rate \
4319 head (confidence_head.* absent in this export)"
4320 );
4321 }
4322 // SAMPLED ADMISSION (T>0): session-fixed config; counters live on the session so
4323 // randomness never repeats across bursts. None/temp==0 = the greedy route.
4324 let sp_on: Option<crate::spec::SpecSampling> = sess.sampling.filter(|s| s.temp > 0.0);
4325 let pen_on = sp_on.as_ref().is_some_and(|s| s.pen_on());
4326 let mut out: Vec<u32> = Vec::with_capacity(burst_target + b);
4327 let mut drafted = 0usize;
4328 let mut accepted_n = 0usize;
4329 // Engine-bundle slice 2 — identical to the bin arm: deferred chain readback under
4330 // the stash arm with a resident embed table (ladder policy only).
4331 let defer_rb = crate::spec::dspark_defer_readback_on() && !vt_policy.is_confidence();
4332 let (embd_qt, embd_rb) = self.embd.qt_and_row_bytes(n_embd);
4333 let embd_gpu = if !defer_rb || crate::spec::spec_host_embd() {
4334 None
4335 } else {
4336 Some(
4337 self.embd_gpu
4338 .get_or_init(|| e.upload_u8(&self.embd.raw).expect("embed table upload")),
4339 )
4340 };
4341 // Slice 3/4c SERVE ENGAGEMENT (graphs-serve lane; DSF-ROUNDCOST §9.3 -> §10): the
4342 // verify-graph pool lives on the MODEL (`dspark_vgraphs`, one per process) and its
4343 // keys — (segment, vt) and (vt, rung, hi) — carry NOTHING session-scoped, so ANY
4344 // session whose round matches a key replays the same capture (this is the
4345 // cache-reuse-pool the old bin-arm-only note asked for). Sharing is sound because
4346 // every per-session-varying address the captured bodies touch is indirect:
4347 // conv/ssm state and the ckpt stash resolve through the per-verify refreshed
4348 // pointer table (refresh_tables + copy_indirect_src_f32 — the slice-3
4349 // parity/lifetime law; a baked address is the known 12/12-divergence class), kv
4350 // bases through fa_table, residual/pos/tap through ctx-owned staging rewritten
4351 // every round; per-row t_kv derives in-kernel from pos_seq, and the per-round
4352 // host bookkeeping (parity swap, len bump) runs on THIS session's cache. The
4353 // guard spans the burst: the slab stash is live verify -> commit inside each
4354 // round, and the worker drives bursts from one scheduler thread
4355 // (step_dspark_spec), so sessions interleave at burst boundaries only.
4356 // DEFAULT ON on the serve route since the v0.103 train (owner-ratified
4357 // 2026-08-22, §10 re-gate at flip): MEMRA_DSPARK_VERIFY_GRAPH=0 is the
4358 // kill-switch that keeps this None — the eager walk, byte-identical (the
4359 // kill-switch arm of the serve battery). The bin arm keeps its own opt-in.
4360 let mut vg_guard = self.dspark_vgraphs.lock().unwrap();
4361 if vg_guard.is_none() && embd_gpu.is_some() && crate::spec::dspark_verify_graph_serve_on() {
4362 *vg_guard = crate::spec::DsparkVerifyGraphs::new(e, &sess.cache, vt_cap, n_embd)?;
4363 if vg_guard.is_some() {
4364 // Engagement receipt (the §8 dead-arm lesson): prove the door is LIVE on
4365 // the serve surface — S6b banked the tip server carrying zero door strings.
4366 eprintln!("[dspark-vg] serve pool ENGAGED (vt_cap={vt_cap})");
4367 }
4368 }
4369 let vgraphs: &mut Option<crate::spec::DsparkVerifyGraphs> = &mut vg_guard;
4370 'outer: while out.len() < burst_target && !sess.done {
4371 let start = sess.cache.pos;
4372 if start + nd + 1 > sess.max_ctx {
4373 sess.done = true;
4374 break;
4375 }
4376 sess.rounds += 1;
4377 let mut vt = sess.vt;
4378 // ---- draft: block = [last, MASK x b-1] (identical to the bin arm) ----
4379 // RAII: a `?` exit restores the pre-scope value instead of latching exact
4380 // ON engine-wide across every later request (hermes finding, fixed
4381 // 2026-08-23 — this burst had several `?`s between the manual true/false).
4382 let exact_scope = e.exact_scope(true);
4383 let mut block: Vec<u32> = vec![c.mask_token_id; b];
4384 block[0] = sess.last;
4385 let noise = e.htod(&self.embd.gather(n_embd, &block))?;
4386 let pos_block: Vec<i32> = ((start as i32)..(start + b) as i32).collect();
4387 let dh = draft.forward_round(e, &mut sess.dkv, &noise, &pos_block)?;
4388 // Harvest: logits over rows r0..r0+nd (see the bin arm / the postmortem).
4389 let mut rows = e.uninit(nd * n_embd)?;
4390 {
4391 let dv = e.view(&dh, b * n_embd);
4392 let src = dv.slice(r0 * n_embd..(r0 + nd) * n_embd);
4393 e.copy_view_into(&mut rows, 0, &src, nd * n_embd)?;
4394 }
4395 // TRIMMED DRAFT HEAD (lane/dflash2-head-trim, 2026-08-25): DFlash2 family
4396 // only — the selector consumes (value, candidate-id) pairs, so a d2t remap
4397 // after top-k restores true ids; the markov/chain arms argmax dl columns
4398 // into token ids DIRECTLY and must keep the full head. Reuses the FR-Spec
4399 // self-trim the load path builds on the MTP struct (MEMRA_FRSPEC_TRIM):
4400 // gathered rows of the target's own head, zero requant. Verify stays
4401 // full-vocab, so the trim moves draft acceptance only, never output.
4402 let trim = if draft.dflash2.is_some() {
4403 self.mtp
4404 .as_ref()
4405 .filter(|m| m.d2t_from_target_head)
4406 .and_then(|m| m.shared_head_head.as_ref().zip(m.d2t.as_ref()))
4407 .filter(|(_, d2t)| !d2t.is_empty())
4408 } else {
4409 None
4410 };
4411 let (dl_head, dl_vocab) = match trim {
4412 Some((head, d2t)) => (head, d2t.len()),
4413 None => (&self.output, n_vocab),
4414 };
4415 let trim_d2t = trim.map(|(_, d2t)| d2t.as_slice());
4416 let mut dl = e.matmul(dl_head, &rows, nd)?;
4417 // Family/sampling-keyed proposal — identical to the bin arm (see there for
4418 // the program law: sampled records the true q, DFlash2 rides the selector,
4419 // the markov/plain greedy chain keeps the slice-2 deferral). Confidence
4420 // policy: stash markov prev-token embeddings d2d during the chain, one host
4421 // readback after — identical to the bin arm.
4422 let want_conf_emb = vt_policy.is_confidence()
4423 && draft.confidence.as_ref().is_some_and(|ch| ch.with_markov);
4424 let mut conf_emb: Option<CudaSlice<f32>> = match (&draft.markov, want_conf_emb) {
4425 (Some(mk), true) => Some(e.uninit(nd * mk.rank)?),
4426 (None, true) => unreachable!(
4427 "with_markov confidence head without a markov table — the loader forbids it"
4428 ),
4429 _ => None,
4430 };
4431 let mut cand: Vec<u32> = Vec::with_capacity(nd + 1);
4432 let mut prop: Option<DsparkDraftSample> = None;
4433 let mut chain_dev: Option<CudaSlice<u32>> = None;
4434 // Slice 2: arm choice read before the chain readback (see the bin arm; the
4435 // serve arm has no CKPT_GATE oracle — the bin arm carries it).
4436 let ckpt_on = std::env::var("MEMRA_DSPARK_CKPT").as_deref() != Ok("0");
4437 let mut deferred = false;
4438 if let Some(sp) = sp_on.as_ref() {
4439 // SAMPLED proposal (family-keyed; identical to the bin arm).
4440 let (tail, ds) = draft.dspark_propose_sampled(
4441 e,
4442 &mut dl,
4443 &rows,
4444 nd,
4445 dl_vocab,
4446 sess.last,
4447 sp,
4448 &mut sess.sctr,
4449 &mut sess.uctr,
4450 conf_emb.as_mut(),
4451 trim_d2t,
4452 )?;
4453 drop(exact_scope);
4454 cand.push(sess.last);
4455 cand.extend_from_slice(&tail);
4456 prop = Some(ds);
4457 } else if draft.dflash2.is_some() {
4458 // DFlash2: candidate path selector replaces the markov chain
4459 // (identical to the bin arm).
4460 let path = draft
4461 .dflash2_propose_greedy(e, &dl, &rows, nd, dl_vocab, sess.last, trim_d2t)?;
4462 drop(exact_scope);
4463 cand.push(sess.last);
4464 cand.extend_from_slice(&path);
4465 } else {
4466 let markov_on = std::env::var("MEMRA_DFLASH_MARKOV").as_deref() != Ok("0");
4467 let mut chain_d = e.stream().alloc_zeros::<u32>(nd + 1)?;
4468 if let (Some(mk), true) = (&draft.markov, markov_on) {
4469 e.set_u32_one(&mut chain_d, sess.last)?;
4470 for k in 0..nd {
4471 let mut f = e.uninit(mk.rank)?;
4472 e.gather_row_bf16(&mk.w1_bf16, &chain_d, k, &mut f, mk.rank)?;
4473 if let Some(ce) = conf_emb.as_mut() {
4474 let fv = e.view(&f, mk.rank);
4475 e.copy_view_into(ce, k * mk.rank, &fv, mk.rank)?;
4476 }
4477 let bias = e.matmul(&mk.w2, &f, 1)?;
4478 e.add_row_inplace(&mut dl, &bias, n_vocab, k * n_vocab)?;
4479 e.argmax_token_device_col(&dl, k, n_vocab, &mut chain_d, k + 1)?;
4480 }
4481 } else {
4482 if want_conf_emb {
4483 // chain_d[0] must carry the anchor — slot 0's prev token.
4484 e.set_u32_one(&mut chain_d, sess.last)?;
4485 }
4486 for i in 0..nd {
4487 if let (Some(ce), Some(mk)) = (conf_emb.as_mut(), &draft.markov) {
4488 let mut f = e.uninit(mk.rank)?;
4489 e.gather_row_bf16(&mk.w1_bf16, &chain_d, i, &mut f, mk.rank)?;
4490 let fv = e.view(&f, mk.rank);
4491 e.copy_view_into(ce, i * mk.rank, &fv, mk.rank)?;
4492 }
4493 e.argmax_token_device_col(&dl, i, n_vocab, &mut chain_d, i + 1)?;
4494 }
4495 }
4496 drop(exact_scope);
4497 deferred = embd_gpu.is_some() && ckpt_on;
4498 chain_dev = Some(chain_d);
4499 }
4500 // ---- H4 confidence window: size THIS round's verify from the head ----
4501 if vt_policy.is_confidence() {
4502 let ch = draft.confidence.as_ref().expect("asserted at burst entry");
4503 let (rows_h, emb_h) = match conf_emb.as_ref() {
4504 Some(ce) => {
4505 let (a, b2) = e.dtoh_pair(&rows, ce)?;
4506 (a, Some(b2))
4507 }
4508 None => (e.dtoh(&rows)?, None),
4509 };
4510 let rank = draft.markov.as_ref().map(|m| m.rank).unwrap_or(0);
4511 let mut raws = Vec::with_capacity(nd);
4512 for k in 0..nd {
4513 let hrow = &rows_h[k * n_embd..(k + 1) * n_embd];
4514 let emb = emb_h.as_ref().map(|eh| &eh[k * rank..(k + 1) * rank]);
4515 raws.push(ch.raw_score(hrow, emb));
4516 }
4517 vt = vt_policy
4518 .size_window(&raws, vt_cap)
4519 .expect("confidence policies always size the window");
4520 }
4521 // Non-deferred greedy chain readback (the sampled and DFlash2 proposals
4522 // built `cand` at the walk; deferred rounds build it after the merged
4523 // readback — bytes identical, chain_d written before either sync).
4524 if let Some(chain_d) = chain_dev.as_ref() {
4525 if !deferred {
4526 let chain = e.dtoh_u32(chain_d)?;
4527 cand.push(sess.last);
4528 cand.extend_from_slice(&chain[1..]);
4529 }
4530 }
4531
4532 // ---- snapshot, then verify t=vt (ckpt stash default; oracle arms kept) ----
4533 // Slice 1: batched snap (see DsparkSnapBatch) with the legacy per-layer
4534 // snapshot as the kill-switch / non-uniform fallback.
4535 let mut snap_legacy: Option<crate::cache::CacheSnapshot> = None;
4536 if !sess.snapb_off && sess.snapb.is_none() {
4537 sess.snapb = DsparkSnapBatch::new(e, &sess.cache)?;
4538 sess.snapb_off = sess.snapb.is_none();
4539 } else if let Some(sb) = sess.snapb.as_mut() {
4540 sb.refresh(e, &sess.cache)?;
4541 }
4542 let snap: &crate::cache::CacheSnapshot = match sess.snapb.as_ref() {
4543 Some(sb) => &sb.snap,
4544 None => {
4545 snap_legacy = Some(sess.cache.snapshot(e)?);
4546 snap_legacy.as_ref().unwrap()
4547 }
4548 };
4549 let _ = &snap_legacy;
4550 // Slice 3: the tap-sink buffer is persistent per vt in the graphs ctx
4551 // (captured segments bake its address — a per-round alloc here would make
4552 // every session's replayed tap copies write freed memory); fully rewritten
4553 // by every verify, so pool ownership changes no bytes.
4554 let tap_buf = match vgraphs.as_mut().and_then(|g| g.tap_bufs.remove(&vt)) {
4555 Some(buf) => buf,
4556 None => e.uninit(vt * n_taps * n_embd)?,
4557 };
4558 sess.cache.dflash_taps = Some(DflashTapSink {
4559 layer_ids: c.target_layer_ids.clone(),
4560 buf: tap_buf,
4561 hidden: n_embd,
4562 t: vt,
4563 base: 0,
4564 });
4565 // Composition guard (sampled admission × model-owned pool, this train's
4566 // cross-product): the slab flag is a per-round statement, but only the
4567 // graphs-aware verify (`_am_ckpt_dev`) clears it. Serve sessions MIX arms
4568 // within one process-lifetime pool — a SAMPLED round rides the raw-logits
4569 // twins (no graphs param) and must not inherit `round_slab=true` from a
4570 // previous greedy session's captured round, or its commit is steered at
4571 // slabs the round never wrote. Clear at the round boundary; the deferred
4572 // arm re-derives it inside the verify. (The bin arm has the same shape but
4573 // fixes its sampling mode per process, so no mixed rounds exist there.)
4574 if let Some(g) = vgraphs.as_mut() {
4575 g.round_slab = false;
4576 }
4577 // The whole fallible verify window runs inside a closure so the Err path
4578 // can return the sink buffer to the ctx pool before propagating — the
4579 // serve-surface twin of the EOS-orphan lesson: a mid-verify error
4580 // propagates OUT of the burst, the request dies, the session's cache is
4581 // dropped — but the PROCESS (and the pool, with the tap-buffer address
4582 // baked into its captures) lives on. Recover the ctx-owned buffer before
4583 // the error escapes, or the next session's replayed tap copies write
4584 // freed memory. The bin arm has no such path (a gate-binary error ends
4585 // the process).
4586 let verify_out = (|| -> Result<
4587 (
4588 Vec<u32>,
4589 Option<CudaSlice<f32>>,
4590 Option<crate::spec::DsparkVerifyCkpt>,
4591 ),
4592 Box<dyn std::error::Error>,
4593 > {
4594 if sp_on.is_some() {
4595 // SAMPLED: raw verify logits for the rejection walk (bin-arm twin).
4596 if ckpt_on {
4597 let (tl, vck) = self.dspark_verify_t_logits_ckpt(
4598 e,
4599 &cand[..vt],
4600 start,
4601 &mut sess.cache,
4602 )?;
4603 Ok((Vec::new(), Some(tl), Some(vck)))
4604 } else {
4605 Ok((
4606 Vec::new(),
4607 Some(self.dspark_verify_t_logits(
4608 e,
4609 &cand[..vt],
4610 start,
4611 &mut sess.cache,
4612 )?),
4613 None,
4614 ))
4615 }
4616 } else if deferred {
4617 // Slice 2: device-token verify + ONE merged readback (see the bin arm).
4618 let chain_d = chain_dev.as_ref().expect("deferred implies greedy chain");
4619 let g = embd_gpu.expect("deferred implies resident embed");
4620 let (am_d, vck) = self.dspark_verify_t_am_ckpt_dev(
4621 e,
4622 chain_d,
4623 vt,
4624 start,
4625 &mut sess.cache,
4626 (g, embd_qt, embd_rb),
4627 vgraphs.as_mut(),
4628 )?;
4629 let ch = e.stream().clone_dtoh(chain_d)?;
4630 let am = e.stream().clone_dtoh(&am_d)?;
4631 e.stream().synchronize()?;
4632 cand.push(sess.last);
4633 cand.extend_from_slice(&ch[1..]);
4634 Ok((am, None, Some(vck)))
4635 } else if ckpt_on {
4636 let (vam, vck) =
4637 self.dspark_verify_t_am_ckpt(e, &cand[..vt], start, &mut sess.cache)?;
4638 Ok((vam, None, Some(vck)))
4639 } else {
4640 Ok((
4641 self.dspark_verify_t_am(e, &cand[..vt], start, &mut sess.cache)?,
4642 None,
4643 None,
4644 ))
4645 }
4646 })();
4647 let (vam, tl, vck) = match verify_out {
4648 Ok(v) => v,
4649 Err(err) => {
4650 if let Some(taps) = sess.cache.dflash_taps.take() {
4651 if let Some(g) = vgraphs.as_mut() {
4652 g.tap_bufs.insert(vt, taps.buf);
4653 }
4654 }
4655 return Err(err);
4656 }
4657 };
4658 let taps = sess.cache.dflash_taps.take().unwrap();
4659 // Return the tap buffer to the ctx pool IMMEDIATELY — an EOS/budget break
4660 // between accept and ingest must never orphan an address the captured graphs
4661 // bake (the bin arm's lesson, and it holds doubly here: the pool outlives
4662 // the SESSION, not just the round). Ingest reads it borrowed.
4663 let tap_local: Option<CudaSlice<f32>> = match vgraphs.as_mut() {
4664 Some(g) => {
4665 g.tap_bufs.insert(vt, taps.buf);
4666 None
4667 }
4668 None => Some(taps.buf),
4669 };
4670 let tap_ref: &CudaSlice<f32> = match &tap_local {
4671 Some(b) => b,
4672 None => &vgraphs.as_ref().expect("ctx present above").tap_bufs[&vt],
4673 };
4674
4675 // ---- accept ----
4676 // Penalized-sampled: anchor joins the window before the walk (committed this
4677 // round via the out.push below); accepted drafts extend it after — identical
4678 // to the bin arm.
4679 if pen_on {
4680 sess.pen_hist.push(sess.last);
4681 }
4682 let (m, next) = match (sp_on.as_ref(), tl.as_ref()) {
4683 (Some(sp), Some(tl)) => {
4684 let w0 = sess
4685 .pen_hist
4686 .len()
4687 .saturating_sub(sp.penalty_last_n.min(crate::spec::PEN_WINDOW_MAX));
4688 dspark_accept_sampled(
4689 e,
4690 tl,
4691 &cand,
4692 vt,
4693 n_vocab,
4694 &dl,
4695 prop.as_ref()
4696 .expect("sampled round without a proposal record"),
4697 sp,
4698 &sess.pen_hist[w0..],
4699 &mut sess.sctr,
4700 &mut sess.uctr,
4701 )?
4702 }
4703 _ => {
4704 let m = dspark_accept_prefix(&cand, &vam, vt);
4705 (m, vam[m])
4706 }
4707 };
4708 drafted += vt - 1;
4709 accepted_n += m;
4710 // keep = the rows this round adds to the PUBLIC stream. Without eos that is
4711 // the anchor + all accepted drafts (m+1). With eos it is the anchor + drafts
4712 // UP TO AND INCLUDING eos: the walk may accept real tokens past eos (they are
4713 // the model's own continuation), but emission stops at eos, and a parked
4714 // session whose cache holds rows past the public stream can never resume —
4715 // the park gate `pos() == fed` would refuse every eos-terminated stream
4716 // (measured: 7/8 turns on the mtreuse gate, overshoot 1-6 rows). Truncating
4717 // the commit at eos uses the SAME prefix-commit machinery as a mid-round
4718 // rejection, so the hybrid (GDN) state is exact by the same argument.
4719 // Emitted bytes are untouched — this only changes post-eos cache state.
4720 let mut keep = m + 1;
4721 let mut terminal = false;
4722 if eos.contains(&sess.last) {
4723 terminal = true;
4724 keep = 1;
4725 } else {
4726 for (j, &dt) in cand[1..=m].iter().enumerate() {
4727 if eos.contains(&dt) {
4728 terminal = true;
4729 keep = j + 2; // anchor + drafts through eos
4730 break;
4731 }
4732 }
4733 }
4734 // The request's max_tokens boundary is also a commit boundary, not merely an
4735 // output slice. It is NOT the scheduler's smaller per-tick burst quantum: accepted
4736 // surplus crossing that quantum stays public and the session remains live. Only at
4737 // the true request boundary do we keep the publishable prefix so cache.pos == fed at
4738 // retire and mark the session terminal until a non-empty next-turn suffix resumes
4739 // it. This uses the same prefix-commit machinery as EOS/rejection and makes
4740 // max-token sessions safe to park instead of permanently cold (Hermes
4741 // `f22a180d1638b95a`).
4742 let (bounded_keep, budget_terminal) =
4743 dspark_commit_limit(keep, out.len(), request_room);
4744 keep = bounded_keep;
4745 terminal |= budget_terminal;
4746 out.push(sess.last);
4747 out.extend_from_slice(&cand[1..keep]);
4748 sess.done = terminal;
4749 if pen_on {
4750 // Only the PUBLIC drafts feed the penalty window — tokens accepted past
4751 // eos never reach the stream, and a resumed session must not penalize
4752 // ghosts (the parked pen_hist seeds the resume's window).
4753 sess.pen_hist.extend_from_slice(&cand[1..keep]);
4754 }
4755
4756 // ---- commit/rollback (stash arm default; replay oracle kept) ----
4757 // Slice 3: rounds whose linear column stash lives in the graphs ctx's slabs
4758 // commit through the slab twin (same semantics, slab-addressed sources) —
4759 // identical to the bin arm's dispatch.
4760 let slab_commit = vgraphs.as_ref().map(|g| g.round_slab).unwrap_or(false);
4761 if keep < vt {
4762 if slab_commit {
4763 self.dspark_commit_prefix_slab(
4764 e,
4765 &mut sess.cache,
4766 snap,
4767 vgraphs.as_ref().expect("slab_commit implies ctx"),
4768 keep,
4769 )?;
4770 } else if let Some(vck) = vck.as_ref() {
4771 self.dspark_commit_prefix(e, &mut sess.cache, snap, vck, keep)?;
4772 } else {
4773 crate::pp::restore_cache_checkpoint(e, self, None, &mut sess.cache, snap)?;
4774 debug_assert_eq!(sess.cache.pos, start, "rollback landed off the round start");
4775 let ram = self.dspark_verify_t_am(e, &cand[..keep], start, &mut sess.cache)?;
4776 if sp_on.is_none() {
4777 // greedy-only oracle; the sampled arm replays to rebuild state.
4778 debug_assert_eq!(
4779 &ram[..],
4780 &vam[..keep],
4781 "prefix replay must reproduce the verify argmaxes"
4782 );
4783 }
4784 }
4785 }
4786
4787 // ---- ingest the kept rows' ctx features into the draft KV ----
4788 {
4789 let tv = e.view(tap_ref, vt * n_taps * n_embd);
4790 let keep_view = tv.slice(0..keep * n_taps * n_embd);
4791 let mut kept = e.uninit(keep * n_taps * n_embd)?;
4792 e.copy_view_into(&mut kept, 0, &keep_view, keep * n_taps * n_embd)?;
4793 let f = draft.ctx_features(e, &kept, keep)?;
4794 let pos_k: Vec<i32> =
4795 ((sess.ctx_len as i32)..(sess.ctx_len + keep) as i32).collect();
4796 draft.ingest_ctx(e, &mut sess.dkv, &f, &pos_k, keep)?;
4797 sess.ctx_len += keep;
4798 }
4799 if sess.done {
4800 // EOS or the public budget landed this round: cache, draft KV and ctx_len are
4801 // all clamped to the public stream (park shape); `next` is beyond the terminal
4802 // boundary and must not become the anchor of a resumed session.
4803 break 'outer;
4804 }
4805 sess.last = next;
4806 // Ladder update only — the confidence policies recompute vt from the
4807 // head every round, post-draft pre-verify; their carry just keeps
4808 // observability (sess.vt = the last confidence-sized window).
4809 if vt_policy.is_confidence() {
4810 sess.vt = vt;
4811 } else if adapt {
4812 sess.vt = (m + 2).clamp(3, vt_cap);
4813 }
4814 }
4815 Ok((out, drafted, accepted_n))
4816 }
4817}
4818
4819// ================= Harvest-convention gate (CPU; DSPARK-POSTMORTEM-20260820.md) =========
4820// The parity oracle is row-count-agnostic (it reproduces the markov MODULE on whatever
4821// rows it is fed) and the E2E gate is harvest-independent (verify-side truth), so
4822// NEITHER can catch a wrong row->position mapping — that blindness is how the q38
4823// misalignment shipped. These tests pin the convention itself as logic the round
4824// consumes, so a mutation back to the mask-fill harvest under the Dspark variant fails
4825// HERE, naming the convention.
4826#[cfg(test)]
4827mod dflash2_tests {
4828
4829 /// The tail-import refusal arms (lane/dspark-draft-plane-20260827 review finding: these
4830 /// were claimed tested and were not). Pure, so they run everywhere; the geometry mirrors
4831 /// the served DFlash2 drafter (5 layers, 8 kv x 128 dim f32 rows, window 2048 + block 8).
4832 #[test]
4833 fn tail_import_refuses_every_geometry_disagreement_and_accepts_the_exported_shape() {
4834 let rb = 8 * 128 * 4; // n_kv * head_dim * f32
4835 let win = 2048 + 8; // window_rows = sliding_window + block
4836 // THE EXPORTED SHAPE: window_rows ending exactly at len, same geometry — accepted.
4837 assert!(
4838 super::tail_geometry_ok(5, rb, 30_329 - win, win, 30_329, 5, rb, win, 34_433).is_ok()
4839 );
4840 // A short history where the tail IS the whole history — accepted.
4841 assert!(super::tail_geometry_ok(5, rb, 0, 100, 100, 5, rb, win, 34_433).is_ok());
4842 // Every refusal arm, each by name:
4843 let arm =
4844 |l, r, b, rows, len, cap| super::tail_geometry_ok(l, r, b, rows, len, 5, rb, win, cap);
4845 assert_eq!(
4846 arm(4, rb, 30_329 - win, win, 30_329, 34_433).unwrap_err(),
4847 "layer count differs from the live drafter"
4848 );
4849 assert_eq!(
4850 arm(5, rb - 4, 30_329 - win, win, 30_329, 34_433).unwrap_err(),
4851 "row geometry differs from the live drafter"
4852 );
4853 assert_eq!(
4854 arm(5, rb, 30_329 - win, win, 30_329, 30_000).unwrap_err(),
4855 "logical length exceeds the session cap"
4856 );
4857 // THE RUN-2 BUG, pinned: a tail whose base+rows lands past its own logical length —
4858 // the export-at-current-length defect the gate caught on the box.
4859 assert_eq!(
4860 arm(5, rb, 30_364 - win, win, 30_329, 34_433).unwrap_err(),
4861 "tail does not end at its own logical length"
4862 );
4863 assert_eq!(
4864 arm(5, rb, 30_329 - (win - 100), win - 100, 30_329, 34_433).unwrap_err(),
4865 "tail shorter than the drafter's readable window"
4866 );
4867 }
4868
4869 use super::{
4870 DsparkHarvest, dflash2_walk_greedy, dflash2_walk_sampled, dspark_commit_limit,
4871 rejection_accept_len,
4872 };
4873
4874 #[test]
4875 fn max_tokens_caps_the_committed_prefix_not_only_the_visible_slice() {
4876 // A round crossing the scheduler's 32-token quantum is not terminal when the
4877 // request still has room. The whole accepted prefix stays public and committed.
4878 assert_eq!(dspark_commit_limit(5, 30, 100), (5, false));
4879 // The same round at the true request boundary is clamped and terminal so the
4880 // parked cache cannot contain rows the worker did not publish.
4881 assert_eq!(dspark_commit_limit(5, 30, 33), (3, true));
4882 assert_eq!(dspark_commit_limit(2, 3, 10), (2, false));
4883 assert_eq!(dspark_commit_limit(1, 0, 1), (1, false));
4884 }
4885
4886 /// f32 -> bf16 bytes (truncation; test values are bf16-exact small integers).
4887 fn bf16(vals: &[f32]) -> Vec<u8> {
4888 vals.iter()
4889 .flat_map(|v| ((v.to_bits() >> 16) as u16).to_le_bytes())
4890 .collect()
4891 }
4892
4893 const V: usize = 8; // test vocab
4894 const R: usize = 2; // selector rank
4895 const K: usize = 2; // top_k
4896
4897 /// Codebooks for the chain tests: pred rows are one-hot-ish, succ rows chosen so
4898 /// the slot-1 winner FLIPS with the slot-0 choice.
4899 fn books() -> (Vec<u8>, Vec<u8>) {
4900 let mut pred = vec![0f32; V * R];
4901 pred[0] = 1.0; // tok 0: [1, 0] (the anchor)
4902 pred[1 * R + 1] = 1.0; // tok 1: [0, 1]
4903 pred[2 * R] = 1.0; // tok 2: [1, 0]
4904 let mut succ = vec![0f32; V * R];
4905 succ[1 * R] = 2.0; // tok 1: [2, 0]
4906 succ[2 * R + 1] = 5.0; // tok 2: [0, 5]
4907 succ[3 * R + 1] = 3.0; // tok 3: [0, 3]
4908 succ[4 * R] = 10.0; // tok 4: [10, 0]
4909 (bf16(&pred), bf16(&succ))
4910 }
4911
4912 #[test]
4913 fn selector_walk_is_a_chain_not_per_slot_argmax() {
4914 let (pred, succ) = books();
4915 // slot 0 candidates {1, 2}, slot 1 candidates {3, 4}; hproj all-ones.
4916 let cand: Vec<u32> = vec![1, 2, 3, 4];
4917 let hproj = vec![1.0f32; 2 * R];
4918 // Anchor 0 (pred [1,0]): slot 0 scores = <[1,0],succ> -> tok1: 2, tok2: 0
4919 // -> picks 1. Slot 1 must then walk from pred[1]=[0,1]: tok3 scores 3,
4920 // tok4 scores 0 -> picks 3. A mutation that seeds every slot from the ANCHOR
4921 // (pred[0]=[1,0]) scores tok3: 0 / tok4: 10 and picks 4 instead — the chain
4922 // IS the semantics (reference CandidateSelector.select: `predecessor` is the
4923 // previously CHOSEN candidate, seeded by anchor_ids).
4924 let path = dflash2_walk_greedy(&pred, &succ, V, R, K, &[0.0; 4], &cand, &hproj, 0, 2);
4925 assert_eq!(
4926 path,
4927 vec![1, 3],
4928 "walk must seed slot p from slot p-1's CHOSEN candidate \
4929 (z-lab model.py CandidateSelector.select)"
4930 );
4931 }
4932
4933 #[test]
4934 fn selector_walk_unary_term_participates() {
4935 let (pred, succ) = books();
4936 let cand: Vec<u32> = vec![1, 2, 3, 4];
4937 let hproj = vec![1.0f32; 2 * R];
4938 // unary +10 on slot-0 candidate 2 overrides the bilinear 2-vs-0 margin;
4939 // the chain then walks from pred[2]=[1,0] and slot 1 flips to tok 4.
4940 let path = dflash2_walk_greedy(
4941 &pred,
4942 &succ,
4943 V,
4944 R,
4945 K,
4946 &[0.0, 10.0, 0.0, 0.0],
4947 &cand,
4948 &hproj,
4949 0,
4950 2,
4951 );
4952 assert_eq!(
4953 path,
4954 vec![2, 4],
4955 "score = unary + bilinear (reference: `unary[:, position] + einsum(...)`); \
4956 dropping the unary term picks tok 1 here"
4957 );
4958 }
4959
4960 #[test]
4961 fn selector_walk_hidden_gate_participates() {
4962 let (pred, succ) = books();
4963 let cand: Vec<u32> = vec![1, 2, 3, 4];
4964 // hproj [0, .] zeroes the pred[0]=[1,0] gate for slot 0: tok1's bilinear 2
4965 // vanishes, and the unary tiebreak (+1 on tok2) decides. The chain from tok2
4966 // (pred [1,0]) with slot-1 hproj [1,1] then picks tok4 (10 vs 0).
4967 let hproj = vec![0.0f32, 1.0, 1.0, 1.0];
4968 let path = dflash2_walk_greedy(
4969 &pred,
4970 &succ,
4971 V,
4972 R,
4973 K,
4974 &[0.0, 1.0, 0.0, 0.0],
4975 &cand,
4976 &hproj,
4977 0,
4978 2,
4979 );
4980 assert_eq!(
4981 path,
4982 vec![2, 4],
4983 "the bilinear gate is pred_row .* HIDDEN_PROJECTION (reference: \
4984 `predecessor_codebook(predecessor) * hidden[:, position]`); ignoring \
4985 hproj leaves tok1's margin standing"
4986 );
4987 }
4988
4989 #[test]
4990 fn dflash2_harvest_is_census_keyed() {
4991 // DFlash2 is mask-fill BY CONSTRUCTION (reference dflash_generate harvests
4992 // rows 1-verify_size:; card: "7 draft tokens per verification step").
4993 assert_eq!(
4994 DsparkHarvest::for_family_value(true, None, false),
4995 DsparkHarvest::Dflash
4996 );
4997 assert_eq!(
4998 DsparkHarvest::for_family_value(true, Some("dflash"), false),
4999 DsparkHarvest::Dflash
5000 );
5001 // The family key BEATS the strategy census: a (hypothetical) DFlash2 export
5002 // whose config also strategy-censuses dspark still harvests mask-fill.
5003 assert_eq!(
5004 DsparkHarvest::for_family_value(true, None, true),
5005 DsparkHarvest::Dflash
5006 );
5007 // An env override to the SHIFTED harvest contradicts the census — REFUSE,
5008 // never re-key (the postmortem's misalignment class in reverse).
5009 assert!(
5010 std::panic::catch_unwind(|| DsparkHarvest::for_family_value(
5011 true,
5012 Some("dspark"),
5013 false
5014 ))
5015 .is_err(),
5016 "MEMRA_DSPARK_HARVEST=dspark on a DFlash2 checkpoint must refuse"
5017 );
5018 // Non-DFlash2 checkpoints ride the strategy-keyed resolution (env wins).
5019 assert_eq!(
5020 DsparkHarvest::for_family_value(false, Some("dspark"), false),
5021 DsparkHarvest::Dspark
5022 );
5023 assert_eq!(
5024 DsparkHarvest::for_family_value(false, None, false),
5025 DsparkHarvest::Dflash
5026 );
5027 assert_eq!(
5028 DsparkHarvest::for_family_value(false, None, true),
5029 DsparkHarvest::Dspark,
5030 "unset env on a DSPARK-strategy export must keep the ratified census flip"
5031 );
5032 }
5033
5034 // ============ SAMPLED ADMISSION (T>0) gates — lane/dspark-sampled-admission-20260820 =
5035 // The device kernels are oracled by sample_check (filter_stats/gumbel/residual arms);
5036 // these pin the HOST math the route ships — the selector's sampled walk, the accept
5037 // rule, and the round COMPOSITION (accept + residual + bonus must reproduce the target
5038 // distribution p exactly; a mis-composition leaves every kernel individually correct,
5039 // which is why the composition arm exists — sample_check arm 6's lesson).
5040
5041 #[test]
5042 fn sampled_walk_tiny_temp_matches_greedy() {
5043 // T->0 continuity: at tiny temperature the candidate softmax concentrates on the
5044 // argmax and the sampled walk must reproduce the greedy chain token-for-token
5045 // (the frspec gate-(1) shape). Same fixture as the chain test.
5046 let (pred, succ) = books();
5047 let cand: Vec<u32> = vec![1, 2, 3, 4];
5048 let hproj = vec![1.0f32; 2 * R];
5049 let greedy = dflash2_walk_greedy(&pred, &succ, V, R, K, &[0.0; 4], &cand, &hproj, 0, 2);
5050 let mut u = || 0.5f32;
5051 let (path, q_chosen, q_rows) = dflash2_walk_sampled(
5052 &pred, &succ, V, R, K, &[0.0; 4], &cand, &hproj, 0, 2, 1e-6, &mut u,
5053 );
5054 assert_eq!(
5055 path, greedy,
5056 "tiny-T sampled walk must equal the greedy chain"
5057 );
5058 assert_eq!(q_rows.len(), 2 * K);
5059 for (p, &q) in path.iter().zip(&q_chosen) {
5060 let _ = p;
5061 assert!(
5062 q > 0.999,
5063 "tiny-T chosen-candidate prob must be ~1, got {q}"
5064 );
5065 }
5066 }
5067
5068 #[test]
5069 fn sampled_walk_records_the_distribution_it_samples() {
5070 // The recorded q IS the proposal: per slot the q_rows sum to ~1, q_chosen is the
5071 // row value at the drawn candidate, and the CDF walk picks the candidate whose
5072 // cumulative bracket contains the uniform.
5073 let (pred, succ) = books();
5074 let cand: Vec<u32> = vec![1, 2, 3, 4];
5075 let hproj = vec![1.0f32; 2 * R];
5076 // slot-0 scores at anchor 0: tok1 = 2.0, tok2 = 0.0; at T=2.0 the softmax is
5077 // e^1/(e^1+e^0) ~= 0.731 for tok1.
5078 let q1 = (1f64.exp() / (1f64.exp() + 1.0)) as f32;
5079 for (u0, want0) in [(q1 - 0.01, 1u32), (q1 + 0.01, 2u32)] {
5080 let mut seq = vec![u0, 0.0f32].into_iter();
5081 let mut u = move || seq.next().unwrap();
5082 let (path, q_chosen, q_rows) = dflash2_walk_sampled(
5083 &pred, &succ, V, R, K, &[0.0; 4], &cand, &hproj, 0, 2, 2.0, &mut u,
5084 );
5085 assert_eq!(
5086 path[0], want0,
5087 "CDF walk must place u={u0} in the right candidate bracket"
5088 );
5089 let row0: f32 = q_rows[..K].iter().sum();
5090 assert!(
5091 (row0 - 1.0).abs() < 1e-5,
5092 "slot-0 q must sum to 1, got {row0}"
5093 );
5094 let ci = cand[..K].iter().position(|&c| c == path[0]).unwrap();
5095 assert_eq!(
5096 q_chosen[0], q_rows[ci],
5097 "q_chosen must be the recorded row prob of the drawn candidate"
5098 );
5099 assert!(
5100 (q_rows[0] - q1).abs() < 1e-4,
5101 "slot-0 tok1 prob must be softmax(scores/T), got {} want {q1}",
5102 q_rows[0]
5103 );
5104 }
5105 }
5106
5107 #[test]
5108 fn sampled_walk_chains_the_drawn_candidate() {
5109 // The chain conditions on the DRAWN candidate, not the argmax: forcing the
5110 // low-prob slot-0 candidate (tok 2) flips slot 1's winner (tok 4 over tok 3),
5111 // exactly like the greedy chain test — a walk that seeds every slot from the
5112 // anchor (or the argmax) fails here.
5113 let (pred, succ) = books();
5114 let cand: Vec<u32> = vec![1, 2, 3, 4];
5115 let hproj = vec![1.0f32; 2 * R];
5116 let mut seq = vec![0.99f32, 0.01].into_iter();
5117 let mut u = move || seq.next().unwrap();
5118 let (path, _, _) = dflash2_walk_sampled(
5119 &pred, &succ, V, R, K, &[0.0; 4], &cand, &hproj, 0, 2, 2.0, &mut u,
5120 );
5121 assert_eq!(path[0], 2, "u=0.99 must draw the low-prob candidate");
5122 assert_eq!(
5123 path[1], 4,
5124 "slot 1 must walk from pred[2] (the DRAWN token), which scores tok4 at 10 \
5125 — chaining from the anchor or the argmax picks tok3"
5126 );
5127 }
5128
5129 #[test]
5130 fn rejection_accept_walk_is_the_leviathan_rule() {
5131 // accept while u*q < p, strict, prefix-stop at the first reject.
5132 assert_eq!(
5133 rejection_accept_len(&[0.5, 0.5], &[0.5, 0.5], &[0.9, 0.9]),
5134 2
5135 );
5136 assert_eq!(
5137 rejection_accept_len(&[0.5, 0.5], &[0.5, 0.5], &[1.0, 0.0]),
5138 0
5139 );
5140 // u*q == p is a REJECT (strict <) — the frspec test byte-for-byte.
5141 assert_eq!(rejection_accept_len(&[0.25], &[0.5], &[0.5]), 0);
5142 // q == 0 with p > 0 accepts unconditionally (the skey exactness signature).
5143 assert_eq!(rejection_accept_len(&[1e-6], &[0.0], &[0.999]), 1);
5144 // prefix stop: slot 1 rejects, slot 2 never tested.
5145 assert_eq!(
5146 rejection_accept_len(&[0.9, 0.0, 0.9], &[0.1, 0.9, 0.1], &[0.5, 0.5, 0.5]),
5147 1
5148 );
5149 }
5150
5151 // ---- round composition: the committed-token distribution must equal the target p ----
5152 // CPU mirror of the shipped rule for the FIRST post-anchor slot: draft x ~ q, accept
5153 // iff u*q(x) < p(x) (rejection_accept_len — the shipped fn), else commit a residual
5154 // sample ~ norm(max(0, p - q)). The marginal of the committed token is exactly p —
5155 // for ANY q — which is the whole correctness claim of the route's sampled admission.
5156
5157 fn tv(a: &[f64], b: &[f64]) -> f64 {
5158 a.iter().zip(b).map(|(x, y)| (x - y).abs()).sum::<f64>() / 2.0
5159 }
5160
5161 /// One composed trial with an injectable accept rule; returns the committed token.
5162 fn compose_once(
5163 p: &[f32],
5164 q: &[f32],
5165 u_draw: f32,
5166 u_accept: f32,
5167 u_resid: f32,
5168 invert_accept: bool,
5169 skip_q_in_residual: bool,
5170 ) -> usize {
5171 let n = p.len();
5172 // draft ~ q (CDF walk, the walk_sampled convention)
5173 let mut acc = 0f64;
5174 let mut x = n - 1;
5175 for (i, &qi) in q.iter().enumerate() {
5176 acc += qi as f64;
5177 if (u_draw as f64) < acc {
5178 x = i;
5179 break;
5180 }
5181 }
5182 let accepted = if invert_accept {
5183 !((u_accept as f64) * (q[x] as f64) < p[x] as f64)
5184 } else {
5185 rejection_accept_len(&p[x..=x], &q[x..=x], &[u_accept]) == 1
5186 };
5187 if accepted {
5188 return x;
5189 }
5190 // residual ~ norm(max(0, p - q)) (the device kernel's fixed-order CDF walk)
5191 let r: Vec<f64> = p
5192 .iter()
5193 .zip(q)
5194 .map(|(&pi, &qi)| {
5195 let qq = if skip_q_in_residual { 0.0 } else { qi as f64 };
5196 (pi as f64 - qq).max(0.0)
5197 })
5198 .collect();
5199 let total: f64 = r.iter().sum();
5200 let mut acc = 0f64;
5201 let target = u_resid as f64 * total;
5202 for (i, &ri) in r.iter().enumerate() {
5203 acc += ri;
5204 if acc >= target && ri > 0.0 {
5205 return i;
5206 }
5207 }
5208 n - 1
5209 }
5210
5211 fn compose_tv(q: &[f32], invert_accept: bool, skip_q_in_residual: bool) -> f64 {
5212 // target p: a spread-out 8-token distribution
5213 let p: Vec<f32> = vec![0.30, 0.22, 0.15, 0.12, 0.09, 0.06, 0.04, 0.02];
5214 let trials = 200_000usize;
5215 let mut counts = vec![0f64; V];
5216 for t in 0..trials {
5217 // three independent uniforms per trial off the host Philox stream
5218 let u_draw = crate::spec::host_u01(7, (t * 3) as u32);
5219 let u_accept = crate::spec::host_u01(7, (t * 3 + 1) as u32);
5220 let u_resid = crate::spec::host_u01(7, (t * 3 + 2) as u32);
5221 counts[compose_once(
5222 &p,
5223 q,
5224 u_draw,
5225 u_accept,
5226 u_resid,
5227 invert_accept,
5228 skip_q_in_residual,
5229 )] += 1.0;
5230 }
5231 let emp: Vec<f64> = counts.iter().map(|c| c / trials as f64).collect();
5232 let pf: Vec<f64> = p.iter().map(|&v| v as f64).collect();
5233 tv(&emp, &pf)
5234 }
5235
5236 #[test]
5237 fn sampled_round_composition_matches_the_target() {
5238 // Monte-Carlo floor at 200k draws over 8 tokens ~ 0.004 TV; bound 0.01.
5239 // (a) full-vocab q (the Rows families' shape), far from p;
5240 let q_rows: Vec<f32> = vec![0.02, 0.04, 0.06, 0.09, 0.12, 0.15, 0.22, 0.30];
5241 // (b) SPARSE candidate-set q (the DFlash2 selector shape: support on 2 of 8).
5242 let q_sparse: Vec<f32> = vec![0.0, 0.7, 0.0, 0.3, 0.0, 0.0, 0.0, 0.0];
5243 for (name, q) in [("rows", &q_rows), ("sparse", &q_sparse)] {
5244 let d = compose_tv(q, false, false);
5245 assert!(
5246 d < 0.01,
5247 "composition[{name}]: committed-token distribution must equal p \
5248 (TV {d:.4} >= 0.01)"
5249 );
5250 }
5251 }
5252
5253 #[test]
5254 fn composition_teeth_inverted_accept_fails() {
5255 // DECISIVE teeth: the same harness with the accept inequality inverted must
5256 // MISS the target — otherwise the composition gate is vacuous.
5257 let q: Vec<f32> = vec![0.02, 0.04, 0.06, 0.09, 0.12, 0.15, 0.22, 0.30];
5258 let d = compose_tv(&q, true, false);
5259 assert!(
5260 d > 0.05,
5261 "inverted accept rule must fail the composition bound (TV {d:.4})"
5262 );
5263 }
5264
5265 #[test]
5266 fn composition_teeth_residual_without_q_fails() {
5267 // Sampling the reject slot from p instead of norm(max(0, p-q)) double-counts
5268 // the overlap mass min(p,q) — the committed distribution leaves p.
5269 let q: Vec<f32> = vec![0.0, 0.7, 0.0, 0.3, 0.0, 0.0, 0.0, 0.0];
5270 let d = compose_tv(&q, false, true);
5271 assert!(
5272 d > 0.05,
5273 "residual that skips the q subtraction must fail the bound (TV {d:.4})"
5274 );
5275 }
5276
5277 // ---- PENALIZED round composition (lane/dspark-penalized-sampled-20260821) ----
5278 // Multi-slot rounds where the penalty state EVOLVES within the round. The base trunk
5279 // logits are state-independent, so ALL context dependence flows through penalties —
5280 // the sharpest fixture for "verify row j's target is penalized by the tokens accepted
5281 // before j in the same round", and the proposal concentrates on ONE token, so the
5282 // dominant drafted block is a self-hit (a drafted token penalizing its own successor
5283 // — the within-round case a frozen round-start window cannot see). The reference is
5284 // EXACT (analytic chain p1(a)·p2(b|a), the plain sampler's semantics); the spec arm
5285 // is the shipped round rule — chain draw from q, `rejection_accept_len`, residual
5286 // norm(max(0, p−q)) at the reject slot, bonus from the one-past row on full accept —
5287 // with per-slot penalized p (mirroring penalize_logits_rows_inc_f32's window rule).
5288
5289 const PV: usize = 6;
5290 const PEN_REP: f32 = 1.6;
5291 const PEN_FREQ: f32 = 0.8;
5292 const PEN_PRESENT: f32 = 1.2;
5293
5294 fn pen_base() -> Vec<f32> {
5295 vec![1.5, 0.8, 0.3, -0.2, -0.7, -1.2]
5296 }
5297
5298 /// The proposal: heavy on token 0 so drafted blocks repeat it (the self-hit case).
5299 fn pen_q() -> Vec<f32> {
5300 vec![0.85, 0.06, 0.04, 0.03, 0.01, 0.01]
5301 }
5302
5303 /// CPU mirror of penalize_logits_f32 / the plain sampler's apply_penalties: first
5304 /// occurrence does the whole adjustment, cnt = occurrences in the window, rep
5305 /// divides positive logits and multiplies negative ones.
5306 fn pen_apply(logits: &mut [f32], window: &[u32]) {
5307 let mut seen: Vec<u32> = Vec::new();
5308 for &id in window {
5309 if seen.contains(&id) {
5310 continue;
5311 }
5312 seen.push(id);
5313 let cnt = window.iter().filter(|&&h| h == id).count() as f32;
5314 let v = &mut logits[id as usize];
5315 if *v > 0.0 {
5316 *v /= PEN_REP;
5317 } else {
5318 *v *= PEN_REP;
5319 }
5320 *v -= PEN_FREQ * cnt + PEN_PRESENT;
5321 }
5322 }
5323
5324 /// Penalized target at history `window` (temp 1.0, no truncation filters — those are
5325 /// orthogonal and covered by the unpenalized composition tests + kernel oracles).
5326 fn pen_target(window: &[u32]) -> Vec<f64> {
5327 let mut l = pen_base();
5328 pen_apply(&mut l, window);
5329 let mx = l.iter().cloned().fold(f32::NEG_INFINITY, f32::max) as f64;
5330 let ex: Vec<f64> = l.iter().map(|&v| ((v as f64) - mx).exp()).collect();
5331 let z: f64 = ex.iter().sum();
5332 ex.iter().map(|v| v / z).collect()
5333 }
5334
5335 /// Which penalty-arm mutation the harness runs — `None` is the shipped rule.
5336 #[derive(Clone, Copy, PartialEq)]
5337 enum PenMutation {
5338 None,
5339 /// All rows (walk + bonus) penalized with the ROUND-START window only — the
5340 /// within-round update dropped (the frspec per-round posture; what a flat
5341 /// `penalize_logits_rows` launch would ship).
5342 FrozenWindow,
5343 /// Reject-slot residual computed from the UNPENALIZED p (a raw-tlogits column
5344 /// copy instead of the penalized buffer).
5345 UnpenalizedResidual,
5346 /// Full-accept bonus drawn from the UNPENALIZED one-past row.
5347 UnpenalizedBonus,
5348 }
5349
5350 /// Emit `want` committed tokens through spec rounds of `k` drafts (the shipped round
5351 /// rule, penalty-aware) and return them. `hist0` = the pre-stream window (the prompt
5352 /// seed); uniforms come off the injected stream.
5353 fn pen_round_stream(
5354 hist0: &[u32],
5355 k: usize,
5356 want: usize,
5357 mutation: PenMutation,
5358 next_u: &mut dyn FnMut() -> f32,
5359 ) -> Vec<u32> {
5360 let q = pen_q();
5361 let mut hist: Vec<u32> = hist0.to_vec();
5362 let mut committed: Vec<u32> = Vec::new();
5363 while committed.len() < want {
5364 // draft k tokens ~ q (fixed-order CDF walk, the walk_sampled convention)
5365 let drafted: Vec<u32> = (0..k)
5366 .map(|_| {
5367 let u = next_u() as f64;
5368 let mut acc = 0f64;
5369 let mut bi = 0usize;
5370 for (i, &qi) in q.iter().enumerate() {
5371 acc += qi as f64;
5372 if u < acc {
5373 bi = i;
5374 break;
5375 }
5376 }
5377 bi as u32
5378 })
5379 .collect();
5380 // per-slot penalized p at the drafted ids (row j's window = hist ++ drafted[..j])
5381 let pj: Vec<f32> = (0..k)
5382 .map(|j| {
5383 let win: Vec<u32> = if mutation == PenMutation::FrozenWindow {
5384 hist.clone()
5385 } else {
5386 hist.iter()
5387 .copied()
5388 .chain(drafted[..j].iter().copied())
5389 .collect()
5390 };
5391 pen_target(&win)[drafted[j] as usize] as f32
5392 })
5393 .collect();
5394 let qj: Vec<f32> = drafted.iter().map(|&d| q[d as usize]).collect();
5395 let us: Vec<f32> = (0..k).map(|_| next_u()).collect();
5396 let m = rejection_accept_len(&pj, &qj, &us);
5397 committed.extend_from_slice(&drafted[..m]);
5398 hist.extend_from_slice(&drafted[..m]);
5399 let next: u32 = if m == k {
5400 // bonus ~ p at the one-past row (window carries the WHOLE drafted block)
5401 let win: Vec<u32> = if matches!(
5402 mutation,
5403 PenMutation::FrozenWindow | PenMutation::UnpenalizedBonus
5404 ) {
5405 if mutation == PenMutation::UnpenalizedBonus {
5406 Vec::new() // raw row: no penalties at all
5407 } else {
5408 hist[..hist.len() - m].to_vec() // round-start window
5409 }
5410 } else {
5411 hist.clone()
5412 };
5413 let p = pen_target(&win);
5414 let u = next_u() as f64;
5415 let mut acc = 0f64;
5416 let mut bi = PV - 1;
5417 for (i, &pi) in p.iter().enumerate() {
5418 acc += pi;
5419 if u < acc {
5420 bi = i;
5421 break;
5422 }
5423 }
5424 bi as u32
5425 } else {
5426 // residual ~ norm(max(0, p_m − q)) at the reject slot's state
5427 let win: Vec<u32> = match mutation {
5428 PenMutation::UnpenalizedResidual => Vec::new(),
5429 PenMutation::FrozenWindow => hist[..hist.len() - m].to_vec(),
5430 _ => hist.clone(),
5431 };
5432 let p = pen_target(&win);
5433 let r: Vec<f64> = p
5434 .iter()
5435 .zip(&q)
5436 .map(|(&pi, &qi)| (pi - qi as f64).max(0.0))
5437 .collect();
5438 let total: f64 = r.iter().sum();
5439 let target = next_u() as f64 * total;
5440 let mut acc = 0f64;
5441 let mut bi = PV - 1;
5442 for (i, &ri) in r.iter().enumerate() {
5443 acc += ri;
5444 if acc >= target && ri > 0.0 {
5445 bi = i;
5446 break;
5447 }
5448 }
5449 bi as u32
5450 };
5451 committed.push(next);
5452 hist.push(next);
5453 }
5454 committed.truncate(want);
5455 committed
5456 }
5457
5458 /// Joint TV of the spec arm's first two committed tokens vs the EXACT penalized
5459 /// chain p1(a)·p2(b|a) — the plain sampler's distribution over the same two steps.
5460 fn pen_compose_tv(hist0: &[u32], k: usize, mutation: PenMutation) -> f64 {
5461 let trials = 300_000usize;
5462 let mut counts = vec![0f64; PV * PV];
5463 for t in 0..trials {
5464 // stride 64: a k<=2 round consumes <=2k+1 uniforms, <=2 rounds per trial
5465 let mut ctr = (t as u32) * 64;
5466 let mut next_u = move || {
5467 let u = crate::spec::host_u01(11, ctr);
5468 ctr = ctr.wrapping_add(1);
5469 u
5470 };
5471 let s = pen_round_stream(hist0, k, 2, mutation, &mut next_u);
5472 counts[s[0] as usize * PV + s[1] as usize] += 1.0;
5473 }
5474 let p1 = pen_target(hist0);
5475 let mut tv = 0f64;
5476 for a in 0..PV {
5477 let mut w: Vec<u32> = hist0.to_vec();
5478 w.push(a as u32);
5479 let p2 = pen_target(&w);
5480 for b in 0..PV {
5481 let refp = p1[a] * p2[b];
5482 tv += (counts[a * PV + b] / trials as f64 - refp).abs();
5483 }
5484 }
5485 tv / 2.0
5486 }
5487
5488 #[test]
5489 fn penalized_round_composition_matches_the_penalized_chain() {
5490 // MC floor at 300k trials over 36 cells ~ 0.004 TV; bound 0.01. Fixture (a):
5491 // k=2, empty prompt window — the drafted pair (0,0) dominates, so slot 2's
5492 // accept is the SELF-HIT case (its own predecessor was drafted this round).
5493 // Fixture (b): k=1, prompt window [1,1] — the bonus is the successor of a
5494 // same-round accepted draft, and cnt>1 exercises the freq×count path.
5495 for (name, hist0, k) in [
5496 ("k2-selfhit", vec![], 2usize),
5497 ("k1-bonus-successor", vec![1u32, 1u32], 1usize),
5498 ] {
5499 let d = pen_compose_tv(&hist0, k, PenMutation::None);
5500 eprintln!("penalized composition[{name}]: TV {d:.4} (bound 0.01)");
5501 assert!(
5502 d < 0.01,
5503 "penalized composition[{name}]: committed-token distribution must equal \
5504 the penalized chain (TV {d:.4} >= 0.01)"
5505 );
5506 }
5507 }
5508
5509 #[test]
5510 fn penalized_composition_teeth_frozen_window_fails() {
5511 // DECISIVE teeth: penalizing every verify row with the ROUND-START window —
5512 // dropping the within-round penalty update, i.e. a flat penalize_logits_rows
5513 // launch where the route ships penalize_logits_rows_inc — must MISS the
5514 // penalized chain, or the composition gate cannot see the one thing this lane
5515 // adds over the frozen-window prior art.
5516 let d = pen_compose_tv(&[], 2, PenMutation::FrozenWindow);
5517 eprintln!("penalized teeth[frozen-window]: TV {d:.4} (must exceed 0.05)");
5518 assert!(
5519 d > 0.05,
5520 "within-round penalty update dropped (frozen round-start window) must FAIL \
5521 the composition bound (TV {d:.4})"
5522 );
5523 }
5524
5525 #[test]
5526 fn penalized_composition_teeth_unpenalized_residual_fails() {
5527 // The reject-slot residual must read the PENALIZED column: a raw-tlogits column
5528 // copy (p_raw − q) commits from the wrong measure. Non-empty prompt window so
5529 // even round-start reject slots hit the mutation (an empty-window fixture only
5530 // sees it on within-round rejects and the margin thins to ~0.055).
5531 let d = pen_compose_tv(&[1, 1], 2, PenMutation::UnpenalizedResidual);
5532 eprintln!("penalized teeth[unpenalized-residual]: TV {d:.4} (must exceed 0.05)");
5533 assert!(
5534 d > 0.05,
5535 "residual computed from the unpenalized p must FAIL the composition bound \
5536 (TV {d:.4})"
5537 );
5538 }
5539
5540 #[test]
5541 fn penalized_composition_teeth_unpenalized_bonus_fails() {
5542 // The full-accept bonus row must carry the whole drafted block in its window:
5543 // a raw one-past row draw commits the unpenalized measure right after a
5544 // same-round accept.
5545 let d = pen_compose_tv(&[1, 1], 1, PenMutation::UnpenalizedBonus);
5546 eprintln!("penalized teeth[unpenalized-bonus]: TV {d:.4} (must exceed 0.05)");
5547 assert!(
5548 d > 0.05,
5549 "bonus drawn from the unpenalized one-past row must FAIL the composition \
5550 bound (TV {d:.4})"
5551 );
5552 }
5553}
5554
5555#[cfg(test)]
5556mod dspark_harvest_tests {
5557 use super::{DsparkHarvest, DsparkVtPolicy, dspark_accept_prefix, dspark_strategy_census};
5558
5559 const B: usize = 7; // q38 arm-a block_size
5560
5561 #[test]
5562 fn dspark_strategy_requires_shifted_harvest() {
5563 let h = DsparkHarvest::Dspark;
5564 assert_eq!(
5565 h.first_row(),
5566 0,
5567 "DSPARK-strategy checkpoints (SpecForge OnlineDSparkModel, \
5568 training.strategy=dspark — the q38 arm-a export) supervise ALL rows with \
5569 SHIFTED labels: label_offsets = arange(1, block_size+1), i.e. the ANCHOR \
5570 row's output is draft 1 (specforge/algorithms/common/\
5571 dflash_family_model.py:816; sglang v0.5.17 dspark_draft.py:248,260). \
5572 Harvesting from row 1 re-opens the DSPARK-POSTMORTEM-20260820 slot \
5573 misalignment (accept 2.9 -> 1.43)."
5574 );
5575 assert_eq!(
5576 h.n_drafts(B),
5577 B,
5578 "DSpark harvests gamma = block_size drafts per round (sglang \
5579 dspark_config.py:269, verify_num_draft_tokens = gamma+1); b-1 is the \
5580 DFlash mask-fill count and drops the best-trained slot \
5581 (DSPARK-POSTMORTEM-20260820.md §3-H1)."
5582 );
5583 for row in 0..B {
5584 assert_eq!(
5585 h.trained_offset_of_row(row),
5586 row + 1,
5587 "OnlineDSparkModel trains row k to predict anchor+k+1 \
5588 (dflash_family_model.py:816); a same-position (mask-fill) mapping \
5589 here verifies every slot one position early — the postmortem's \
5590 collapse."
5591 );
5592 }
5593 }
5594
5595 #[test]
5596 fn dflash_strategy_keeps_mask_fill_harvest() {
5597 // Guards the reverse mutation: z-lab dflash checkpoints (the gemma arm) are
5598 // mask-fill — row k FILLS anchor+k, the anchor row is loss-excluded
5599 // (dflash_family_model.py:453-472). Shifting THEM would break the gemma arm.
5600 let h = DsparkHarvest::Dflash;
5601 assert_eq!(h.first_row(), 1, "DFlash drafts start at mask row 1");
5602 assert_eq!(h.n_drafts(B), B - 1, "DFlash harvests block_size-1 drafts");
5603 for row in 1..B {
5604 assert_eq!(h.trained_offset_of_row(row), row);
5605 }
5606 }
5607
5608 #[test]
5609 fn every_candidate_verifies_the_position_its_row_was_trained_for() {
5610 // The round's invariant: draft candidate i (1-based; verified against the
5611 // trunk's prediction for anchor+i) is filled from drafter output row
5612 // first_row + i - 1. Alignment == that row was TRAINED for offset i.
5613 for h in [DsparkHarvest::Dflash, DsparkHarvest::Dspark] {
5614 for i in 1..=h.n_drafts(B) {
5615 let row = h.first_row() + i - 1;
5616 assert_eq!(
5617 h.trained_offset_of_row(row),
5618 i,
5619 "{h:?}: candidate {i} rides row {row}, which is trained for \
5620 offset {} — harvest misaligned",
5621 h.trained_offset_of_row(row)
5622 );
5623 }
5624 }
5625 }
5626
5627 #[test]
5628 fn env_seam_parses_and_refuses() {
5629 assert_eq!(
5630 DsparkHarvest::from_env_value(None),
5631 DsparkHarvest::Dflash,
5632 "the ENV-ONLY parser keeps the historical arm; the ratified strategy-keyed \
5633 default lives in resolve_value (checkpoint census), not here"
5634 );
5635 assert_eq!(
5636 DsparkHarvest::from_env_value(Some("dspark")),
5637 DsparkHarvest::Dspark
5638 );
5639 assert_eq!(
5640 DsparkHarvest::from_env_value(Some("dflash")),
5641 DsparkHarvest::Dflash
5642 );
5643 assert!(
5644 std::panic::catch_unwind(|| DsparkHarvest::from_env_value(Some("shifted"))).is_err(),
5645 "unknown harvest values must REFUSE, not default"
5646 );
5647 assert_eq!(
5648 DsparkHarvest::from_name("dspark"),
5649 Some(DsparkHarvest::Dspark)
5650 );
5651 assert_eq!(
5652 DsparkHarvest::from_name("dflash"),
5653 Some(DsparkHarvest::Dflash)
5654 );
5655 assert_eq!(DsparkHarvest::from_name("mask-fill"), None);
5656 }
5657
5658 /// The owner-ratified default flips (2026-08-20). Each assertion names its
5659 /// evidence; mutating either resolve back to the old default fails these.
5660 #[test]
5661 fn ratified_default_harvest_is_strategy_keyed() {
5662 // DSPARK-strategy checkpoint + unset env = the shifted harvest (B1: accept
5663 // 1.38->2.41 agentic / 1.53->3.66 math, E2E ALL EXACT x5, interleaved x5).
5664 assert_eq!(
5665 DsparkHarvest::resolve_value(None, true),
5666 DsparkHarvest::Dspark,
5667 "owner-ratified 2026-08-20: unset env defaults a DSPARK-strategy \
5668 checkpoint to the shifted harvest (DSPARK-POSTMORTEM-20260820.md B1)"
5669 );
5670 // mask-fill checkpoint + unset env = the historical arm, byte-identical.
5671 assert_eq!(
5672 DsparkHarvest::resolve_value(None, false),
5673 DsparkHarvest::Dflash
5674 );
5675 assert_eq!(
5676 DsparkHarvest::resolve_value(Some(""), false),
5677 DsparkHarvest::Dflash
5678 );
5679 // Explicit env overrides the census in BOTH directions (the A/B seam).
5680 assert_eq!(
5681 DsparkHarvest::resolve_value(Some("dflash"), true),
5682 DsparkHarvest::Dflash
5683 );
5684 assert_eq!(
5685 DsparkHarvest::resolve_value(Some("dspark"), false),
5686 DsparkHarvest::Dspark
5687 );
5688 // Unknown values still REFUSE through the resolve path.
5689 assert!(
5690 std::panic::catch_unwind(|| DsparkHarvest::resolve_value(Some("shifted"), true))
5691 .is_err()
5692 );
5693 }
5694
5695 #[test]
5696 fn strategy_census_reads_the_checkpoint_not_the_env() {
5697 // The q38 arm-a export shape: both signals present.
5698 let q38 = r#"{"architectures": ["Qwen3DSparkModel"], "block_size": 7,
5699 "dflash_config": {"projector_type": "dspark", "markov_rank": 256}}"#;
5700 assert!(dspark_strategy_census(q38));
5701 // Either signal alone suffices.
5702 assert!(dspark_strategy_census(
5703 r#"{"architectures": ["Qwen3DSparkModel"]}"#
5704 ));
5705 assert!(dspark_strategy_census(
5706 r#"{"dflash_config": {"projector_type": "dspark"}}"#
5707 ));
5708 // A mask-fill DFlash export carries neither -> historical default.
5709 let dflash = r#"{"architectures": ["Qwen3DFlashModel"],
5710 "dflash_config": {"attention_mode": "gqa"}}"#;
5711 assert!(!dspark_strategy_census(dflash));
5712 assert!(!dspark_strategy_census("{}"));
5713 }
5714
5715 #[test]
5716 fn ratified_default_vt_is_confidence_slot_tau_half() {
5717 // Head-carrying checkpoint + unset env = confidence-slot tau=.5 (H4 cell 3:
5718 // the tau ladder's knee; cell 2: 93.9%/97.7% of fixed-8 accept at wall >=
5719 // the reactive ladder, exactness 11/11 ALL EXACT).
5720 assert_eq!(
5721 DsparkVtPolicy::resolve_value(None, None, None, true),
5722 DsparkVtPolicy::ConfidenceSlot { tau: 0.5 },
5723 "owner-ratified 2026-08-20: unset MEMRA_DSPARK_VT defaults to \
5724 confidence-slot tau=.5 on a head-carrying checkpoint (H4 cells 2-3)"
5725 );
5726 // tau env still steers the default arm (and a bad tau still refuses).
5727 assert_eq!(
5728 DsparkVtPolicy::resolve_value(None, Some("0.35"), None, true),
5729 DsparkVtPolicy::ConfidenceSlot { tau: 0.35 }
5730 );
5731 assert!(
5732 std::panic::catch_unwind(|| DsparkVtPolicy::resolve_value(
5733 None,
5734 Some("nan-ish"),
5735 None,
5736 true
5737 ))
5738 .is_err()
5739 );
5740 // Census: no accept-rate head -> nothing to schedule with -> ladder.
5741 assert_eq!(
5742 DsparkVtPolicy::resolve_value(None, None, None, false),
5743 DsparkVtPolicy::Ladder
5744 );
5745 // MEMRA_DFLASH_ADAPT=0 is an explicit fixed-window request: honored.
5746 assert_eq!(
5747 DsparkVtPolicy::resolve_value(None, None, Some("0"), true),
5748 DsparkVtPolicy::Ladder
5749 );
5750 // Explicit values keep their exact prior semantics through resolve.
5751 assert_eq!(
5752 DsparkVtPolicy::resolve_value(Some("ladder"), None, None, true),
5753 DsparkVtPolicy::Ladder
5754 );
5755 assert_eq!(
5756 DsparkVtPolicy::resolve_value(Some("confidence"), Some("0.35"), None, true),
5757 DsparkVtPolicy::Confidence { tau: 0.35 }
5758 );
5759 // Explicit confidence mode with ADAPT=0 stays a refusal.
5760 assert!(
5761 std::panic::catch_unwind(|| DsparkVtPolicy::resolve_value(
5762 Some("confidence-slot"),
5763 None,
5764 Some("0"),
5765 true
5766 ))
5767 .is_err()
5768 );
5769 }
5770
5771 /// End-to-end alignment fixture in miniature: a mock drafter whose row r argmaxes
5772 /// to token BASE + (its trained offset under the DSPARK strategy), and a mock trunk
5773 /// whose prediction for anchor+j is BASE + j. The DSpark harvest accepts the whole
5774 /// block; feeding the same drafter through the mask-fill harvest accepts ZERO —
5775 /// the postmortem's collapse reproduced as pure logic.
5776 #[test]
5777 fn dspark_trained_rows_through_mask_fill_harvest_accept_nothing() {
5778 const BASE: u32 = 1000;
5779 let anchor: u32 = BASE; // token at the round anchor position (offset 0)
5780 // trunk verify argmaxes: vam[j] = prediction for anchor offset j+1
5781 let vam: Vec<u32> = (1..=B as u32 + 1).map(|j| BASE + j).collect();
5782 // drafter rows trained under the DSPARK strategy: row r predicts offset r+1
5783 let dspark_trained_row_argmax =
5784 |r: usize| BASE + DsparkHarvest::Dspark.trained_offset_of_row(r) as u32;
5785
5786 // Correct (shifted) harvest: candidate i <- row i-1.
5787 let h = DsparkHarvest::Dspark;
5788 let mut cand = vec![anchor];
5789 for i in 1..=h.n_drafts(B) {
5790 cand.push(dspark_trained_row_argmax(h.first_row() + i - 1));
5791 }
5792 let vt = h.n_drafts(B) + 1;
5793 assert_eq!(
5794 dspark_accept_prefix(&cand, &vam, vt),
5795 vt - 1,
5796 "aligned harvest must accept the full block"
5797 );
5798
5799 // Mask-fill harvest of the SAME dspark-trained drafter: candidate i <- row i,
5800 // which was trained for offset i+1 — every slot one position late.
5801 let wrong = DsparkHarvest::Dflash;
5802 let mut cand_wrong = vec![anchor];
5803 for i in 1..=wrong.n_drafts(B) {
5804 cand_wrong.push(dspark_trained_row_argmax(wrong.first_row() + i - 1));
5805 }
5806 let vt_wrong = wrong.n_drafts(B) + 1;
5807 assert_eq!(
5808 dspark_accept_prefix(&cand_wrong, &vam, vt_wrong),
5809 0,
5810 "mask-fill harvest of a dspark-trained drafter verifies every slot against \
5811 a position the row was not trained for (DSPARK-POSTMORTEM-20260820.md)"
5812 );
5813 }
5814}
5815
5816// ================= Verify-window policy gate (CPU; H4, DSPARK-POSTMORTEM-20260820.md) ===
5817// Pins the confidence-vt semantics as logic the round consumes: cumprod survival over
5818// sigmoid scores, thresholded, anchor + kept drafts, floor 2 / cap vt_cap — and the env
5819// seam's refuse-on-ambiguity. Mutating the policy (per-slot threshold instead of
5820// survival, off-by-one on the anchor, silent unknown-value fallback) fails HERE.
5821#[cfg(test)]
5822mod dspark_vt_tests {
5823 use super::{ConfidenceHead, DsparkVtPolicy, dspark_confidence_vt, dspark_slot_confidence_vt};
5824
5825 /// Pre-sigmoid logit for a target probability: sigmoid(logit(p)) == p.
5826 fn logit(p: f32) -> f32 {
5827 (p / (1.0 - p)).ln()
5828 }
5829
5830 #[test]
5831 fn confidence_vt_is_cumprod_survival_not_per_slot_threshold() {
5832 // sigmoids = [0.9, 0.8, 0.9, ...]: every PER-SLOT score clears tau=0.5, but
5833 // cumulative survival sinks below it at slot 6 (0.9, 0.72, 0.648, 0.583,
5834 // 0.525, then 0.472 < 0.5) — the window must stop where the EXPECTED
5835 // accepted-prefix stops paying, not where a slot looks locally fine.
5836 let raws: Vec<f32> = [0.9, 0.8, 0.9, 0.9, 0.9, 0.9, 0.9]
5837 .iter()
5838 .map(|&p| logit(p))
5839 .collect();
5840 assert_eq!(
5841 dspark_confidence_vt(&raws, 0.5, 8),
5842 6,
5843 "keeps 5 drafts + anchor"
5844 );
5845 // Tighter threshold closes the window sooner; looser opens it to the cap.
5846 assert_eq!(
5847 dspark_confidence_vt(&raws, 0.7, 8),
5848 3,
5849 "tau=0.7 keeps 2 drafts"
5850 );
5851 assert_eq!(
5852 dspark_confidence_vt(&raws, 0.05, 8),
5853 8,
5854 "tau→0 = full block"
5855 );
5856 }
5857
5858 #[test]
5859 fn slot_arm_truncates_at_first_low_confidence_slot() {
5860 // Owner directive (2026-08-20): submit only the longest prefix whose EVERY
5861 // slot clears tau on its own sigmoid. On the survival test's raws
5862 // ([0.9, 0.8, 0.9 x5], tau=0.5) every slot clears per-slot, so the slot arm
5863 // opens the full block where survival stopped at 6 — the two stopping
5864 // statistics must stay distinct arms.
5865 let raws: Vec<f32> = [0.9, 0.8, 0.9, 0.9, 0.9, 0.9, 0.9]
5866 .iter()
5867 .map(|&p| logit(p))
5868 .collect();
5869 assert_eq!(dspark_slot_confidence_vt(&raws, 0.5, 8), 8);
5870 assert_eq!(dspark_confidence_vt(&raws, 0.5, 8), 6);
5871 // A low-confidence tail never enters verify: [0.9, 0.9, 0.3, 0.9, ...]
5872 // truncates at slot 3 REGARDLESS of the confident slots behind it — a kept
5873 // slot after a dropped one could never commit (prefix accept rule).
5874 let tail: Vec<f32> = [0.9, 0.9, 0.3, 0.9, 0.9, 0.9, 0.9]
5875 .iter()
5876 .map(|&p| logit(p))
5877 .collect();
5878 assert_eq!(
5879 dspark_slot_confidence_vt(&tail, 0.5, 8),
5880 3,
5881 "2 drafts + anchor"
5882 );
5883 // Tighter tau keeps less.
5884 assert_eq!(
5885 dspark_slot_confidence_vt(&tail, 0.95, 8),
5886 2,
5887 "floor at tau=0.95"
5888 );
5889 }
5890
5891 #[test]
5892 fn confidence_vt_floor_and_cap() {
5893 // A hopeless round still verifies ONE draft (the draft forward is paid;
5894 // vt=1 would guarantee an empty round at the same cost class).
5895 let cold: Vec<f32> = [0.1f32, 0.1, 0.1].iter().map(|&p| logit(p)).collect();
5896 assert_eq!(
5897 dspark_confidence_vt(&cold, 0.5, 8),
5898 2,
5899 "floor = anchor + 1 draft"
5900 );
5901 assert_eq!(
5902 dspark_slot_confidence_vt(&cold, 0.5, 8),
5903 2,
5904 "slot arm same floor"
5905 );
5906 // The MEMRA_DFLASH_VERIFY_T cap still binds a confident round.
5907 let hot: Vec<f32> = vec![logit(0.99); 7];
5908 assert_eq!(dspark_confidence_vt(&hot, 0.5, 5), 5, "vt_cap binds");
5909 assert_eq!(
5910 dspark_confidence_vt(&hot, 0.5, 8),
5911 8,
5912 "full block when confident"
5913 );
5914 assert_eq!(
5915 dspark_slot_confidence_vt(&hot, 0.5, 5),
5916 5,
5917 "slot arm same cap"
5918 );
5919 // No scores (defensive): floor.
5920 assert_eq!(dspark_confidence_vt(&[], 0.5, 8), 2);
5921 assert_eq!(dspark_slot_confidence_vt(&[], 0.5, 8), 2);
5922 }
5923
5924 #[test]
5925 fn vt_policy_env_seam_parses_and_refuses() {
5926 assert_eq!(
5927 DsparkVtPolicy::from_env_value(None, None, None),
5928 DsparkVtPolicy::Ladder,
5929 "default stays the shipped ladder — the H4 arm is opt-in"
5930 );
5931 assert_eq!(
5932 DsparkVtPolicy::from_env_value(Some(""), None, None),
5933 DsparkVtPolicy::Ladder
5934 );
5935 assert_eq!(
5936 DsparkVtPolicy::from_env_value(Some("ladder"), None, Some("0")),
5937 DsparkVtPolicy::Ladder,
5938 "ladder + ADAPT=0 = the fixed-window arm, untouched"
5939 );
5940 assert_eq!(
5941 DsparkVtPolicy::from_env_value(Some("confidence"), None, None),
5942 DsparkVtPolicy::Confidence { tau: 0.5 },
5943 "tau defaults to 0.5 (raw sigmoid, no STS sidecar — postmortem §3-H4)"
5944 );
5945 assert_eq!(
5946 DsparkVtPolicy::from_env_value(Some("confidence"), Some("0.35"), Some("1")),
5947 DsparkVtPolicy::Confidence { tau: 0.35 }
5948 );
5949 assert_eq!(
5950 DsparkVtPolicy::from_env_value(Some("confidence-slot"), Some("0.6"), None),
5951 DsparkVtPolicy::ConfidenceSlot { tau: 0.6 },
5952 "the owner-directive per-slot arm parses with the same tau env"
5953 );
5954 assert!(
5955 std::panic::catch_unwind(|| DsparkVtPolicy::from_env_value(
5956 Some("confidence-slot"),
5957 None,
5958 Some("0")
5959 ))
5960 .is_err(),
5961 "confidence-slot + MEMRA_DFLASH_ADAPT=0 must REFUSE like confidence"
5962 );
5963 assert!(
5964 std::panic::catch_unwind(|| DsparkVtPolicy::from_env_value(Some("static"), None, None))
5965 .is_err(),
5966 "unknown policy values must REFUSE, not default — a typo silently \
5967 reverting the window policy invalidates an A/B"
5968 );
5969 assert!(
5970 std::panic::catch_unwind(|| DsparkVtPolicy::from_env_value(
5971 Some("confidence"),
5972 None,
5973 Some("0")
5974 ))
5975 .is_err(),
5976 "confidence + MEMRA_DFLASH_ADAPT=0 is contradictory and must REFUSE"
5977 );
5978 for bad in ["0", "1", "1.5", "-0.1", "nan"] {
5979 assert!(
5980 std::panic::catch_unwind(|| DsparkVtPolicy::from_env_value(
5981 Some("confidence"),
5982 Some(bad),
5983 None
5984 ))
5985 .is_err(),
5986 "tau={bad} must REFUSE (survival threshold lives in (0,1))"
5987 );
5988 }
5989 }
5990
5991 #[test]
5992 fn raw_score_matches_the_parity_gate_dot() {
5993 // The head is a raw linear proj over [hidden ; markov_prev_embedding] + b —
5994 // the exact stage-5 contract in dspark_q38_parity.rs.
5995 let ch = ConfidenceHead {
5996 w: vec![0.5, -1.0, 2.0, 0.25, -0.5],
5997 b: 0.125,
5998 in_dim: 5,
5999 with_markov: true,
6000 };
6001 let hidden = [1.0f32, 2.0, 3.0];
6002 let emb = [4.0f32, 8.0];
6003 let want = 0.125 + 0.5 * 1.0 - 1.0 * 2.0 + 2.0 * 3.0 + 0.25 * 4.0 - 0.5 * 8.0;
6004 assert_eq!(ch.raw_score(&hidden, Some(&emb)), want);
6005 let ch_plain = ConfidenceHead {
6006 w: vec![0.5, -1.0, 2.0],
6007 b: -0.25,
6008 in_dim: 3,
6009 with_markov: false,
6010 };
6011 let want_plain = -0.25 + 0.5 * 1.0 - 1.0 * 2.0 + 2.0 * 3.0;
6012 assert_eq!(ch_plain.raw_score(&hidden, None), want_plain);
6013 }
6014}
6015
6016#[cfg(test)]
6017mod dspark_prefix_capture_tests {
6018 use super::{dspark_spec_prompt_fits, take_dspark_prefix_capture};
6019
6020 /// INCIDENT REGRESSION (2026-08-25). This gate is the only admission check the dspark
6021 /// route has, and it checked the ctx ceiling ONLY — so a short prompt was admitted and
6022 /// then panicked in the cold prime (`prime_cache needs T >= 16`), inside the GPU worker
6023 /// thread, which exits 70 and kills every live session on the box. Two crash loops and
6024 /// ~5 minutes of customer 502s came from a 5-token "Say OK." — the class our own
6025 /// watchdog sends. The floor belongs HERE, in the gate, not in each caller.
6026 #[test]
6027 fn a_prompt_below_the_prime_floor_never_enters_the_dspark_route() {
6028 let floor = crate::hybrid_forward::PRIME_MIN_T;
6029 for short in [1usize, 5, floor - 1] {
6030 assert!(
6031 !dspark_spec_prompt_fits(short, 262_144, 8, 2_048, true),
6032 "a {short}-token prompt must decline to the plain path, not prime"
6033 );
6034 }
6035 // At and above the floor the route admits exactly as before (ceiling still applies).
6036 assert!(dspark_spec_prompt_fits(floor, 262_144, 8, 2_048, true));
6037 assert!(dspark_spec_prompt_fits(512, 262_144, 8, 2_048, true));
6038 assert!(!dspark_spec_prompt_fits(512, 300, 8, 2_048, true));
6039 }
6040
6041 #[test]
6042 fn session_prompt_preflight_matches_dflash2_and_windowed_caps() {
6043 // DFlash2 uses the request ctx cap: prompt + block + 8 fits exactly, one row less does not.
6044 assert!(dspark_spec_prompt_fits(96, 111, 7, 2_048, true));
6045 assert!(!dspark_spec_prompt_fits(96, 110, 7, 2_048, true));
6046
6047 // Legacy/windowed drafts are additionally bounded by their own sliding window.
6048 assert!(dspark_spec_prompt_fits(113, 8_192, 7, 128, false));
6049 assert!(!dspark_spec_prompt_fits(114, 8_192, 7, 128, false));
6050 assert!(!dspark_spec_prompt_fits(
6051 usize::MAX,
6052 usize::MAX,
6053 7,
6054 usize::MAX,
6055 true,
6056 ));
6057 }
6058
6059 #[test]
6060 fn prompt_end_capture_is_full_prompt_and_one_shot() {
6061 let prompt_len = 96;
6062 let mut slot = Some(crate::spec::SpecBoundaryCapture {
6063 snap: crate::cache::CacheSnapshot {
6064 kv_len: Vec::new(),
6065 tp_kv_len: Vec::new(),
6066 conv: Vec::new(),
6067 ssm: Vec::new(),
6068 pos: prompt_len,
6069 },
6070 pos: prompt_len,
6071 logits: vec![1.0, 2.0],
6072 last_h: Vec::new(),
6073 });
6074
6075 let capture = take_dspark_prefix_capture(&mut slot).expect("first drain gets capture");
6076 assert_eq!(capture.pos, prompt_len, "capture is at full prompt end");
6077 assert_eq!(capture.snap.pos, prompt_len);
6078 assert!(
6079 capture.last_h.is_empty(),
6080 "DFlash publishes no hidden anchor"
6081 );
6082 assert!(
6083 take_dspark_prefix_capture(&mut slot).is_none(),
6084 "capture drains exactly once",
6085 );
6086 }
6087}
6088
6089#[cfg(test)]
6090mod dflash_precision_tests {
6091 use super::dflash_precision;
6092
6093 #[test]
6094 fn default_and_supported_precision_programs_are_explicit() {
6095 assert_eq!(dflash_precision(None), Ok("q4"));
6096 for prec in ["q4", "q8", "mixed", "bf16", "fc"] {
6097 assert_eq!(dflash_precision(Some(prec)), Ok(prec));
6098 }
6099 }
6100
6101 #[test]
6102 fn q5_and_typos_refuse_instead_of_silently_selecting_q8() {
6103 for prec in ["q5", "Q4", "", "typo"] {
6104 let err = dflash_precision(Some(prec)).unwrap_err();
6105 assert!(err.contains("want q4, q8, mixed, bf16, or fc"));
6106 }
6107 }
6108}