[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
+1428 -181

No files matched your search

+6 -2
View File
@@ -41,20 +41,24 @@ Built from the measured hardware physics and engineering lessons of our hardened
- **🎉 First real interactive GUI conversation — 2026-12-01 (measured):** via the `strata-ctl` web GUI on Sogliola, *"Ciao, sono Federico"* → *"Ciao Federico! Piacere di conoscerti. Come posso aiutarti oggi?"* — **2650 prompt + 53 completion tokens · 4.2 tok/s decode · first token 618 s** (the 618 s is sequential prefill of the ~2650-token agent prompt, ~140 ms/token; decode ~4.2 tok/s). Host-CPU busy-wait eliminated via `hipDeviceScheduleBlockingSync` (measured A/B 101.2% → 54.2%); the residual ~54% is kernel-launch cost, removed by HIP graph capture (M2). - **🎉 First real interactive GUI conversation — 2026-12-01 (measured):** via the `strata-ctl` web GUI on Sogliola, *"Ciao, sono Federico"* → *"Ciao Federico! Piacere di conoscerti. Come posso aiutarti oggi?"* — **2650 prompt + 53 completion tokens · 4.2 tok/s decode · first token 618 s** (the 618 s is sequential prefill of the ~2650-token agent prompt, ~140 ms/token; decode ~4.2 tok/s). Host-CPU busy-wait eliminated via `hipDeviceScheduleBlockingSync` (measured A/B 101.2% → 54.2%); the residual ~54% is kernel-launch cost, removed by HIP graph capture (M2).
- **⚡ Prefill batched + tensor-core — 2026-12-02 (measured):** chunked batched forward (M=B) + FP16 WMMA grouped MoE + BF16 WMMA dense projections + FlashAttention-2 WMMA prefill (P staged in LDS, no global scores scratch). Synthetic 2048-token prefill on `gfx1150` (FP16 KV, chunk 256): **60 s → 12.9 s (-78%)**, ~6.3 ms/token (a 16 k-token agent prompt ~105 s, was ~7 min). Greedy-vs-reference stays EXACT (blocking gate); internal M=1-vs-M=B parity relaxed to a global-scale tolerance (approved P1 policy). The 618 s first-token above is historical (sequential prefill). - **⚡ Prefill batched + tensor-core — 2026-12-02 (measured):** chunked batched forward (M=B) + FP16 WMMA grouped MoE + BF16 WMMA dense projections + FlashAttention-2 WMMA prefill (P staged in LDS, no global scores scratch). Synthetic 2048-token prefill on `gfx1150` (FP16 KV, chunk 256): **60 s → 12.9 s (-78%)**, ~6.3 ms/token (a 16 k-token agent prompt ~105 s, was ~7 min). Greedy-vs-reference stays EXACT (blocking gate); internal M=1-vs-M=B parity relaxed to a global-scale tolerance (approved P1 policy). The 618 s first-token above is historical (sequential prefill).
- **🧠 Flat VRAM + long-prompt clamp — 2026-12-02:** persistent per-layer KV/ShortConv states reused across requests (no ±3.75 GB alloc/free sawtooth), SWA-window checkpoints + prefix cache cap 8 (grid-protected, LRU-on-restore), 512 MiB buffer-pool cap; long→short session switches reuse the persistent KV. Generation budget clamped to the window (`clamp_max_new`) instead of hard-erroring past 16382 prompt tokens with strata-ctl's fixed max_new=16384; window configurable via `serve --max-context N`. Verified live: a 16504-token prompt generates (was ERR 0 tokens). - **🧠 Flat VRAM + long-prompt clamp — 2026-12-02:** persistent per-layer KV/ShortConv states reused across requests (no ±3.75 GB alloc/free sawtooth), SWA-window checkpoints + prefix cache cap 8 (grid-protected, LRU-on-restore), 512 MiB buffer-pool cap; long→short session switches reuse the persistent KV. Generation budget clamped to the window (`clamp_max_new`) instead of hard-erroring past 16382 prompt tokens with strata-ctl's fixed max_new=16384; window configurable via `serve --max-context N`. Verified live: a 16504-token prompt generates (was ERR 0 tokens).
- **🚀 DSpark speculative drafter (opt-in `VETTA_SPEC=1`, 100% GPU) — 2026-12-02 (measured):** single-pass base-unembed Top-512 screen + on-GPU Markov head + GPU verify argmax (`<=32 B` D2H), 0-LDS Wave32 online-softmax block attention (safe past 16k+ context), M-tiled Wave32 BF16 router GEMV, zero-scratch small-M SWA GQA, `PrefixCache` `DsparkSnapshot` save/restore for multi-turn, and accepted-count EMA governor (`n_draft` starts at 5, adapts 2..7). Lossless contract proven in `proofs/speculative_draft.lean` (200-token `spec_lossless_gate` EXACT + multi-turn `RESUME` EXACT). Measured on `gfx1150` (`Inkling-2-Mini`, `temperature=0`):
- **Rust coding prompt (`RingBuffer<T>`, 128 tok):** OFF **`6.83 tok/s`** → `VETTA_SPEC=1` **`13.93 tok/s`** (**2.04×**, `n_draft=5`, 100% EXACT — matching/edging `strata-inkling --draft dspark` at `13.66 tok/s`).
- **Short prose prompt (`"The capital of France is"`, 96 tok):** `nd=5` **`4.58 → 9.09 tok/s`** (**+98.5%**); adaptive EMA **`8.93 tok/s`** decode.
- **M1.5 (Embedder lane — BGE-M3):** native encoder forward-pass (LayerNorm, bidirectional full-attn, GELU-erf, CLS pooling + L2 — recipe declared in the manifest), XLM-R importer, SPM tokenizer, `vetta-infer embed` wire; acceptance cosine ≥ 0.999 vs the live `vetta-semantics` oracle (`:8091`) + publisher fixture + anisotropy canary. Optional reranker head. May double as the HIP kernel bring-up bench. - **M1.5 (Embedder lane — BGE-M3):** native encoder forward-pass (LayerNorm, bidirectional full-attn, GELU-erf, CLS pooling + L2 — recipe declared in the manifest), XLM-R importer, SPM tokenizer, `vetta-infer embed` wire; acceptance cosine ≥ 0.999 vs the live `vetta-semantics` oracle (`:8091`) + publisher fixture + anisotropy canary. Optional reranker head. May double as the HIP kernel bring-up bench.
- **M2 (Hybrid GDN + NVMe Zero-Copy DMA Streaming):** speculative drafter integration (next), then layer streaming in DMA — the hard memory frontier: Chunkwise Parallel GDN (WY-representation, target `250–350+ ppts`), `Clover-35B-A3B` & MTP MoE support, `io_uring O_DIRECT` + `hipHostRegister` `SlabRing`, Hot/Cold expert cache + lookahead prefetch. - **M2 (Hybrid GDN + NVMe Zero-Copy DMA Streaming):** DSpark drafter ✅ landed; next is layer streaming in DMA — the hard memory frontier: Chunkwise Parallel GDN (WY-representation, target `250–350+ ppts`), `Clover-35B-A3B` & MTP MoE support, `io_uring O_DIRECT` + `hipHostRegister` `SlabRing`, Hot/Cold expert cache + lookahead prefetch.
- **M3 (Distributed Control Plane — Lyra + Sogliola):** Remote `DraftProvider` + domain `PrefetchAdvisor` over 2.5 Gbps LAN + live telemetry-driven domain expert pre-warming. - **M3 (Distributed Control Plane — Lyra + Sogliola):** Remote `DraftProvider` + domain `PrefetchAdvisor` over 2.5 Gbps LAN + live telemetry-driven domain expert pre-warming.
## Quick Verification ## Quick Verification
```sh ```sh
# Lean 4 formal proofs (0 sorryAx, 6 files) # Lean 4 formal proofs (0 sorryAx, 7 files)
lean proofs/slab_ring_dma.lean lean proofs/slab_ring_dma.lean
lean proofs/bus_lifecycle.lean lean proofs/bus_lifecycle.lean
lean proofs/serve_session.lean lean proofs/serve_session.lean
lean proofs/arena_plan.lean lean proofs/arena_plan.lean
lean proofs/inkling_loop.lean lean proofs/inkling_loop.lean
lean proofs/prefix_cache.lean lean proofs/prefix_cache.lean
lean proofs/speculative_draft.lean
# Pure-Rust workspace tests (no GPU required) # Pure-Rust workspace tests (no GPU required)
cargo test --workspace cargo test --workspace
+173 -45
View File
@@ -32,7 +32,7 @@ use vetta_infer_ld::SafetensorsArchive;
#[cfg(feature = "hip")] #[cfg(feature = "hip")]
use vetta_infer_ld::layer::forward_batch_taps; use vetta_infer_ld::layer::forward_batch_taps;
#[cfg(feature = "hip")] #[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::session::ServeSession;
use crate::{err_line, ready_line}; use crate::{err_line, ready_line};
@@ -80,6 +80,8 @@ fn is_grid(seq: usize) -> bool { seq % 512 == 0 }
struct Checkpoint { struct Checkpoint {
tokens: Vec<i32>, tokens: Vec<i32>,
layers: Vec<Option<LayerSnapshot>>, layers: Vec<Option<LayerSnapshot>>,
#[cfg(feature = "hip")]
dspark: Option<DsparkSnapshot>,
lru: u64, lru: u64,
} }
@@ -113,7 +115,12 @@ impl PrefixCache {
/// Takes `&mut self` to refresh the hit checkpoint's LRU tick: without this a /// 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 /// 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. /// 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]; let ck = &self.pool[idx];
// A usable checkpoint must cover EVERY layer: a partially-restored state // 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)?; 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.tick += 1;
self.pool[idx].lru = self.tick; 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 / /// Snapshot all layer states (and optional DSpark context) at `tokens.len()`
/// evict oldest unpinned). Mirrors poolInsert in proofs/prefix_cache.lean. /// and insert (update / grow / evict oldest unpinned). Mirrors poolInsert in
fn save(&mut self, tokens: &[i32], states: &[Option<LayerState>], d: &Dims) -> Result<(), String> { /// 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(); let seq = tokens.len();
if seq == 0 { return Ok(()); } if seq == 0 { return Ok(()); }
let layers: Vec<Option<LayerSnapshot>> = states.iter().enumerate() let layers: Vec<Option<LayerSnapshot>> = states.iter().enumerate()
.map(|(ip, st)| st.as_ref().map(|s| s.snapshot(d, seq, is_swa(ip))).transpose()) .map(|(ip, st)| st.as_ref().map(|s| s.snapshot(d, seq, is_swa(ip))).transpose())
.collect::<Result<_, _>>()?; .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; self.tick += 1;
let lru = self.tick; let lru = self.tick;
if let Some(ck) = self.pool.iter_mut().find(|c| c.tokens.len() == seq) { 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; ck.tokens = tokens.to_vec(); ck.layers = layers; ck.lru = lru;
#[cfg(feature = "hip")] { ck.dspark = dspark; }
return Ok(()); return Ok(());
} }
if self.pool.len() < PREFIX_CACHE_CAP { 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(()); return Ok(());
} }
let victim = self.pool.iter().enumerate() let victim = self.pool.iter().enumerate()
.filter(|(_, c)| !pinned_anchor(c.tokens.len())) .filter(|(_, c)| !pinned_anchor(c.tokens.len()))
.min_by_key(|(_, c)| (is_grid(c.tokens.len()) as u8, c.lru)).map(|(i, _)| i); .min_by_key(|(_, c)| (is_grid(c.tokens.len()) as u8, c.lru)).map(|(i, _)| i);
if let Some(i) = victim { 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(()) Ok(())
} }
@@ -190,6 +220,9 @@ pub struct InklingEngine {
/// mtp.safetensors passes layout_check. Enables opt-in greedy speculation. /// mtp.safetensors passes layout_check. Enables opt-in greedy speculation.
#[cfg(feature = "hip")] #[cfg(feature = "hip")]
spec_dw: Option<DsparkWeights>, spec_dw: Option<DsparkWeights>,
/// Persistent DSpark context rings reused across requests (mirrors `states`).
#[cfg(feature = "hip")]
dctx: RefCell<Option<DsparkContext>>,
} }
impl InklingEngine { impl InklingEngine {
@@ -258,6 +291,8 @@ impl InklingEngine {
max_context, max_context,
#[cfg(feature = "hip")] #[cfg(feature = "hip")]
spec_dw, spec_dw,
#[cfg(feature = "hip")]
dctx: RefCell::new(None),
}) })
} }
@@ -343,6 +378,30 @@ pub fn serve_gen(
let cap = max_context; let cap = max_context;
let mut states = eng.states.borrow_mut(); 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 // Prefix checkpoint reuse (proofs/prefix_cache.lean restore_equiv): restore
// the longest cached strict prefix of this prompt and prefill only the NEW // 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). // 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() { if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() {
let matched = eng.prefix.borrow().best_match(&g.ids); let matched = eng.prefix.borrow().best_match(&g.ids);
if let Some((idx, _l)) = matched { if let Some((idx, _l)) = matched {
match eng.prefix.borrow_mut().restore(idx, &mut states[..], &eng.d, cap) { #[cfg(feature = "hip")]
Ok(n) => start = n, 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(_) => { Err(_) => {
// Incomplete/failed restore: fall back to a clean cold prefill. // Incomplete/failed restore: fall back to a clean cold prefill.
*states = (0..eng.n_layers).map(|_| None).collect(); *states = (0..eng.n_layers).map(|_| None).collect();
@@ -371,6 +447,10 @@ pub fn serve_gen(
return; return;
} }
} }
#[cfg(feature = "hip")]
if let Some(dc) = dctx_guard.as_mut() {
dc.len = 0;
}
} }
if std::env::var("VETTA_DBG_PREFIX").is_ok() { if std::env::var("VETTA_DBG_PREFIX").is_ok() {
eprintln!("[prefix] prompt_len={n_prompt} restored={start}"); 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 // Weights are resident in eng.cache (loaded once at boot, reused across all
// requests): no per-request NVMe re-read or re-upload. // 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. --- // --- Prefill: chunked batched (M=B) forward over the NEW prompt tokens. ---
// Each chunk runs ONE forward_batch over B tokens (weight streaming + kernel // Each chunk runs ONE forward_batch over B tokens (weight streaming + kernel
// launches amortized across B), growing KV/history; logits come from the last // 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)?; let pb = DeviceBuf::alloc(take * 4)?;
pb.h2d_bytes(&(pos..pos + take as i32).flat_map(|p| p.to_le_bytes()).collect::<Vec<u8>>())?; 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 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.commit(dw, &taps, &pb, take as i32, eng.d.eps, 1e6)?;
dc.len = (pos + take as i32) as usize; dc.len = (pos + take as i32) as usize;
Ok(l) Ok(l)
@@ -481,6 +540,9 @@ pub fn serve_gen(
// prefix; grid entries are protected from eviction (is_grid) and refreshed // prefix; grid entries are protected from eviction (is_grid) and refreshed
// on restore (lru), so turn 3+ keeps advancing instead of falling to 1024. // 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 { 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); let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d);
if std::env::var("VETTA_DBG_PREFIX").is_ok() { if std::env::var("VETTA_DBG_PREFIX").is_ok() {
eprintln!("[prefix] grid save seq={pos}"); 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 // stable prefix and prefill only the new dialogue suffix. Mirrors strata
// --auto-ckpt's prompt-boundary save (proofs/prefix_cache.lean restore_equiv). // --auto-ckpt's prompt-boundary save (proofs/prefix_cache.lean restore_equiv).
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos > 0 { 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); let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d);
if std::env::var("VETTA_DBG_PREFIX").is_ok() { if std::env::var("VETTA_DBG_PREFIX").is_ok() {
eprintln!("[prefix] prompt-boundary save seq={pos}"); eprintln!("[prefix] prompt-boundary save seq={pos}");
@@ -539,7 +604,7 @@ pub fn serve_gen(
#[cfg(feature = "hip")] #[cfg(feature = "hip")]
if spec_enabled { if spec_enabled {
let dw = eng.spec_dw.as_ref().unwrap(); 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 t1 = Instant::now();
let mut lg = vec![0f32; eng.vocab]; let mut lg = vec![0f32; eng.vocab];
if let Err(e) = logits.d2h(&mut lg) { if let Err(e) = logits.d2h(&mut lg) {
@@ -568,11 +633,13 @@ pub fn serve_gen(
return; return;
} }
let mut cur_pos = pos; let mut next_tok = tok0; let mut cur_pos = pos; let mut next_tok = tok0;
// Measured optimum on real text (gfx1150, GEN 96): n_draft=2 gives the best // Measured on gfx1150 after single-pass GPU drafter + WMMA/fdot2 + small-M SWA:
// decode tok/s (6.09) vs 3=5.78, 4=5.54, 5=4.58, 7=5.15, 1=5.25 — at ~30-50% // 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
// acceptance a larger verify batch wastes compute on rejected drafts. Start // 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
// at 2 and escalate only when acceptance is very high (cost-aware governor). // Track an EMA of ACCEPTED tokens per round (not acceptance ratio, which
let mut ema = 0.5f32; let mut n_draft = 2usize; // 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. // 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 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; 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 left = effective_max_new - generated;
let nd = nd_override.unwrap_or(n_draft).min(left.saturating_sub(1)); 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, Ok(v) => v,
Err(e) => { Err(e) => {
emit_all(emit, sess.on_error(&e)); emit_all(emit, sess.on_error(&e));
@@ -607,10 +674,14 @@ pub fn serve_gen(
if generated >= effective_max_new { break; } if generated >= effective_max_new { break; }
} }
if nd > 0 { if nd > 0 {
let acc = (em.len().saturating_sub(1)) as f32 / nd as f32; let acc = em.len().saturating_sub(1);
ema = 0.9 * ema + 0.1 * acc; ema_acc = 0.85 * ema_acc + 0.15 * (acc as f32);
n_draft = if ema >= 0.9 { 7 } else if ema >= 0.75 { 4 } else { 2 }; n_draft = if ema_acc >= 3.5 { 7 }
offered += nd; accepted += em.len().saturating_sub(1); 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; rounds += 1;
cur_pos = nc; next_tok = nt; pos = nc; 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; let decode_ms = t1.elapsed().as_secs_f64() * 1000.0;
if std::env::var("VETTA_DBG_SPEC").is_ok() { 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 { 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()); emit_all(emit, sess.on_finish(finish, decode_ms).unwrap_or_default());
stop.store(false, Ordering::Relaxed); stop.store(false, Ordering::Relaxed);
@@ -693,6 +764,9 @@ pub fn serve_gen(
// counts tokens actually folded into `states` (history[..pos]); a sampled token // counts tokens actually folded into `states` (history[..pos]); a sampled token
// not forwarded (EOS / last length step) is excluded, keeping the ckpt valid. // not forwarded (EOS / last length step) is excluded, keeping the ckpt valid.
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos > 0 { 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); let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d);
if std::env::var("VETTA_DBG_PREFIX").is_ok() { if std::env::var("VETTA_DBG_PREFIX").is_ok() {
eprintln!("[prefix] full-sequence save seq={pos}"); 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"); 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(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_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_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(()) 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. /// Launch k_embed_bf16_gather: `b` token rows from BF16 table `[vocab, d]` → f32.
#[cfg(feature = "hip")] #[cfg(feature = "hip")]
pub fn embed_bf16_gather(table: &DeviceBuf, tokens: &DeviceBuf, out: &DeviceBuf, b: i32, d: i32, vocab: i32) -> Result<(), String> { 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). /// 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); /// Uses BF16 WMMA tensor-core GEMM whenever k%64==0 (both prefill AND M=1..15
/// decode (m<16) keeps the tiled-LDS scalar kernel. VETTA_NO_BF16_WMMA=1 forces /// decode/verify: coalesced uint4 weight loads + matrix cores, AND bit-identical
/// scalar everywhere (A/B baseline). WMMA changes f32 accumulation order (~1e-3). /// 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")] #[cfg(feature = "hip")]
pub fn gemm_bf16(x: &DeviceBuf, w: &DeviceBuf, y: &DeviceBuf, m: i32, n: i32, k: i32) -> Result<(), String> { 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); return gemm_bf16_wmma(x, w, y, m, n, k);
} }
let rc = unsafe { 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 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 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()); 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 scratch = flash_scores_scratch(n_head, swa_window, cur_pos)?;
let rc = unsafe { 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()) 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()); } if rc != 0 { return Err("flash_swa_gqa_prefill_wmma launch failed".into()); }
return Ok(()); 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 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 scratch = DeviceBuf::alloc_unpooled((m as usize) * (n_head as usize) * (n_win_max as usize) * 4)?;
let rc = unsafe { let rc = unsafe {
@@ -1298,6 +1455,76 @@ mod gpu_tests {
assert!(max_rel < 1e-4, "dspark_block_attn parity failed: {max_rel}"); 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). /// DSpark SwiGLU vs CPU oracle (silu(g)*u).
#[test] #[test]
#[ignore] #[ignore]
+148 -57
View File
@@ -223,9 +223,12 @@ mod gpu {
Ok(()) Ok(())
} }
/// Full DSpark block-8 draft (Step 1, linear). Given the committed context /// Full DSpark block-8 draft (Step 1, linear) — 100% on-GPU Markov loop.
/// rings (bf16) + frnn, produce `n_draft` speculative token ids after /// Given the committed context rings (bf16) + frnn, produce `n_draft`
/// `anchor_tok` at `anchor_pos`. Trunk embed/unembed are passed in (bf16). /// 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 /// Lossless by construction (proofs/speculative_draft.lean): the trunk verify
/// step (b5) accepts/rejects; this only proposes. /// step (b5) accepts/rejects; this only proposes.
#[allow(clippy::too_many_arguments)] #[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 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 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 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 scale = 1.0f32 / (hd as f32).sqrt();
let al = |n: usize| DeviceBuf::alloc(n * 4); let al = |n: usize| DeviceBuf::alloc(n * 4);
// cur[B,D]: slot0 = rms(embed(anchor)), slots 1..B-1 = mask_embed. // cur[B,D]: slot0 = rms(embed(anchor)), slots 1..B-1 = mask_embed.
let cur = al(b as usize * d)?; 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)?; 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::rms_norm_f32(&emb0, Some(embed_norm), &emb0, 1, d as i32, eps)?;
hip::copy_f32_at(&emb0, &cur, 0, d)?; 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)?; } 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::vec_add(&res, &o, &cur, b as usize * d)?;
} }
hip::rms_norm_f32(&cur, Some(&w.norm), &cur, b, d as i32, eps)?; 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)?; // Single-pass base-unembed Top-512 screen across all nd steps (reads unembed ONCE!).
// context = frnn[anchor_pos-1] (bf16 ring row -> f32). 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_slot = (anchor_pos - 1).rem_euclid(frnn_cap);
let fr_tok = DeviceBuf::alloc(4)?; fr_tok.h2d_bytes(&fr_slot.to_le_bytes())?; let st_a = al(rank)?; st_a.zero_async()?;
let ctx = al(d)?; let st_b = al(rank)?;
hip::embed_bf16_gather(frnn, &fr_tok, &ctx, 1, d as i32, frnn_cap)?; let latent = al(rank)?;
let mut ctx_h = vec![0f32; d]; ctx.d2h(&mut ctx_h)?; let corr = al(d)?;
// Recurrent Markov head. let n_blks = ((n_cand + 7) / 8) as usize;
let state = al(rank)?; state.h2d(&vec![0f32; rank])?; let blk_val = al(n_blks)?;
let latent = al(rank)?; let joint = al(2 * rank + 2 * d)?; let proj = al(3 * rank)?; let blk_id = al(n_blks)?;
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;
for step in 1..=nd { for step in 1..=nd {
let mut state_h = vec![0f32; rank]; state.d2h(&mut state_h)?; let (st_in, st_out) = if step % 2 == 1 { (&st_a, &st_b) } else { (&st_b, &st_a) };
let pt = DeviceBuf::alloc(4)?; pt.h2d_bytes(&prev.to_le_bytes())?; hip::dspark_markov_proj_bf16(
hip::embed_bf16_gather(&w.markov_w1, &pt, &mw1_row, 1, rank as i32, DS_VOCAB_PAD as i32)?; &d_toks, step - 1, st_in, st_out, &latent, &cur, step,
let mut mw1_h = vec![0f32; rank]; mw1_row.d2h(&mut mw1_h)?; frnn, fr_slot, &w.markov_w1, &w.rnn_proj_w, &w.rnn_proj_b,
let mut jh = Vec::with_capacity(2 * rank + 2 * d); d as i32, rank as i32,
jh.extend_from_slice(&state_h); )?;
jh.extend_from_slice(&mw1_h); hip::dspark_markov_corr_bf16(&latent, &w.hidden_out_w, &w.hidden_out_b, &corr, d as i32, rank as i32)?;
jh.extend_from_slice(&cur_h[step * d..(step + 1) * d]); hip::dspark_cand_argmax(
jh.extend_from_slice(&ctx_h); unembed, &cand_val, &cand_id, step - 1, &corr,
joint.h2d(&jh)?; &blk_val, &blk_id, &d_toks, step, n_cand, d as i32, vocab,
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)?; // Single <=32B D2H copy for all drafted token ids.
hip::copy_f32_sub(&cur, step * d, &cur_step, d)?; let mut raw = vec![0u8; (nd + 1) * 4];
hip::dspark_corr_combine(&cur_step, &corr, &w.hidden_out_b, &combined, d as i32)?; d_toks.d2h_bytes(&mut raw)?;
hip::router_gemv(&combined, unembed, &logits, vocab, d as i32)?; for step in 0..nd {
let mut lh = vec![0f32; vocab as usize]; logits.d2h(&mut lh)?; let off = (step + 1) * 4;
let mut best = 0usize; let mut bz = f32::NEG_INFINITY; out_ids[step] = i32::from_le_bytes([raw[off], raw[off + 1], raw[off + 2], raw[off + 3]]);
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;
} }
Ok(()) 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] + /// Persistent DSpark context rings (bf16): per-layer k/v [cap, kv_dim] +
/// frnn [frnn_cap, D]. `len` = committed context length (truncated on /// frnn [frnn_cap, D]. `len` = committed context length (truncated on
/// partial accept; ring slots of kept vs rejected spans are disjoint). /// partial accept; ring slots of kept vs rejected spans are disjoint).
@@ -331,7 +348,7 @@ mod gpu {
impl DsparkContext { impl DsparkContext {
pub fn new(cap: usize, frnn_cap: usize) -> Result<Self, String> { pub fn new(cap: usize, frnn_cap: usize) -> Result<Self, String> {
let ring = |n: usize| -> Result<DeviceBuf, 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; let kv = cap * DS_KV * DS_HD;
Ok(Self { 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 /// 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. /// 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> { 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 /// One greedy speculative round: draft nd -> batched trunk verify (capture
/// taps + hist snaps) -> accept longest prefix -> commit ctx + rollback hist /// taps + hist snaps, skipping redundant last-row unembed) -> single GPU
/// to `accepted`. Returns (emit, new_cur_pos, new_next_tok, done). /// 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). /// Lossless vs plain batched greedy (proofs/speculative_draft.lean).
#[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]
pub fn spec_round( pub fn spec_round(
@@ -374,13 +461,13 @@ mod gpu {
cur_pos: i32, next_tok: i32, nd: usize, vocab: usize, max_seq: usize, cur_pos: i32, next_tok: i32, nd: usize, vocab: usize, max_seq: usize,
max_left: usize, is_stop: impl Fn(i32) -> bool, max_left: usize, is_stop: impl Fn(i32) -> bool,
) -> Result<(Vec<i32>, i32, i32, bool), String> { ) -> 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 alloc = |n: usize| DeviceBuf::alloc(n);
let h = d.hidden; let h = d.hidden;
let embed = cache.raw("model.llm.embed.weight")?; let embed = cache.raw("model.llm.embed.weight")?;
let embed_norm = cache.bf16_f32("model.llm.embed_norm.weight")?; let embed_norm = cache.bf16_f32("model.llm.embed_norm.weight")?;
let unembed = cache.raw("model.llm.unembed.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]; let mut draft = vec![0i32; nd];
if nd > 0 { if nd > 0 {
let kref = [&dctx.k[0], &dctx.k[1], &dctx.k[2]]; 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, 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)?; 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 b = nd + 1;
let mut tokens = vec![0i32; b]; let mut tokens = vec![0i32; b];
tokens[0] = next_tok; tokens[0] = next_tok;
for i in 0..nd { tokens[i + 1] = draft[i]; } 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)?]; let mut taps = [alloc(b * h * 4)?, alloc(b * h * 4)?, alloc(b * h * 4)?, alloc(b * h * 4)?];
spec_begin(b); 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(); 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)?; let tn_bf = alloc(b * h * 2)?;
hip::cast_f32_bf16(&taps[3], &tn_bf, b * h)?; hip::cast_f32_bf16(&taps[3], &tn_bf, b * h)?;
let lg = alloc(b * vocab * 4)?; let lg = alloc(b * vocab * 4)?;
hip::gemm_bf16(&tn_bf, &unembed, &lg, b as i32, vocab as i32, h as i32)?; 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]; let mut greedy = vec![0i32; b];
for i in 0..b { for i in 0..b {
let row = &lgh[i * vocab..(i + 1) * vocab]; let off = i * 4;
let mut best = 0usize; let mut bz = f32::NEG_INFINITY; greedy[i] = i32::from_le_bytes([raw_g[off], raw_g[off + 1], raw_g[off + 2], raw_g[off + 3]]);
for (v, &z) in row.iter().enumerate() { if z > bz { bz = z; best = v; } }
greedy[i] = best as i32;
} }
// 4. accept // 4. accept
let r = spec_accept_greedy(&draft, &greedy, next_tok, max_left, is_stop); let r = spec_accept_greedy(&draft, &greedy, next_tok, max_left, is_stop);
// 5. commit ctx for fed tokens, truncate to accepted; rollback hist // 5. commit ctx for ACCEPTED tokens only + rollback hist
let pos = alloc(b * 4)?; if r.accepted > 0 {
let pv: Vec<i32> = (0..b as i32).map(|i| cur_pos + i).collect(); 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>>())?; 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)?; dctx.commit(dw, &taps, &pos, acc as i32, d.eps, 1e6)?;
}
dctx.len = cur_pos as usize + r.accepted; dctx.len = cur_pos as usize + r.accepted;
rollback_spec(d, states, r.accepted)?; rollback_spec(d, states, r.accepted)?;
Ok((r.emit, cur_pos + r.accepted as i32, r.next_tok, r.done)) Ok((r.emit, cur_pos + r.accepted as i32, r.next_tok, r.done))
@@ -425,7 +516,7 @@ mod gpu {
} }
#[cfg(feature = "hip")] #[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 /// 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 /// verify loop). `greedy[i]` is the trunk argmax from feeding row i (anchor for
+25 -8
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)?; 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]. // w13 grouped GEMM: gather input tokens via bucket_tok -> gu [total, 2*inter].
let gu = DeviceBuf::alloc(total * 2 * inter * 4)?; 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)?; 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)?; 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 // 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). // (bucket_tok=None reads tok = beg+t0+m in-kernel; no host identity h2d sync).
let y_part = DeviceBuf::alloc(total * h * 4)?; 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. // Scatter-back + weighted reduce per token.
let moeout = DeviceBuf::alloc((b as usize) * h * 4)?; 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)?; 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, cache: &WeightCache, d: &Dims, tokens: &[i32], vocab: usize, max_seq: usize,
base_pos: i32, cap: f32, states: &mut [Option<LayerState>], base_pos: i32, cap: f32, states: &mut [Option<LayerState>],
) -> Result<DeviceBuf, String> { ) -> 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 /// 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>], base_pos: i32, cap: f32, states: &mut [Option<LayerState>],
taps_out: &mut [DeviceBuf; 4], taps_out: &mut [DeviceBuf; 4],
) -> Result<DeviceBuf, String> { ) -> 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( fn forward_batch_inner(
cache: &WeightCache, d: &Dims, tokens: &[i32], vocab: usize, max_seq: usize, cache: &WeightCache, d: &Dims, tokens: &[i32], vocab: usize, max_seq: usize,
base_pos: i32, cap: f32, states: &mut [Option<LayerState>], base_pos: i32, cap: f32, states: &mut [Option<LayerState>],
mut taps: Option<&mut [DeviceBuf; 4]>, mut taps: Option<&mut [DeviceBuf; 4]>, skip_unembed: bool,
) -> Result<DeviceBuf, String> { ) -> Result<Option<DeviceBuf>, String> {
let h = d.hidden; let bu = tokens.len(); let h = d.hidden; let bu = tokens.len();
if bu == 0 { return Err("forward_batch: empty tokens".into()); } if bu == 0 { return Err("forward_batch: empty tokens".into()); }
let b = bu as i32; let b = bu as i32;
@@ -1166,9 +1178,14 @@ fn forward_batch_inner(
let onorm = cache.bf16_f32("model.llm.norm.weight")?; 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)?; vetta_infer_hip::rms_norm_f32(&mix, Some(&onorm), &t[3], b, h as i32, d.eps)?;
} }
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 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)?; let l = unembed_logits(cache, &last, h, vocab, d.eps)?;
if cap > 0.0 { vetta_infer_hip::softcap(&logits, &logits, vocab, cap)?; } if cap > 0.0 { vetta_infer_hip::softcap(&l, &l, vocab, cap)?; }
Some(l)
};
if prof { if prof {
vetta_infer_hip::synchronize()?; vetta_infer_hip::synchronize()?;
let exp = EXPERT_NS.with(|c| c.replace(0)); 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 /// 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 /// 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. /// 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 { 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) 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() { } else if a.k % 64 == 0
// P1: FP16 WMMA tensor-core grouped GEMM (~8x fdot2 ALU throughput). NVFP4 && (b > 12 || std::env::var("VETTA_FORCE_MOE_WMMA").is_ok())
// E2M1 dequant is exact in f16; only the f32 accumulation order differs && std::env::var("VETTA_NO_MOE_WMMA").is_err()
// (~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. // 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) 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 { } 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) 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)
+25 -8
View File
@@ -132,12 +132,26 @@ Five ideas explain almost everything that will surprise you:
instead of hard-erroring past 16382 prompt tokens, and the window is instead of hard-erroring past 16382 prompt tokens, and the window is
configurable (`serve --max-context N` / `VETTA_MAX_CONTEXT`, advertised in configurable (`serve --max-context N` / `VETTA_MAX_CONTEXT`, advertised in
READY). Verified live: a 16504-token prompt generates (previously ERR 0 tokens). READY). Verified live: a 16504-token prompt generates (previously ERR 0 tokens).
- **What is NOT done yet (the frontier):** speculative **drafter integration** - **DSpark speculative drafter landed at `strata` parity (2026-12-02, measured).**
(next), **layer streaming in DMA** (the hard one: `io_uring O_DIRECT` + Opt-in via `VETTA_SPEC=1` (lossless contract proven in `proofs/speculative_draft.lean`,
`hipHostRegister` SlabRing, Hot/Cold expert cache + lookahead prefetch), HIP 200-token `spec_lossless_gate` EXACT, multi-turn `PrefixCache` + `DsparkSnapshot`
graph capture (collapse per-token launches → near-zero host CPU), and the INT8 restore EXACT). All drafting runs 100% on GPU: single-pass base-unembed Top-512
`sf4_i8` fused MoE (the reference's further 2×/5-8× MoE axis). Correctness is screen (reads 922 MB `unembed` once per round), on-GPU Markov loop + candidate
already there; speed and memory streaming are the next axes. argmax (`<=32 B` D2H), 0-LDS Wave32 online-softmax block attention (regression-tested
at `c_len = 17_000`), M-tiled Wave32 router GEMV, zero-scratch small-M SWA GQA,
`fdot2` MoE for `b <= 12`, and an accepted-count EMA governor starting at `n_draft = 5`.
Measured on `gfx1150` (`Inkling-2-Mini`, `temperature=0`):
- **Rust coding prompt (`RingBuffer<T>`, 128 tok):** OFF **`6.83 tok/s`** →
`VETTA_SPEC=1` **`13.93 tok/s`** (**2.04×**, `n_draft=5`, 100% EXACT) vs
`strata-inkling --draft dspark` **`13.66 tok/s`** on the exact same prompt.
- **Short prose prompt (`"The capital of France is"`, 96 tok):** `nd=5` jumped from
**`4.58` → `9.09 tok/s`** (**+98.5%**); default adaptive EMA **`8.93 tok/s`** decode.
Full changelog & root-cause breakdown: `review/2026-12-02-fix-drafter-e-ottimizzazioni.md`.
- **What is NOT done yet (the frontier):** **layer streaming in DMA** (the hard one:
`io_uring O_DIRECT` + `hipHostRegister` SlabRing, Hot/Cold expert cache + lookahead
prefetch), HIP graph capture (collapse per-token launches → near-zero host CPU),
and the INT8 `sf4_i8` fused MoE (the reference's further 2×/5-8× MoE axis).
Correctness and speculative drafting are landed; DMA memory streaming is next.
## The road to the goal ## The road to the goal
@@ -159,8 +173,9 @@ on 2026-12-01 (see *Current state*). The path, in order:
57.8× measured); batched/chunked prefill ✅; WMMA MoE + BF16 dense + 57.8× measured); batched/chunked prefill ✅; WMMA MoE + BF16 dense +
flash-FA2 prefill ✅ (prefill 60→12.9 s measured); flat VRAM ✅; budget clamp flash-FA2 prefill ✅ (prefill 60→12.9 s measured); flat VRAM ✅; budget clamp
✅. Remaining: INT8 fused MoE, HIP graph capture (host CPU). ✅. Remaining: INT8 fused MoE, HIP graph capture (host CPU).
7. **Drafter + DMA layer streaming** — ⏳ next: speculative drafter integration, 7. **Drafter + DMA layer streaming** — ⏳ DSpark speculative drafter ✅ landed
then layer streaming in DMA (`io_uring O_DIRECT` + `hipHostRegister` SlabRing, (`13.93 tok/s` on Rust coding, 2.04× vs OFF, matching `strata-inkling`); next is
layer streaming in DMA (`io_uring O_DIRECT` + `hipHostRegister` SlabRing,
Hot/Cold expert cache + lookahead prefetch) — the hard memory frontier. Hot/Cold expert cache + lookahead prefetch) — the hard memory frontier.
8. **M3 Lyra co-processor** — remote drafting, semantic domain routing, 8. **M3 Lyra co-processor** — remote drafting, semantic domain routing,
domain-aware expert prefetch. domain-aware expert prefetch.
@@ -176,7 +191,9 @@ lean proofs/slab_ring_dma.lean
lean proofs/bus_lifecycle.lean lean proofs/bus_lifecycle.lean
lean proofs/serve_session.lean lean proofs/serve_session.lean
lean proofs/arena_plan.lean lean proofs/arena_plan.lean
lean proofs/inkling_loop.lean
lean proofs/prefix_cache.lean lean proofs/prefix_cache.lean
lean proofs/speculative_draft.lean
# Opt-in live tests against the real Inkling artifact: # Opt-in live tests against the real Inkling artifact:
cargo test -p vetta-infer-ld -- --ignored inkling cargo test -p vetta-infer-ld -- --ignored inkling
+667 -51
View File
@@ -147,6 +147,20 @@ extern "C" int vetta_rms_norm_f32(const float* x, const float* w, float* y,
return 0; return 0;
} }
// ---- BF16 & Wave32 helpers (shared across DSpark, router, MoE kernels) -----
__device__ __forceinline__ float bf16_to_f32(uint16_t h) {
return __uint_as_float(((uint32_t)h) << 16);
}
// DPP-accelerated wave32 sum (gfx11): 2 DPP moves + 3 shfl instead of 5 shfl.
__device__ __forceinline__ float wave32_sum(float v) {
v += __builtin_bit_cast(float, __builtin_amdgcn_mov_dpp(__builtin_bit_cast(int, v), 0xB1, 0xf, 0xf, true));
v += __builtin_bit_cast(float, __builtin_amdgcn_mov_dpp(__builtin_bit_cast(int, v), 0x4E, 0xf, 0xf, true));
v += __shfl_xor(v, 4, 32);
v += __shfl_xor(v, 8, 32);
v += __shfl_xor(v, 16, 32);
return v;
}
// ---- DSpark drafter: mix 4 taps + RMSNorm, and per-head RMSNorm + NeoX RoPE -- // ---- DSpark drafter: mix 4 taps + RMSNorm, and per-head RMSNorm + NeoX RoPE --
// Exact port of strata k_dspark_mix_taps / k_dspark_rmsnorm_rope (f32 throughout; // Exact port of strata k_dspark_mix_taps / k_dspark_rmsnorm_rope (f32 throughout;
// the bf16 store happens in the caller). NeoX half-split pairs (d, d+hd/2). // the bf16 store happens in the caller). NeoX half-split pairs (d, d+hd/2).
@@ -254,9 +268,65 @@ extern "C" int vetta_dspark_rmsnorm_rope(float* x, const float* nw,
// Non-causal DSpark block attention: each of the B draft query slots attends to // Non-causal DSpark block attention: each of the B draft query slots attends to
// the committed ctx window [c0, c0+c_len) (bf16 ring, slot=pos%cap) PLUS ALL B // the committed ctx window [c0, c0+c_len) (bf16 ring, slot=pos%cap) PLUS ALL B
// draft keys/values (f32). GQA n_rep=H/KV. One block per (qi,hh); dynamic shared // draft keys/values (f32). GQA n_rep=H/KV.
// holds tot_k scores + hd reduction scratch. Exact port of the reference loop. // Fast Wave32 online-softmax path for hd==128: ZERO shared memory scores array
__device__ __forceinline__ float bf16_to_f32(uint16_t h); // defined below // (eliminates the 64 KiB LDS crash on global layer 1 above ~16,248 tokens!) +
// vectorized float4/uint2 loads + DPP wave32_sum (~4-8x faster than scalar).
__global__ void __launch_bounds__(128) k_dspark_block_attn_w32(
const float* __restrict__ q, const float* __restrict__ kd,
const float* __restrict__ vd, const uint16_t* __restrict__ ck,
const uint16_t* __restrict__ cv, float* __restrict__ out,
int B, int H, int KV, int c0, int c_len, int cap,
float scale, int n_rep) {
const int wave = threadIdx.x >> 5;
const int lane = threadIdx.x & 31;
const int hh = blockIdx.x * 4 + wave;
const int qi = blockIdx.y;
if (hh >= H || qi >= B) return;
const int d0 = lane * 4;
const int kvh = hh / n_rep;
const float4 qv = *reinterpret_cast<const float4*>(q + ((size_t)qi * H + hh) * 128 + d0);
const float q0 = qv.x * scale, q1 = qv.y * scale, q2 = qv.z * scale, q3 = qv.w * scale;
float max_l = -1e30f;
float sum_e = 0.0f;
float o0 = 0.0f, o1 = 0.0f, o2 = 0.0f, o3 = 0.0f;
const int tot = c_len + B;
for (int t = 0; t < tot; ++t) {
float k0, k1, k2, k3, v0, v1, v2, v3;
if (t < c_len) {
const int slot = ((c0 + t) % cap + cap) % cap;
const size_t idx = ((size_t)slot * KV + kvh) * 128 + d0;
const uint2 kw = *reinterpret_cast<const uint2*>(ck + idx);
const uint2 vw = *reinterpret_cast<const uint2*>(cv + idx);
k0 = bf16_to_f32(kw.x & 0xFFFFu); k1 = bf16_to_f32(kw.x >> 16);
k2 = bf16_to_f32(kw.y & 0xFFFFu); k3 = bf16_to_f32(kw.y >> 16);
v0 = bf16_to_f32(vw.x & 0xFFFFu); v1 = bf16_to_f32(vw.x >> 16);
v2 = bf16_to_f32(vw.y & 0xFFFFu); v3 = bf16_to_f32(vw.y >> 16);
} else {
const int di = t - c_len;
const size_t idx = ((size_t)di * KV + kvh) * 128 + d0;
const float4 kw = *reinterpret_cast<const float4*>(kd + idx);
const float4 vw = *reinterpret_cast<const float4*>(vd + idx);
k0 = kw.x; k1 = kw.y; k2 = kw.z; k3 = kw.w;
v0 = vw.x; v1 = vw.y; v2 = vw.z; v3 = vw.w;
}
const float sc = wave32_sum(fmaf(q0, k0, fmaf(q1, k1, fmaf(q2, k2, q3 * k3))));
const float nm = fmaxf(max_l, sc);
const float a = expf(max_l - nm);
const float b = expf(sc - nm);
o0 = fmaf(o0, a, b * v0); o1 = fmaf(o1, a, b * v1);
o2 = fmaf(o2, a, b * v2); o3 = fmaf(o3, a, b * v3);
sum_e = fmaf(sum_e, a, b);
max_l = nm;
}
const float inv = 1.0f / fmaxf(sum_e, 1e-30f);
*reinterpret_cast<float4*>(out + ((size_t)qi * H + hh) * 128 + d0) =
make_float4(o0 * inv, o1 * inv, o2 * inv, o3 * inv);
}
// Generic fallback for synthetic hd != 128 tests.
__global__ void k_dspark_block_attn( __global__ void k_dspark_block_attn(
const float* __restrict__ q, const float* __restrict__ kd, const float* __restrict__ q, const float* __restrict__ kd,
const float* __restrict__ vd, const uint16_t* __restrict__ ck, const float* __restrict__ vd, const uint16_t* __restrict__ ck,
@@ -277,7 +347,7 @@ __global__ void k_dspark_block_attn(
for (int t = tid; t < tot_k; t += nt) { for (int t = tid; t < tot_k; t += nt) {
float dot = 0.f; float dot = 0.f;
if (t < c_len) { if (t < c_len) {
const uint16_t* kp = ck + (((size_t)((c0 + t) % cap) * KV + kvh) * hd); const uint16_t* kp = ck + (((size_t)(((c0 + t) % cap + cap) % cap) * KV + kvh) * hd);
for (int j = 0; j < hd; ++j) dot += qv[j] * bf16_to_f32(kp[j]); for (int j = 0; j < hd; ++j) dot += qv[j] * bf16_to_f32(kp[j]);
} else { } else {
const float* kp = kd + (((size_t)(t - c_len) * KV + kvh) * hd); const float* kp = kd + (((size_t)(t - c_len) * KV + kvh) * hd);
@@ -313,7 +383,7 @@ __global__ void k_dspark_block_attn(
for (int d = tid; d < hd; d += nt) { for (int d = tid; d < hd; d += nt) {
float acc = 0.f; float acc = 0.f;
for (int t = 0; t < c_len; ++t) { for (int t = 0; t < c_len; ++t) {
const uint16_t* vp = cv + (((size_t)((c0 + t) % cap) * KV + kvh) * hd); const uint16_t* vp = cv + (((size_t)(((c0 + t) % cap + cap) % cap) * KV + kvh) * hd);
acc += sc[t] * inv * bf16_to_f32(vp[d]); acc += sc[t] * inv * bf16_to_f32(vp[d]);
} }
for (int di = 0; di < B; ++di) { for (int di = 0; di < B; ++di) {
@@ -331,9 +401,16 @@ extern "C" int vetta_dspark_block_attn(
float scale, vetta_stream_t stream) { float scale, vetta_stream_t stream) {
if (B <= 0 || H <= 0 || KV <= 0 || hd <= 0 || hd > 128 || H % KV != 0) return 1; if (B <= 0 || H <= 0 || KV <= 0 || hd <= 0 || hd > 128 || H % KV != 0) return 1;
const int n_rep = H / KV; const int n_rep = H / KV;
hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0;
if (hd == 128) {
dim3 grid((H + 3) / 4, B);
k_dspark_block_attn_w32<<<grid, 128, 0, s>>>(q, kd, vd, ck, cv, out, B, H, KV,
c0, c_len, cap, scale, n_rep);
HIP_CHECK(hipGetLastError());
return 0;
}
const int tot_k = c_len + B; const int tot_k = c_len + B;
const size_t sh = (size_t)(tot_k + hd) * 4; const size_t sh = (size_t)(tot_k + hd) * 4;
hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0;
k_dspark_block_attn<<<B * H, hd, sh, s>>>(q, kd, vd, ck, cv, out, B, H, KV, k_dspark_block_attn<<<B * H, hd, sh, s>>>(q, kd, vd, ck, cv, out, B, H, KV,
hd, c0, c_len, cap, scale, n_rep); hd, c0, c_len, cap, scale, n_rep);
HIP_CHECK(hipGetLastError()); HIP_CHECK(hipGetLastError());
@@ -477,11 +554,7 @@ extern "C" int vetta_dspark_scatter_bf16(const float* src, uint16_t* dst,
return 0; return 0;
} }
// ---- BF16 helpers ---------------------------------------------------------- // ---- BF16/FP16 rounding helpers (bf16_to_f32 defined at top) ---------------
__device__ __forceinline__ float bf16_to_f32(uint16_t h) {
return __uint_as_float(((uint32_t)h) << 16);
}
// round-to-nearest-even f32 -> bf16 -> f32 (exact strata f32_to_bf16 round trip). // round-to-nearest-even f32 -> bf16 -> f32 (exact strata f32_to_bf16 round trip).
__device__ __forceinline__ float bf16_round(float f) { __device__ __forceinline__ float bf16_round(float f) {
@@ -1080,58 +1153,98 @@ extern "C" int vetta_gather_channel(const float* msgs, float* dst, int ch, int B
// (NOT bf16-rounded) against the bf16 gate weight promoted to f32. Rounding the // (NOT bf16-rounded) against the bf16 gate weight promoted to f32. Rounding the
// router input to bf16 flips top-k expert selection -> large MoE divergence. // router input to bf16 flips top-k expert selection -> large MoE divergence.
__global__ void k_router_gemv(const float* __restrict__ x, // ---- k_router_gemv & k_router_gemv_batched: Wave32 vectorized F32 x BF16 ----
const uint16_t* __restrict__ w, // 8 waves/block (1 wave per output row n), uint4 (8 BF16) + 2x float4 loads,
// DPP wave32_sum (zero shared memory). Batched path tiles M by 8 so each wave
// reads W[n,:] ONCE across up to 8 tokens (8x less weight bandwidth for DSpark
// B=8 layers and trunk router!), while preserving the exact per-(m,n) lane
// accumulation order of k_router_gemv (bit-exact parity).
__global__ void __launch_bounds__(256) k_router_gemv(
const float* __restrict__ x, const uint16_t* __restrict__ w,
float* __restrict__ y, int N, int K) { float* __restrict__ y, int N, int K) {
const int n = blockIdx.x; const int wave = threadIdx.x >> 5;
const int lane = threadIdx.x & 31;
const int n = blockIdx.x * 8 + wave;
if (n >= N) return; if (n >= N) return;
const int tid = threadIdx.x;
const int nt = blockDim.x;
const uint16_t* wr = w + (size_t)n * K; const uint16_t* wr = w + (size_t)n * K;
const int k8 = K & ~7;
float acc = 0.f; float acc = 0.f;
for (int kk = tid; kk < K; kk += nt) acc += x[kk] * bf16_to_f32(wr[kk]); for (int kk = lane * 8; kk < k8; kk += 256) {
__shared__ float red[256]; const uint4 w8 = *reinterpret_cast<const uint4*>(wr + kk);
red[tid] = acc; const float4 x0 = *reinterpret_cast<const float4*>(x + kk);
__syncthreads(); const float4 x1 = *reinterpret_cast<const float4*>(x + kk + 4);
for (int s = nt / 2; s > 0; s >>= 1) { if (tid < s) red[tid] += red[tid + s]; __syncthreads(); } acc = fmaf(bf16_to_f32(w8.x & 0xFFFFu), x0.x, fmaf(bf16_to_f32(w8.x >> 16), x0.y, acc));
if (tid == 0) y[n] = red[0]; acc = fmaf(bf16_to_f32(w8.y & 0xFFFFu), x0.z, fmaf(bf16_to_f32(w8.y >> 16), x0.w, acc));
acc = fmaf(bf16_to_f32(w8.z & 0xFFFFu), x1.x, fmaf(bf16_to_f32(w8.z >> 16), x1.y, acc));
acc = fmaf(bf16_to_f32(w8.w & 0xFFFFu), x1.z, fmaf(bf16_to_f32(w8.w >> 16), x1.w, acc));
}
for (int kk = k8 + lane; kk < K; kk += 32) {
acc = fmaf(bf16_to_f32(wr[kk]), x[kk], acc);
}
acc = wave32_sum(acc);
if (lane == 0) y[n] = acc;
} }
extern "C" int vetta_router_gemv(const float* x, const uint16_t* w, float* y, extern "C" int vetta_router_gemv(const float* x, const uint16_t* w, float* y,
int N, int K, vetta_stream_t stream) { int N, int K, vetta_stream_t stream) {
if (N <= 0 || K <= 0) return 1; if (N <= 0 || K <= 0) return 1;
hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0;
k_router_gemv<<<N, 256, 0, s>>>(x, w, y, N, K); k_router_gemv<<<(N + 7) / 8, 256, 0, s>>>(x, w, y, N, K);
HIP_CHECK(hipGetLastError()); HIP_CHECK(hipGetLastError());
return 0; return 0;
} }
// ---- k_router_gemv_batched: f32 router logits for M tokens ------------------ __global__ void __launch_bounds__(256) k_router_gemv_batched(
// x [M,K] f32 (router reads F32 mlpin, exact strata launch_f32_linear), w [N,K] const float* __restrict__ x, const uint16_t* __restrict__ w,
// bf16, y [M,N]. grid (N, M); block (n,m) reduces x[m,:]·w[n,:].
__global__ void k_router_gemv_batched(const float* __restrict__ x,
const uint16_t* __restrict__ w,
float* __restrict__ y, int N, int K, int M) { float* __restrict__ y, int N, int K, int M) {
const int n = blockIdx.x; const int wave = threadIdx.x >> 5;
const int m = blockIdx.y; const int lane = threadIdx.x & 31;
if (n >= N || m >= M) return; const int n = blockIdx.x * 8 + wave;
const int tid = threadIdx.x; const int m0 = blockIdx.y * 8;
const int nt = blockDim.x; if (n >= N || m0 >= M) return;
const int tm = (M - m0 < 8) ? (M - m0) : 8;
const uint16_t* wr = w + (size_t)n * K; const uint16_t* wr = w + (size_t)n * K;
const float* xr = x + (size_t)m * K; const int k8 = K & ~7;
float acc = 0.f; float acc[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
for (int kk = tid; kk < K; kk += nt) acc += xr[kk] * bf16_to_f32(wr[kk]); for (int kk = lane * 8; kk < k8; kk += 256) {
__shared__ float red[256]; const uint4 w8 = *reinterpret_cast<const uint4*>(wr + kk);
red[tid] = acc; const float f0 = bf16_to_f32(w8.x & 0xFFFFu), f1 = bf16_to_f32(w8.x >> 16);
__syncthreads(); const float f2 = bf16_to_f32(w8.y & 0xFFFFu), f3 = bf16_to_f32(w8.y >> 16);
for (int s = nt / 2; s > 0; s >>= 1) { if (tid < s) red[tid] += red[tid + s]; __syncthreads(); } const float f4 = bf16_to_f32(w8.z & 0xFFFFu), f5 = bf16_to_f32(w8.z >> 16);
if (tid == 0) y[(size_t)m * N + n] = red[0]; const float f6 = bf16_to_f32(w8.w & 0xFFFFu), f7 = bf16_to_f32(w8.w >> 16);
#pragma unroll
for (int mi = 0; mi < 8; ++mi) {
if (mi < tm) {
const float* xr = x + (size_t)(m0 + mi) * K + kk;
const float4 x0 = *reinterpret_cast<const float4*>(xr);
const float4 x1 = *reinterpret_cast<const float4*>(xr + 4);
acc[mi] = fmaf(f0, x0.x, fmaf(f1, x0.y, acc[mi]));
acc[mi] = fmaf(f2, x0.z, fmaf(f3, x0.w, acc[mi]));
acc[mi] = fmaf(f4, x1.x, fmaf(f5, x1.y, acc[mi]));
acc[mi] = fmaf(f6, x1.z, fmaf(f7, x1.w, acc[mi]));
}
}
}
for (int kk = k8 + lane; kk < K; kk += 32) {
const float fv = bf16_to_f32(wr[kk]);
#pragma unroll
for (int mi = 0; mi < 8; ++mi) {
if (mi < tm) acc[mi] = fmaf(fv, x[(size_t)(m0 + mi) * K + kk], acc[mi]);
}
}
#pragma unroll
for (int mi = 0; mi < 8; ++mi) {
if (mi < tm) {
const float sum = wave32_sum(acc[mi]);
if (lane == 0) y[(size_t)(m0 + mi) * N + n] = sum;
}
}
} }
extern "C" int vetta_router_gemv_batched(const float* x, const uint16_t* w, float* y, extern "C" int vetta_router_gemv_batched(const float* x, const uint16_t* w, float* y,
int N, int K, int M, vetta_stream_t stream) { int N, int K, int M, vetta_stream_t stream) {
if (N <= 0 || K <= 0 || M <= 0) return 1; if (N <= 0 || K <= 0 || M <= 0) return 1;
dim3 grid(N, M); dim3 grid((N + 7) / 8, (M + 7) / 8);
hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0;
k_router_gemv_batched<<<grid, 256, 0, s>>>(x, w, y, N, K, M); k_router_gemv_batched<<<grid, 256, 0, s>>>(x, w, y, N, K, M);
HIP_CHECK(hipGetLastError()); HIP_CHECK(hipGetLastError());
@@ -1228,15 +1341,7 @@ __device__ __forceinline__ float fdot2_f32(uint32_t a, uint32_t b, float c) {
return __builtin_amdgcn_fdot2(__builtin_bit_cast(__half2, a), return __builtin_amdgcn_fdot2(__builtin_bit_cast(__half2, a),
__builtin_bit_cast(__half2, b), c, false); __builtin_bit_cast(__half2, b), c, false);
} }
// DPP-accelerated wave32 sum (gfx11): 2 DPP moves + 3 shfl instead of 5 shfl. // (wave32_sum defined at top of file)
__device__ __forceinline__ float wave32_sum(float v) {
v += __builtin_bit_cast(float, __builtin_amdgcn_mov_dpp(__builtin_bit_cast(int, v), 0xB1, 0xf, 0xf, true));
v += __builtin_bit_cast(float, __builtin_amdgcn_mov_dpp(__builtin_bit_cast(int, v), 0x4E, 0xf, 0xf, true));
v += __shfl_xor(v, 4, 32);
v += __shfl_xor(v, 8, 32);
v += __shfl_xor(v, 16, 32);
return v;
}
// ---- RDNA3.5 (gfx11) FP16 WMMA tensor-core helpers ------------------------- // ---- RDNA3.5 (gfx11) FP16 WMMA tensor-core helpers -------------------------
// 16x16x16 f16->f32 matrix tile. The f16 product is exact in f32; only the // 16x16x16 f16->f32 matrix tile. The f16 product is exact in f32; only the
@@ -3081,3 +3186,514 @@ extern "C" int vetta_flash_swa_gqa_prefill_wmma(const float* q, const uint16_t*
HIP_CHECK(hipGetLastError()); HIP_CHECK(hipGetLastError());
return 0; return 0;
} }
// ============================================================================
// Fast On-GPU DSpark Drafting & Batched Verify Argmax (zero mid-loop host syncs)
// ============================================================================
// Single-pass base-unembed Top-2-per-block screen across ALL n_draft <= 7 steps!
// Reads unembed_bf16[V, D] ONCE (~922 MB) instead of n_draft times (~4.6-6.5 GB).
// cur_steps [n_draft, D] (f32) is <= 64 KB so it stays L1/L2 resident with zero
// LDS pressure and exact F32 precision. Grid = 256 blocks -> 512 candidates/step.
// When V <= 512 (unit tests), scores all V tokens directly into cand_val/cand_id.
__global__ void __launch_bounds__(256) k_dspark_base_top2_screen(
const uint16_t* __restrict__ unembed_bf16, // [V, D]
const float* __restrict__ cur_steps, // [n_draft, D] (cur + D)
float* __restrict__ cand_val, // [n_draft, n_cand]
int32_t* __restrict__ cand_id, // [n_draft, n_cand]
int n_draft, int D, int V, int n_cand) {
const int tid = threadIdx.x;
const int wave = tid >> 5;
const int lane = tid & 31;
const int k8 = D & ~7;
if (V <= n_cand) {
// Small-vocab exact mode (e.g. unit test V=512): score every token v < V.
const int v = blockIdx.x * 8 + wave;
if (v >= n_cand) return;
if (v >= V) {
if (lane == 0) {
for (int t = 0; t < n_draft; ++t) {
cand_val[(size_t)t * n_cand + v] = -1e30f;
cand_id[(size_t)t * n_cand + v] = -1;
}
}
return;
}
const uint16_t* wr = unembed_bf16 + (size_t)v * D;
float acc[7] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
for (int kk = lane * 8; kk < k8; kk += 256) {
const uint4 w8 = *reinterpret_cast<const uint4*>(wr + kk);
const float f0 = bf16_to_f32(w8.x & 0xFFFFu), f1 = bf16_to_f32(w8.x >> 16);
const float f2 = bf16_to_f32(w8.y & 0xFFFFu), f3 = bf16_to_f32(w8.y >> 16);
const float f4 = bf16_to_f32(w8.z & 0xFFFFu), f5 = bf16_to_f32(w8.z >> 16);
const float f6 = bf16_to_f32(w8.w & 0xFFFFu), f7 = bf16_to_f32(w8.w >> 16);
#pragma unroll
for (int t = 0; t < 7; ++t) {
if (t < n_draft) {
const float* cr = cur_steps + (size_t)t * D + kk;
const float4 x0 = *reinterpret_cast<const float4*>(cr);
const float4 x1 = *reinterpret_cast<const float4*>(cr + 4);
acc[t] = fmaf(f0, x0.x, fmaf(f1, x0.y, acc[t]));
acc[t] = fmaf(f2, x0.z, fmaf(f3, x0.w, acc[t]));
acc[t] = fmaf(f4, x1.x, fmaf(f5, x1.y, acc[t]));
acc[t] = fmaf(f6, x1.z, fmaf(f7, x1.w, acc[t]));
}
}
}
for (int kk = k8 + lane; kk < D; kk += 32) {
const float fv = bf16_to_f32(wr[kk]);
#pragma unroll
for (int t = 0; t < 7; ++t) {
if (t < n_draft) acc[t] = fmaf(fv, cur_steps[(size_t)t * D + kk], acc[t]);
}
}
#pragma unroll
for (int t = 0; t < 7; ++t) {
if (t < n_draft) {
const float z = wave32_sum(acc[t]);
if (lane == 0) {
cand_val[(size_t)t * n_cand + v] = z;
cand_id[(size_t)t * n_cand + v] = v;
}
}
}
return;
}
float best1_v[7], best2_v[7];
int32_t best1_i[7], best2_i[7];
#pragma unroll
for (int t = 0; t < 7; ++t) {
best1_v[t] = -1e30f; best2_v[t] = -1e30f;
best1_i[t] = -1; best2_i[t] = -1;
}
const int stride = gridDim.x * 8;
for (int v = blockIdx.x * 8 + wave; v < V; v += stride) {
const uint16_t* wr = unembed_bf16 + (size_t)v * D;
float acc[7] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
for (int kk = lane * 8; kk < k8; kk += 256) {
const uint4 w8 = *reinterpret_cast<const uint4*>(wr + kk);
const float f0 = bf16_to_f32(w8.x & 0xFFFFu), f1 = bf16_to_f32(w8.x >> 16);
const float f2 = bf16_to_f32(w8.y & 0xFFFFu), f3 = bf16_to_f32(w8.y >> 16);
const float f4 = bf16_to_f32(w8.z & 0xFFFFu), f5 = bf16_to_f32(w8.z >> 16);
const float f6 = bf16_to_f32(w8.w & 0xFFFFu), f7 = bf16_to_f32(w8.w >> 16);
#pragma unroll
for (int t = 0; t < 7; ++t) {
if (t < n_draft) {
const float* cr = cur_steps + (size_t)t * D + kk;
const float4 x0 = *reinterpret_cast<const float4*>(cr);
const float4 x1 = *reinterpret_cast<const float4*>(cr + 4);
acc[t] = fmaf(f0, x0.x, fmaf(f1, x0.y, acc[t]));
acc[t] = fmaf(f2, x0.z, fmaf(f3, x0.w, acc[t]));
acc[t] = fmaf(f4, x1.x, fmaf(f5, x1.y, acc[t]));
acc[t] = fmaf(f6, x1.z, fmaf(f7, x1.w, acc[t]));
}
}
}
for (int kk = k8 + lane; kk < D; kk += 32) {
const float fv = bf16_to_f32(wr[kk]);
#pragma unroll
for (int t = 0; t < 7; ++t) {
if (t < n_draft) acc[t] = fmaf(fv, cur_steps[(size_t)t * D + kk], acc[t]);
}
}
#pragma unroll
for (int t = 0; t < 7; ++t) {
if (t < n_draft) {
const float z = wave32_sum(acc[t]);
if (lane == 0) {
if (z > best1_v[t]) {
best2_v[t] = best1_v[t]; best2_i[t] = best1_i[t];
best1_v[t] = z; best1_i[t] = v;
} else if (z > best2_v[t]) {
best2_v[t] = z; best2_i[t] = v;
}
}
}
}
}
__shared__ float s_v[7][16];
__shared__ int32_t s_i[7][16];
if (lane == 0) {
for (int t = 0; t < n_draft; ++t) {
s_v[t][wave * 2 + 0] = best1_v[t]; s_i[t][wave * 2 + 0] = best1_i[t];
s_v[t][wave * 2 + 1] = best2_v[t]; s_i[t][wave * 2 + 1] = best2_i[t];
}
}
__syncthreads();
if (tid < n_draft) {
float b1v = -1e30f, b2v = -1e30f;
int32_t b1i = -1, b2i = -1;
for (int j = 0; j < 16; ++j) {
const float z = s_v[tid][j];
const int32_t id = s_i[tid][j];
if (z > b1v) {
b2v = b1v; b2i = b1i;
b1v = z; b1i = id;
} else if (z > b2v) {
b2v = z; b2i = id;
}
}
cand_val[(size_t)tid * n_cand + blockIdx.x * 2 + 0] = b1v;
cand_id[(size_t)tid * n_cand + blockIdx.x * 2 + 0] = b1i;
cand_val[(size_t)tid * n_cand + blockIdx.x * 2 + 1] = b2v;
cand_id[(size_t)tid * n_cand + blockIdx.x * 2 + 1] = b2i;
}
}
extern "C" int vetta_dspark_base_top2_screen(
const uint16_t* unembed_bf16, const float* cur_steps,
float* cand_val, int32_t* cand_id,
int n_draft, int D, int V, int n_cand, vetta_stream_t stream) {
if (n_draft <= 0 || n_draft > 7 || D <= 0 || V <= 0 || n_cand <= 0) return 1;
hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0;
const int n_blks = (V <= n_cand) ? ((n_cand + 7) / 8) : (n_cand / 2);
k_dspark_base_top2_screen<<<n_blks, 256, 0, s>>>(
unembed_bf16, cur_steps, cand_val, cand_id, n_draft, D, V, n_cand);
HIP_CHECK(hipGetLastError());
return 0;
}
// On-GPU Markov RNN projection + GRU state update (zero host round-trips!).
// Reads *prev_tok_ptr on device, gathers markov_w1[prev_tok] (BF16) and
// frnn_ring[frnn_slot] (BF16), computes 3*rank rows of rnn_proj_w (BF16).
__global__ void __launch_bounds__(256) k_dspark_markov_proj_bf16(
const int32_t* __restrict__ prev_tok_ptr, // [1] device token id
const float* __restrict__ state_in, // [rank]
float* __restrict__ state_out, // [rank]
float* __restrict__ latent_out, // [rank]
const float* __restrict__ cur_step, // [D] f32
const uint16_t* __restrict__ frnn_ring, // [frnn_cap, D] bf16
int frnn_slot,
const uint16_t* __restrict__ markov_w1, // [V_pad, rank] bf16
const uint16_t* __restrict__ rnn_proj_w, // [3*rank, 2*rank + 2*D] bf16
const float* __restrict__ rnn_proj_b, // [3*rank] f32
int D, int rank) {
const int wave = threadIdx.x >> 5;
const int lane = threadIdx.x & 31;
const int r = blockIdx.x * 8 + wave;
if (r >= rank) return;
const int prev_tok = *prev_tok_ptr;
const int in_dim = 2 * rank + 2 * D;
const uint16_t* mw_row = markov_w1 + (size_t)prev_tok * rank;
const uint16_t* fr_row = frnn_ring + (size_t)frnn_slot * D;
const uint16_t* w0 = rnn_proj_w + (size_t)r * in_dim;
const uint16_t* w1 = rnn_proj_w + (size_t)(rank + r) * in_dim;
const uint16_t* w2 = rnn_proj_w + (size_t)(2 * rank + r) * in_dim;
auto dot4_bf_f4 = [](uint2 w4, float4 xv, float acc) -> float {
acc = fmaf(bf16_to_f32(w4.x & 0xFFFFu), xv.x, acc);
acc = fmaf(bf16_to_f32(w4.x >> 16), xv.y, acc);
acc = fmaf(bf16_to_f32(w4.y & 0xFFFFu), xv.z, acc);
acc = fmaf(bf16_to_f32(w4.y >> 16), xv.w, acc);
return acc;
};
auto dot4_bf_bf = [](uint2 w4, uint2 x4, float acc) -> float {
acc = fmaf(bf16_to_f32(w4.x & 0xFFFFu), bf16_to_f32(x4.x & 0xFFFFu), acc);
acc = fmaf(bf16_to_f32(w4.x >> 16), bf16_to_f32(x4.x >> 16), acc);
acc = fmaf(bf16_to_f32(w4.y & 0xFFFFu), bf16_to_f32(x4.y & 0xFFFFu), acc);
acc = fmaf(bf16_to_f32(w4.y >> 16), bf16_to_f32(x4.y >> 16), acc);
return acc;
};
float d0 = 0.f, d1 = 0.f, d2 = 0.f;
for (int i = lane * 4; i < rank; i += 128) {
const float4 sv = *reinterpret_cast<const float4*>(state_in + i);
const uint2 mv = *reinterpret_cast<const uint2*>(mw_row + i);
d0 = dot4_bf_f4(*reinterpret_cast<const uint2*>(w0 + i), sv,
dot4_bf_bf(*reinterpret_cast<const uint2*>(w0 + rank + i), mv, d0));
d1 = dot4_bf_f4(*reinterpret_cast<const uint2*>(w1 + i), sv,
dot4_bf_bf(*reinterpret_cast<const uint2*>(w1 + rank + i), mv, d1));
d2 = dot4_bf_f4(*reinterpret_cast<const uint2*>(w2 + i), sv,
dot4_bf_bf(*reinterpret_cast<const uint2*>(w2 + rank + i), mv, d2));
}
const int off_h = 2 * rank;
const int off_c = 2 * rank + D;
for (int i = lane * 4; i < D; i += 128) {
const float4 hv = *reinterpret_cast<const float4*>(cur_step + i);
const uint2 cv = *reinterpret_cast<const uint2*>(fr_row + i);
d0 = dot4_bf_f4(*reinterpret_cast<const uint2*>(w0 + off_h + i), hv,
dot4_bf_bf(*reinterpret_cast<const uint2*>(w0 + off_c + i), cv, d0));
d1 = dot4_bf_f4(*reinterpret_cast<const uint2*>(w1 + off_h + i), hv,
dot4_bf_bf(*reinterpret_cast<const uint2*>(w1 + off_c + i), cv, d1));
d2 = dot4_bf_f4(*reinterpret_cast<const uint2*>(w2 + off_h + i), hv,
dot4_bf_bf(*reinterpret_cast<const uint2*>(w2 + off_c + i), cv, d2));
}
d0 = wave32_sum(d0) + rnn_proj_b[r];
d1 = wave32_sum(d1) + rnn_proj_b[rank + r];
d2 = wave32_sum(d2) + rnn_proj_b[2 * rank + r];
if (lane == 0) {
const float gate = 1.0f / (1.0f + expf(-d0));
const float cand = tanhf(d1);
state_out[r] = fmaf(gate, state_in[r] - cand, cand);
latent_out[r] = tanhf(d2);
}
}
extern "C" int vetta_dspark_markov_proj_bf16(
const int32_t* prev_tok_ptr, const float* state_in, float* state_out,
float* latent_out, const float* cur_step, const uint16_t* frnn_ring,
int frnn_slot, const uint16_t* markov_w1, const uint16_t* rnn_proj_w,
const float* rnn_proj_b, int D, int rank, vetta_stream_t stream) {
if (D <= 0 || rank <= 0 || (D & 3) != 0 || (rank & 3) != 0) return 1;
hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0;
k_dspark_markov_proj_bf16<<<(rank + 7) / 8, 256, 0, s>>>(
prev_tok_ptr, state_in, state_out, latent_out, cur_step, frnn_ring,
frnn_slot, markov_w1, rnn_proj_w, rnn_proj_b, D, rank);
HIP_CHECK(hipGetLastError());
return 0;
}
// On-GPU Markov correction vector: corr[d] = dot(hidden_out_w[d], latent) + bias[d].
__global__ void __launch_bounds__(256) k_dspark_markov_corr_bf16(
const float* __restrict__ latent, // [rank]
const uint16_t* __restrict__ hidden_out_w, // [D, rank] bf16
const float* __restrict__ hidden_out_b, // [D] f32
float* __restrict__ corr_out, // [D] f32
int D, int rank) {
const int wave = threadIdx.x >> 5;
const int lane = threadIdx.x & 31;
const int d = blockIdx.x * 8 + wave;
if (d >= D) return;
const uint16_t* wh = hidden_out_w + (size_t)d * rank;
float acc = 0.f;
for (int r = lane * 8; r < rank; r += 256) {
const uint4 w8 = *reinterpret_cast<const uint4*>(wh + r);
const float4 l0 = *reinterpret_cast<const float4*>(latent + r);
const float4 l1 = *reinterpret_cast<const float4*>(latent + r + 4);
acc = fmaf(bf16_to_f32(w8.x & 0xFFFFu), l0.x, fmaf(bf16_to_f32(w8.x >> 16), l0.y, acc));
acc = fmaf(bf16_to_f32(w8.y & 0xFFFFu), l0.z, fmaf(bf16_to_f32(w8.y >> 16), l0.w, acc));
acc = fmaf(bf16_to_f32(w8.z & 0xFFFFu), l1.x, fmaf(bf16_to_f32(w8.z >> 16), l1.y, acc));
acc = fmaf(bf16_to_f32(w8.w & 0xFFFFu), l1.z, fmaf(bf16_to_f32(w8.w >> 16), l1.w, acc));
}
acc = wave32_sum(acc) + hidden_out_b[d];
if (lane == 0) corr_out[d] = acc;
}
extern "C" int vetta_dspark_markov_corr_bf16(
const float* latent, const uint16_t* hidden_out_w, const float* hidden_out_b,
float* corr_out, int D, int rank, vetta_stream_t stream) {
if (D <= 0 || rank <= 0 || (rank & 7) != 0) return 1;
hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0;
k_dspark_markov_corr_bf16<<<(D + 7) / 8, 256, 0, s>>>(
latent, hidden_out_w, hidden_out_b, corr_out, D, rank);
HIP_CHECK(hipGetLastError());
return 0;
}
// On-GPU 512-candidate scorer + 2-stage deterministic argmax -> writes winning
// token id directly into *out_tok on device (zero logits D2H!).
__global__ void __launch_bounds__(256) k_dspark_cand_argmax_s1(
const uint16_t* __restrict__ unembed_bf16, // [V, D]
const float* __restrict__ cand_base_val, // [n_cand]
const int32_t* __restrict__ cand_id, // [n_cand]
const float* __restrict__ corr, // [D]
float* __restrict__ blk_val, // [gridDim.x]
int32_t* __restrict__ blk_id, // [gridDim.x]
int n_cand, int D, int V) {
const int wave = threadIdx.x >> 5;
const int lane = threadIdx.x & 31;
const int ci = blockIdx.x * 8 + wave;
float score = -1e30f;
int32_t tok = V;
if (ci < n_cand) {
const int32_t v = cand_id[ci];
if (v >= 0 && v < V) {
const uint16_t* wr = unembed_bf16 + (size_t)v * D;
const int k8 = D & ~7;
float acc = 0.f;
for (int kk = lane * 8; kk < k8; kk += 256) {
const uint4 w8 = *reinterpret_cast<const uint4*>(wr + kk);
const float4 c0 = *reinterpret_cast<const float4*>(corr + kk);
const float4 c1 = *reinterpret_cast<const float4*>(corr + kk + 4);
acc = fmaf(bf16_to_f32(w8.x & 0xFFFFu), c0.x, fmaf(bf16_to_f32(w8.x >> 16), c0.y, acc));
acc = fmaf(bf16_to_f32(w8.y & 0xFFFFu), c0.z, fmaf(bf16_to_f32(w8.y >> 16), c0.w, acc));
acc = fmaf(bf16_to_f32(w8.z & 0xFFFFu), c1.x, fmaf(bf16_to_f32(w8.z >> 16), c1.y, acc));
acc = fmaf(bf16_to_f32(w8.w & 0xFFFFu), c1.z, fmaf(bf16_to_f32(w8.w >> 16), c1.w, acc));
}
for (int kk = k8 + lane; kk < D; kk += 32) {
acc = fmaf(bf16_to_f32(wr[kk]), corr[kk], acc);
}
score = cand_base_val[ci] + wave32_sum(acc);
tok = v;
}
}
__shared__ float s_v[8];
__shared__ int32_t s_i[8];
if (lane == 0) { s_v[wave] = score; s_i[wave] = tok; }
__syncthreads();
if (threadIdx.x == 0) {
float bv = -1e30f;
int32_t bi = V;
for (int w = 0; w < 8; ++w) {
if (s_v[w] > bv || (s_v[w] == bv && s_i[w] < bi)) {
bv = s_v[w]; bi = s_i[w];
}
}
blk_val[blockIdx.x] = bv;
blk_id[blockIdx.x] = bi;
}
}
__global__ void __launch_bounds__(256) k_dspark_cand_argmax_s2(
const float* __restrict__ blk_val,
const int32_t* __restrict__ blk_id,
int n_blks, int32_t* __restrict__ out_tok) {
const int tid = threadIdx.x;
float v = (tid < n_blks) ? blk_val[tid] : -1e30f;
int32_t id = (tid < n_blks) ? blk_id[tid] : 0x7FFFFFFF;
__shared__ float s_v[256];
__shared__ int32_t s_i[256];
s_v[tid] = v; s_i[tid] = id;
__syncthreads();
for (int s = 128; s > 0; s >>= 1) {
if (tid < s) {
if (s_v[tid + s] > s_v[tid] || (s_v[tid + s] == s_v[tid] && s_i[tid + s] < s_i[tid])) {
s_v[tid] = s_v[tid + s]; s_i[tid] = s_i[tid + s];
}
}
__syncthreads();
}
if (tid == 0) *out_tok = s_i[0];
}
extern "C" int vetta_dspark_cand_argmax(
const uint16_t* unembed_bf16, const float* cand_base_val, const int32_t* cand_id,
const float* corr, float* blk_val, int32_t* blk_id, int32_t* out_tok,
int n_cand, int D, int V, vetta_stream_t stream) {
if (n_cand <= 0 || D <= 0 || V <= 0) return 1;
const int n_blks = (n_cand + 7) / 8;
if (n_blks > 256) return 1;
hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0;
k_dspark_cand_argmax_s1<<<n_blks, 256, 0, s>>>(
unembed_bf16, cand_base_val, cand_id, corr, blk_val, blk_id, n_cand, D, V);
k_dspark_cand_argmax_s2<<<1, 256, 0, s>>>(blk_val, blk_id, n_blks, out_tok);
HIP_CHECK(hipGetLastError());
return 0;
}
// On-GPU batched argmax over logits[B, V] -> out_ids[B] (deterministic first-max).
// Eliminates copying B * 800 KB of verify logits to CPU!
__global__ void __launch_bounds__(256) k_batched_argmax_f32(
const float* __restrict__ logits, int32_t* __restrict__ out_ids, int B, int V) {
const int b = blockIdx.x;
if (b >= B) return;
const int tid = threadIdx.x;
const float* row = logits + (size_t)b * V;
float bv = -INFINITY;
int32_t bi = V;
for (int v = tid; v < V; v += 256) {
const float z = row[v];
if (z > bv || (z == bv && v < bi)) { bv = z; bi = v; }
}
__shared__ float s_v[256];
__shared__ int32_t s_i[256];
s_v[tid] = bv; s_i[tid] = bi;
__syncthreads();
for (int s = 128; s > 0; s >>= 1) {
if (tid < s) {
if (s_v[tid + s] > s_v[tid] || (s_v[tid + s] == s_v[tid] && s_i[tid + s] < s_i[tid])) {
s_v[tid] = s_v[tid + s]; s_i[tid] = s_i[tid + s];
}
}
__syncthreads();
}
if (tid == 0) out_ids[b] = s_i[0];
}
extern "C" int vetta_batched_argmax_f32(
const float* logits, int32_t* out_ids, int B, int V, vetta_stream_t stream) {
if (B <= 0 || V <= 0) return 1;
hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0;
k_batched_argmax_f32<<<B, 256, 0, s>>>(logits, out_ids, B, V);
HIP_CHECK(hipGetLastError());
return 0;
}
// Per-query deterministic Wave32 online-softmax SWA GQA over FP16 KV (hd==128).
// Used for BOTH M=1 decode (pos_arr==NULL -> cur_pos_scalar) and M<16 spec verify
// (pos_arr!=NULL): ZERO global scores_scratch (eliminates 48x sync hipMalloc/hipFree
// per verify round!), vectorized uint2 FP16 loads + DPP wave32_sum, and bit-identical
// between M=1 and M=nd+1 for exact lossless speculation.
__global__ void __launch_bounds__(128) k_flash_swa_gqa_smallm_f16(
const float* __restrict__ q,
const uint16_t* __restrict__ k,
const uint16_t* __restrict__ v,
float* __restrict__ out,
int n_head, int n_kv, int seq,
float scale, int swa_window,
const int32_t* __restrict__ pos_arr, int cur_pos_scalar,
const float* __restrict__ rel_bias, int max_rel,
const float* __restrict__ sink_logit,
const float* __restrict__ gate, int M) {
const int wave = threadIdx.x >> 5;
const int lane = threadIdx.x & 31;
const int h = blockIdx.x * 4 + wave;
const int m = blockIdx.y;
if (h >= n_head || m >= M) return;
const int d0 = lane * 4;
const int kvh = h / (n_head / n_kv);
const int cur_pos = pos_arr ? pos_arr[m] : cur_pos_scalar;
const int k_start = (swa_window > 0 && cur_pos >= swa_window) ? (cur_pos - swa_window + 1) : 0;
const float4 qv = *reinterpret_cast<const float4*>(q + ((size_t)m * n_head + h) * 128 + d0);
const float q0 = qv.x * scale, q1 = qv.y * scale, q2 = qv.z * scale, q3 = qv.w * scale;
const uint16_t* kh = k + (size_t)kvh * seq * 128;
const uint16_t* vh = v + (size_t)kvh * seq * 128;
const float* rb = rel_bias ? (rel_bias + ((size_t)m * n_head + h) * max_rel) : nullptr;
float max_l = sink_logit ? sink_logit[(size_t)m * n_head + h] : -1e30f;
float sum_e = sink_logit ? 1.0f : 0.0f;
float o0 = 0.0f, o1 = 0.0f, o2 = 0.0f, o3 = 0.0f;
for (int s = k_start; s <= cur_pos; ++s) {
const size_t off = (size_t)(s % seq) * 128 + d0;
const uint2 kw = *reinterpret_cast<const uint2*>(kh + off);
const uint2 vw = *reinterpret_cast<const uint2*>(vh + off);
const float k0 = f16_to_f32(kw.x & 0xFFFFu), k1 = f16_to_f32(kw.x >> 16);
const float k2 = f16_to_f32(kw.y & 0xFFFFu), k3 = f16_to_f32(kw.y >> 16);
const float v0 = f16_to_f32(vw.x & 0xFFFFu), v1 = f16_to_f32(vw.x >> 16);
const float v2 = f16_to_f32(vw.y & 0xFFFFu), v3 = f16_to_f32(vw.y >> 16);
float sc = wave32_sum(fmaf(q0, k0, fmaf(q1, k1, fmaf(q2, k2, q3 * k3))));
const int dist = cur_pos - s;
if (rb && dist < max_rel) sc += rb[dist];
const float nm = fmaxf(max_l, sc);
const float a = (sum_e > 0.0f) ? expf(max_l - nm) : 0.0f;
const float b = expf(sc - nm);
o0 = fmaf(o0, a, b * v0); o1 = fmaf(o1, a, b * v1);
o2 = fmaf(o2, a, b * v2); o3 = fmaf(o3, a, b * v3);
sum_e = fmaf(sum_e, a, b);
max_l = nm;
}
const float inv = 1.0f / fmaxf(sum_e, 1e-30f);
o0 *= inv; o1 *= inv; o2 *= inv; o3 *= inv;
if (gate) {
const float4 gv = *reinterpret_cast<const float4*>(gate + ((size_t)m * n_head + h) * 128 + d0);
o0 *= 1.0f / (1.0f + expf(-gv.x));
o1 *= 1.0f / (1.0f + expf(-gv.y));
o2 *= 1.0f / (1.0f + expf(-gv.z));
o3 *= 1.0f / (1.0f + expf(-gv.w));
}
*reinterpret_cast<float4*>(out + ((size_t)m * n_head + h) * 128 + d0) =
make_float4(o0, o1, o2, o3);
}
extern "C" int vetta_flash_swa_gqa_smallm_f16(
const float* q, const uint16_t* k, const uint16_t* v, float* out,
int n_head, int n_kv, int seq, int hd, float scale, int swa_window,
const int32_t* pos_arr, int cur_pos_scalar,
const float* rel_bias, int max_rel, const float* sink_logit,
const float* gate, int M, vetta_stream_t stream) {
if (n_head <= 0 || n_kv <= 0 || seq <= 0 || hd != 128 || (n_head % n_kv) != 0 || M <= 0) return 1;
hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0;
dim3 grid((n_head + 3) / 4, M);
k_flash_swa_gqa_smallm_f16<<<grid, 128, 0, s>>>(
q, k, v, out, n_head, n_kv, seq, scale, swa_window,
pos_arr, cur_pos_scalar, rel_bias, max_rel, sink_logit, gate, M);
HIP_CHECK(hipGetLastError());
return 0;
}
@@ -0,0 +1,144 @@
# Fix e ottimizzazioni DSpark drafter (`vetta-infer`)
**Data:** 2026-12-02
**Hardware di misura:** AMD Radeon 890M (`gfx1150`, RDNA 3.5 UMA, 48 GiB VRAM)
**Modello:** `/mnt/models/Inkling/safetensors/` (trunk 19 GB NVFP4/BF16 + `mtp.safetensors` 607 MB BF16)
**Baseline di partenza:** commit `91c1baa` / `ba51499` (Step 1 completato)
---
## 1. Sintesi del risultato
La matematica del drafter DSpark era corretta (`dspark_draft_parity` 7/7 e `spec_lossless_gate` 200/200), ma il throughput crollava con `n_draft` crescente (`4.58 tok/s` a `nd=5`, `6.11 tok/s` a `nd=2` sul prompt breve) invece di scalare come in `strata-inkling`.
Dopo gli interventi descritti sotto, su **entrambi** i workload misurati il drafter scala in modo pulito e **eguaglia/supera `strata-inkling --draft dspark`** con parità greedy **100% bit-exact**:
- **Coding reale in Rust (`RingBuffer<T>`, 128 token, chat template Inkling):**
- `vetta-infer` spec OFF: **`6.83 tok/s`** (`18,742 ms`)
- `vetta-infer` spec ON (default `VETTA_SPEC=1`, EMA adattivo, `n_draft=5`): **`13.93 tok/s`** (`9,188 ms`, **2.04× speedup**, 100% EXACT)
- `strata-inkling --draft dspark` (stesso prompt): **`13.66 tok/s`** (`9,372 ms`, 100% EXACT)
- **Prosa breve (`"The capital of France is"`, 96 token):**
- Prima (`ba51499`): `OFF 4.01` | `nd=2 6.11` | `nd=5 4.58 tok/s`
- Dopo: `OFF 4.63–4.70` | `nd=2 9.21` | `nd=5 9.09 tok/s` (**+98.5% / ~2× più veloce a `nd=5`**; EMA adattivo `8.93 tok/s` decode)
---
## 2. Cause radice trovate (7 colli di bottiglia + 2 bug di correttezza)
### Prestazioni (perché `nd=5` collassava a `4.58 tok/s`)
1. **`dspark_draft` leggeva `unembed` (922 MB BF16) `nd` volte con 4 sync CPU↔GPU per ogni step:**
Ad ogni step `1..=nd` veniva lanciato un full GEMV `[200058 × 2304]` su `unembed` (4.6 GB di banda buttati a `nd=5`), più un loop di copie D2H/H2D sincrone per il Markov head e l'argmax su CPU.
2. **Doppio `unembed` + 4.8 MB D2H + argmax su CPU in `spec_round`:**
`spec_round` chiamava `forward_batch_taps` (che faceva già 1 `unembed` sull'ultima riga) e poi rifaceva un `gemm_bf16` su tutte le `B = nd + 1` righe di `taps[3]`, copiava `B × 200058 × 4 B` (`4.8 MB` a `nd=5`) su CPU e cercava l'argmax in Rust.
3. **`gemm_bf16` usava il kernel scalare lento per `m < 16`:**
Il dispatch WMMA si attivava solo per `m >= 16`; tutte le verify speculative (`m = 2..8`) e il decode (`m = 1`) cadevano sul kernel scalare.
4. **MoE `expert_arena_grouped_gemv_f16` usava WMMA `16×16` anche per `b <= 12`:**
In verify speculativo (`b = 3..8`) quasi tutti i bucket di esperti hanno 1–2 token: il tile WMMA `M=16` paddava 14–15 righe a zero sprecando compute.
5. **48 `hipMalloc` + 48 `hipFree` sincroni per round nella SWA GQA verify (`m < 16`):**
`flash_swa_gqa_prefill_f16` allocava e liberava `scores_scratch` a ogni layer SWA quando `m > 1`, inserendo 96 sincronizzazioni di driver per singolo round speculativo.
6. **`k_router_gemv_batched` scalare (non vettorizzato e non M-tiled):**
I 3 layer DSpark (`B = 8`) rileggevano i pesi BF16 8 volte invece di 1 sola volta.
7. **Governatore EMA bloccato su `n_draft = 2`:**
La vecchia soglia era basata sul **rapporto** `accepted / nd` (`>= 0.90 -> 7`, `>= 0.75 -> 4`, altrimenti `2`). A `nd=5` sul codice accettare 2.3 token/round significa `ratio = 0.46`, che forzava il governatore a scendere a `n_draft = 2` (tagliando del ~17% la velocità sul codice!).
### Bug di correttezza in produzione (chat lunga e multi-turn)
8. **Crash garantito LDS > 64 KiB su contesto lungo (`k_dspark_block_attn`):**
Il vecchio kernel allocava `(c_len + B + hd) * 4` byte di shared memory. Sul layer Global `il = 1` (`c_len = anchor_pos`), sopra `~16,248` token superava i 64 KiB di LDS di RDNA 3.5 causando il fallimento del lancio HIP.
9. **`PrefixCache` non salvava/ripristinava `DsparkContext`:**
Al Turno 2+ di una conversazione, il `RESUME` ripristinava solo i KV del trunk lasciando i ring `k/v` e `frnn` di `DsparkContext` azzerati o di un'altra sessione, corrompendo i draft del turno successivo. Inoltre `DsparkContext` veniva riallocato a ogni richiesta invece di restare persistente su `InklingEngine`.
---
## 3. Modifiche applicate (file per file)
### [`kernels/hip/vetta_kernels.hip`](../kernels/hip/vetta_kernels.hip)
- **`k_dspark_block_attn_w32` (fast path `hd == 128` in `vetta_dspark_block_attn`):** online-softmax Wave32 interamente nei registri con **0 byte di LDS** (risolve il crash >16.2k token) e load vettorizzati `float4`/`uint2`.
- **`k_router_gemv` e `k_router_gemv_batched`:** riscritti con Wave32 vettorizzato `uint4`/`float4` (`8` wave/blocco) e **M-tiling per 8 righe**, così `B = 8` nei layer DSpark legge i pesi una sola volta (8× meno banda).
- **Drafter 100% su GPU (zero sync nel loop Markov):**
- `k_dspark_base_top2_screen`: singolo passaggio su `unembed` per tutti gli `nd <= 7` step contemporaneamente, producendo i Top-512 candidati per step (`n_cand = 512`, con modalità esatta all-tokens se `V <= n_cand`).
- `k_dspark_markov_proj_bf16`, `k_dspark_markov_corr_bf16`, `k_dspark_cand_argmax_s1`/`s2`: proiezione Markov ricorrente, correzione sui 512 candidati e argmax interamente on-device.
- **`k_batched_argmax_f32`:** argmax batched su GPU per la fase di verify (`B * 4` byte D2H invece di `B * 800 KB`).
- **`k_flash_swa_gqa_smallm_f16`:** kernel Wave32 deterministico per-query online-softmax (`hd == 128`) condiviso tra decode `M = 1` e verify `M < 16` con **0 allocazioni `scores_scratch`** (elimina le 48 `hipMalloc` + 48 `hipFree` per round).
### [`crates/vetta-infer-hip/src/lib.rs`](../crates/vetta-infer-hip/src/lib.rs)
- Aggiunti binding FFI e wrapper Rust safe con bounds checking per `dspark_base_top2_screen`, `dspark_markov_proj_bf16`, `dspark_markov_corr_bf16`, `dspark_cand_argmax`, `batched_argmax_f32`.
- Cablato `k_flash_swa_gqa_smallm_f16` in `flash_swa_gqa_decode_f16` e `flash_swa_gqa_prefill_f16` (`m < 16`).
- Esteso il dispatch WMMA in `gemm_bf16` a `m >= 1 && k % 64 == 0` (prima era `m >= 16`).
- Aggiunto test GPU di regressione `dspark_block_attn_long_context_no_lds_overflow` a `c_len = 17_000`.
### [`crates/vetta-infer-ld/src/packer.rs`](../crates/vetta-infer-ld/src/packer.rs) e [`crates/vetta-infer-ld/src/layer.rs`](../crates/vetta-infer-ld/src/layer.rs)
- `expert_arena_grouped_gemv_f16` ora riceve `b: i32` e usa `nvfp4_grouped_gemv_f16` (`fdot2`, bit-exact rispetto a `M=1`) per `b <= 12` e `nvfp4_grouped_gemm_wmma` per `b > 12` (override `VETTA_FORCE_MOE_WMMA=1` mantenuto per A/B).
- Aggiunta `forward_batch_taps_no_logits` (`skip_unembed = true`) usata da `spec_round` per eliminare il doppio `unembed`.
### [`crates/vetta-infer-ld/src/dspark.rs`](../crates/vetta-infer-ld/src/dspark.rs)
- Riscritta `dspark_draft` con `dspark_base_top2_screen` + loop Markov su GPU e una sola copia D2H finale (`<= 32 byte`).
- Riscritta `spec_round` usando `forward_batch_taps_no_logits` + singolo `gemm_bf16` batched + `batched_argmax_f32` (`B * 4` byte D2H) + commit di `dctx` solo per i token effettivamente accettati.
- Aggiunti `DsparkSnapshot`, `DsparkContext::snapshot` e `DsparkContext::restore` (gestione corretta del wrap-around sui ring SWA dei layer 0/2, stato completo sul layer Global 1 e `frnn[seq - 1]`).
### [`crates/vetta-infer-gw/src/serve.rs`](../crates/vetta-infer-gw/src/serve.rs)
- `dctx: RefCell<Option<DsparkContext>>` reso persistente su `InklingEngine` (riallocato solo se `cap > c.cap`).
- Integrato `dspark: Option<DsparkSnapshot>` in `Checkpoint` / `PrefixCache::save` / `PrefixCache::restore`: se un checkpoint ripristinato non ha stato DSpark (es. salvato con spec OFF), `spec_enabled` scende pulitamente a `false` per quel turno evitando di eseguire il drafter su ring azzerati.
- Aggiornato il governatore adattivo da ratio (`accepted / nd`) a **EMA dei token accettati per round** (`ema_acc`, partenza `2.0`, `n_draft = 5`, aggiornamento `0.85 * ema_acc + 0.15 * acc`, scala `7 / 5 / 4 / 3 / 2` per soglie `>= 3.5 / 2.0 / 1.1 / 0.6`).
- Aggiunto test GPU di regressione `serve_gen_spec_prefix_cache_multi_turn_parity`.
---
## 4. Benchmark misurati (`gfx1150`, stesso hardware e modello)
### A. Prompt reale di coding Rust (`RingBuffer<T>`, 69 token prompt, `GEN 128`, `temperature=0`, warm)
| Motore / Configurazione | Decode ms (128 tok) | Decode tok/s | Speedup vs OFF | Rounds | Accettati / Offerti | Match vs OFF |
|---|---:|---:|---:|---:|---:|:---:|
| `vetta-infer` OFF | `18,742.3 ms` | `6.83 tok/s` | `1.00×` | — | — | baseline |
| `vetta-infer` `VETTA_SPEC_ND=2` | `10,730.6 ms` | `11.93 tok/s` | `1.75×` | 53 | `74 / 104` (71.2%) | **EXACT** |
| `vetta-infer` `VETTA_SPEC_ND=3` | `9,208.9 ms` | `13.90 tok/s` | `2.04×` | 43 | `84 / 128` (65.6%) | **EXACT** |
| `vetta-infer` `VETTA_SPEC_ND=4` | `9,164.0 ms` | `13.97 tok/s` | `2.05×` | 40 | `87 / 157` (55.4%) | **EXACT** |
| `vetta-infer` `VETTA_SPEC_ND=5` | `9,347.0 ms` | `13.69 tok/s` | `2.00×` | 39 | `88 / 190` (46.3%) | **EXACT** |
| `vetta-infer` `VETTA_SPEC_ND=6` | `9,382.9 ms` | `13.64 tok/s` | `2.00×` | 37 | `90 / 222` (40.5%) | **EXACT** |
| `vetta-infer` `VETTA_SPEC_ND=7` | `9,421.8 ms` | `13.59 tok/s` | `1.99×` | 36 | `91 / 251` (36.3%) | **EXACT** |
| **`vetta-infer` `VETTA_SPEC=1` (EMA default)** | **`9,188.0 ms`** | **`13.93 tok/s`** | **`2.04×`** | **39** | **`88 / 177` (49.7%, `n_draft=5`)** | **EXACT** |
| `strata-inkling --draft dspark` | `9,372.2 ms` | `13.66 tok/s` | — | ~39 | `90 / 195` (46.2%) | **EXACT** |
*(Overhead di `dc.commit` in prefill misurato sul medesimo prompt: `509.6 ms` SPEC vs `506.0 ms` OFF wall-time = `+3.6 ms` / `+0.7%`.)*
### B. Prompt breve canonico (`"The capital of France is"`, 5 token prompt, `GEN 96`, `temperature=0`)
| Configurazione | Prima (`ba51499`) decode tok/s | Dopo decode tok/s | Delta |
|---|---:|---:|---:|
| `OFF` (totale `serve_gen_spec_perf`) | `4.01 tok/s` | `4.63–4.70 tok/s` | `+16%` |
| `VETTA_SPEC_ND=2` | `6.11 tok/s` | `9.21 tok/s` | `+51%` |
| `VETTA_SPEC_ND=3` | `5.78 tok/s` | `8.98–9.09 tok/s` | `+57%` |
| `VETTA_SPEC_ND=4` | `5.54 tok/s` | `8.83–8.93 tok/s` | `+61%` |
| `VETTA_SPEC_ND=5` | **`4.58 tok/s`** | **`9.02–9.09 tok/s`** | **`+98.5%`** |
| `VETTA_SPEC_ND=7` | `5.15 tok/s` | `8.43–8.72 tok/s` | `+69%` |
| `VETTA_SPEC=1` (EMA default) | `6.09 tok/s` | `8.93 tok/s` (`n_draft=4`, `48/155`) | `+47%` |
---
## 5. Validazione eseguita (tutto verde)
- **Workspace CPU con `-D warnings`:** `RUSTFLAGS="-D warnings" cargo test --workspace` → **100% PASS, 0 warning**.
- **Prove formali Lean 4:** tutti e 7 i file in `proofs/*.lean` verificati con `lean` → **0 `sorryAx`**.
- **Kernel HIP GPU (`vetta-infer-hip --ignored --test-threads=1`):**
- `dspark_block_attn_parity`: `max_rel_err = 5.668e-7` (**PASS**)
- `dspark_block_attn_long_context_no_lds_overflow` (`c_len = 17_000`): `max_rel_err = 5.091e-5` (**PASS**)
- `router_gemv_batched_parity`: `max_rel_err = 0.000e0` (**PASS**)
- `gemm_bf16_parity_vs_cpu`: `max_rel_err = 1.570e-6` (**PASS**)
- **Drafter & lossless gate (`vetta-infer-ld --ignored --test-threads=1`):**
- `dspark_draft_parity`: 7/7 EXACT (**PASS**)
- `spec_lossless_gate`: **200 token EXACT match** (`rounds=165 offered=1127 accepted=34`) (**PASS**)
- **Serve & PrefixCache (`vetta-infer-gw --ignored --test-threads=1`):**
- `serve_gen_spec_multi_token_parity`: 16 token di riferimento EXACT (**PASS**)
- `serve_gen_spec_prefix_cache_multi_turn_parity`: `off_resumed=45 on_resumed=45`, Turn 1 (16 tok) e Turn 2 (24 tok) 100% EXACT (**PASS**)
- `serve_gen_spec_perf`: OFF `4.63 tok/s` | ON decode `8.93 tok/s` (**PASS**)
- **Build release:** `cargo build --release --features hip` completata senza warning (`target/release/vetta-infer` aggiornato).
---
## 6. Note operative
- Il drafter resta **opt-in** via `VETTA_SPEC=1` (path di default `OFF` invariato e +16% più veloce grazie al dispatch WMMA su `gemm_bf16` e al kernel SWA small-M).
- `VETTA_SPEC_ND=<k>` permette comunque di fissare `n_draft` per A/B; `VETTA_DBG_SPEC=1` stampa le statistiche per richiesta su `stderr`.
- Le modifiche sono pronte nel working tree (non ancora committate) e `inkling-server.service` è rimasto spento durante i test.