[HIP] k2 attention-prep kernels: L2 clip, relpos bias projection, KV store

- k_l2_clip / vetta_l2_clip: exact strata Q/R/K per-head L2 clip — v = x*scale
  (scale nullable), fac = min(1, clip/(sqrt(sum v^2)+1e-6)), optional tau
  fac *= 1 + 0.1*log(max(1,(pos+1)/8192)) (kLogScaleAlpha=0.1, floor=8192);
  x = v*fac, in place. Config: qk_clip=22.627, rel_clip=8.0; tau=!is_swa.
- k_relpos_bias / vetta_relpos_bias: rel_bias[h,dist] = sum_rc R[h,rc] *
  rel_proj[rc,dist] for dist < lim=min(pos+1,rel_extent). R pre-clipped
  [n_head,d_rel=16], rel_proj [d_rel,rel_extent=1024] (rel_logits_proj.proj).
- k_kv_store / vetta_kv_store: K (pre-clipped) stored as-is, V RMS-normalized
  (rsqrt(mean v^2 + eps)), into a contiguous f32 KV cache [n_kv,seq,hd] at pos.
  (Paged FP16/FP8 KV pool is a later perf refinement; contiguous f32 first.)
- Combined parity test vs CPU oracles: l2_clip (scale+tau and plain), relpos
  bias, kv_store (K exact, V <1e-5). These complete the k2 attention prep; with
  gemm_bf16 (projections) + shortconv4 + flash_swa_gqa the full attention block
  can now be composed.

Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (4 files, 42 theorems) green; GPU 14/14 (--features hip).
This commit is contained in:
adm committed 2026-12-01 14:38:38 +01:00
1 parent a5ee804641
commit b5d6d7cee3
3 files changed
+220

No files matched your search

+99
View File
@@ -64,6 +64,9 @@ mod ffi {
pub fn vetta_moe_reduce(y_part: *const c_float, tk_w: *const c_float, out: *mut c_float, top_k: c_int, hidden: c_int, stream: *mut c_void) -> c_int;
pub fn vetta_shortconv4_decode(cur: *const c_float, static_w: *const c_float, hist: *mut c_float, out: *mut c_float, slot_ids: *const i32, m: c_int, c: c_int, stream: *mut c_void) -> c_int;
pub fn vetta_attn_res_mix(blocks: *const c_float, cur: *const c_float, queries: *const c_float, out: *mut c_float, n_blocks: c_int, m: c_int, n_queries: c_int, d: c_int, eps: c_float, stream: *mut c_void) -> c_int;
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;
}
}
@@ -280,6 +283,32 @@ pub fn attn_res_mix(blocks: &DeviceBuf, cur: &DeviceBuf, queries: &DeviceBuf, ou
Ok(())
}
/// Launch k_l2_clip: per-head L2 clip + optional scale + optional tau (in place).
#[cfg(feature = "hip")]
pub fn l2_clip(x: &DeviceBuf, scale: Option<&DeviceBuf>, rows: i32, hd: i32, clip: f32, apply_tau: bool, pos: i32) -> Result<(), String> {
let sc = scale.map(|b| b.ptr as *const f32).unwrap_or(std::ptr::null());
let rc = unsafe { ffi::vetta_l2_clip(x.ptr as *mut f32, sc, rows, hd, clip, apply_tau as i32, pos, std::ptr::null_mut()) };
if rc != 0 { return Err("l2_clip launch failed".into()); }
Ok(())
}
/// Launch k_relpos_bias: rel_bias[h,dist] = sum_rc R[h,rc]*rel_proj[rc,dist].
#[cfg(feature = "hip")]
pub fn relpos_bias(r: &DeviceBuf, rel_proj: &DeviceBuf, rel_bias: &DeviceBuf, n_head: i32, d_rel: i32, rel_extent: i32, lim: i32) -> Result<(), String> {
let rc = unsafe { ffi::vetta_relpos_bias(r.ptr as *const f32, rel_proj.ptr as *const f32, rel_bias.ptr as *mut f32, n_head, d_rel, rel_extent, lim, std::ptr::null_mut()) };
if rc != 0 { return Err("relpos_bias launch failed".into()); }
Ok(())
}
/// Launch k_kv_store: K (pre-clipped) as-is + V RMS-normalized into f32 cache.
#[cfg(feature = "hip")]
#[allow(clippy::too_many_arguments)]
pub fn kv_store(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(k_in.ptr as *const f32, v_in.ptr as *const f32, k_cache.ptr as *mut f32, v_cache.ptr as *mut f32, pos, n_kv, hd, seq, rms_eps, std::ptr::null_mut()) };
if rc != 0 { return Err("kv_store launch failed".into()); }
Ok(())
}
#[cfg(all(test, feature = "hip"))]
mod gpu_tests {
use super::*;
@@ -765,6 +794,76 @@ mod gpu_tests {
assert!(max_rel < 1e-4, "attn_res_mix parity failed: {max_rel}");
}
fn l2_clip_cpu(x: &[f32], scale: Option<&[f32]>, rows: usize, hd: usize, clip: f32, apply_tau: bool, pos: i32) -> Vec<f32> {
let mut out = vec![0f32; rows * hd];
for r in 0..rows {
let v: Vec<f32> = (0..hd).map(|d| x[r * hd + d] * scale.map(|s| s[r * hd + d]).unwrap_or(1.0)).collect();
let ss: f32 = v.iter().map(|t| t * t).sum();
let mut fac = (clip / (ss.sqrt() + 1e-6)).min(1.0);
if apply_tau { let rr = (pos + 1) as f32 / 8192.0; fac *= 1.0 + 0.1 * rr.max(1.0).ln(); }
for d in 0..hd { out[r * hd + d] = v[d] * fac; }
}
out
}
#[test]
#[ignore]
fn k2_prep_kernels_parity() {
// --- l2_clip (with scale + tau, and without) ---
let (rows, hd) = (4usize, 8usize);
let x: Vec<f32> = (0..rows * hd).map(|i| ((i % 29) as f32 - 14.0) * 0.5).collect();
let scale: Vec<f32> = (0..rows * hd).map(|i| 0.5 + (i % 7) as f32 * 0.1).collect();
for &(use_scale, tau, pos) in &[(true, true, 10000i32), (false, false, 0)] {
let clip = 2.0f32;
let want = l2_clip_cpu(&x, use_scale.then_some(scale.as_slice()), rows, hd, clip, tau, pos);
let dx = DeviceBuf::alloc(x.len() * 4).unwrap(); dx.h2d(&x).unwrap();
let ds = DeviceBuf::alloc(scale.len() * 4).unwrap(); ds.h2d(&scale).unwrap();
l2_clip(&dx, use_scale.then_some(&ds), rows as i32, hd as i32, clip, tau, pos).unwrap();
let mut got = vec![0f32; x.len()]; dx.d2h(&mut got).unwrap();
let mut mr = 0f32; for (g, w) in got.iter().zip(want.iter()) { mr = mr.max((g - w).abs() / w.abs().max(1e-3)); }
assert!(mr < 1e-5, "l2_clip parity failed (scale={use_scale} tau={tau}): {mr}");
}
// --- relpos_bias ---
let (n_head, d_rel, rel_extent, lim) = (4usize, 4usize, 16usize, 10i32);
let r: Vec<f32> = (0..n_head * d_rel).map(|i| ((i % 13) as f32 - 6.0) * 0.1).collect();
let rp: Vec<f32> = (0..d_rel * rel_extent).map(|i| ((i % 11) as f32 - 5.0) * 0.05).collect();
let mut want_rb = vec![0f32; n_head * rel_extent];
for h in 0..n_head { for dist in 0..lim as usize { let mut acc = 0f32; for rc in 0..d_rel { acc += r[h * d_rel + rc] * rp[rc * rel_extent + dist]; } want_rb[h * rel_extent + dist] = acc; } }
let dr = DeviceBuf::alloc(r.len() * 4).unwrap(); dr.h2d(&r).unwrap();
let drp = DeviceBuf::alloc(rp.len() * 4).unwrap(); drp.h2d(&rp).unwrap();
let drb = DeviceBuf::alloc(want_rb.len() * 4).unwrap();
drb.h2d(&vec![0f32; want_rb.len()]).unwrap();
relpos_bias(&dr, &drp, &drb, n_head as i32, d_rel as i32, rel_extent as i32, lim).unwrap();
let mut got_rb = vec![0f32; want_rb.len()]; drb.d2h(&mut got_rb).unwrap();
let mut mr = 0f32; for (g, w) in got_rb.iter().zip(want_rb.iter()) { mr = mr.max((g - w).abs() / w.abs().max(1e-3)); }
assert!(mr < 1e-5, "relpos_bias parity failed: {mr}");
// --- kv_store ---
let (n_kv, hd2, seq, pos) = (2usize, 8usize, 16usize, 5i32);
let eps = 1e-6f32;
let k_in: Vec<f32> = (0..n_kv * hd2).map(|i| ((i % 17) as f32 - 8.0) * 0.2).collect();
let v_in: Vec<f32> = (0..n_kv * hd2).map(|i| ((i % 19) as f32 - 9.0) * 0.3).collect();
let mut want_k = vec![0f32; n_kv * seq * hd2];
let mut want_v = vec![0f32; n_kv * seq * hd2];
for h in 0..n_kv {
let ss: f32 = (0..hd2).map(|d| v_in[h * hd2 + d] * v_in[h * hd2 + d]).sum();
let fac = 1.0 / (ss / hd2 as f32 + eps).sqrt();
for d in 0..hd2 { let off = (h * seq + pos as usize) * hd2 + d; want_k[off] = k_in[h * hd2 + d]; want_v[off] = v_in[h * hd2 + d] * fac; }
}
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();
let dkc = DeviceBuf::alloc(want_k.len() * 4).unwrap();
let dvc = DeviceBuf::alloc(want_v.len() * 4).unwrap();
dkc.h2d(&vec![0f32; want_k.len()]).unwrap();
dvc.h2d(&vec![0f32; want_v.len()]).unwrap();
kv_store(&dki, &dvi, &dkc, &dvc, pos, n_kv as i32, hd2 as i32, seq as i32, eps).unwrap();
let mut got_k = vec![0f32; want_k.len()]; dkc.d2h(&mut got_k).unwrap();
let mut got_v = vec![0f32; want_v.len()]; dvc.d2h(&mut got_v).unwrap();
assert_eq!(got_k, want_k, "kv_store K must match exactly");
let mut mr = 0f32; for (g, w) in got_v.iter().zip(want_v.iter()) { mr = mr.max((g - w).abs() / w.abs().max(1e-3)); }
assert!(mr < 1e-5, "kv_store V parity failed: {mr}");
eprintln!("k2 prep kernels (l2_clip + relpos_bias + kv_store): parity OK");
}
fn bytemuck_u16(v: &[u16]) -> &[u8] {
unsafe { std::slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * 2) }
}