[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

+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]