[HIP][Core] DSpark GPU drafter + verify perf & correctness fixes (13.93 tok/s, strata parity)

Fix all DSpark speculative bottlenecks and long-context/multi-turn bugs:
- Single-pass base-unembed Top-512 screen + on-GPU Markov loop & argmax (reads 922 MB unembed once per round, <=32 B D2H).
- On-GPU batched verify argmax + forward_batch_taps_no_logits (eliminates double unembed and 4.8 MB D2H per round).
- Wave32 online-softmax dspark_block_attn (0 bytes LDS, fixes >16.2k token crash on Global layer 1; regression-tested at c_len=17000).
- Vectorized M-tiled Wave32 router_gemv_batched, zero-scratch small-M SWA GQA, WMMA gemm_bf16 for m>=1, fdot2 MoE for b<=12.
- Persistent DsparkContext + PrefixCache DsparkSnapshot save/restore (multi-turn RESUME parity tested).
- Accepted-count EMA governor starting at n_draft=5 (adapts 2..7).
- Docs (README.md, docs/ORIENTATION.md) + changelog in review/2026-12-02-fix-drafter-e-ottimizzazioni.md.

Measured on gfx1150 (Inkling-2-Mini, temperature=0, 100% greedy EXACT):
- Rust coding (RingBuffer<T>, 128 tok): OFF 6.83 -> VETTA_SPEC=1 13.93 tok/s (2.04x, n_draft=5; strata-inkling 13.66 tok/s).
- Short prose (capital, 96 tok): nd=5 4.58 -> 9.09 tok/s (+98.5%); adaptive EMA 8.93 tok/s decode.
Validated: cargo test --workspace (-D warnings), all 7 Lean 4 proofs (0 sorryAx), HIP/LD/GW GPU parity gates.
This commit is contained in:
adm committed 2026-12-02 23:13:43 +01:00
1 parent 91c1baaf27
commit c1c5221642
9 files changed
+1433 -186

No files matched your search

+173 -45
View File
@@ -32,7 +32,7 @@ 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 vetta_infer_ld::dspark::{layout_check, spec_round, DsparkContext, DsparkSnapshot, DsparkWeights, DS_HIDDEN};
use crate::session::ServeSession;
use crate::{err_line, ready_line};
@@ -80,6 +80,8 @@ fn is_grid(seq: usize) -> bool { seq % 512 == 0 }
struct Checkpoint {
tokens: Vec<i32>,
layers: Vec<Option<LayerSnapshot>>,
#[cfg(feature = "hip")]
dspark: Option<DsparkSnapshot>,
lru: u64,
}
@@ -113,7 +115,12 @@ impl PrefixCache {
/// Takes `&mut self` to refresh the hit checkpoint's LRU tick: without this a
/// just-restored grid checkpoint keeps its old tick and gets evicted by the
/// next turn's boundary/full saves, regressing turn 3+ to the pinned anchor.
fn restore(&mut self, idx: usize, states: &mut [Option<LayerState>], d: &Dims, max_seq: usize) -> Result<usize, String> {
/// Returns `(restored_len, dspark_restored)`.
fn restore(
&mut self, idx: usize, states: &mut [Option<LayerState>], d: &Dims, max_seq: usize,
#[cfg(feature = "hip")] dctx: Option<&mut DsparkContext>,
) -> Result<(usize, bool), String> {
let mut dspark_ok = false;
{
let ck = &self.pool[idx];
// A usable checkpoint must cover EVERY layer: a partially-restored state
@@ -136,35 +143,58 @@ impl PrefixCache {
states[ip].as_mut().unwrap().restore(d, s)?;
}
}
#[cfg(feature = "hip")]
if let (Some(dc), Some(ds)) = (dctx, ck.dspark.as_ref()) {
dc.restore(ds)?;
dspark_ok = true;
}
}
self.tick += 1;
self.pool[idx].lru = self.tick;
Ok(self.pool[idx].tokens.len())
Ok((self.pool[idx].tokens.len(), dspark_ok))
}
/// Snapshot all layer states at `tokens.len()` and insert (update / grow /
/// evict oldest unpinned). Mirrors poolInsert in proofs/prefix_cache.lean.
fn save(&mut self, tokens: &[i32], states: &[Option<LayerState>], d: &Dims) -> Result<(), String> {
/// Snapshot all layer states (and optional DSpark context) at `tokens.len()`
/// and insert (update / grow / evict oldest unpinned). Mirrors poolInsert in
/// proofs/prefix_cache.lean.
fn save(
&mut self, tokens: &[i32], states: &[Option<LayerState>], d: &Dims,
#[cfg(feature = "hip")] dctx: Option<&DsparkContext>,
) -> Result<(), String> {
let seq = tokens.len();
if seq == 0 { return Ok(()); }
let layers: Vec<Option<LayerSnapshot>> = states.iter().enumerate()
.map(|(ip, st)| st.as_ref().map(|s| s.snapshot(d, seq, is_swa(ip))).transpose())
.collect::<Result<_, _>>()?;
#[cfg(feature = "hip")]
let dspark = match dctx {
Some(dc) if dc.len >= seq => Some(dc.snapshot(seq, d.swa_win as usize)?),
_ => None,
};
self.tick += 1;
let lru = self.tick;
if let Some(ck) = self.pool.iter_mut().find(|c| c.tokens.len() == seq) {
ck.tokens = tokens.to_vec(); ck.layers = layers; ck.lru = lru;
#[cfg(feature = "hip")] { ck.dspark = dspark; }
return Ok(());
}
if self.pool.len() < PREFIX_CACHE_CAP {
self.pool.push(Checkpoint { tokens: tokens.to_vec(), layers, lru });
self.pool.push(Checkpoint {
tokens: tokens.to_vec(), layers,
#[cfg(feature = "hip")] dspark,
lru,
});
return Ok(());
}
let victim = self.pool.iter().enumerate()
.filter(|(_, c)| !pinned_anchor(c.tokens.len()))
.min_by_key(|(_, c)| (is_grid(c.tokens.len()) as u8, c.lru)).map(|(i, _)| i);
if let Some(i) = victim {
self.pool[i] = Checkpoint { tokens: tokens.to_vec(), layers, lru };
self.pool[i] = Checkpoint {
tokens: tokens.to_vec(), layers,
#[cfg(feature = "hip")] dspark,
lru,
};
}
Ok(())
}
@@ -190,6 +220,9 @@ pub struct InklingEngine {
/// mtp.safetensors passes layout_check. Enables opt-in greedy speculation.
#[cfg(feature = "hip")]
spec_dw: Option<DsparkWeights>,
/// Persistent DSpark context rings reused across requests (mirrors `states`).
#[cfg(feature = "hip")]
dctx: RefCell<Option<DsparkContext>>,
}
impl InklingEngine {
@@ -258,6 +291,8 @@ impl InklingEngine {
max_context,
#[cfg(feature = "hip")]
spec_dw,
#[cfg(feature = "hip")]
dctx: RefCell::new(None),
})
}
@@ -343,6 +378,30 @@ pub fn serve_gen(
let cap = max_context;
let mut states = eng.states.borrow_mut();
// 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 mut 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_guard = eng.dctx.borrow_mut();
#[cfg(feature = "hip")]
if spec_enabled {
let need_new = dctx_guard.as_ref().map_or(true, |c| c.cap < cap);
if need_new {
match DsparkContext::new(cap, DS_HIDDEN) {
Ok(c) => *dctx_guard = Some(c),
Err(e) => {
emit_all(emit, sess.on_error(&e));
stop.store(false, Ordering::Relaxed);
return;
}
}
}
}
// Prefix checkpoint reuse (proofs/prefix_cache.lean restore_equiv): restore
// the longest cached strict prefix of this prompt and prefill only the NEW
// suffix tokens. VETTA_NO_PREFIX_CACHE forces cold prefill (A/B measurement).
@@ -350,8 +409,25 @@ pub fn serve_gen(
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() {
let matched = eng.prefix.borrow().best_match(&g.ids);
if let Some((idx, _l)) = matched {
match eng.prefix.borrow_mut().restore(idx, &mut states[..], &eng.d, cap) {
Ok(n) => start = n,
#[cfg(feature = "hip")]
let res = eng.prefix.borrow_mut().restore(
idx, &mut states[..], &eng.d, cap,
if spec_enabled { dctx_guard.as_mut() } else { None },
);
#[cfg(not(feature = "hip"))]
let res = eng.prefix.borrow_mut().restore(idx, &mut states[..], &eng.d, cap);
match res {
Ok((n, dspark_ok)) => {
start = n;
#[cfg(feature = "hip")]
if spec_enabled && !dspark_ok {
// Checkpoint lacked DSpark state (e.g. saved while spec was off):
// never run the drafter over zeroed prefix rings.
spec_enabled = false;
}
#[cfg(not(feature = "hip"))]
let _ = dspark_ok;
}
Err(_) => {
// Incomplete/failed restore: fall back to a clean cold prefill.
*states = (0..eng.n_layers).map(|_| None).collect();
@@ -371,6 +447,10 @@ pub fn serve_gen(
return;
}
}
#[cfg(feature = "hip")]
if let Some(dc) = dctx_guard.as_mut() {
dc.len = 0;
}
}
if std::env::var("VETTA_DBG_PREFIX").is_ok() {
eprintln!("[prefix] prompt_len={n_prompt} restored={start}");
@@ -389,27 +469,6 @@ 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<DsparkContext> = 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
@@ -450,7 +509,7 @@ pub fn serve_gen(
let pb = DeviceBuf::alloc(take * 4)?;
pb.h2d_bytes(&(pos..pos + take as i32).flat_map(|p| p.to_le_bytes()).collect::<Vec<u8>>())?;
let dw = eng.spec_dw.as_ref().unwrap();
let dc = dctx.as_mut().unwrap();
let dc = dctx_guard.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)
@@ -481,6 +540,9 @@ pub fn serve_gen(
// prefix; grid entries are protected from eviction (is_grid) and refreshed
// on restore (lru), so turn 3+ keeps advancing instead of falling to 1024.
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos as usize == next_grid {
#[cfg(feature = "hip")]
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d, if spec_enabled { dctx_guard.as_ref() } else { None });
#[cfg(not(feature = "hip"))]
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d);
if std::env::var("VETTA_DBG_PREFIX").is_ok() {
eprintln!("[prefix] grid save seq={pos}");
@@ -512,6 +574,9 @@ pub fn serve_gen(
// stable prefix and prefill only the new dialogue suffix. Mirrors strata
// --auto-ckpt's prompt-boundary save (proofs/prefix_cache.lean restore_equiv).
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos > 0 {
#[cfg(feature = "hip")]
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d, if spec_enabled { dctx_guard.as_ref() } else { None });
#[cfg(not(feature = "hip"))]
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d);
if std::env::var("VETTA_DBG_PREFIX").is_ok() {
eprintln!("[prefix] prompt-boundary save seq={pos}");
@@ -539,7 +604,7 @@ pub fn serve_gen(
#[cfg(feature = "hip")]
if spec_enabled {
let dw = eng.spec_dw.as_ref().unwrap();
let mut dc = dctx.take().unwrap();
let dc = dctx_guard.as_mut().unwrap();
let t1 = Instant::now();
let mut lg = vec![0f32; eng.vocab];
if let Err(e) = logits.d2h(&mut lg) {
@@ -568,11 +633,13 @@ pub fn serve_gen(
return;
}
let mut cur_pos = pos; let mut next_tok = tok0;
// Measured optimum on real text (gfx1150, GEN 96): n_draft=2 gives the best
// decode tok/s (6.09) vs 3=5.78, 4=5.54, 5=4.58, 7=5.15, 1=5.25 — at ~30-50%
// acceptance a larger verify batch wastes compute on rejected drafts. Start
// at 2 and escalate only when acceptance is very high (cost-aware governor).
let mut ema = 0.5f32; let mut n_draft = 2usize;
// Measured on gfx1150 after single-pass GPU drafter + WMMA/fdot2 + small-M SWA:
// Rust coding prompt (128 tok): OFF 6.83 | nd=2 11.93 | nd=3 13.90 | nd=4 13.97 | nd=5 13.69 tok/s
// Short prose prompt (96 tok): OFF 4.70 | nd=2 9.21 | nd=3 9.09 | nd=4 8.93 | nd=5 9.09 tok/s
// Track an EMA of ACCEPTED tokens per round (not acceptance ratio, which
// naturally drops as nd grows and used to clamp code generation down to nd=2).
// Start at 5 (optimal on code/structured text) and adapt smoothly 2..7.
let mut ema_acc = 2.0f32; let mut n_draft = 5usize;
// VETTA_SPEC_ND fixes n_draft (bypasses the EMA) for A/B measurement.
let nd_override = std::env::var("VETTA_SPEC_ND").ok().and_then(|v| v.parse::<usize>().ok());
let mut offered = 0usize; let mut accepted = 0usize; let mut rounds = 0usize;
@@ -589,7 +656,7 @@ pub fn serve_gen(
}
let left = effective_max_new - generated;
let nd = nd_override.unwrap_or(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) {
let (em, nc, nt, done) = match spec_round(&eng.cache, &eng.d, dw, 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));
@@ -607,10 +674,14 @@ pub fn serve_gen(
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.9 { 7 } else if ema >= 0.75 { 4 } else { 2 };
offered += nd; accepted += em.len().saturating_sub(1);
let acc = em.len().saturating_sub(1);
ema_acc = 0.85 * ema_acc + 0.15 * (acc as f32);
n_draft = if ema_acc >= 3.5 { 7 }
else if ema_acc >= 2.0 { 5 }
else if ema_acc >= 1.1 { 4 }
else if ema_acc >= 0.6 { 3 }
else { 2 };
offered += nd; accepted += acc;
}
rounds += 1;
cur_pos = nc; next_tok = nt; pos = nc;
@@ -620,10 +691,10 @@ pub fn serve_gen(
}
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));
eprintln!("[spec] rounds={rounds} offered={offered} accepted={accepted} ema_acc={ema_acc:.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);
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d, Some(dc));
}
emit_all(emit, sess.on_finish(finish, decode_ms).unwrap_or_default());
stop.store(false, Ordering::Relaxed);
@@ -693,6 +764,9 @@ pub fn serve_gen(
// counts tokens actually folded into `states` (history[..pos]); a sampled token
// not forwarded (EOS / last length step) is excluded, keeping the ckpt valid.
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos > 0 {
#[cfg(feature = "hip")]
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d, None);
#[cfg(not(feature = "hip"))]
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d);
if std::env::var("VETTA_DBG_PREFIX").is_ok() {
eprintln!("[prefix] full-sequence save seq={pos}");
@@ -970,4 +1044,58 @@ mod tests {
assert_eq!(off_n, on_n, "spec must emit the same token count");
});
}
/// GPU: multi-turn PrefixCache + DsparkSnapshot restore regression test.
/// Turn 1 prefills + generates 16 tokens and saves a checkpoint with DSpark
/// state; Turn 2 extends Turn 1's exact prompt + generated tokens with a
/// follow-up suffix, hitting RESUME on Turn 1's checkpoint and restoring
/// DSpark rings + frnn_last. Turn 2 output with VETTA_SPEC=1 must match
/// VETTA_SPEC=0 100% EXACT and emit a non-zero RESUME.
#[test]
#[ignore]
fn serve_gen_spec_prefix_cache_multi_turn_parity() {
crate::gpu_isolated(|| {
let turn1_ids = "200002,200004,34182,279,154554,150628,25,220,15,200010,200000,200004,10970,261,4660,11,5603,59195,9268,328,261,6164,12,13448,8459,6462,13,200010,200001,200004";
let run_two_turns = |spec: bool| -> (Vec<i32>, Vec<i32>, usize) {
if spec { unsafe { std::env::set_var("VETTA_SPEC", "1"); } } else { unsafe { std::env::remove_var("VETTA_SPEC"); } }
let eng = InklingEngine::new("/mnt/models/Inkling/safetensors").unwrap();
let stop = AtomicBool::new(false);
// Turn 1
let g1 = match parse_serve_line(&format!("GEN 16 temperature=0 {turn1_ids}"), eng.vocab()).unwrap() {
ServeCommand::Gen(g) => g,
_ => panic!("expected Gen"),
};
let mut l1 = Vec::new();
serve_gen(&eng, &g1, &stop, &mut |l| l1.push(l));
let t1: Vec<i32> = l1.iter().filter(|l| l.starts_with("T ")).map(|l| l[2..].trim().parse().unwrap()).collect();
// Turn 2 extends Turn 1 prompt + Turn 1 reply + short follow-up prompt
let mut turn2_vec: Vec<String> = turn1_ids.split(',').map(|s| s.to_string()).collect();
for &id in &t1 { turn2_vec.push(id.to_string()); }
for extra in [200010, 200000, 200004, 10970, 261, 2324, 13, 200010, 200001, 200004] {
turn2_vec.push(extra.to_string());
}
let turn2_ids = turn2_vec.join(",");
let g2 = match parse_serve_line(&format!("GEN 24 temperature=0 {turn2_ids}"), eng.vocab()).unwrap() {
ServeCommand::Gen(g) => g,
_ => panic!("expected Gen"),
};
let mut l2 = Vec::new();
serve_gen(&eng, &g2, &stop, &mut |l| l2.push(l));
let t2: Vec<i32> = l2.iter().filter(|l| l.starts_with("T ")).map(|l| l[2..].trim().parse().unwrap()).collect();
let resumed: usize = l2.iter()
.find(|l| l.starts_with("RESUME "))
.and_then(|l| l[7..].trim().parse().ok())
.unwrap_or(0);
unsafe { std::env::remove_var("VETTA_SPEC"); }
(t1, t2, resumed)
};
let (off_t1, off_t2, off_resumed) = run_two_turns(false);
let (on_t1, on_t2, on_resumed) = run_two_turns(true);
eprintln!("multi-turn prefix cache: off_resumed={off_resumed} on_resumed={on_resumed} t1_len={} t2_len={}", on_t1.len(), on_t2.len());
assert!(on_resumed > 0, "Turn 2 with VETTA_SPEC=1 must hit PrefixCache RESUME");
assert_eq!(on_resumed, off_resumed, "Turn 2 RESUME length must match OFF");
assert_eq!(on_t1, off_t1, "Turn 1 tokens must match OFF exactly");
assert_eq!(on_t2, off_t2, "Turn 2 tokens after PrefixCache+DsparkSnapshot restore must match OFF exactly");
});
}
}
+231 -4
View File
@@ -186,6 +186,36 @@ mod ffi {
pub fn vetta_ctrl_pack(cur: *const c_float, msg: *const c_float, packed: *mut u16, d: c_int, eps: c_float, stream: *mut c_void) -> c_int;
pub fn vetta_ctrl_pack_batched(cur: *const c_float, msg: *const c_float, packed: *mut u16, d: c_int, eps: c_float, m: c_int, stream: *mut c_void) -> c_int;
pub fn vetta_ctrl_apply(cur: *const c_float, msg: *const c_float, gain: *const c_float, forget: *const c_float, out: *mut c_float, n: usize, stream: *mut c_void) -> c_int;
pub fn vetta_dspark_base_top2_screen(
unembed_bf16: *const u16, cur_steps: *const c_float,
cand_val: *mut c_float, cand_id: *mut i32,
n_draft: c_int, d: c_int, v: c_int, n_cand: c_int, stream: *mut c_void,
) -> c_int;
pub fn vetta_dspark_markov_proj_bf16(
prev_tok_ptr: *const i32, state_in: *const c_float, state_out: *mut c_float,
latent_out: *mut c_float, cur_step: *const c_float, frnn_ring: *const u16,
frnn_slot: c_int, markov_w1: *const u16, rnn_proj_w: *const u16,
rnn_proj_b: *const c_float, d: c_int, rank: c_int, stream: *mut c_void,
) -> c_int;
pub fn vetta_dspark_markov_corr_bf16(
latent: *const c_float, hidden_out_w: *const u16, hidden_out_b: *const c_float,
corr_out: *mut c_float, d: c_int, rank: c_int, stream: *mut c_void,
) -> c_int;
pub fn vetta_dspark_cand_argmax(
unembed_bf16: *const u16, cand_base_val: *const c_float, cand_id: *const i32,
corr: *const c_float, blk_val: *mut c_float, blk_id: *mut i32, out_tok: *mut i32,
n_cand: c_int, d: c_int, v: c_int, stream: *mut c_void,
) -> c_int;
pub fn vetta_batched_argmax_f32(
logits: *const c_float, out_ids: *mut i32, b: c_int, v: c_int, stream: *mut c_void,
) -> c_int;
pub fn vetta_flash_swa_gqa_smallm_f16(
q: *const c_float, k: *const u16, v: *const u16, out: *mut c_float,
n_head: c_int, n_kv: c_int, seq: c_int, hd: c_int, scale: c_float,
swa_window: c_int, pos_arr: *const c_int, cur_pos_scalar: c_int,
rel_bias: *const c_float, max_rel: c_int, sink_logit: *const c_float,
gate: *const c_float, m: c_int, stream: *mut c_void,
) -> c_int;
}
}
@@ -531,6 +561,110 @@ pub fn dspark_scatter_bf16(src: &DeviceBuf, dst: &DeviceBuf, pos: &DeviceBuf, m:
Ok(())
}
/// Single-pass DSpark base-unembed Top-2-per-block screen across all `n_draft` steps.
/// Reads `unembed` [vocab, d] ONCE and screens `cur[1..=n_draft, :]` into
/// `cand_val` / `cand_id` [n_draft, n_cand].
#[cfg(feature = "hip")]
#[allow(clippy::too_many_arguments)]
pub fn dspark_base_top2_screen(
unembed: &DeviceBuf, cur: &DeviceBuf, cand_val: &DeviceBuf, cand_id: &DeviceBuf,
n_draft: i32, d: i32, vocab: i32, n_cand: i32,
) -> Result<(), String> {
if (n_draft as usize + 1) * (d as usize) * 4 > cur.bytes {
return Err("dspark_base_top2_screen cur overflow".into());
}
let cur_steps = unsafe { (cur.ptr as *const f32).add(d as usize) };
let rc = unsafe {
ffi::vetta_dspark_base_top2_screen(
unembed.ptr as *const u16, cur_steps, cand_val.ptr as *mut f32, cand_id.ptr as *mut i32,
n_draft, d, vocab, n_cand, std::ptr::null_mut(),
)
};
if rc != 0 { return Err("dspark_base_top2_screen launch failed".into()); }
Ok(())
}
/// On-GPU DSpark Markov RNN projection + GRU state update (zero host round-trips).
#[cfg(feature = "hip")]
#[allow(clippy::too_many_arguments)]
pub fn dspark_markov_proj_bf16(
d_toks: &DeviceBuf, tok_idx: usize, state_in: &DeviceBuf, state_out: &DeviceBuf,
latent_out: &DeviceBuf, cur: &DeviceBuf, step_idx: usize, frnn_ring: &DeviceBuf,
frnn_slot: i32, markov_w1: &DeviceBuf, rnn_proj_w: &DeviceBuf, rnn_proj_b: &DeviceBuf,
d: i32, rank: i32,
) -> Result<(), String> {
if (tok_idx + 1) * 4 > d_toks.bytes || (step_idx + 1) * (d as usize) * 4 > cur.bytes {
return Err("dspark_markov_proj_bf16 index overflow".into());
}
let prev_ptr = unsafe { (d_toks.ptr as *const i32).add(tok_idx) };
let cur_step = unsafe { (cur.ptr as *const f32).add(step_idx * d as usize) };
let rc = unsafe {
ffi::vetta_dspark_markov_proj_bf16(
prev_ptr, state_in.ptr as *const f32, state_out.ptr as *mut f32,
latent_out.ptr as *mut f32, cur_step, frnn_ring.ptr as *const u16,
frnn_slot, markov_w1.ptr as *const u16, rnn_proj_w.ptr as *const u16,
rnn_proj_b.ptr as *const f32, d, rank, std::ptr::null_mut(),
)
};
if rc != 0 { return Err("dspark_markov_proj_bf16 launch failed".into()); }
Ok(())
}
/// On-GPU DSpark Markov correction vector: corr = hidden_out_w @ latent + bias.
#[cfg(feature = "hip")]
pub fn dspark_markov_corr_bf16(
latent: &DeviceBuf, hidden_out_w: &DeviceBuf, hidden_out_b: &DeviceBuf,
corr_out: &DeviceBuf, d: i32, rank: i32,
) -> Result<(), String> {
let rc = unsafe {
ffi::vetta_dspark_markov_corr_bf16(
latent.ptr as *const f32, hidden_out_w.ptr as *const u16, hidden_out_b.ptr as *const f32,
corr_out.ptr as *mut f32, d, rank, std::ptr::null_mut(),
)
};
if rc != 0 { return Err("dspark_markov_corr_bf16 launch failed".into()); }
Ok(())
}
/// On-GPU DSpark candidate scorer + argmax -> writes winning token into `d_toks[out_tok_idx]`.
#[cfg(feature = "hip")]
#[allow(clippy::too_many_arguments)]
pub fn dspark_cand_argmax(
unembed: &DeviceBuf, cand_val: &DeviceBuf, cand_id: &DeviceBuf, step_idx: usize,
corr: &DeviceBuf, blk_val: &DeviceBuf, blk_id: &DeviceBuf,
d_toks: &DeviceBuf, out_tok_idx: usize, n_cand: i32, d: i32, vocab: i32,
) -> Result<(), String> {
let off = step_idx * (n_cand as usize);
if (off + n_cand as usize) * 4 > cand_val.bytes
|| (off + n_cand as usize) * 4 > cand_id.bytes
|| (out_tok_idx + 1) * 4 > d_toks.bytes
{
return Err("dspark_cand_argmax index overflow".into());
}
let cv = unsafe { (cand_val.ptr as *const f32).add(off) };
let ci = unsafe { (cand_id.ptr as *const i32).add(off) };
let ot = unsafe { (d_toks.ptr as *mut i32).add(out_tok_idx) };
let rc = unsafe {
ffi::vetta_dspark_cand_argmax(
unembed.ptr as *const u16, cv, ci, corr.ptr as *const f32,
blk_val.ptr as *mut f32, blk_id.ptr as *mut i32, ot,
n_cand, d, vocab, std::ptr::null_mut(),
)
};
if rc != 0 { return Err("dspark_cand_argmax launch failed".into()); }
Ok(())
}
/// On-GPU batched argmax over `logits [b, vocab]` -> `out_ids [b]` (deterministic first-max).
#[cfg(feature = "hip")]
pub fn batched_argmax_f32(logits: &DeviceBuf, out_ids: &DeviceBuf, b: i32, vocab: i32) -> Result<(), String> {
let rc = unsafe {
ffi::vetta_batched_argmax_f32(logits.ptr as *const f32, out_ids.ptr as *mut i32, b, vocab, std::ptr::null_mut())
};
if rc != 0 { return Err("batched_argmax_f32 launch failed".into()); }
Ok(())
}
/// Launch k_embed_bf16_gather: `b` token rows from BF16 table `[vocab, d]` → f32.
#[cfg(feature = "hip")]
pub fn embed_bf16_gather(table: &DeviceBuf, tokens: &DeviceBuf, out: &DeviceBuf, b: i32, d: i32, vocab: i32) -> Result<(), String> {
@@ -542,12 +676,13 @@ pub fn embed_bf16_gather(table: &DeviceBuf, tokens: &DeviceBuf, out: &DeviceBuf,
}
/// Launch k_gemm_bf16: y[m,n] = x[m,k] @ w[n,k]^T (BF16 in, f32 accumulate).
/// Prefill (m>=16, k%64==0) dispatches the BF16 WMMA tensor-core kernel (P1 b6);
/// decode (m<16) keeps the tiled-LDS scalar kernel. VETTA_NO_BF16_WMMA=1 forces
/// scalar everywhere (A/B baseline). WMMA changes f32 accumulation order (~1e-3).
/// Uses BF16 WMMA tensor-core GEMM whenever k%64==0 (both prefill AND M=1..15
/// decode/verify: coalesced uint4 weight loads + matrix cores, AND bit-identical
/// per-row between M=1 and M=nd+1 for lossless speculation).
/// VETTA_NO_BF16_WMMA=1 forces the tiled-LDS scalar fallback (A/B baseline).
#[cfg(feature = "hip")]
pub fn gemm_bf16(x: &DeviceBuf, w: &DeviceBuf, y: &DeviceBuf, m: i32, n: i32, k: i32) -> Result<(), String> {
if m >= 16 && k % 64 == 0 && std::env::var("VETTA_NO_BF16_WMMA").is_err() {
if m >= 1 && k % 64 == 0 && std::env::var("VETTA_NO_BF16_WMMA").is_err() {
return gemm_bf16_wmma(x, w, y, m, n, k);
}
let rc = unsafe {
@@ -634,6 +769,17 @@ pub fn flash_swa_gqa_decode_f16(q: &DeviceBuf, k: &DeviceBuf, v: &DeviceBuf, out
let rb = rel_bias.map(|b| b.ptr as *const f32).unwrap_or(std::ptr::null());
let sk = sink_logit.map(|b| b.ptr as *const f32).unwrap_or(std::ptr::null());
let gt = gate.map(|b| b.ptr as *const f32).unwrap_or(std::ptr::null());
if hd == 128 && std::env::var("VETTA_NO_FLASH_SMALLM").is_err() {
let rc = unsafe {
ffi::vetta_flash_swa_gqa_smallm_f16(
q.ptr as *const f32, k.ptr as *const u16, v.ptr as *const u16, out.ptr as *mut f32,
n_head, n_kv, seq, hd, scale, swa_window, std::ptr::null(), cur_pos,
rb, max_rel, sk, gt, 1, std::ptr::null_mut(),
)
};
if rc != 0 { return Err("flash_swa_gqa_smallm_f16 launch failed".into()); }
return Ok(());
}
let scratch = flash_scores_scratch(n_head, swa_window, cur_pos)?;
let rc = unsafe {
ffi::vetta_flash_swa_gqa_decode_f16(q.ptr as *const f32, k.ptr as *const u16, v.ptr as *const u16, out.ptr as *mut f32, n_head, n_kv, seq, hd, scale, swa_window, cur_pos, rb, max_rel, sk, gt, scratch.ptr as *mut f32, std::ptr::null_mut())
@@ -671,6 +817,17 @@ pub fn flash_swa_gqa_prefill_f16(q: &DeviceBuf, k: &DeviceBuf, v: &DeviceBuf, ou
if rc != 0 { return Err("flash_swa_gqa_prefill_wmma launch failed".into()); }
return Ok(());
}
if hd == 128 && std::env::var("VETTA_NO_FLASH_SMALLM").is_err() {
let rc = unsafe {
ffi::vetta_flash_swa_gqa_smallm_f16(
q.ptr as *const f32, k.ptr as *const u16, v.ptr as *const u16, out.ptr as *mut f32,
n_head, n_kv, seq, hd, scale, swa_window, pos.ptr as *const i32, 0,
rb, max_rel, sk, gt, m, std::ptr::null_mut(),
)
};
if rc != 0 { return Err("flash_swa_gqa_smallm_f16 launch failed".into()); }
return Ok(());
}
let n_win_max = if swa_window > 0 && max_pos >= swa_window { swa_window } else { max_pos + 1 };
let scratch = DeviceBuf::alloc_unpooled((m as usize) * (n_head as usize) * (n_win_max as usize) * 4)?;
let rc = unsafe {
@@ -1298,6 +1455,76 @@ mod gpu_tests {
assert!(max_rel < 1e-4, "dspark_block_attn parity failed: {max_rel}");
}
/// Regression test: DSpark Global layer 1 attention at c_len = 17_000.
/// Previously allocated `(c_len + B + hd) * 4` bytes of LDS (> 64 KiB above
/// ~16,248 tokens), causing a guaranteed HIP launch failure on RDNA 3.5.
/// The Wave32 online-softmax kernel uses 0 bytes of shared memory and must
/// match CPU on sampled (qi, head) outputs.
#[test]
#[ignore]
fn dspark_block_attn_long_context_no_lds_overflow() {
let (b, h, kv, hd, cap) = (8usize, 8usize, 2usize, 128usize, 17_024usize);
let (c0, c_len) = (0i32, 17_000usize);
let scale = 1.0f32 / (hd as f32).sqrt();
let n_rep = h / kv;
let ck: Vec<u16> = (0..cap * kv * hd).map(|i| f32_to_bf16(((i % 29) as f32 - 14.0) * 0.02)).collect();
let cv: Vec<u16> = (0..cap * kv * hd).map(|i| f32_to_bf16(((i % 17) as f32 - 8.0) * 0.04)).collect();
let q: Vec<f32> = (0..b * h * hd).map(|i| ((i % 23) as f32 - 11.0) * 0.03).collect();
let kd: Vec<f32> = (0..b * kv * hd).map(|i| ((i % 31) as f32 - 15.0) * 0.02).collect();
let vd: Vec<f32> = (0..b * kv * hd).map(|i| ((i % 13) as f32 - 6.0) * 0.05).collect();
let dq = DeviceBuf::alloc(q.len() * 4).unwrap(); dq.h2d(&q).unwrap();
let dkd = DeviceBuf::alloc(kd.len() * 4).unwrap(); dkd.h2d(&kd).unwrap();
let dvd = DeviceBuf::alloc(vd.len() * 4).unwrap(); dvd.h2d(&vd).unwrap();
let dck = DeviceBuf::alloc(ck.len() * 2).unwrap(); dck.h2d_bytes(bytemuck_u16(&ck)).unwrap();
let dcv = DeviceBuf::alloc(cv.len() * 2).unwrap(); dcv.h2d_bytes(bytemuck_u16(&cv)).unwrap();
let dy = DeviceBuf::alloc(b * h * hd * 4).unwrap();
dspark_block_attn(&dq, &dkd, &dvd, &dck, &dcv, &dy, b as i32, h as i32, kv as i32, hd as i32, c0, c_len as i32, cap as i32, scale).unwrap();
let mut got = vec![0f32; b * h * hd];
dy.d2h(&mut got).unwrap();
assert!(got.iter().all(|v| v.is_finite()), "long-context dspark_block_attn produced non-finite output");
// Verify sampled (qi, hh) pairs against CPU online-softmax oracle.
let mut max_rel = 0f32;
for &(qi, hh) in &[(0usize, 0usize), (3, 4), (7, 7)] {
let kvh = hh / n_rep;
let qv = &q[(qi * h + hh) * hd..(qi * h + hh + 1) * hd];
let mut mx = f32::NEG_INFINITY;
let mut sum = 0f32;
let mut acc = vec![0f32; hd];
for t in 0..(c_len + b) {
let mut dot = 0f32;
if t < c_len {
let slot = (c0 as usize + t) % cap;
for j in 0..hd { dot += qv[j] * bf16_to_f32(ck[(slot * kv + kvh) * hd + j]); }
} else {
let di = t - c_len;
for j in 0..hd { dot += qv[j] * kd[(di * kv + kvh) * hd + j]; }
}
dot *= scale;
let nm = mx.max(dot);
let alpha = (mx - nm).exp();
let w = (dot - nm).exp();
sum = sum * alpha + w;
if t < c_len {
let slot = (c0 as usize + t) % cap;
for j in 0..hd { acc[j] = acc[j] * alpha + w * bf16_to_f32(cv[(slot * kv + kvh) * hd + j]); }
} else {
let di = t - c_len;
for j in 0..hd { acc[j] = acc[j] * alpha + w * vd[(di * kv + kvh) * hd + j]; }
}
mx = nm;
}
let inv = 1.0f32 / sum;
let gscale = acc.iter().fold(0f32, |a, v| a.max((v * inv).abs())).max(1e-6);
for j in 0..hd {
let w = acc[j] * inv;
let g = got[(qi * h + hh) * hd + j];
max_rel = max_rel.max((g - w).abs() / gscale);
}
}
eprintln!("dspark_block_attn_long_context (c_len={c_len}) max_rel_err={max_rel:.3e}");
assert!(max_rel < 1e-4, "long-context dspark_block_attn parity failed: {max_rel}");
}
/// DSpark SwiGLU vs CPU oracle (silu(g)*u).
#[test]
#[ignore]
+149 -58
View File
@@ -223,9 +223,12 @@ mod gpu {
Ok(())
}
/// Full DSpark block-8 draft (Step 1, linear). Given the committed context
/// rings (bf16) + frnn, produce `n_draft` speculative token ids after
/// `anchor_tok` at `anchor_pos`. Trunk embed/unembed are passed in (bf16).
/// Full DSpark block-8 draft (Step 1, linear) — 100% on-GPU Markov loop.
/// Given the committed context rings (bf16) + frnn, produce `n_draft`
/// speculative token ids after `anchor_tok` at `anchor_pos`.
/// Single-pass base-unembed Top-512 screen reads unembed ONCE (instead of
/// n_draft times), then runs the recurrent Markov head + 512-candidate
/// scorer + argmax completely on GPU with ONE final <=32B D2H copy.
/// Lossless by construction (proofs/speculative_draft.lean): the trunk verify
/// step (b5) accepts/rejects; this only proposes.
#[allow(clippy::too_many_arguments)]
@@ -239,13 +242,18 @@ mod gpu {
let d = DS_HIDDEN; let hd = DS_HD; let h = DS_HEADS; let kv = DS_KV;
let q_dim = h * hd; let kv_dim = kv * hd; let inter = DS_INTER; let rank = DS_MARKOV_RANK;
let b = DS_BLOCK as i32;
let nd = n_draft.min(b - 1) as usize;
if nd == 0 { return Ok(()); }
let scale = 1.0f32 / (hd as f32).sqrt();
let al = |n: usize| DeviceBuf::alloc(n * 4);
// cur[B,D]: slot0 = rms(embed(anchor)), slots 1..B-1 = mask_embed.
let cur = al(b as usize * d)?;
let tok = DeviceBuf::alloc(4)?; tok.h2d_bytes(&anchor_tok.to_le_bytes())?;
let d_toks = DeviceBuf::alloc((nd + 1) * 4)?;
let mut init_toks = vec![0i32; nd + 1];
init_toks[0] = anchor_tok;
d_toks.h2d_bytes(&init_toks.iter().flat_map(|t| t.to_le_bytes()).collect::<Vec<u8>>())?;
let emb0 = al(d)?;
hip::embed_bf16_gather(embed, &tok, &emb0, 1, d as i32, vocab)?;
hip::embed_bf16_gather(embed, &d_toks, &emb0, 1, d as i32, vocab)?;
hip::rms_norm_f32(&emb0, Some(embed_norm), &emb0, 1, d as i32, eps)?;
hip::copy_f32_at(&emb0, &cur, 0, d)?;
for i in 1..b as usize { hip::copy_f32_at(&w.mask_embed, &cur, i * d, d)?; }
@@ -280,46 +288,55 @@ mod gpu {
hip::vec_add(&res, &o, &cur, b as usize * d)?;
}
hip::rms_norm_f32(&cur, Some(&w.norm), &cur, b, d as i32, eps)?;
let mut cur_h = vec![0f32; b as usize * d]; cur.d2h(&mut cur_h)?;
// context = frnn[anchor_pos-1] (bf16 ring row -> f32).
// Single-pass base-unembed Top-512 screen across all nd steps (reads unembed ONCE!).
let n_cand: i32 = 512;
let cand_val = al(nd * n_cand as usize)?;
let cand_id = al(nd * n_cand as usize)?;
hip::dspark_base_top2_screen(unembed, &cur, &cand_val, &cand_id, nd as i32, d as i32, vocab, n_cand)?;
// On-GPU recurrent Markov head: zero mid-loop host round-trips!
let fr_slot = (anchor_pos - 1).rem_euclid(frnn_cap);
let fr_tok = DeviceBuf::alloc(4)?; fr_tok.h2d_bytes(&fr_slot.to_le_bytes())?;
let ctx = al(d)?;
hip::embed_bf16_gather(frnn, &fr_tok, &ctx, 1, d as i32, frnn_cap)?;
let mut ctx_h = vec![0f32; d]; ctx.d2h(&mut ctx_h)?;
// Recurrent Markov head.
let state = al(rank)?; state.h2d(&vec![0f32; rank])?;
let latent = al(rank)?; let joint = al(2 * rank + 2 * d)?; let proj = al(3 * rank)?;
let mw1_row = al(rank)?; let corr = al(d)?; let cur_step = al(d)?; let combined = al(d)?;
let logits = al(vocab as usize)?;
let mut prev = anchor_tok;
let nd = n_draft.min(b - 1) as usize;
let st_a = al(rank)?; st_a.zero_async()?;
let st_b = al(rank)?;
let latent = al(rank)?;
let corr = al(d)?;
let n_blks = ((n_cand + 7) / 8) as usize;
let blk_val = al(n_blks)?;
let blk_id = al(n_blks)?;
for step in 1..=nd {
let mut state_h = vec![0f32; rank]; state.d2h(&mut state_h)?;
let pt = DeviceBuf::alloc(4)?; pt.h2d_bytes(&prev.to_le_bytes())?;
hip::embed_bf16_gather(&w.markov_w1, &pt, &mw1_row, 1, rank as i32, DS_VOCAB_PAD as i32)?;
let mut mw1_h = vec![0f32; rank]; mw1_row.d2h(&mut mw1_h)?;
let mut jh = Vec::with_capacity(2 * rank + 2 * d);
jh.extend_from_slice(&state_h);
jh.extend_from_slice(&mw1_h);
jh.extend_from_slice(&cur_h[step * d..(step + 1) * d]);
jh.extend_from_slice(&ctx_h);
joint.h2d(&jh)?;
hip::router_gemv(&joint, &w.rnn_proj_w, &proj, (3 * rank) as i32, (2 * rank + 2 * d) as i32)?;
hip::dspark_markov_gru(&proj, &w.rnn_proj_b, &state, &latent, rank as i32)?;
hip::router_gemv(&latent, &w.hidden_out_w, &corr, d as i32, rank as i32)?;
hip::copy_f32_sub(&cur, step * d, &cur_step, d)?;
hip::dspark_corr_combine(&cur_step, &corr, &w.hidden_out_b, &combined, d as i32)?;
hip::router_gemv(&combined, unembed, &logits, vocab, d as i32)?;
let mut lh = vec![0f32; vocab as usize]; logits.d2h(&mut lh)?;
let mut best = 0usize; let mut bz = f32::NEG_INFINITY;
for (v, &z) in lh.iter().enumerate() { if z > bz { bz = z; best = v; } }
out_ids[step - 1] = best as i32;
prev = best as i32;
let (st_in, st_out) = if step % 2 == 1 { (&st_a, &st_b) } else { (&st_b, &st_a) };
hip::dspark_markov_proj_bf16(
&d_toks, step - 1, st_in, st_out, &latent, &cur, step,
frnn, fr_slot, &w.markov_w1, &w.rnn_proj_w, &w.rnn_proj_b,
d as i32, rank as i32,
)?;
hip::dspark_markov_corr_bf16(&latent, &w.hidden_out_w, &w.hidden_out_b, &corr, d as i32, rank as i32)?;
hip::dspark_cand_argmax(
unembed, &cand_val, &cand_id, step - 1, &corr,
&blk_val, &blk_id, &d_toks, step, n_cand, d as i32, vocab,
)?;
}
// Single <=32B D2H copy for all drafted token ids.
let mut raw = vec![0u8; (nd + 1) * 4];
d_toks.d2h_bytes(&mut raw)?;
for step in 0..nd {
let off = (step + 1) * 4;
out_ids[step] = i32::from_le_bytes([raw[off], raw[off + 1], raw[off + 2], raw[off + 3]]);
}
Ok(())
}
/// Snapshot of DSpark context rings at `seq_len` for PrefixCache restore.
/// Stores SWA window `min(seq_len, swa_win)` for layers 0/2, full `[0..seq_len)`
/// for global layer 1, and the single `frnn[seq_len - 1]` row (4.6 KiB).
pub struct DsparkSnapshot {
pub seq_len: usize,
pub k: [DeviceBuf; 3],
pub v: [DeviceBuf; 3],
pub kv_start: [usize; 3],
pub n_rows: [usize; 3],
pub frnn_last: DeviceBuf,
}
/// 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).
@@ -331,7 +348,7 @@ mod gpu {
impl DsparkContext {
pub fn new(cap: usize, frnn_cap: usize) -> Result<Self, String> {
let ring = |n: usize| -> Result<DeviceBuf, String> {
let b = DeviceBuf::alloc(n * 2)?; b.zero_async()?; Ok(b)
let b = DeviceBuf::alloc_unpooled(n * 2)?; b.zero_async()?; Ok(b)
};
let kv = cap * DS_KV * DS_HD;
Ok(Self {
@@ -342,6 +359,75 @@ mod gpu {
})
}
/// Snapshot committed DSpark context at `seq_len` so PrefixCache hits
/// restore exact drafter KV/frnn instead of running with zeroed rings.
pub fn snapshot(&self, seq_len: usize, swa_win: usize) -> Result<DsparkSnapshot, String> {
let kv_row_b = DS_KV * DS_HD * 2;
let mut k_snaps: Vec<DeviceBuf> = Vec::with_capacity(DS_LAYERS);
let mut v_snaps: Vec<DeviceBuf> = Vec::with_capacity(DS_LAYERS);
let mut kv_start = [0usize; 3];
let mut n_rows = [0usize; 3];
for il in 0..DS_LAYERS {
let is_swa = DS_SWA_LAYERS.contains(&il);
let n = if is_swa { seq_len.min(swa_win) } else { seq_len };
let s0 = seq_len.saturating_sub(n);
kv_start[il] = s0;
n_rows[il] = n;
let kb = DeviceBuf::alloc_unpooled((n * kv_row_b).max(2))?;
let vb = DeviceBuf::alloc_unpooled((n * kv_row_b).max(2))?;
if n > 0 {
let slot0 = s0 % self.cap;
let first = n.min(self.cap - slot0);
kb.copy2d_at(0, &self.k[il], slot0 * kv_row_b, kv_row_b, kv_row_b, kv_row_b, first)?;
vb.copy2d_at(0, &self.v[il], slot0 * kv_row_b, kv_row_b, kv_row_b, kv_row_b, first)?;
if first < n {
let rem = n - first;
kb.copy2d_at(first * kv_row_b, &self.k[il], 0, kv_row_b, kv_row_b, kv_row_b, rem)?;
vb.copy2d_at(first * kv_row_b, &self.v[il], 0, kv_row_b, kv_row_b, kv_row_b, rem)?;
}
}
k_snaps.push(kb);
v_snaps.push(vb);
}
let fr_row_b = DS_HIDDEN * 2;
let frnn_last = DeviceBuf::alloc_unpooled(fr_row_b)?;
if seq_len > 0 {
let slot = (seq_len - 1) % self.frnn_cap;
frnn_last.copy2d_at(0, &self.frnn, slot * fr_row_b, fr_row_b, fr_row_b, fr_row_b, 1)?;
} else {
frnn_last.zero_async()?;
}
let [k0, k1, k2]: [DeviceBuf; 3] = k_snaps.try_into().map_err(|_| "dspark snap k len")?;
let [v0, v1, v2]: [DeviceBuf; 3] = v_snaps.try_into().map_err(|_| "dspark snap v len")?;
Ok(DsparkSnapshot { seq_len, k: [k0, k1, k2], v: [v0, v1, v2], kv_start, n_rows, frnn_last })
}
/// Restore a `DsparkSnapshot` into `self` (whose `cap` must be >= `snap.seq_len`).
pub fn restore(&mut self, snap: &DsparkSnapshot) -> Result<(), String> {
let kv_row_b = DS_KV * DS_HD * 2;
for il in 0..DS_LAYERS {
let n = snap.n_rows[il];
if n > 0 {
let slot0 = snap.kv_start[il] % self.cap;
let first = n.min(self.cap - slot0);
self.k[il].copy2d_at(slot0 * kv_row_b, &snap.k[il], 0, kv_row_b, kv_row_b, kv_row_b, first)?;
self.v[il].copy2d_at(slot0 * kv_row_b, &snap.v[il], 0, kv_row_b, kv_row_b, kv_row_b, first)?;
if first < n {
let rem = n - first;
self.k[il].copy2d_at(0, &snap.k[il], first * kv_row_b, kv_row_b, kv_row_b, kv_row_b, rem)?;
self.v[il].copy2d_at(0, &snap.v[il], first * kv_row_b, kv_row_b, kv_row_b, kv_row_b, rem)?;
}
}
}
if snap.seq_len > 0 {
let fr_row_b = DS_HIDDEN * 2;
let slot = (snap.seq_len - 1) % self.frnn_cap;
self.frnn.copy2d_at(slot * fr_row_b, &snap.frnn_last, 0, fr_row_b, fr_row_b, fr_row_b, 1)?;
}
self.len = snap.seq_len;
Ok(())
}
/// 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> {
@@ -363,8 +449,9 @@ mod gpu {
}
/// 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).
/// taps + hist snaps, skipping redundant last-row unembed) -> single GPU
/// batched unembed + GPU argmax (<=32B D2H!) -> accept longest prefix ->
/// commit ctx for ACCEPTED tokens only + rollback hist to `accepted`.
/// Lossless vs plain batched greedy (proofs/speculative_draft.lean).
#[allow(clippy::too_many_arguments)]
pub fn spec_round(
@@ -374,13 +461,13 @@ mod gpu {
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, i32, bool), String> {
use crate::layer::{forward_batch_taps, rollback_spec, spec_begin, spec_end};
use crate::layer::{forward_batch_taps_no_logits, 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
// 1. draft (single-pass Top-512 screen + on-GPU Markov loop)
let mut draft = vec![0i32; nd];
if nd > 0 {
let kref = [&dctx.k[0], &dctx.k[1], &dctx.k[2]];
@@ -389,35 +476,39 @@ mod gpu {
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
// 2. batched verify B=nd+1 (anchor + drafts), capture taps + hist snaps (skip single-row unembed)
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)?;
forward_batch_taps_no_logits(cache, d, &tokens, vocab, max_seq, cur_pos, states, &mut taps)?;
spec_end();
// 3. per-row greedy from taps[3] (h_norm) via bf16 unembed gemm
// 3. per-row greedy from taps[3] (h_norm): ONE batched unembed + on-GPU argmax (b*4 B D2H!)
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 d_greedy = alloc(b * 4)?;
hip::batched_argmax_f32(&lg, &d_greedy, b as i32, vocab as i32)?;
let mut raw_g = vec![0u8; b * 4];
d_greedy.d2h_bytes(&mut raw_g)?;
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;
let off = i * 4;
greedy[i] = i32::from_le_bytes([raw_g[off], raw_g[off + 1], raw_g[off + 2], raw_g[off + 3]]);
}
// 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<i32> = (0..b as i32).map(|i| cur_pos + i).collect();
pos.h2d_bytes(&pv.iter().flat_map(|p| p.to_le_bytes()).collect::<Vec<u8>>())?;
dctx.commit(dw, &taps, &pos, b as i32, d.eps, 1e6)?;
// 5. commit ctx for ACCEPTED tokens only + rollback hist
if r.accepted > 0 {
let acc = r.accepted;
let pos = alloc(acc * 4)?;
let pv: Vec<i32> = (0..acc as i32).map(|i| cur_pos + i).collect();
pos.h2d_bytes(&pv.iter().flat_map(|p| p.to_le_bytes()).collect::<Vec<u8>>())?;
dctx.commit(dw, &taps, &pos, acc 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))
@@ -425,7 +516,7 @@ mod gpu {
}
#[cfg(feature = "hip")]
pub use gpu::{DsparkLayer, DsparkWeights, DsparkContext, dspark_context, dspark_draft, spec_round};
pub use gpu::{DsparkLayer, DsparkWeights, DsparkContext, DsparkSnapshot, 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
+26 -9
View File
@@ -900,13 +900,13 @@ fn moe_batched(
vetta_infer_hip::moe_scatter_buckets(ids, &dcur, &dbtk, &ds2b, total as i32, top_k as i32)?;
// w13 grouped GEMM: gather input tokens via bucket_tok -> gu [total, 2*inter].
let gu = DeviceBuf::alloc(total * 2 * inter * 4)?;
expert_arena_grouped_gemv_f16(&w13, &doff, Some(&dbtk), &mlpin16, &gu)?;
expert_arena_grouped_gemv_f16(&w13, &doff, Some(&dbtk), &mlpin16, &gu, b)?;
let act16 = DeviceBuf::alloc(total * inter * 2)?;
vetta_infer_hip::situ_f16_batched(&gu, &act16, inter as i32, d.beta, d.lb, total as i32)?;
// w2 grouped GEMM: SiTU output is already bucket-ordered -> identity index
// (bucket_tok=None reads tok = beg+t0+m in-kernel; no host identity h2d sync).
let y_part = DeviceBuf::alloc(total * h * 4)?;
expert_arena_grouped_gemv_f16(&w2, &doff, None, &act16, &y_part)?;
expert_arena_grouped_gemv_f16(&w2, &doff, None, &act16, &y_part, b)?;
// Scatter-back + weighted reduce per token.
let moeout = DeviceBuf::alloc((b as usize) * h * 4)?;
vetta_infer_hip::moe_reduce_buckets_masked(&y_part, &ds2b, weights, &moeout, b, top_k as i32, h as i32)?;
@@ -1071,7 +1071,7 @@ pub fn forward_batch(
cache: &WeightCache, d: &Dims, tokens: &[i32], vocab: usize, max_seq: usize,
base_pos: i32, cap: f32, states: &mut [Option<LayerState>],
) -> Result<DeviceBuf, String> {
forward_batch_inner(cache, d, tokens, vocab, max_seq, base_pos, cap, states, None)
Ok(forward_batch_inner(cache, d, tokens, vocab, max_seq, base_pos, cap, states, None, false)?.unwrap())
}
/// forward_batch + DSpark target-tap capture: visits 5/23/41 entry residual and
@@ -1082,14 +1082,26 @@ pub fn forward_batch_taps(
base_pos: i32, cap: f32, states: &mut [Option<LayerState>],
taps_out: &mut [DeviceBuf; 4],
) -> Result<DeviceBuf, String> {
forward_batch_inner(cache, d, tokens, vocab, max_seq, base_pos, cap, states, Some(taps_out))
Ok(forward_batch_inner(cache, d, tokens, vocab, max_seq, base_pos, cap, states, Some(taps_out), false)?.unwrap())
}
/// forward_batch_taps skipping the single-row unembed: used by `spec_round`
/// verify, which computes all B rows of logits directly from `taps_out[3]` in
/// one batched unembed + GPU argmax (avoids running unembed twice per round!).
pub fn forward_batch_taps_no_logits(
cache: &WeightCache, d: &Dims, tokens: &[i32], vocab: usize, max_seq: usize,
base_pos: i32, states: &mut [Option<LayerState>],
taps_out: &mut [DeviceBuf; 4],
) -> Result<(), String> {
let _ = forward_batch_inner(cache, d, tokens, vocab, max_seq, base_pos, 0.0, states, Some(taps_out), true)?;
Ok(())
}
fn forward_batch_inner(
cache: &WeightCache, d: &Dims, tokens: &[i32], vocab: usize, max_seq: usize,
base_pos: i32, cap: f32, states: &mut [Option<LayerState>],
mut taps: Option<&mut [DeviceBuf; 4]>,
) -> Result<DeviceBuf, String> {
mut taps: Option<&mut [DeviceBuf; 4]>, skip_unembed: bool,
) -> Result<Option<DeviceBuf>, String> {
let h = d.hidden; let bu = tokens.len();
if bu == 0 { return Err("forward_batch: empty tokens".into()); }
let b = bu as i32;
@@ -1166,9 +1178,14 @@ fn forward_batch_inner(
let onorm = cache.bf16_f32("model.llm.norm.weight")?;
vetta_infer_hip::rms_norm_f32(&mix, Some(&onorm), &t[3], b, h as i32, d.eps)?;
}
let last = DeviceBuf::alloc(h * 4)?; vetta_infer_hip::copy_f32_sub(&mix, (bu - 1) * h, &last, h)?;
let logits = unembed_logits(cache, &last, h, vocab, d.eps)?;
if cap > 0.0 { vetta_infer_hip::softcap(&logits, &logits, vocab, cap)?; }
let logits = if skip_unembed {
None
} else {
let last = DeviceBuf::alloc(h * 4)?; vetta_infer_hip::copy_f32_sub(&mix, (bu - 1) * h, &last, h)?;
let l = unembed_logits(cache, &last, h, vocab, d.eps)?;
if cap > 0.0 { vetta_infer_hip::softcap(&l, &l, vocab, cap)?; }
Some(l)
};
if prof {
vetta_infer_hip::synchronize()?;
let exp = EXPERT_NS.with(|c| c.replace(0));
+9 -6
View File
@@ -202,14 +202,17 @@ pub fn expert_arena_gemv_f16(a: &ExpertArena, ids: &DeviceBuf, slot: i32, x: &De
/// expert eid processes its bucket tokens [exp_off[eid],exp_off[eid+1]) indexed
/// by `bucket_tok`. X [B,K] f16 (gathered) or [total,K] f16 (bucket order, pass an
/// identity index). Y [total_pairs,N] f32 in bucket order. Dispatches NVFP4/MXFP8.
pub fn expert_arena_grouped_gemv_f16(a: &ExpertArena, exp_off: &DeviceBuf, bucket_tok: Option<&DeviceBuf>, x: &DeviceBuf, y: &DeviceBuf) -> Result<(), String> {
/// For small verify/decode batches (`b <= 12`, avg <=1 token/expert), NVFP4 uses
/// Wave32 fdot2 (`nvfp4_grouped_gemv_f16`: bit-exact vs M=1, avoids 16-row WMMA
/// zero-padding waste); larger prefill chunks (`b > 12`) use FP16 WMMA.
pub fn expert_arena_grouped_gemv_f16(a: &ExpertArena, exp_off: &DeviceBuf, bucket_tok: Option<&DeviceBuf>, x: &DeviceBuf, y: &DeviceBuf, b: i32) -> Result<(), String> {
if a.mxfp8 {
vetta_infer_hip::mxfp8_grouped_gemv_f16(&a.packed, &a.scales, exp_off, bucket_tok, x, y, a.n, a.k, a.n_exp as i32, a.w_stride, a.sc_stride)
} else if a.k % 64 == 0 && std::env::var("VETTA_NO_MOE_WMMA").is_err() {
// P1: FP16 WMMA tensor-core grouped GEMM (~8x fdot2 ALU throughput). NVFP4
// E2M1 dequant is exact in f16; only the f32 accumulation order differs
// (~1e-4 measured). K%64==0 required by the BK=64 LDS slab (Inkling w13
// K=2304, w2 K=1152). VETTA_NO_MOE_WMMA=1 falls back to fdot2 for A/B.
} else if a.k % 64 == 0
&& (b > 12 || std::env::var("VETTA_FORCE_MOE_WMMA").is_ok())
&& std::env::var("VETTA_NO_MOE_WMMA").is_err()
{
// P1: FP16 WMMA tensor-core grouped GEMM (~8x fdot2 ALU throughput on prefill).
vetta_infer_hip::nvfp4_grouped_gemm_wmma(&a.packed, &a.scales, &a.outer, exp_off, bucket_tok, x, y, a.n, a.k, a.n_exp as i32, a.w_stride, a.sc_stride)
} else {
vetta_infer_hip::nvfp4_grouped_gemv_f16(&a.packed, &a.scales, &a.outer, exp_off, bucket_tok, x, y, a.n, a.k, a.n_exp as i32, a.w_stride, a.sc_stride)