From b5d6d7cee3f5fd5264914683db6e5f42bf49a32e Mon Sep 17 00:00:00 2001 From: iz0eyj Date: Tue, 1 Dec 2026 14:38:38 +0100 Subject: [PATCH] [HIP] k2 attention-prep kernels: L2 clip, relpos bias projection, KV store MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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). --- crates/vetta-infer-hip/src/lib.rs | 99 +++++++++++++++++++++++++++ kernels/hip/vetta_kernels.h | 14 ++++ kernels/hip/vetta_kernels.hip | 107 ++++++++++++++++++++++++++++++ 3 files changed, 220 insertions(+) diff --git a/crates/vetta-infer-hip/src/lib.rs b/crates/vetta-infer-hip/src/lib.rs index 1fbebbd..83258bb 100644 --- a/crates/vetta-infer-hip/src/lib.rs +++ b/crates/vetta-infer-hip/src/lib.rs @@ -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 { + let mut out = vec![0f32; rows * hd]; + for r in 0..rows { + let v: Vec = (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 = (0..rows * hd).map(|i| ((i % 29) as f32 - 14.0) * 0.5).collect(); + let scale: Vec = (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 = (0..n_head * d_rel).map(|i| ((i % 13) as f32 - 6.0) * 0.1).collect(); + let rp: Vec = (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 = (0..n_kv * hd2).map(|i| ((i % 17) as f32 - 8.0) * 0.2).collect(); + let v_in: Vec = (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) } } diff --git a/kernels/hip/vetta_kernels.h b/kernels/hip/vetta_kernels.h index c287776..4a437ac 100644 --- a/kernels/hip/vetta_kernels.h +++ b/kernels/hip/vetta_kernels.h @@ -99,6 +99,20 @@ int vetta_attn_res_mix(const float* blocks, const float* cur, const float* queri float* out, int n_blocks, int M, int n_queries, int D, float eps, vetta_stream_t stream); +// k_l2_clip: per-head L2 clip + optional per-dim scale + optional tau (in place). +int vetta_l2_clip(float* x, const float* scale, int rows, int hd, float clip, + int apply_tau, int pos, vetta_stream_t stream); + +// k_relpos_bias: rel_bias[h,dist] = sum_rc R[h,rc]*rel_proj[rc,dist], dist contiguous f32 cache. +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); + // Core <15 microkernel entry points (implemented progressively in M1 & M2): // 1. k_embed_bf16 // 2. k_rms_norm diff --git a/kernels/hip/vetta_kernels.hip b/kernels/hip/vetta_kernels.hip index 47a62bf..7860d5d 100644 --- a/kernels/hip/vetta_kernels.hip +++ b/kernels/hip/vetta_kernels.hip @@ -687,4 +687,111 @@ extern "C" int vetta_attn_res_mix(const float* blocks, const float* cur, const f k_attn_res_mix<<>>(blocks, cur, queries, out, n_blocks, M, n_queries, D, eps); HIP_CHECK(hipGetLastError()); return 0; +} + +// ---- k_l2_clip: per-head L2 clip + optional per-dim scale + optional tau ---- +// Exact strata k2 Q/R/K clip: v = x * scale (scale nullable); ss = sum(v^2); +// fac = min(1, clip/(sqrt(ss)+1e-6)); if apply_tau: fac *= 1 + 0.1*log(max(1, +// (pos+1)/8192)); x = v*fac. One block per row (head), in place. + +__global__ void k_l2_clip(float* __restrict__ x, const float* __restrict__ scale, + int rows, int hd, float clip, int apply_tau, int pos) { + const int r = blockIdx.x; + if (r >= rows) return; + const int tid = threadIdx.x; + const int nt = blockDim.x; + float* xv = x + (size_t)r * hd; + const float* sc = scale ? (scale + (size_t)r * hd) : nullptr; + __shared__ float red[256]; + __shared__ float fac_s; + const float v = (tid < hd) ? (xv[tid] * (sc ? sc[tid] : 1.f)) : 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) { + float fac = fminf(1.f, clip / (sqrtf(red[0]) + 1e-6f)); + if (apply_tau) { + const float rr = (float)(pos + 1) / 8192.f; + fac *= 1.f + 0.1f * logf(fmaxf(1.f, rr)); + } + fac_s = fac; + } + __syncthreads(); + if (tid < hd) xv[tid] = v * fac_s; +} + +extern "C" int vetta_l2_clip(float* x, const float* scale, int rows, int hd, + float clip, int apply_tau, int pos, vetta_stream_t stream) { + if (rows <= 0 || hd <= 0 || hd > 256) return 1; + hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; + k_l2_clip<<>>(x, scale, rows, hd, clip, apply_tau, pos); + HIP_CHECK(hipGetLastError()); + return 0; +} + +// ---- k_relpos_bias: rel_bias[h,dist] = sum_rc R[h,rc]*rel_proj[rc,dist] ---- +// R already L2-clipped [n_head,d_rel]; rel_proj [d_rel,rel_extent]; output +// rel_bias [n_head,rel_extent] for dist < lim = min(pos+1, rel_extent). + +__global__ void k_relpos_bias(const float* __restrict__ r, const float* __restrict__ rel_proj, + float* __restrict__ rel_bias, int n_head, int d_rel, + int rel_extent, int lim) { + const int h = blockIdx.x; + if (h >= n_head) return; + const int tid = threadIdx.x; + const int nt = blockDim.x; + const float* rh = r + (size_t)h * d_rel; + float* dst = rel_bias + (size_t)h * rel_extent; + for (int dist = tid; dist < lim; dist += nt) { + float acc = 0.f; + for (int rc = 0; rc < d_rel; ++rc) acc += rh[rc] * rel_proj[(size_t)rc * rel_extent + dist]; + dst[dist] = acc; + } +} + +extern "C" int vetta_relpos_bias(const float* r, const float* rel_proj, float* rel_bias, + int n_head, int d_rel, int rel_extent, int lim, + vetta_stream_t stream) { + if (n_head <= 0 || d_rel <= 0 || rel_extent <= 0 || lim < 0) return 1; + hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; + k_relpos_bias<<>>(r, rel_proj, rel_bias, n_head, d_rel, rel_extent, lim); + HIP_CHECK(hipGetLastError()); + return 0; +} + +// ---- k_kv_store: K (pre-clipped) stored as-is; V RMS-normalized; contiguous +// f32 cache [n_kv, seq, hd] at position pos. Exact strata K-clip/V-rmsnorm. + +__global__ void k_kv_store(const float* __restrict__ k_in, const float* __restrict__ v_in, + float* __restrict__ k_cache, float* __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] = kv[tid]; + v_cache[off] = v * fac_s; + } +} + +extern "C" 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) { + 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<<>>(k_in, v_in, k_cache, v_cache, pos, n_kv, hd, seq, rms_eps); + HIP_CHECK(hipGetLastError()); + return 0; } \ No newline at end of file