Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cd853cda8b | ||
|
|
74b3384270 |
No files matched your search
@@ -28,8 +28,14 @@ pub fn chat_turn(
|
||||
on_text: &mut dyn FnMut(&str),
|
||||
) -> Result<String, String> {
|
||||
let prompt = render_prompt(history, effort)?;
|
||||
if std::env::var("VETTA_DBG_PROMPT").is_ok() {
|
||||
eprintln!("[chat] prompt={prompt:?}");
|
||||
}
|
||||
let enc = tok.encode(prompt, false).map_err(|e| e.to_string())?;
|
||||
let ids: Vec<i32> = enc.get_ids().iter().map(|&x| x as i32).collect();
|
||||
if std::env::var("VETTA_DBG_PROMPT").is_ok() {
|
||||
eprintln!("[chat] prompt_ids={ids:?}");
|
||||
}
|
||||
let g = ParsedGen {
|
||||
max_new,
|
||||
sampling: SamplingOpts::default(), // greedy, deterministic
|
||||
@@ -40,6 +46,11 @@ pub fn chat_turn(
|
||||
ids,
|
||||
};
|
||||
let stop = AtomicBool::new(false);
|
||||
// In the plain-content path (effort none) the assistant content channel closes
|
||||
// at <|end_message|> (200010); the model then emits EOS. Stop at end_message so
|
||||
// the reply is exactly the content even if the trailing EOS is delayed by a
|
||||
// near-tie (the reference closes the channel here too).
|
||||
let stop_at_end_message = effort.trim() == "none";
|
||||
let mut generated: Vec<u32> = Vec::new();
|
||||
let mut printed = 0usize;
|
||||
let mut full = String::new();
|
||||
@@ -57,6 +68,9 @@ pub fn chat_turn(
|
||||
}
|
||||
full = txt;
|
||||
}
|
||||
if stop_at_end_message && id == 200010 {
|
||||
stop.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
};
|
||||
serve_gen(eng, &g, &stop, &mut emit);
|
||||
}
|
||||
|
||||
@@ -229,6 +229,12 @@ pub fn serve_gen(
|
||||
return;
|
||||
}
|
||||
let rep = sample_logits_exact(&mut lg, &opts, &history, None, &mut rng, &mut scratch);
|
||||
if std::env::var("VETTA_DBG_LOGITS").is_ok() {
|
||||
let mut idx: Vec<usize> = (0..eng.vocab).collect();
|
||||
idx.sort_by(|&a, &b| lg[b].partial_cmp(&lg[a]).unwrap());
|
||||
let top: Vec<(usize, f32)> = idx[..5].iter().map(|&i| (i, lg[i])).collect();
|
||||
eprintln!("[dbg] step={step} pos={pos} top5={top:?}");
|
||||
}
|
||||
if rep.nonfinite_logits == eng.vocab {
|
||||
finish = "nonfinite";
|
||||
break;
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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)?;
|
||||
|
||||
@@ -64,6 +64,14 @@ int vetta_flash_swa_gqa_decode(const float* q, const float* k, const float* v,
|
||||
const float* sink_logit, const float* gate,
|
||||
vetta_stream_t stream);
|
||||
|
||||
// k_flash_swa_gqa_decode_f16: FP16 KV cache variant (strata default FP16 KV).
|
||||
int vetta_flash_swa_gqa_decode_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, int cur_pos,
|
||||
const float* rel_bias, int max_rel,
|
||||
const float* sink_logit, const float* gate,
|
||||
vetta_stream_t stream);
|
||||
|
||||
// k_moe_router_topk: Inkling exact sigmoid router (top-K, route_scale norm).
|
||||
int vetta_moe_router_topk(const float* logits, const float* bias,
|
||||
int32_t* topk_ids, float* topk_weights,
|
||||
@@ -146,6 +154,11 @@ int vetta_kv_store(const float* k_in, const float* v_in, float* k_cache,
|
||||
float* v_cache, int pos, int n_kv, int hd, int seq,
|
||||
float rms_eps, vetta_stream_t stream);
|
||||
|
||||
// k_kv_store_f16: K/V rounded to FP16 (RNE) -> contiguous u16 cache (strata FP16 KV).
|
||||
int vetta_kv_store_f16(const float* k_in, const float* v_in, uint16_t* k_cache,
|
||||
uint16_t* v_cache, int pos, int n_kv, int hd, int seq,
|
||||
float rms_eps, vetta_stream_t stream);
|
||||
|
||||
// k_softcap: y = cap * tanh(x / cap) (final logit softcapping).
|
||||
int vetta_softcap(const float* x, float* y, size_t n, float cap, vetta_stream_t stream);
|
||||
|
||||
|
||||
@@ -118,6 +118,11 @@ __device__ __forceinline__ float bf16_round(float f) {
|
||||
return __uint_as_float(((u + r) >> 16) << 16);
|
||||
}
|
||||
|
||||
// FP16 -> f32 (used by the FP16 KV cache + FP16 expert paths).
|
||||
__device__ __forceinline__ float f16_to_f32(uint16_t h) {
|
||||
return __half2float(__ushort_as_half(h));
|
||||
}
|
||||
|
||||
// ---- k_embed_bf16 (kernel #1): gather token rows from a BF16 table ---------
|
||||
// out[b, :] = bf16_to_f32(table[token[b], :]). Exact (no arithmetic).
|
||||
|
||||
@@ -353,6 +358,103 @@ extern "C" int vetta_flash_swa_gqa_decode(const float* q, const float* k, const
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ---- k_flash_swa_gqa_decode_f16: FP16 KV cache variant (exact strata default) --
|
||||
// strata stores K/V in FP16 (KvDtype::FP16, "default lossless FP16"); attention
|
||||
// math stays f32. Reading FP16 KV (rounded at store) matches the reference's
|
||||
// length-dependent accumulation; F32 KV diverges on near-ties as the cache grows.
|
||||
__global__ void k_flash_swa_gqa_decode_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, int hd,
|
||||
float scale, int swa_window, int cur_pos,
|
||||
const float* __restrict__ rel_bias, int max_rel,
|
||||
const float* __restrict__ sink_logit,
|
||||
const float* __restrict__ gate) {
|
||||
const int h = blockIdx.x;
|
||||
const int kvh = h / (n_head / n_kv);
|
||||
const int tid = threadIdx.x;
|
||||
const int nt = blockDim.x;
|
||||
const int k_start = (swa_window > 0 && cur_pos >= swa_window) ? (cur_pos - swa_window + 1) : 0;
|
||||
const int n_win = cur_pos - k_start + 1;
|
||||
extern __shared__ float smem[];
|
||||
float* scores = smem;
|
||||
float* red = smem + n_win;
|
||||
const float* qh = q + (size_t)h * hd;
|
||||
const uint16_t* kh = k + (size_t)kvh * seq * hd;
|
||||
const uint16_t* vh = v + (size_t)kvh * seq * hd;
|
||||
const float* rb = rel_bias ? (rel_bias + (size_t)h * max_rel) : nullptr;
|
||||
const float sink = sink_logit ? sink_logit[h] : -INFINITY;
|
||||
|
||||
float lmax = sink;
|
||||
for (int p = tid; p < n_win; p += nt) {
|
||||
const int s = k_start + p;
|
||||
const uint16_t* ks = kh + (size_t)s * hd;
|
||||
float dot = 0.f;
|
||||
for (int d = 0; d < hd; ++d) dot += qh[d] * f16_to_f32(ks[d]);
|
||||
dot *= scale;
|
||||
const int dist = cur_pos - s;
|
||||
if (rb && dist < max_rel) dot += rb[dist];
|
||||
scores[p] = dot;
|
||||
lmax = fmaxf(lmax, dot);
|
||||
}
|
||||
red[tid] = lmax;
|
||||
__syncthreads();
|
||||
for (int s = nt / 2; s > 0; s >>= 1) {
|
||||
if (tid < s) red[tid] = fmaxf(red[tid], red[tid + s]);
|
||||
__syncthreads();
|
||||
}
|
||||
const float m = red[0];
|
||||
__syncthreads();
|
||||
|
||||
float lsum = 0.f;
|
||||
for (int p = tid; p < n_win; p += nt) {
|
||||
float e = __expf(scores[p] - m);
|
||||
scores[p] = e;
|
||||
lsum += e;
|
||||
}
|
||||
red[tid] = lsum;
|
||||
__syncthreads();
|
||||
for (int s = nt / 2; s > 0; s >>= 1) {
|
||||
if (tid < s) red[tid] += red[tid + s];
|
||||
__syncthreads();
|
||||
}
|
||||
const float total = red[0] + (sink_logit ? __expf(sink - m) : 0.f);
|
||||
const float inv = 1.f / fmaxf(total, 1e-30f);
|
||||
__syncthreads();
|
||||
|
||||
float* oh = out + (size_t)h * hd;
|
||||
for (int d = tid; d < hd; d += nt) {
|
||||
float acc = 0.f;
|
||||
for (int p = 0; p < n_win; ++p) {
|
||||
const int s = k_start + p;
|
||||
acc += scores[p] * inv * f16_to_f32(vh[(size_t)s * hd + d]);
|
||||
}
|
||||
if (gate) acc *= 1.f / (1.f + __expf(-gate[(size_t)h * hd + d]));
|
||||
oh[d] = acc;
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" int vetta_flash_swa_gqa_decode_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, int cur_pos,
|
||||
const float* rel_bias, int max_rel,
|
||||
const float* sink_logit, const float* gate,
|
||||
vetta_stream_t stream) {
|
||||
if (n_head <= 0 || n_kv <= 0 || seq <= 0 || hd <= 0 || (n_head % n_kv) != 0) return 1;
|
||||
if (cur_pos < 0 || cur_pos >= seq) return 1;
|
||||
const int k_start = (swa_window > 0 && cur_pos >= swa_window) ? (cur_pos - swa_window + 1) : 0;
|
||||
const int n_win = cur_pos - k_start + 1;
|
||||
const int nt = 256;
|
||||
const size_t shmem = ((size_t)n_win + nt) * sizeof(float);
|
||||
hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0;
|
||||
k_flash_swa_gqa_decode_f16<<<n_head, nt, shmem, s>>>(q, k, v, out, n_head, n_kv, seq, hd,
|
||||
scale, swa_window, cur_pos, rel_bias, max_rel,
|
||||
sink_logit, gate);
|
||||
HIP_CHECK(hipGetLastError());
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ---- k_moe_router_topk (kernel #11): Inkling exact sigmoid router ----------
|
||||
// Semantics verified against strata k4_moe_router_topk:
|
||||
// p[e] = sigmoid(logits[m,e]) (NaN->0); score[e] = p[e] + bias[e] (NaN->-1e29);
|
||||
@@ -512,10 +614,6 @@ extern "C" int vetta_cast_f32_f16(const float* x, uint16_t* y, size_t n,
|
||||
return 0;
|
||||
}
|
||||
|
||||
__device__ __forceinline__ float f16_to_f32(uint16_t h) {
|
||||
return __half2float(__ushort_as_half(h));
|
||||
}
|
||||
|
||||
// ---- NVFP4 (SF4) codecs — exact semantics from strata ink_hip_common -------
|
||||
// E2M1 nibble LUT; F8_E4M3FN group scale (16 weights/group); f32 outer_scale.
|
||||
// Layout: packed_e2m1 [N, K/2] (low nib = even col, high nib = odd col),
|
||||
@@ -1070,6 +1168,43 @@ extern "C" int vetta_kv_store(const float* k_in, const float* v_in, float* k_cac
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ---- k_kv_store_f16: store K/V rounded to FP16 (exact strata FP16 KV cache) --
|
||||
// K is the post-L2-clip key; V is RMS-normalized then rounded. __float2half_rn
|
||||
// matches strata's f32->fp16 store rounding.
|
||||
__global__ void k_kv_store_f16(const float* __restrict__ k_in, const float* __restrict__ v_in,
|
||||
uint16_t* __restrict__ k_cache, uint16_t* __restrict__ v_cache,
|
||||
int pos, int n_kv, int hd, int seq, float rms_eps) {
|
||||
const int h = blockIdx.x;
|
||||
if (h >= n_kv) return;
|
||||
const int tid = threadIdx.x;
|
||||
const int nt = blockDim.x;
|
||||
const float* kv = k_in + (size_t)h * hd;
|
||||
const float* vv = v_in + (size_t)h * hd;
|
||||
__shared__ float red[256];
|
||||
__shared__ float fac_s;
|
||||
const float v = (tid < hd) ? vv[tid] : 0.f;
|
||||
red[tid] = v * v;
|
||||
__syncthreads();
|
||||
for (int t = nt / 2; t > 0; t >>= 1) { if (tid < t) red[tid] += red[tid + t]; __syncthreads(); }
|
||||
if (tid == 0) fac_s = rsqrtf(red[0] / (float)hd + rms_eps);
|
||||
__syncthreads();
|
||||
if (tid < hd) {
|
||||
const size_t off = (size_t)h * seq * hd + (size_t)pos * hd + tid;
|
||||
k_cache[off] = __half_as_ushort(__float2half_rn(kv[tid]));
|
||||
v_cache[off] = __half_as_ushort(__float2half_rn(v * fac_s));
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" int vetta_kv_store_f16(const float* k_in, const float* v_in, uint16_t* k_cache,
|
||||
uint16_t* v_cache, int pos, int n_kv, int hd, int seq,
|
||||
float rms_eps, vetta_stream_t stream) {
|
||||
if (n_kv <= 0 || hd <= 0 || hd > 256 || seq <= 0 || pos < 0 || pos >= seq) return 1;
|
||||
hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0;
|
||||
k_kv_store_f16<<<n_kv, 256, 0, s>>>(k_in, v_in, k_cache, v_cache, pos, n_kv, hd, seq, rms_eps);
|
||||
HIP_CHECK(hipGetLastError());
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ---- k_softcap: logits = cap * tanh(x / cap) (final logit softcapping) -----
|
||||
|
||||
__global__ void k_softcap(const float* __restrict__ x, float* __restrict__ y, size_t n, float cap) {
|
||||
|
||||
Reference in new issue
Block a user