From df537bf84fbb105413c8361e825e0a41114a4c74 Mon Sep 17 00:00:00 2001 From: iz0eyj Date: Wed, 2 Dec 2026 21:58:31 +0100 Subject: [PATCH] [Proto] DSpark brick 5b-4: opt-in speculative serve decode + EMA (measured) VETTA_SPEC=1 loads resident drafter weights (iff mtp.safetensors passes layout_check) and enables a greedy speculative decode path: prefill captures trunk taps (forward_batch_taps) and commits the DSpark context rings per chunk; decode runs spec_round (batched verify + rollback) with EMA-adaptive n_draft (7->4->2 as acceptance drops). Pure greedy + no penalties only; EOS/stop/length handled per emitted token; prefix save unchanged. Default M=1 decode untouched. MEASURED (real capital prompt, GEN 96, gfx1150): spec OFF 3.97 tok/s total vs ON decode 5.71 tok/s, acceptance 31.4% (49/156), EMA n_draft 7->4, 46 rounds (~2.09 tok/round), ~1.11x overall request. Modest but real, no overclaim. serve_gen_spec_multi_token_parity: spec path emits the EXACT 16 reference tokens (batched decode == M=1 == reference). CPU -D warnings clean, Lean 0 sorryAx, gw GPU 22/22, hip 45/45, ld GPU 65/65. --- crates/vetta-infer-gw/src/serve.rs | 209 ++++++++++++++++++++++++++++- 1 file changed, 208 insertions(+), 1 deletion(-) diff --git a/crates/vetta-infer-gw/src/serve.rs b/crates/vetta-infer-gw/src/serve.rs index 575a163..9e0d867 100644 --- a/crates/vetta-infer-gw/src/serve.rs +++ b/crates/vetta-infer-gw/src/serve.rs @@ -29,6 +29,10 @@ use vetta_infer_hip::DeviceBuf; use vetta_infer_ld::inkling::parse_config; use vetta_infer_ld::layer::{forward_batch, forward_inkling_with_state, is_swa, new_state, Dims, LayerSnapshot, LayerState, WeightCache}; use vetta_infer_ld::SafetensorsArchive; +#[cfg(feature = "hip")] +use vetta_infer_ld::layer::forward_batch_taps; +#[cfg(feature = "hip")] +use vetta_infer_ld::dspark::{layout_check, spec_round, DsparkContext, DsparkWeights, DS_HIDDEN}; use crate::session::ServeSession; use crate::{err_line, ready_line}; @@ -182,6 +186,10 @@ pub struct InklingEngine { /// Resident context window (advertised in READY). Defaults to MAX_CONTEXT; /// VETTA_MAX_CONTEXT / `--max-context` raise it (like strata) for longer agents. max_context: usize, + /// DSpark drafter weights (resident), loaded only when VETTA_SPEC=1 and + /// mtp.safetensors passes layout_check. Enables opt-in greedy speculation. + #[cfg(feature = "hip")] + spec_dw: Option, } impl InklingEngine { @@ -224,6 +232,16 @@ impl InklingEngine { .and_then(|s| s.parse::().ok()) .filter(|&v| v >= 4096) .unwrap_or(MAX_CONTEXT); + // Opt-in DSpark drafter: load resident weights iff VETTA_SPEC=1 and the + // mtp shard passes the strict layout check (else disable, never guess). + #[cfg(feature = "hip")] + let spec_dw = if std::env::var("VETTA_SPEC").is_ok() { + let mtp = ar.dir.join("mtp.safetensors"); + match SafetensorsArchive::open_file(mtp.to_str().unwrap_or_default()) { + Ok(mar) if layout_check(&mar).is_ok() => DsparkWeights::load(&mar).ok(), + _ => None, + } + } else { None }; Ok(Self { cache: WeightCache::new(ar), d, @@ -238,6 +256,8 @@ impl InklingEngine { prefix: RefCell::new(PrefixCache::new()), states: RefCell::new(Vec::new()), max_context, + #[cfg(feature = "hip")] + spec_dw, }) } @@ -369,6 +389,27 @@ pub fn serve_gen( // Weights are resident in eng.cache (loaded once at boot, reused across all // requests): no per-request NVMe re-read or re-upload. + // Opt-in DSpark speculation (pure greedy, no penalties): capture trunk taps + // during prefill to build the drafter context rings, then run a batched + // speculative decode (lossless vs forward_batch B=1, proofs/speculative_draft). + #[cfg(feature = "hip")] + let spec_enabled = eng.spec_dw.is_some() && g.sampling.is_greedy() && !g.sampling.has_penalties(); + #[cfg(not(feature = "hip"))] + let spec_enabled = false; + #[cfg(feature = "hip")] + let mut dctx: Option = None; + #[cfg(feature = "hip")] + if spec_enabled { + match DsparkContext::new(cap, DS_HIDDEN) { + Ok(c) => dctx = Some(c), + Err(e) => { + emit_all(emit, sess.on_error(&e)); + stop.store(false, Ordering::Relaxed); + return; + } + } + } + // --- Prefill: chunked batched (M=B) forward over the NEW prompt tokens. --- // Each chunk runs ONE forward_batch over B tokens (weight streaming + kernel // launches amortized across B), growing KV/history; logits come from the last @@ -399,7 +440,25 @@ pub fn serve_gen( take = next_grid - pos_now; } let toks = &suffix[done..done + take]; - let lg = if take == 1 { + let lg = if spec_enabled { + #[cfg(feature = "hip")] + { + (|| -> Result { + let h = eng.d.hidden; + let mut taps = [DeviceBuf::alloc(take * h * 4)?, DeviceBuf::alloc(take * h * 4)?, DeviceBuf::alloc(take * h * 4)?, DeviceBuf::alloc(take * h * 4)?]; + let l = forward_batch_taps(&eng.cache, &eng.d, toks, eng.vocab, cap, pos, eng.cap, &mut states[..], &mut taps)?; + let pb = DeviceBuf::alloc(take * 4)?; + pb.h2d_bytes(&(pos..pos + take as i32).flat_map(|p| p.to_le_bytes()).collect::>())?; + let dw = eng.spec_dw.as_ref().unwrap(); + let dc = dctx.as_mut().unwrap(); + dc.commit(dw, &taps, &pb, take as i32, eng.d.eps, 1e6)?; + dc.len = (pos + take as i32) as usize; + Ok(l) + })() + } + #[cfg(not(feature = "hip"))] + { Err("spec requires hip".into()) } + } else if take == 1 { eng.forward(toks[0], pos, cap, &mut states[..]) } else { eng.forward_batched(toks, pos, cap, &mut states[..]) @@ -476,6 +535,94 @@ pub fn serve_gen( return; } }; + // --- Opt-in DSpark speculative decode (greedy, lossless vs batched B=1). --- + #[cfg(feature = "hip")] + if spec_enabled { + let dw = eng.spec_dw.as_ref().unwrap(); + let mut dc = dctx.take().unwrap(); + let t1 = Instant::now(); + let mut lg = vec![0f32; eng.vocab]; + if let Err(e) = logits.d2h(&mut lg) { + emit_all(emit, sess.on_error(&e)); + stop.store(false, Ordering::Relaxed); + return; + } + let argmax = |v: &[f32]| -> i32 { + let mut best = 0usize; let mut bz = f32::NEG_INFINITY; + for (i, &z) in v.iter().enumerate() { if z > bz { bz = z; best = i; } } + best as i32 + }; + let tok0 = argmax(&lg); + let mut finish = "length"; + let mut generated = 0usize; + let emit_tok = |t: i32, emit: &mut dyn FnMut(String), sess: &mut ServeSession, history: &mut Vec, generated: &mut usize| -> bool { + match sess.on_token(t as u32) { + Ok(lines) => emit_all(emit, lines), + Err(e) => { emit_all(emit, sess.on_error(&e)); return false; } + } + history.push(t); *generated += 1; + true + }; + if !emit_tok(tok0, emit, &mut sess, &mut history, &mut generated) { + stop.store(false, Ordering::Relaxed); + return; + } + let mut cur_pos = pos; let mut next_tok = tok0; + let mut ema = 0.5f32; let mut n_draft = 7usize; + let mut offered = 0usize; let mut accepted = 0usize; let mut rounds = 0usize; + if tok0 == eng.eos { + finish = "stop"; + } else { + while generated < effective_max_new { + if stop.load(Ordering::Relaxed) { + sess.on_stop(); + let ms = t1.elapsed().as_secs_f64() * 1000.0; + emit_all(emit, sess.on_drain_complete(ms).unwrap_or_default()); + stop.store(false, Ordering::Relaxed); + return; + } + let left = effective_max_new - generated; + let nd = n_draft.min(left.saturating_sub(1)); + let (em, nc, nt, done) = match spec_round(&eng.cache, &eng.d, dw, &mut dc, &mut states[..], cur_pos, next_tok, nd, eng.vocab, cap, left, |t| t == eng.eos) { + Ok(v) => v, + Err(e) => { + emit_all(emit, sess.on_error(&e)); + stop.store(false, Ordering::Relaxed); + return; + } + }; + let mut hit_eos = false; + for &t in &em { + if !emit_tok(t, emit, &mut sess, &mut history, &mut generated) { + stop.store(false, Ordering::Relaxed); + return; + } + if t == eng.eos { hit_eos = true; break; } + if generated >= effective_max_new { break; } + } + if nd > 0 { + let acc = (em.len().saturating_sub(1)) as f32 / nd as f32; + ema = 0.9 * ema + 0.1 * acc; + n_draft = if ema >= 0.5 { 7 } else if ema >= 0.3 { 4 } else { 2 }; + offered += nd; accepted += em.len().saturating_sub(1); + } + rounds += 1; + cur_pos = nc; next_tok = nt; pos = nc; + if hit_eos { finish = "stop"; break; } + if done || generated >= effective_max_new { finish = "length"; break; } + } + } + let decode_ms = t1.elapsed().as_secs_f64() * 1000.0; + if std::env::var("VETTA_DBG_SPEC").is_ok() { + eprintln!("[spec] rounds={rounds} offered={offered} accepted={accepted} ema={ema:.3} n_draft={n_draft} generated={generated} decode_ms={decode_ms:.1} tok_s={:.2}", generated as f64 / (decode_ms / 1000.0)); + } + if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos > 0 { + let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d); + } + emit_all(emit, sess.on_finish(finish, decode_ms).unwrap_or_default()); + stop.store(false, Ordering::Relaxed); + return; + } let mut finish = "length"; for step in 0..effective_max_new { if stop.load(Ordering::Relaxed) { @@ -757,4 +904,64 @@ mod tests { assert!(done.ends_with(" stop"), "finish must be stop, got {done}"); }); } + + /// GPU: the opt-in DSpark speculative serve path (VETTA_SPEC=1, batched + /// verify + rollback + EMA) must emit EXACTLY the same reference tokens as + /// the default M=1 decode for the canonical capital prompt. Verifies the + /// serve orchestration (pos/history/EOS/length) AND that the batched decode + /// path is greedy-vs-reference exact. + #[test] + #[ignore] + fn serve_gen_spec_multi_token_parity() { + crate::gpu_isolated(|| { + unsafe { std::env::set_var("VETTA_SPEC", "1"); } + let eng = InklingEngine::new("/mnt/models/Inkling/safetensors").unwrap(); + assert!(eng.spec_dw.is_some(), "drafter weights must load with VETTA_SPEC=1"); + let g = match parse_serve_line("GEN 16 temperature=0 371,151451,149879,151194,149884", eng.vocab()).unwrap() { + ServeCommand::Gen(g) => g, + _ => panic!("expected Gen"), + }; + let stop = AtomicBool::new(false); + let mut lines: Vec = Vec::new(); + serve_gen(&eng, &g, &stop, &mut |l| lines.push(l)); + let tokens: Vec = lines.iter() + .filter(|l| l.starts_with("T ")) + .map(|l| l[2..].trim().parse().unwrap()) + .collect(); + let want = [152717, 13, 68014, 32, 13, 220, 44781, 164452, 68014, 33, 13, 220, 57345, 745, 164452, 68014]; + unsafe { std::env::remove_var("VETTA_SPEC"); } + assert_eq!(tokens, want, "speculative serve path must match reference exactly"); + }); + } + + /// GPU perf probe: spec-on vs spec-off decode tok/s + acceptance on a real + /// prompt (GEN 96). Prints measured numbers; no speedup claim without them. + #[test] + #[ignore] + fn serve_gen_spec_perf() { + crate::gpu_isolated(|| { + let ids = "371,151451,149879,151194,149884"; + let run = |spec: bool| -> (f64, usize) { + if spec { unsafe { std::env::set_var("VETTA_SPEC", "1"); } } else { unsafe { std::env::remove_var("VETTA_SPEC"); } } + unsafe { std::env::set_var("VETTA_DBG_SPEC", "1"); } + let eng = InklingEngine::new("/mnt/models/Inkling/safetensors").unwrap(); + let g = match parse_serve_line(&format!("GEN 96 temperature=0 {ids}"), eng.vocab()).unwrap() { + ServeCommand::Gen(g) => g, + _ => panic!("expected Gen"), + }; + let stop = AtomicBool::new(false); + let mut lines: Vec = Vec::new(); + let t = Instant::now(); + serve_gen(&eng, &g, &stop, &mut |l| lines.push(l)); + let ms = t.elapsed().as_secs_f64() * 1000.0; + let n = lines.iter().filter(|l| l.starts_with("T ")).count(); + unsafe { std::env::remove_var("VETTA_SPEC"); std::env::remove_var("VETTA_DBG_SPEC"); } + (ms, n) + }; + let (off_ms, off_n) = run(false); + let (on_ms, on_n) = run(true); + eprintln!("spec_perf: OFF {off_n} tok {off_ms:.1}ms {:.2} tok/s | ON {on_n} tok {on_ms:.1}ms {:.2} tok/s", off_n as f64 / (off_ms / 1000.0), on_n as f64 / (on_ms / 1000.0)); + assert_eq!(off_n, on_n, "spec must emit the same token count"); + }); + } } \ No newline at end of file