From 7b617bc333bb708fd07705614e563797cceadf13 Mon Sep 17 00:00:00 2001 From: iz0eyj Date: Wed, 2 Dec 2026 21:30:34 +0100 Subject: [PATCH] [Core] DSpark brick 5b+6: speculative runner + LOSSLESS GATE green (200 tokens) LayerState: per-prefix ShortConv hist snapshots (snap_k/v/a/m[3]) captured during a spec verify batch via spec_update_hist (gated by thread-local spec_begin/end); rollback_spec restores hist<-snap[accepted]. KV ring truncates with no restore (proofs/speculative_draft.lean kept_rejected_disjoint). Normal path unchanged. DsparkContext: persistent bf16 ctx rings (k/v[3] + frnn) + commit (scatter). spec_round: draft nd -> batched trunk verify (forward_batch_taps B=nd+1) -> per-row greedy from taps[3] -> spec_accept_greedy -> commit ctx + rollback hist. Mirrors strata ink_serve.h indexing exactly. b6 GATE: spec_lossless_gate emits EXACTLY the same 200 tokens as plain batched greedy (forward_batch B=1) on real trunk+mtp (163 rounds, nd=7). Diagnostics: batch_determinism, rollback_hist (exact), spec_lockstep (200 rounds hist+KV exact). Acceptance 3.2% on the arbitrary synthetic prompt -> NO speedup claim yet. Verified: CPU -D warnings clean, Lean 0 sorryAx, hip 45/45, ld GPU 65/65. --- crates/vetta-infer-ld/src/dspark.rs | 320 +++++++++++++++++++++++++++- crates/vetta-infer-ld/src/layer.rs | 63 +++++- 2 files changed, 374 insertions(+), 9 deletions(-) diff --git a/crates/vetta-infer-ld/src/dspark.rs b/crates/vetta-infer-ld/src/dspark.rs index d76b410..d1820f1 100644 --- a/crates/vetta-infer-ld/src/dspark.rs +++ b/crates/vetta-infer-ld/src/dspark.rs @@ -92,6 +92,7 @@ mod gpu { use super::*; use crate::packer; use vetta_infer_hip::DeviceBuf; + use vetta_infer_hip as hip; pub struct DsparkLayer { pub dflare_norm: DeviceBuf, @@ -318,10 +319,113 @@ mod gpu { } Ok(()) } + + /// Persistent DSpark context rings (bf16): per-layer k/v [cap, kv_dim] + + /// frnn [frnn_cap, D]. `len` = committed context length (truncated on + /// partial accept; ring slots of kept vs rejected spans are disjoint). + pub struct DsparkContext { + pub k: [DeviceBuf; 3], pub v: [DeviceBuf; 3], pub frnn: DeviceBuf, + pub cap: usize, pub frnn_cap: usize, pub len: usize, + } + + impl DsparkContext { + pub fn new(cap: usize, frnn_cap: usize) -> Result { + let ring = |n: usize| -> Result { + let b = DeviceBuf::alloc(n * 2)?; b.zero_async()?; Ok(b) + }; + let kv = cap * DS_KV * DS_HD; + Ok(Self { + k: [ring(kv)?, ring(kv)?, ring(kv)?], + v: [ring(kv)?, ring(kv)?, ring(kv)?], + frnn: ring(frnn_cap * DS_HIDDEN)?, + cap, frnn_cap, len: 0, + }) + } + + /// Commit the context for `m` fed tokens (taps [4][m,D], pos[m]) into the + /// rings at slot pos%cap. Caller truncates `len` on partial accept. + pub fn commit(&mut self, w: &DsparkWeights, taps: &[DeviceBuf; 4], pos: &DeviceBuf, m: i32, eps: f32, theta: f32) -> Result<(), String> { + let kv = DS_KV * DS_HD; let mu = m as usize; + let ko = [DeviceBuf::alloc(mu * kv * 4)?, DeviceBuf::alloc(mu * kv * 4)?, DeviceBuf::alloc(mu * kv * 4)?]; + let vo = [DeviceBuf::alloc(mu * kv * 4)?, DeviceBuf::alloc(mu * kv * 4)?, DeviceBuf::alloc(mu * kv * 4)?]; + let fr = DeviceBuf::alloc(mu * DS_HIDDEN * 4)?; + let tref = [&taps[0], &taps[1], &taps[2], &taps[3]]; + let kref = [&ko[0], &ko[1], &ko[2]]; + let vref = [&vo[0], &vo[1], &vo[2]]; + dspark_context(w, tref, pos, m, kref, vref, &fr, eps, theta)?; + for il in 0..DS_LAYERS { + hip::dspark_scatter_bf16(&ko[il], &self.k[il], pos, m, kv as i32, self.cap as i32)?; + hip::dspark_scatter_bf16(&vo[il], &self.v[il], pos, m, kv as i32, self.cap as i32)?; + } + hip::dspark_scatter_bf16(&fr, &self.frnn, pos, m, DS_HIDDEN as i32, self.frnn_cap as i32)?; + Ok(()) + } + } + + /// One greedy speculative round: draft nd -> batched trunk verify (capture + /// taps + hist snaps) -> accept longest prefix -> commit ctx + rollback hist + /// to `accepted`. Returns (emit, new_cur_pos, new_next_tok, done). + /// Lossless vs plain batched greedy (proofs/speculative_draft.lean). + #[allow(clippy::too_many_arguments)] + pub fn spec_round( + cache: &crate::layer::WeightCache, d: &crate::layer::Dims, + dw: &DsparkWeights, dctx: &mut DsparkContext, + states: &mut [Option], + cur_pos: i32, next_tok: i32, nd: usize, vocab: usize, max_seq: usize, + max_left: usize, is_stop: impl Fn(i32) -> bool, + ) -> Result<(Vec, i32, i32, bool), String> { + use crate::layer::{forward_batch_taps, rollback_spec, spec_begin, spec_end}; + let alloc = |n: usize| DeviceBuf::alloc(n); + let h = d.hidden; + let embed = cache.raw("model.llm.embed.weight")?; + let embed_norm = cache.bf16_f32("model.llm.embed_norm.weight")?; + let unembed = cache.raw("model.llm.unembed.weight")?; + // 1. draft + let mut draft = vec![0i32; nd]; + if nd > 0 { + let kref = [&dctx.k[0], &dctx.k[1], &dctx.k[2]]; + let vref = [&dctx.v[0], &dctx.v[1], &dctx.v[2]]; + dspark_draft(dw, &embed, &embed_norm, &unembed, kref, vref, &dctx.frnn, + next_tok, cur_pos, nd as i32, dctx.cap as i32, dctx.frnn_cap as i32, + d.swa_win, d.eps, 1e6, vocab as i32, &mut draft)?; + } + // 2. batched verify B=nd+1 (anchor + drafts), capture taps + hist snaps + let b = nd + 1; + let mut tokens = vec![0i32; b]; + tokens[0] = next_tok; + for i in 0..nd { tokens[i + 1] = draft[i]; } + let mut taps = [alloc(b * h * 4)?, alloc(b * h * 4)?, alloc(b * h * 4)?, alloc(b * h * 4)?]; + spec_begin(b); + let _last = forward_batch_taps(cache, d, &tokens, vocab, max_seq, cur_pos, 0.0, states, &mut taps)?; + spec_end(); + // 3. per-row greedy from taps[3] (h_norm) via bf16 unembed gemm + let tn_bf = alloc(b * h * 2)?; + hip::cast_f32_bf16(&taps[3], &tn_bf, b * h)?; + let lg = alloc(b * vocab * 4)?; + hip::gemm_bf16(&tn_bf, &unembed, &lg, b as i32, vocab as i32, h as i32)?; + let mut lgh = vec![0f32; b * vocab]; lg.d2h(&mut lgh)?; + let mut greedy = vec![0i32; b]; + for i in 0..b { + let row = &lgh[i * vocab..(i + 1) * vocab]; + let mut best = 0usize; let mut bz = f32::NEG_INFINITY; + for (v, &z) in row.iter().enumerate() { if z > bz { bz = z; best = v; } } + greedy[i] = best as i32; + } + // 4. accept + let r = spec_accept_greedy(&draft, &greedy, next_tok, max_left, is_stop); + // 5. commit ctx for fed tokens, truncate to accepted; rollback hist + let pos = alloc(b * 4)?; + let pv: Vec = (0..b as i32).map(|i| cur_pos + i).collect(); + pos.h2d_bytes(&pv.iter().flat_map(|p| p.to_le_bytes()).collect::>())?; + dctx.commit(dw, &taps, &pos, b as i32, d.eps, 1e6)?; + dctx.len = cur_pos as usize + r.accepted; + rollback_spec(d, states, r.accepted)?; + Ok((r.emit, cur_pos + r.accepted as i32, r.next_tok, r.done)) + } } #[cfg(feature = "hip")] -pub use gpu::{DsparkLayer, DsparkWeights, dspark_context, dspark_draft}; +pub use gpu::{DsparkLayer, DsparkWeights, DsparkContext, dspark_context, dspark_draft, spec_round}; /// Outcome of one greedy speculative round (mirrors strata ink_serve.h block /// verify loop). `greedy[i]` is the trunk argmax from feeding row i (anchor for @@ -743,4 +847,218 @@ mod tests { eprintln!("dspark_draft ids gpu={ids:?} oracle={want:?}"); assert_eq!(ids, want, "dspark_draft token ids must match the CPU oracle exactly"); } + + /// b6 LOSSLESS GATE: greedy speculative decode (draft + batched verify + + /// rollback) must emit EXACTLY the same tokens as plain batched greedy decode + /// (forward_batch B=1 per step) over 200+ tokens, on the REAL trunk + mtp. + /// Both use the same batched trunk path, so per-token numerics are identical + /// and spec_lossless (Lean) applies. Any divergence = a rollback/ctx bug. + #[test] + #[cfg(feature = "hip")] + #[ignore] + fn spec_lossless_gate() { + use crate::layer::{Dims, WeightCache, forward_batch, forward_batch_taps}; + use vetta_infer_hip::DeviceBuf; + let trunk = "/mnt/models/Inkling/safetensors"; + let mtp = "/mnt/models/Inkling/safetensors/mtp.safetensors"; + if !std::path::Path::new(mtp).exists() { eprintln!("skip: no mtp"); return; } + let ar = std::sync::Arc::new(SafetensorsArchive::open(trunk).unwrap()); + let cache = WeightCache::new(ar.clone()); + let dw = DsparkWeights::load(&SafetensorsArchive::open_file(mtp).unwrap()).unwrap(); + let d = Dims { hidden: 2304, n_head: 24, n_kv: 8, hd: 128, d_rel: 16, rel_extent: 1024, inter: 1152, n_experts: 128, top_k: 8, block_size: 6, qk_clip: 22.627416997969522, rel_clip: 8.0, eps: 1e-6, route_scale: 8.0, beta: 4.0, lb: 25.0, swa_win: 1024 }; + let vocab = 200058usize; let max_seq = 512usize; let n = 200usize; + let al = |bytes: usize| DeviceBuf::alloc(bytes).unwrap(); + let argmax = |lg: &DeviceBuf| -> i32 { + let mut lh = vec![0f32; vocab]; lg.d2h(&mut lh).unwrap(); + let mut best = 0usize; let mut bz = f32::NEG_INFINITY; + for (v, &z) in lh.iter().enumerate() { if z > bz { bz = z; best = v; } } + best as i32 + }; + let prompt = [100i32, 200, 300]; + let pl = prompt.len(); + let mut st_p: Vec> = (0..24).map(|_| None).collect(); + let mut st_s: Vec> = (0..24).map(|_| None).collect(); + let lg_p = forward_batch(&cache, &d, &prompt, vocab, max_seq, 0, 0.0, &mut st_p).unwrap(); + let mut taps0 = [al(pl * d.hidden * 4), al(pl * d.hidden * 4), al(pl * d.hidden * 4), al(pl * d.hidden * 4)]; + let _lg_s = forward_batch_taps(&cache, &d, &prompt, vocab, max_seq, 0, 0.0, &mut st_s, &mut taps0).unwrap(); + let mut dctx = DsparkContext::new(max_seq, DS_HIDDEN).unwrap(); + let pos0 = al(pl * 4); + pos0.h2d_bytes(&(0..pl as i32).flat_map(|p| p.to_le_bytes()).collect::>()).unwrap(); + dctx.commit(&dw, &taps0, &pos0, pl as i32, d.eps, 1e6).unwrap(); + dctx.len = pl; + let tok0 = argmax(&lg_p); + // plain batched greedy (B=1 per step) + let mut emit_p = vec![tok0]; let mut cur_p = pl as i32; let mut next_p = tok0; + while emit_p.len() < n { + let lg = forward_batch(&cache, &d, &[next_p], vocab, max_seq, cur_p, 0.0, &mut st_p).unwrap(); + let t = argmax(&lg); emit_p.push(t); next_p = t; cur_p += 1; + } + // speculative greedy + let mut emit_s = vec![tok0]; let mut cur_s = pl as i32; let mut next_s = tok0; + let mut rounds = 0usize; let mut offered = 0usize; let mut accepted = 0usize; + while emit_s.len() < n { + let left = n - emit_s.len(); + let nd = std::env::var("VETTA_SPEC_ND").ok().and_then(|v| v.parse::().ok()).unwrap_or(left.saturating_sub(1).min(7)); + let (em, nc, nt, done) = spec_round(&cache, &d, &dw, &mut dctx, &mut st_s, cur_s, next_s, nd, vocab, max_seq, left, |_| false).unwrap(); + offered += nd; accepted += em.len().saturating_sub(1); + emit_s.extend(em); cur_s = nc; next_s = nt; rounds += 1; + if done { break; } + } + eprintln!("spec gate: rounds={rounds} offered={offered} accepted={accepted} emit_p.len={} emit_s.len={}", emit_p.len(), emit_s.len()); + assert_eq!(emit_p.len(), emit_s.len(), "token count differs"); + for (i, (a, b)) in emit_p.iter().zip(emit_s.iter()).enumerate() { + assert_eq!(a, b, "lossless gate diverged at token {i}: plain={a} spec={b}"); + } + eprintln!("spec_lossless_gate: {} tokens EXACT match", emit_p.len()); + } + + /// Diagnostic: is the batched trunk per-token deterministic across B? + /// Feed the same 8-token continuation as one B=8 batch (taps -> per-row + /// greedy) vs 8 sequential B=1 forwards. Divergence => batch-dependent + /// numerics (the spec verify B=nd+1 would not match plain B=1 decode). + #[test] + #[cfg(feature = "hip")] + #[ignore] + fn batch_determinism_diag() { + use crate::layer::{Dims, WeightCache, forward_batch, forward_batch_taps}; + use vetta_infer_hip::DeviceBuf; + let ar = std::sync::Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap()); + let cache = WeightCache::new(ar.clone()); + let d = Dims { hidden: 2304, n_head: 24, n_kv: 8, hd: 128, d_rel: 16, rel_extent: 1024, inter: 1152, n_experts: 128, top_k: 8, block_size: 6, qk_clip: 22.627416997969522, rel_clip: 8.0, eps: 1e-6, route_scale: 8.0, beta: 4.0, lb: 25.0, swa_win: 1024 }; + let vocab = 200058usize; let max_seq = 512usize; + let al = |bytes: usize| DeviceBuf::alloc(bytes).unwrap(); + let unembed = cache.raw("model.llm.unembed.weight").unwrap(); + let prompt = [100i32, 200, 300]; + let cont = [1000i32, 2000, 3000, 4000, 5000, 6000, 7000, 8000]; + let nb = cont.len(); + let mut st_b: Vec> = (0..24).map(|_| None).collect(); + let mut st_s: Vec> = (0..24).map(|_| None).collect(); + let _ = forward_batch(&cache, &d, &prompt, vocab, max_seq, 0, 0.0, &mut st_b).unwrap(); + let _ = forward_batch(&cache, &d, &prompt, vocab, max_seq, 0, 0.0, &mut st_s).unwrap(); + // B=8 batch + let mut taps = [al(nb * d.hidden * 4), al(nb * d.hidden * 4), al(nb * d.hidden * 4), al(nb * d.hidden * 4)]; + let _ = forward_batch_taps(&cache, &d, &cont, vocab, max_seq, 3, 0.0, &mut st_b, &mut taps).unwrap(); + let tn = al(nb * d.hidden * 2); vetta_infer_hip::cast_f32_bf16(&taps[3], &tn, nb * d.hidden).unwrap(); + let lg = al(nb * vocab * 4); vetta_infer_hip::gemm_bf16(&tn, &unembed, &lg, nb as i32, vocab as i32, d.hidden as i32).unwrap(); + let mut lgh = vec![0f32; nb * vocab]; lg.d2h(&mut lgh).unwrap(); + let mut g8 = vec![0i32; nb]; + for i in 0..nb { let row = &lgh[i * vocab..(i + 1) * vocab]; let mut best = 0; let mut bz = f32::NEG_INFINITY; for (v, &z) in row.iter().enumerate() { if z > bz { bz = z; best = v as i32; } } g8[i] = best; } + // sequential B=1 + let mut g1 = vec![0i32; nb]; + for i in 0..nb { + let l = forward_batch(&cache, &d, &[cont[i]], vocab, max_seq, 3 + i as i32, 0.0, &mut st_s).unwrap(); + let mut lh = vec![0f32; vocab]; l.d2h(&mut lh).unwrap(); + let mut best = 0; let mut bz = f32::NEG_INFINITY; for (v, &z) in lh.iter().enumerate() { if z > bz { bz = z; best = v as i32; } } g1[i] = best; + } + eprintln!("batch_determinism g8={g8:?}"); + eprintln!("batch_determinism g1={g1:?}"); + assert_eq!(g8, g1, "batched trunk is NOT per-token deterministic across B"); + } + + /// Diagnostic: after a B=2 verify + rollback_spec(1), is every layer's hist + /// EXACTLY equal to plain B=1 feeding the same anchor? Isolates rollback. + #[test] + #[cfg(feature = "hip")] + #[ignore] + fn rollback_hist_diag() { + use crate::layer::{Dims, WeightCache, forward_batch, forward_batch_taps, rollback_spec, spec_begin, spec_end}; + use vetta_infer_hip::DeviceBuf; + let ar = std::sync::Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap()); + let cache = WeightCache::new(ar.clone()); + let d = Dims { hidden: 2304, n_head: 24, n_kv: 8, hd: 128, d_rel: 16, rel_extent: 1024, inter: 1152, n_experts: 128, top_k: 8, block_size: 6, qk_clip: 22.627416997969522, rel_clip: 8.0, eps: 1e-6, route_scale: 8.0, beta: 4.0, lb: 25.0, swa_win: 1024 }; + let vocab = 200058usize; let max_seq = 512usize; + let al = |bytes: usize| DeviceBuf::alloc(bytes).unwrap(); + let prompt = [100i32, 200, 300]; + let mut st_p: Vec> = (0..24).map(|_| None).collect(); + let mut st_s: Vec> = (0..24).map(|_| None).collect(); + let _ = forward_batch(&cache, &d, &prompt, vocab, max_seq, 0, 0.0, &mut st_p).unwrap(); + let _ = forward_batch(&cache, &d, &prompt, vocab, max_seq, 0, 0.0, &mut st_s).unwrap(); + // plain: feed anchor 1000 @3 + let _ = forward_batch(&cache, &d, &[1000], vocab, max_seq, 3, 0.0, &mut st_p).unwrap(); + // spec: feed [1000@3, 2000@4] B=2, rollback to 1 + let mut taps = [al(2 * d.hidden * 4), al(2 * d.hidden * 4), al(2 * d.hidden * 4), al(2 * d.hidden * 4)]; + spec_begin(2); + let _ = forward_batch_taps(&cache, &d, &[1000, 2000], vocab, max_seq, 3, 0.0, &mut st_s, &mut taps).unwrap(); + spec_end(); + rollback_spec(&d, &mut st_s, 1).unwrap(); + // compare hist + let mut mism = 0usize; + for ip in 0..24 { + let p = st_p[ip].as_ref().unwrap(); let s = st_s[ip].as_ref().unwrap(); + for pass in 0..3 { + for (hp, hs, nm) in [(&p.hist_k[pass], &s.hist_k[pass], "k"), (&p.hist_v[pass], &s.hist_v[pass], "v"), (&p.hist_a[pass], &s.hist_a[pass], "a"), (&p.hist_m[pass], &s.hist_m[pass], "m")] { + let np = hp.bytes / 4; let mut vp = vec![0f32; np]; hp.d2h(&mut vp).unwrap(); + let mut vs = vec![0f32; np]; hs.d2h(&mut vs).unwrap(); + if vp != vs { mism += 1; if mism <= 6 { let md = vp.iter().zip(vs.iter()).map(|(a, b)| (a - b).abs()).fold(0f32, f32::max); eprintln!("hist mismatch ip={ip} pass={pass} {nm} maxdiff={md:.3e}"); } } + } + } + } + eprintln!("rollback_hist_diag: {mism} hist buffers differ"); + assert_eq!(mism, 0, "rollback_spec(1) hist != plain B=1 hist"); + } + + /// Lockstep: each spec round (nd=1), feed plain the exact committed prefix + /// and compare hist. Reports the FIRST round where spec hist != plain hist. + #[test] + #[cfg(feature = "hip")] + #[ignore] + fn spec_lockstep_diag() { + use crate::layer::{Dims, WeightCache, forward_batch, forward_batch_taps}; + use vetta_infer_hip::DeviceBuf; + let ar = std::sync::Arc::new(SafetensorsArchive::open("/mnt/models/Inkling/safetensors").unwrap()); + let cache = WeightCache::new(ar.clone()); + let dw = DsparkWeights::load(&SafetensorsArchive::open_file("/mnt/models/Inkling/safetensors/mtp.safetensors").unwrap()).unwrap(); + let d = Dims { hidden: 2304, n_head: 24, n_kv: 8, hd: 128, d_rel: 16, rel_extent: 1024, inter: 1152, n_experts: 128, top_k: 8, block_size: 6, qk_clip: 22.627416997969522, rel_clip: 8.0, eps: 1e-6, route_scale: 8.0, beta: 4.0, lb: 25.0, swa_win: 1024 }; + let vocab = 200058usize; let max_seq = 512usize; + let al = |bytes: usize| DeviceBuf::alloc(bytes).unwrap(); + let argmax = |lg: &DeviceBuf| -> i32 { let mut lh = vec![0f32; vocab]; lg.d2h(&mut lh).unwrap(); let mut best = 0; let mut bz = f32::NEG_INFINITY; for (v, &z) in lh.iter().enumerate() { if z > bz { bz = z; best = v as i32; } } best }; + let prompt = [100i32, 200, 300]; let pl = prompt.len(); + let mut st_p: Vec> = (0..24).map(|_| None).collect(); + let mut st_s: Vec> = (0..24).map(|_| None).collect(); + let lg_p = forward_batch(&cache, &d, &prompt, vocab, max_seq, 0, 0.0, &mut st_p).unwrap(); + let mut taps0 = [al(pl * d.hidden * 4), al(pl * d.hidden * 4), al(pl * d.hidden * 4), al(pl * d.hidden * 4)]; + let _ = forward_batch_taps(&cache, &d, &prompt, vocab, max_seq, 0, 0.0, &mut st_s, &mut taps0).unwrap(); + let mut dctx = DsparkContext::new(max_seq, DS_HIDDEN).unwrap(); + let pos0 = al(pl * 4); pos0.h2d_bytes(&(0..pl as i32).flat_map(|p| p.to_le_bytes()).collect::>()).unwrap(); + dctx.commit(&dw, &taps0, &pos0, pl as i32, d.eps, 1e6).unwrap(); dctx.len = pl; + let tok0 = argmax(&lg_p); + let mut cur = pl as i32; let mut next = tok0; + for round in 0..200 { + let (em, nc, nt, _done) = spec_round(&cache, &d, &dw, &mut dctx, &mut st_s, cur, next, 1, vocab, max_seq, 1000, |_| false).unwrap(); + let accepted = em.len(); + // plain feeds committed prefix: [next] + em[0..accepted-1] + let mut fed = vec![next]; fed.extend_from_slice(&em[..accepted - 1]); + for (j, t) in fed.iter().enumerate() { + let _ = forward_batch(&cache, &d, &[*t], vocab, max_seq, cur + j as i32, 0.0, &mut st_p).unwrap(); + } + // compare hist + let mut mism = 0usize; let mut first = String::new(); + for ip in 0..24 { let p = st_p[ip].as_ref().unwrap(); let s = st_s[ip].as_ref().unwrap(); + for pass in 0..3 { for (hp, hs, nm) in [(&p.hist_k[pass], &s.hist_k[pass], "k"), (&p.hist_v[pass], &s.hist_v[pass], "v"), (&p.hist_a[pass], &s.hist_a[pass], "a"), (&p.hist_m[pass], &s.hist_m[pass], "m")] { + let np = hp.bytes / 4; let mut vp = vec![0f32; np]; hp.d2h(&mut vp).unwrap(); let mut vs = vec![0f32; np]; hs.d2h(&mut vs).unwrap(); + if vp != vs { mism += 1; if first.is_empty() { let md = vp.iter().zip(vs.iter()).map(|(a, b)| (a - b).abs()).fold(0f32, f32::max); first = format!("ip={ip} pass={pass} {nm} maxdiff={md:.3e}"); } } + } } + } + if mism > 0 { eprintln!("LOCKSTEP DIVERGE round={round} accepted={accepted} cur={cur} mism={mism} first[{first}]"); panic!("hist diverged at round {round}"); } + // compare KV committed region: layout [n_kv, seq, hd], pos 0 { eprintln!("LOCKSTEP KV DIVERGE round={round} accepted={accepted} keep={keep} kvm={kvm} first[{kvfirst}]"); panic!("KV diverged at round {round}"); } + cur = nc; next = nt; + } + eprintln!("spec_lockstep_diag: 200 rounds hist EXACT"); + } } \ No newline at end of file diff --git a/crates/vetta-infer-ld/src/layer.rs b/crates/vetta-infer-ld/src/layer.rs index 6176588..ab88c58 100644 --- a/crates/vetta-infer-ld/src/layer.rs +++ b/crates/vetta-infer-ld/src/layer.rs @@ -48,6 +48,13 @@ pub struct LayerState { pub hist_k: [DeviceBuf; 3], pub hist_v: [DeviceBuf; 3], // [3, n_kv*hd] each pub hist_a: [DeviceBuf; 3], pub hist_m: [DeviceBuf; 3], // [3, hidden] each pub max_seq: usize, + // DSpark speculative rollback: per-prefix ShortConv history snapshots + // [(B+1)*3*C] captured during a spec verify batch (spec_recording). On + // partial accept, hist <- snap[accepted]; the KV ring truncates with no + // restore (proofs/speculative_draft.lean kept_rejected_disjoint). + pub spec_b: usize, + pub snap_k: [Option; 3], pub snap_v: [Option; 3], + pub snap_a: [Option; 3], pub snap_m: [Option; 3], } /// Forward-pass dimensions (subset of TextConfig needed by a layer). @@ -268,9 +275,49 @@ pub fn new_state(d: &Dims, max_seq: usize, n_passes: usize) -> Result = const { std::cell::Cell::new((false, 0)) }; +} +/// Enable DSpark spec capture for a verify batch of `b` tokens (thread-local). +pub fn spec_begin(b: usize) { SPEC_REC.with(|c| c.set((true, b))); } +/// Disable spec capture (snapshots stay allocated for reuse across rounds). +pub fn spec_end() { SPEC_REC.with(|c| c.set((false, c.get().1))); } +fn spec_recording() -> bool { SPEC_REC.with(|c| c.get().0) } + +/// update_hist + (when spec-recording) per-prefix history snapshots. The snaps +/// kernel reads hist BEFORE update_hist rolls it, so snaps[0]=hist0. +fn spec_update_hist(in_x: &DeviceBuf, hist: &DeviceBuf, snap: &mut Option, b: i32, c: i32) -> Result<(), String> { + if spec_recording() { + let n = (b as usize + 1) * 3 * c as usize; + if snap.as_ref().map_or(true, |s| s.bytes != n * 4) { + *snap = Some(DeviceBuf::alloc(n * 4)?); + } + vetta_infer_hip::shortconv4_hist_snaps(in_x, hist, snap.as_ref().unwrap(), b, c)?; + } + vetta_infer_hip::shortconv4_update_hist(in_x, hist, b, c) +} + +/// Roll back every layer's ShortConv history to the state after `accepted` tokens +/// of the spec verify batch (hist <- snap[accepted]). KV needs no restore. +pub fn rollback_spec(d: &Dims, states: &mut [Option], accepted: usize) -> Result<(), String> { + let kv = 3 * d.kv_dim(); let hh = 3 * d.hidden; + for st in states.iter_mut().flatten() { + for p in 0..3 { + if let Some(s) = st.snap_k[p].as_ref() { vetta_infer_hip::copy_f32_sub(s, accepted * kv, &st.hist_k[p], kv)?; } + if let Some(s) = st.snap_v[p].as_ref() { vetta_infer_hip::copy_f32_sub(s, accepted * kv, &st.hist_v[p], kv)?; } + if let Some(s) = st.snap_a[p].as_ref() { vetta_infer_hip::copy_f32_sub(s, accepted * hh, &st.hist_a[p], hh)?; } + if let Some(s) = st.snap_m[p].as_ref() { vetta_infer_hip::copy_f32_sub(s, accepted * hh, &st.hist_m[p], hh)?; } + } + } + Ok(()) +} + /// A checkpoint of one layer's decode state at a prefix boundary `seq_len`: the /// KV prefix `[n_kv, seq_len, hd]` per pass + the ShortConv history rings. Sized /// to seq_len (KV unpooled), held in the prefix cache across requests. Restoring @@ -611,9 +658,9 @@ fn layer_forward_swa_batched( } // k2: ShortConv prefill (parallel causal) + history roll, then clip/relpos/KV. vetta_infer_hip::shortconv4_prefill_par(&k_raw, &w.k_sconv, None, &st.hist_k[pass], &k_cv, b, kv_dim as i32, 0)?; - vetta_infer_hip::shortconv4_update_hist(&k_raw, &st.hist_k[pass], b, kv_dim as i32)?; + spec_update_hist(&k_raw, &st.hist_k[pass], &mut st.snap_k[pass], b, kv_dim as i32)?; vetta_infer_hip::shortconv4_prefill_par(&v_raw, &w.v_sconv, None, &st.hist_v[pass], &v_cv, b, kv_dim as i32, 0)?; - vetta_infer_hip::shortconv4_update_hist(&v_raw, &st.hist_v[pass], b, kv_dim as i32)?; + spec_update_hist(&v_raw, &st.hist_v[pass], &mut st.snap_v[pass], b, kv_dim as i32)?; vetta_infer_hip::l2_clip_batched(&q, Some(&w.q_sc), (b as usize * d.n_head) as i32, d.hd as i32, d.qk_clip, false, 0, d.n_head as i32, None)?; vetta_infer_hip::l2_clip_batched(&r_raw, Some(&w.r_sc), (b as usize * d.n_head) as i32, d.d_rel as i32, d.rel_clip, false, 0, d.n_head as i32, None)?; vetta_infer_hip::l2_clip_batched(&k_cv, None, (b as usize * d.n_kv) as i32, d.hd as i32, d.qk_clip, false, 0, d.n_kv as i32, None)?; @@ -625,7 +672,7 @@ fn layer_forward_swa_batched( vetta_infer_hip::cast_f32_bf16(&aout, &aout_bf, bu * q_dim)?; vetta_infer_hip::gemm_bf16(&aout_bf, &w.wo, &oproj, b, h as i32, q_dim as i32)?; vetta_infer_hip::shortconv4_prefill_par(&oproj, &w.a_sconv, None, &st.hist_a[pass], &asc, b, h as i32, 0)?; - vetta_infer_hip::shortconv4_update_hist(&oproj, &st.hist_a[pass], b, h as i32)?; + spec_update_hist(&oproj, &st.hist_a[pass], &mut st.snap_a[pass], b, h as i32)?; if w.ip % d.block_size == 0 { blocks.snapshot(cur)?; vetta_infer_hip::copy_f32(&asc, cur, bu * h)?; @@ -651,7 +698,7 @@ fn layer_forward_swa_batched( // k7: mlp shortconv + plain residual add. let msc = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::shortconv4_prefill_par(&moeout, &w.m_sconv, None, &st.hist_m[pass], &msc, b, h as i32, 0)?; - vetta_infer_hip::shortconv4_update_hist(&moeout, &st.hist_m[pass], b, h as i32)?; + spec_update_hist(&moeout, &st.hist_m[pass], &mut st.snap_m[pass], b, h as i32)?; vetta_infer_hip::vec_add(cur, &msc, cur, bu * h)?; Ok(()) } @@ -1374,9 +1421,9 @@ fn layer_forward_full_batched( let k_cv = DeviceBuf::alloc(bu * kv_dim * 4)?; let v_cv = DeviceBuf::alloc(bu * kv_dim * 4)?; vetta_infer_hip::shortconv4_prefill_par(&k_raw, &w.k_static, Some(&k_dyn), &st.hist_k[pass], &k_cv, b, kv_dim as i32, d.n_kv as i32)?; - vetta_infer_hip::shortconv4_update_hist(&k_raw, &st.hist_k[pass], b, kv_dim as i32)?; + spec_update_hist(&k_raw, &st.hist_k[pass], &mut st.snap_k[pass], b, kv_dim as i32)?; vetta_infer_hip::shortconv4_prefill_par(&v_raw, &w.v_static, Some(&v_dyn), &st.hist_v[pass], &v_cv, b, kv_dim as i32, d.n_kv as i32)?; - vetta_infer_hip::shortconv4_update_hist(&v_raw, &st.hist_v[pass], b, kv_dim as i32)?; + spec_update_hist(&v_raw, &st.hist_v[pass], &mut st.snap_v[pass], b, kv_dim as i32)?; // tau on Q/R (per-token pos), K clip without tau. vetta_infer_hip::l2_clip_batched(&q, Some(&w.q_sc), (b as usize * d.n_head) as i32, d.hd as i32, d.qk_clip, true, 0, d.n_head as i32, Some(pos))?; vetta_infer_hip::l2_clip_batched(&r_raw, Some(&w.r_sc), (b as usize * d.n_head) as i32, d.d_rel as i32, d.rel_clip, true, 0, d.n_head as i32, Some(pos))?; @@ -1392,7 +1439,7 @@ fn layer_forward_full_batched( vetta_infer_hip::gemm_bf16(&aout_bf, &w.wo, &oproj, b, h as i32, q_dim as i32)?; let asc = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::shortconv4_prefill_par(&oproj, &w.a_sconv, None, &st.hist_a[pass], &asc, b, h as i32, 0)?; - vetta_infer_hip::shortconv4_update_hist(&oproj, &st.hist_a[pass], b, h as i32)?; + spec_update_hist(&oproj, &st.hist_a[pass], &mut st.snap_a[pass], b, h as i32)?; if w.ip % d.block_size == 0 { blocks.snapshot(cur)?; vetta_infer_hip::copy_f32(&asc, cur, bu * h)?; @@ -1416,7 +1463,7 @@ fn layer_forward_full_batched( let moeout = moe_batched(cache, w.ip, &mlpin, &ids, &weights, d, h, b)?; let msc = DeviceBuf::alloc(bu * h * 4)?; vetta_infer_hip::shortconv4_prefill_par(&moeout, &w.m_sconv, None, &st.hist_m[pass], &msc, b, h as i32, 0)?; - vetta_infer_hip::shortconv4_update_hist(&moeout, &st.hist_m[pass], b, h as i32)?; + spec_update_hist(&moeout, &st.hist_m[pass], &mut st.snap_m[pass], b, h as i32)?; vetta_infer_hip::vec_add(cur, &msc, cur, bu * h)?; Ok(()) }