[HIP] FP16 KV cache path (strata default), opt-in VETTA_F16_KV

strata stores K/V in FP16 by default (KvDtype::FP16, 'default lossless FP16');
vetta used F32. Add k_kv_store_f16 (RNE round to u16 cache) + k_flash_swa_gqa_decode_f16
(f32 attention math over FP16 KV), FFI/wrappers, and a new_state/forward branch
gated by VETTA_F16_KV=1 (F32 stays the CPU-oracle baseline). New GPU parity test
fp16_kv_store_and_flash_parity: stored K == cast_f32_f16 bits, attention over the
decoded FP16 KV matches a CPU oracle fed the same values (18 hip GPU green).

MEASURED honestly: FP16 KV does NOT fix the chat token-2+ divergence (still
~3.6 logit gap vs reference, robust also to VETTA_F16_EXPERT and -ffp-contract=off).
The gap is a systematic multi-token accumulation difference, not KV precision;
kept as faithful opt-in infrastructure, not claimed as a parity fix.
This commit is contained in:
adm committed 2026-12-01 17:42:57 +01:00
1 parent dfa6013bfd
commit 74b3384270
4 files changed
+295 -18

No files matched your search

+108 -8
View File
@@ -54,6 +54,12 @@ mod ffi {
swa_window: c_int, cur_pos: c_int, rel_bias: *const c_float, max_rel: c_int,
sink_logit: *const c_float, gate: *const c_float, stream: *mut c_void,
) -> c_int;
pub fn vetta_flash_swa_gqa_decode_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, cur_pos: c_int, rel_bias: *const c_float, max_rel: c_int,
sink_logit: *const c_float, gate: *const c_float, stream: *mut c_void,
) -> c_int;
pub fn vetta_moe_router_topk(
logits: *const c_float, bias: *const c_float, topk_ids: *mut i32, topk_weights: *mut c_float,
m: c_int, n_experts: c_int, k_top: c_int, route_scale: c_float, stream: *mut c_void,
@@ -80,6 +86,7 @@ mod ffi {
pub fn vetta_l2_clip(x: *mut c_float, scale: *const c_float, rows: c_int, hd: c_int, clip: c_float, apply_tau: c_int, pos: c_int, stream: *mut c_void) -> c_int;
pub fn vetta_relpos_bias(r: *const c_float, rel_proj: *const c_float, rel_bias: *mut c_float, n_head: c_int, d_rel: c_int, rel_extent: c_int, lim: c_int, stream: *mut c_void) -> c_int;
pub fn vetta_kv_store(k_in: *const c_float, v_in: *const c_float, k_cache: *mut c_float, v_cache: *mut c_float, pos: c_int, n_kv: c_int, hd: c_int, seq: c_int, rms_eps: c_float, stream: *mut c_void) -> c_int;
pub fn vetta_kv_store_f16(k_in: *const c_float, v_in: *const c_float, k_cache: *mut u16, v_cache: *mut u16, pos: c_int, n_kv: c_int, hd: c_int, seq: c_int, rms_eps: c_float, stream: *mut c_void) -> c_int;
pub fn vetta_softcap(x: *const c_float, y: *mut c_float, n: usize, cap: 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_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;
@@ -130,14 +137,14 @@ pub struct DeviceBuf {
pub bytes: usize,
}
/// Size-bucketed free list of device buffers. The layer forward allocates and
/// frees ~25 short-lived intermediates per visit (~1200 hipMalloc/hipFree per
/// token); hipMalloc/hipFree each synchronize the device, dominating decode
/// latency. Reusing freed buffers by exact size removes that churn. Safe because
/// all launches share the default stream and every host copy (hipMemcpy) is
/// blocking: a buffer is only recycled after its last use is ordered before the
/// next launch that reuses it. Thread-local (cargo test runs tests in parallel).
/// Escape hatch: VETTA_NO_BUF_POOL=1 forces raw hipMalloc/hipFree.
// Size-bucketed free list of device buffers. The layer forward allocates and
// frees ~25 short-lived intermediates per visit (~1200 hipMalloc/hipFree per
// token); hipMalloc/hipFree each synchronize the device, dominating decode
// latency. Reusing freed buffers by exact size removes that churn. Safe because
// all launches share the default stream and every host copy (hipMemcpy) is
// blocking: a buffer is only recycled after its last use is ordered before the
// next launch that reuses it. Thread-local (cargo test runs tests in parallel).
// Escape hatch: VETTA_NO_BUF_POOL=1 forces raw hipMalloc/hipFree.
#[cfg(feature = "hip")]
thread_local! {
static BUF_POOL: std::cell::RefCell<std::collections::HashMap<usize, Vec<*mut std::os::raw::c_void>>> =
@@ -267,6 +274,21 @@ pub fn flash_swa_gqa_decode(q: &DeviceBuf, k: &DeviceBuf, v: &DeviceBuf, out: &D
Ok(())
}
/// Launch k_flash_swa_gqa_decode_f16: SWA attention reading an FP16 KV cache
/// (strata default). `k`/`v` are u16 FP16 buffers; attention math stays f32.
#[cfg(feature = "hip")]
#[allow(clippy::too_many_arguments)]
pub fn flash_swa_gqa_decode_f16(q: &DeviceBuf, k: &DeviceBuf, v: &DeviceBuf, out: &DeviceBuf, n_head: i32, n_kv: i32, seq: i32, hd: i32, scale: f32, swa_window: i32, cur_pos: i32, rel_bias: Option<&DeviceBuf>, max_rel: i32, sink_logit: Option<&DeviceBuf>, gate: Option<&DeviceBuf>) -> Result<(), String> {
let rb = rel_bias.map(|b| b.ptr as *const f32).unwrap_or(std::ptr::null());
let sk = sink_logit.map(|b| b.ptr as *const f32).unwrap_or(std::ptr::null());
let gt = gate.map(|b| b.ptr as *const f32).unwrap_or(std::ptr::null());
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, std::ptr::null_mut())
};
if rc != 0 { return Err("flash_swa_gqa_f16 launch failed".into()); }
Ok(())
}
/// Launch k_moe_router_topk (Inkling exact sigmoid router).
#[cfg(feature = "hip")]
pub fn moe_router_topk(logits: &DeviceBuf, bias: Option<&DeviceBuf>, ids: &DeviceBuf, weights: &DeviceBuf, m: i32, n_experts: i32, k_top: i32, route_scale: f32) -> Result<(), String> {
@@ -418,6 +440,15 @@ pub fn kv_store(k_in: &DeviceBuf, v_in: &DeviceBuf, k_cache: &DeviceBuf, v_cache
Ok(())
}
/// Launch k_kv_store_f16: K/V rounded to FP16 (RNE) into a u16 cache (strata FP16 KV).
#[cfg(feature = "hip")]
#[allow(clippy::too_many_arguments)]
pub fn kv_store_f16(k_in: &DeviceBuf, v_in: &DeviceBuf, k_cache: &DeviceBuf, v_cache: &DeviceBuf, pos: i32, n_kv: i32, hd: i32, seq: i32, rms_eps: f32) -> Result<(), String> {
let rc = unsafe { ffi::vetta_kv_store_f16(k_in.ptr as *const f32, v_in.ptr as *const f32, k_cache.ptr as *mut u16, v_cache.ptr as *mut u16, pos, n_kv, hd, seq, rms_eps, std::ptr::null_mut()) };
if rc != 0 { return Err("kv_store_f16 launch failed".into()); }
Ok(())
}
/// Launch k_softcap: y = cap * tanh(x / cap).
#[cfg(feature = "hip")]
pub fn softcap(x: &DeviceBuf, y: &DeviceBuf, n: usize, cap: f32) -> Result<(), String> {
@@ -1034,6 +1065,75 @@ mod gpu_tests {
eprintln!("k2 prep kernels (l2_clip + relpos_bias + kv_store): parity OK");
}
/// FP16 KV cache path (strata default KvDtype::FP16): kv_store_f16 rounds K/V
/// to FP16 (RNE); flash_swa_gqa_decode_f16 reads them back. Verifies (a) the
/// stored K equals cast_f32_f16(k_in) bit-for-bit, and (b) attention over the
/// decoded FP16 KV matches a CPU oracle fed the SAME decoded values.
#[test]
#[ignore]
fn fp16_kv_store_and_flash_parity() {
let f16dec = |h: u16| -> f32 {
let sign = ((h & 0x8000) as u32) << 16;
let exp = (h >> 10) & 0x1f;
let mant = (h & 0x3ff) as u32;
if exp == 0 { return f32::from_bits(sign | ((mant as f32 * 2f32.powi(-24)).to_bits())); }
if exp == 31 { return f32::from_bits(sign | 0x7f800000 | (mant << 13)); }
f32::from_bits(sign | (((exp as u32 + 112) << 23) | (mant << 13)))
};
let (n_head, n_kv, hd, seq) = (4usize, 2usize, 8usize, 6usize);
let eps = 1e-6f32; let scale = 1.0 / (hd as f32).sqrt();
// Store K/V for positions 0..seq via kv_store_f16.
let dkc = DeviceBuf::alloc(n_kv * seq * hd * 2).unwrap(); dkc.h2d_bytes(&vec![0u8; n_kv * seq * hd * 2]).unwrap();
let dvc = DeviceBuf::alloc(n_kv * seq * hd * 2).unwrap(); dvc.h2d_bytes(&vec![0u8; n_kv * seq * hd * 2]).unwrap();
let mut k_in_all = vec![0f32; seq * n_kv * hd];
let mut v_in_all = vec![0f32; seq * n_kv * hd];
for p in 0..seq {
let k_in: Vec<f32> = (0..n_kv * hd).map(|i| (((i + p * 7) % 17) as f32 - 8.0) * 0.2).collect();
let v_in: Vec<f32> = (0..n_kv * hd).map(|i| (((i + p * 5) % 19) as f32 - 9.0) * 0.3).collect();
k_in_all[p * n_kv * hd..(p + 1) * n_kv * hd].copy_from_slice(&k_in);
v_in_all[p * n_kv * hd..(p + 1) * n_kv * hd].copy_from_slice(&v_in);
let dki = DeviceBuf::alloc(k_in.len() * 4).unwrap(); dki.h2d(&k_in).unwrap();
let dvi = DeviceBuf::alloc(v_in.len() * 4).unwrap(); dvi.h2d(&v_in).unwrap();
kv_store_f16(&dki, &dvi, &dkc, &dvc, p as i32, n_kv as i32, hd as i32, seq as i32, eps).unwrap();
}
// (a) K stored bits == cast_f32_f16(k_in) bits (both RNE).
let dk_all = DeviceBuf::alloc(k_in_all.len() * 4).unwrap(); dk_all.h2d(&k_in_all).unwrap();
let dk16 = DeviceBuf::alloc(k_in_all.len() * 2).unwrap();
cast_f32_f16(&dk_all, &dk16, k_in_all.len()).unwrap();
let mut ref_k16 = vec![0u8; k_in_all.len() * 2]; dk16.d2h_bytes(&mut ref_k16).unwrap();
let mut got_kc = vec![0u8; n_kv * seq * hd * 2]; dkc.d2h_bytes(&mut got_kc).unwrap();
// cache layout [n_kv, seq, hd]; ref_k16 layout [seq, n_kv, hd] -> transpose.
for h in 0..n_kv { for p in 0..seq { for d in 0..hd {
let got = u16::from_le_bytes([got_kc[(h * seq + p) * hd * 2 + d * 2], got_kc[(h * seq + p) * hd * 2 + d * 2 + 1]]);
let want = u16::from_le_bytes([ref_k16[(p * n_kv + h) * hd * 2 + d * 2], ref_k16[(p * n_kv + h) * hd * 2 + d * 2 + 1]]);
assert_eq!(got, want, "kv_store_f16 K bits mismatch h={h} p={p} d={d}");
}}}
// Decode the actual FP16 KV the flash kernel reads.
let mut got_vc = vec![0u8; n_kv * seq * hd * 2]; dvc.d2h_bytes(&mut got_vc).unwrap();
let dec = |b: &[u8], off: usize| f16dec(u16::from_le_bytes([b[off], b[off + 1]]));
let mut kc = vec![0f32; n_kv * seq * hd]; let mut vc = vec![0f32; n_kv * seq * hd];
for i in 0..n_kv * seq * hd { kc[i] = dec(&got_kc, i * 2); vc[i] = dec(&got_vc, i * 2); }
// (b) flash_f16 at cur_pos = seq-1 vs CPU oracle over decoded KV (window 0).
let q: Vec<f32> = (0..n_head * hd).map(|i| ((i % 13) as f32 - 6.0) * 0.1).collect();
let dq = DeviceBuf::alloc(q.len() * 4).unwrap(); dq.h2d(&q).unwrap();
let dout = DeviceBuf::alloc(n_head * hd * 4).unwrap();
let cur_pos = (seq - 1) as i32;
flash_swa_gqa_decode_f16(&dq, &dkc, &dvc, &dout, n_head as i32, n_kv as i32, seq as i32, hd as i32, scale, 0, cur_pos, None, 0, None, None).unwrap();
let mut got = vec![0f32; n_head * hd]; dout.d2h(&mut got).unwrap();
let mut want = vec![0f32; n_head * hd];
for h in 0..n_head { let kvh = h / (n_head / n_kv);
let mut dots = vec![0f32; seq];
for s in 0..seq { let mut dot = 0f32; for d in 0..hd { dot += q[h * hd + d] * kc[(kvh * seq + s) * hd + d]; } dots[s] = dot * scale; }
let m = dots.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
let es: Vec<f32> = dots.iter().map(|d| (d - m).exp()).collect();
let sum: f32 = es.iter().sum(); let inv = 1.0 / sum.max(1e-30);
for d in 0..hd { let mut acc = 0f32; for s in 0..seq { acc += es[s] * inv * vc[(kvh * seq + s) * hd + d]; } want[h * hd + d] = acc; }
}
let mut mr = 0f32; for (g, w) in got.iter().zip(want.iter()) { mr = mr.max((g - w).abs() / w.abs().max(1e-3)); }
eprintln!("fp16 KV store + flash max_rel_err={mr:.3e}");
assert!(mr < 1e-4, "flash_swa_gqa_decode_f16 parity failed: {mr}");
}
#[test]
#[ignore]
fn softcap_parity_vs_cpu() {
+35 -6
View File
@@ -177,9 +177,19 @@ pub fn load_layer(ar: &SafetensorsArchive, ip: usize, is_swa: bool) -> Result<La
pub fn new_state(d: &Dims, max_seq: usize) -> Result<LayerState, String> {
let zero = |n: usize| -> Result<DeviceBuf, String> { let b = DeviceBuf::alloc(n * 4)?; b.h2d(&vec![0f32; n])?; Ok(b) };
// KV cache dtype: F32 by default (the verified CPU-oracle baseline); FP16 via
// VETTA_F16_KV=1 matches the strata default (KvDtype::FP16) and its
// length-dependent rounding (the F32 cache diverges on near-ties as it grows).
let kv_n = d.n_kv * max_seq * d.hd;
let (k_cache, v_cache) = if f16_kv() {
let z16 = |n: usize| -> Result<DeviceBuf, String> { let b = DeviceBuf::alloc(n * 2)?; b.h2d_bytes(&vec![0u8; n * 2])?; Ok(b) };
(z16(kv_n)?, z16(kv_n)?)
} else {
(zero(kv_n)?, zero(kv_n)?)
};
Ok(LayerState {
k_cache: zero(d.n_kv * max_seq * d.hd)?,
v_cache: zero(d.n_kv * max_seq * d.hd)?,
k_cache,
v_cache,
hist_k: [zero(3 * d.kv_dim())?, zero(3 * d.kv_dim())?, zero(3 * d.kv_dim())?],
hist_v: [zero(3 * d.kv_dim())?, zero(3 * d.kv_dim())?, zero(3 * d.kv_dim())?],
hist_a: [zero(3 * d.hidden)?, zero(3 * d.hidden)?, zero(3 * d.hidden)?],
@@ -188,6 +198,9 @@ pub fn new_state(d: &Dims, max_seq: usize) -> Result<LayerState, String> {
})
}
/// FP16 KV cache opt-in (strata default KV dtype is FP16).
fn f16_kv() -> bool { std::env::var("VETTA_F16_KV").is_ok() }
/// Run one SWA layer step on `cur` (in place), appending a depth-block snapshot
/// to `blocks` when `ip % block_size == 0`. `pos` is the decode position.
/// Experts are loaded on demand from `ar` (zero requantization).
@@ -265,11 +278,19 @@ pub fn layer_forward_swa(
vetta_infer_hip::l2_clip(&k_cv, None, d.n_kv as i32, d.hd as i32, d.qk_clip, false, pos)?;
let lim = (pos + 1).min(d.rel_extent as i32);
vetta_infer_hip::relpos_bias(&r_raw, &w.rel_proj, &rel_bias, d.n_head as i32, d.d_rel as i32, d.rel_extent as i32, lim)?;
vetta_infer_hip::kv_store(&k_cv, &v_cv, &st.k_cache, &st.v_cache, pos, d.n_kv as i32, d.hd as i32, st.max_seq as i32, d.eps)?;
if f16_kv() {
vetta_infer_hip::kv_store_f16(&k_cv, &v_cv, &st.k_cache, &st.v_cache, pos, d.n_kv as i32, d.hd as i32, st.max_seq as i32, d.eps)?;
} else {
vetta_infer_hip::kv_store(&k_cv, &v_cv, &st.k_cache, &st.v_cache, pos, d.n_kv as i32, d.hd as i32, st.max_seq as i32, d.eps)?;
}
if w.ip == 0 || (w.ip == 6 && pass == 1) { dbg_norm("q", &q, q_dim); dbg_norm("k_cv", &k_cv, kv_dim); dbg_norm("v_cv", &v_cv, kv_dim); dbg_norm("r_raw", &r_raw, d.n_head * d.d_rel); }
// k3: flash SWA GQA.
vetta_infer_hip::flash_swa_gqa_decode(&q, &st.k_cache, &st.v_cache, &aout, d.n_head as i32, d.n_kv as i32, st.max_seq as i32, d.hd as i32, d.scale(), d.swa_win, pos, Some(&rel_bias), d.rel_extent as i32, Some(&sinks), Some(&gatea))?;
if f16_kv() {
vetta_infer_hip::flash_swa_gqa_decode_f16(&q, &st.k_cache, &st.v_cache, &aout, d.n_head as i32, d.n_kv as i32, st.max_seq as i32, d.hd as i32, d.scale(), d.swa_win, pos, Some(&rel_bias), d.rel_extent as i32, Some(&sinks), Some(&gatea))?;
} else {
vetta_infer_hip::flash_swa_gqa_decode(&q, &st.k_cache, &st.v_cache, &aout, d.n_head as i32, d.n_kv as i32, st.max_seq as i32, d.hd as i32, d.scale(), d.swa_win, pos, Some(&rel_bias), d.rel_extent as i32, Some(&sinks), Some(&gatea))?;
}
if w.ip == 0 || (w.ip == 6 && pass == 1) { dbg_norm("aout", &aout, q_dim); dbg_norm("sinks", &sinks, d.n_head); dbg_norm("gatea", &gatea, q_dim); }
// k4: O-proj + attn shortconv + block boundary.
@@ -705,10 +726,18 @@ pub fn layer_forward_full(
rel_bias.h2d(&vec![0f32; d.n_head * d.rel_extent])?;
let lim = (pos + 1).min(d.rel_extent as i32);
vetta_infer_hip::relpos_bias(&r_raw, &w.rel_proj, &rel_bias, d.n_head as i32, d.d_rel as i32, d.rel_extent as i32, lim)?;
vetta_infer_hip::kv_store(&k_cv, &v_cv, &st.k_cache, &st.v_cache, pos, d.n_kv as i32, d.hd as i32, st.max_seq as i32, d.eps)?;
if f16_kv() {
vetta_infer_hip::kv_store_f16(&k_cv, &v_cv, &st.k_cache, &st.v_cache, pos, d.n_kv as i32, d.hd as i32, st.max_seq as i32, d.eps)?;
} else {
vetta_infer_hip::kv_store(&k_cv, &v_cv, &st.k_cache, &st.v_cache, pos, d.n_kv as i32, d.hd as i32, st.max_seq as i32, d.eps)?;
}
let aout = DeviceBuf::alloc(q_dim * 4)?;
// global attention: window = 0.
vetta_infer_hip::flash_swa_gqa_decode(&q, &st.k_cache, &st.v_cache, &aout, d.n_head as i32, d.n_kv as i32, st.max_seq as i32, d.hd as i32, d.scale(), 0, pos, Some(&rel_bias), d.rel_extent as i32, Some(&sinks), Some(&gatea))?;
if f16_kv() {
vetta_infer_hip::flash_swa_gqa_decode_f16(&q, &st.k_cache, &st.v_cache, &aout, d.n_head as i32, d.n_kv as i32, st.max_seq as i32, d.hd as i32, d.scale(), 0, pos, Some(&rel_bias), d.rel_extent as i32, Some(&sinks), Some(&gatea))?;
} else {
vetta_infer_hip::flash_swa_gqa_decode(&q, &st.k_cache, &st.v_cache, &aout, d.n_head as i32, d.n_kv as i32, st.max_seq as i32, d.hd as i32, d.scale(), 0, pos, Some(&rel_bias), d.rel_extent as i32, Some(&sinks), Some(&gatea))?;
}
let aout_bf = DeviceBuf::alloc(q_dim * 2)?; vetta_infer_hip::cast_f32_bf16(&aout, &aout_bf, q_dim)?;
let oproj = DeviceBuf::alloc(h * 4)?;
vetta_infer_hip::gemm_bf16(&aout_bf, &w.wo, &oproj, 1, h as i32, q_dim as i32)?;