diff --git a/crates/vetta-infer-hip/src/lib.rs b/crates/vetta-infer-hip/src/lib.rs index c0e1a90..2cb9340 100644 --- a/crates/vetta-infer-hip/src/lib.rs +++ b/crates/vetta-infer-hip/src/lib.rs @@ -44,6 +44,12 @@ mod ffi { q: *const c_float, k: *const c_float, v: *const c_float, out: *mut c_float, n_head: c_int, n_kv: c_int, seq: c_int, hd: c_int, scale: c_float, stream: *mut c_void, ) -> c_int; + pub fn vetta_flash_swa_gqa_decode( + q: *const c_float, k: *const c_float, v: *const c_float, 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, @@ -188,6 +194,21 @@ pub fn flash_gqa_decode(q: &DeviceBuf, k: &DeviceBuf, v: &DeviceBuf, out: &Devic Ok(()) } +/// Launch k_flash_swa_gqa_decode: Inkling SWA window + relpos + sink + gate. +/// `rel_bias`, `sink_logit`, `gate` are optional (None -> NULL). +#[cfg(feature = "hip")] +#[allow(clippy::too_many_arguments)] +pub fn flash_swa_gqa_decode(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(q.ptr as *const f32, k.ptr as *const f32, v.ptr as *const f32, 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 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> { @@ -406,6 +427,75 @@ mod gpu_tests { } } + #[allow(clippy::too_many_arguments)] + fn cpu_swa_attn(q: &[f32], k: &[f32], v: &[f32], n_head: usize, n_kv: usize, seq: usize, hd: usize, scale: f32, window: i32, cur_pos: i32, rb: Option<&[f32]>, max_rel: usize, sink: Option<&[f32]>, gate: Option<&[f32]>) -> Vec { + let k_start = if window > 0 && cur_pos >= window { (cur_pos - window + 1) as usize } else { 0 }; + let mut out = vec![0f32; n_head * hd]; + for h in 0..n_head { + let kvh = h / (n_head / n_kv); + let sink_v = sink.map(|s| s[h]); + let mut m = sink_v.unwrap_or(f32::NEG_INFINITY); + let mut scores = Vec::new(); + let mut positions = Vec::new(); + for s in k_start..=(cur_pos as usize) { + let mut dot = 0f32; + for d in 0..hd { dot += q[h * hd + d] * k[(kvh * seq + s) * hd + d]; } + dot *= scale; + let dist = cur_pos as usize - s; + if let Some(rb) = rb { if dist < max_rel { dot += rb[h * max_rel + dist]; } } + scores.push(dot); + positions.push(s); + m = m.max(dot); + } + let exps: Vec = scores.iter().map(|sc| (sc - m).exp()).collect(); + let mut denom = sink_v.map(|sv| (sv - m).exp()).unwrap_or(0.0); + denom += exps.iter().sum::(); + let inv = 1.0 / denom.max(1e-30); + for d in 0..hd { + let mut acc = 0f32; + for (i, &s) in positions.iter().enumerate() { acc += exps[i] * inv * v[(kvh * seq + s) * hd + d]; } + if let Some(g) = gate { acc *= 1.0 / (1.0 + (-g[h * hd + d]).exp()); } + out[h * hd + d] = acc; + } + } + out + } + + #[test] + #[ignore] + fn flash_swa_gqa_parity_vs_cpu() { + // (window, use_relpos, use_sink, use_gate) + for &(window, ur, us, ug) in &[(4i32, true, true, true), (0, true, true, true), (6, false, false, false), (3, true, false, true)] { + let (n_head, n_kv, seq, hd) = (8usize, 2usize, 32usize, 64usize); + let cur_pos = (seq - 1) as i32; + let max_rel = 32usize; + let scale = 1.0f32 / (hd as f32).sqrt(); + let q: Vec = (0..n_head * hd).map(|i| ((i % 23) as f32 - 11.0) * 0.04).collect(); + let k: Vec = (0..n_kv * seq * hd).map(|i| ((i % 31) as f32 - 15.0) * 0.03).collect(); + let v: Vec = (0..n_kv * seq * hd).map(|i| ((i % 17) as f32 - 8.0) * 0.05).collect(); + let rb: Vec = (0..n_head * max_rel).map(|i| ((i % 13) as f32 - 6.0) * 0.02).collect(); + let sink: Vec = (0..n_head).map(|i| (i as f32) * 0.3 - 1.0).collect(); + let gate: Vec = (0..n_head * hd).map(|i| ((i % 29) as f32 - 14.0) * 0.1).collect(); + let want = cpu_swa_attn(&q, &k, &v, n_head, n_kv, seq, hd, scale, window, cur_pos, ur.then_some(rb.as_slice()), max_rel, us.then_some(sink.as_slice()), ug.then_some(gate.as_slice())); + let dq = DeviceBuf::alloc(q.len() * 4).unwrap(); + let dk = DeviceBuf::alloc(k.len() * 4).unwrap(); + let dv = DeviceBuf::alloc(v.len() * 4).unwrap(); + let dy = DeviceBuf::alloc(want.len() * 4).unwrap(); + let drb = DeviceBuf::alloc(rb.len() * 4).unwrap(); + let dsk = DeviceBuf::alloc(sink.len() * 4).unwrap(); + let dgt = DeviceBuf::alloc(gate.len() * 4).unwrap(); + dq.h2d(&q).unwrap(); dk.h2d(&k).unwrap(); dv.h2d(&v).unwrap(); + drb.h2d(&rb).unwrap(); dsk.h2d(&sink).unwrap(); dgt.h2d(&gate).unwrap(); + flash_swa_gqa_decode(&dq, &dk, &dv, &dy, n_head as i32, n_kv as i32, seq as i32, hd as i32, scale, window, cur_pos, ur.then_some(&drb), max_rel as i32, us.then_some(&dsk), ug.then_some(&dgt)).unwrap(); + let mut got = vec![0f32; want.len()]; + dy.d2h(&mut got).unwrap(); + let mut max_rel_err = 0f32; + for (g, w) in got.iter().zip(want.iter()) { max_rel_err = max_rel_err.max((g - w).abs() / w.abs().max(1e-3)); } + eprintln!("flash_swa window={window} rel={ur} sink={us} gate={ug} max_rel_err={max_rel_err:.3e}"); + assert!(max_rel_err < 1e-4, "flash_swa parity failed: {max_rel_err}"); + } + } + fn cpu_router(logits: &[f32], bias: &[f32], m: usize, n_experts: usize, k_top: usize, route_scale: f32) -> (Vec, Vec) { let mut ids = vec![0i32; m * k_top]; let mut weights = vec![0f32; m * k_top]; diff --git a/kernels/hip/vetta_kernels.h b/kernels/hip/vetta_kernels.h index 959fcbd..75d0efa 100644 --- a/kernels/hip/vetta_kernels.h +++ b/kernels/hip/vetta_kernels.h @@ -50,6 +50,15 @@ int vetta_flash_gqa_decode(const float* q, const float* k, const float* v, float* out, int n_head, int n_kv, int seq, int hd, float scale, vetta_stream_t stream); +// k_flash_swa_gqa_decode: Inkling flash SWA GQA — SWA window + relpos bias + +// attention sink + sigmoid gate. rel_bias/sink_logit/gate may be NULL. +int vetta_flash_swa_gqa_decode(const float* q, const float* k, const float* 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, diff --git a/kernels/hip/vetta_kernels.hip b/kernels/hip/vetta_kernels.hip index fdada35..e372540 100644 --- a/kernels/hip/vetta_kernels.hip +++ b/kernels/hip/vetta_kernels.hip @@ -243,6 +243,108 @@ extern "C" int vetta_flash_gqa_decode(const float* q, const float* k, const floa return 0; } +// ---- k_flash_swa_gqa_decode: Inkling flash SWA GQA (parity) ---------------- +// Exact strata k3_flash_swa_gqa semantics on a contiguous f32 KV cache: +// SWA window: k_start = (window>0 && cur_pos>=window) ? cur_pos-window+1 : 0; +// rel_bias[h, dist] added to score (dist = cur_pos - s, if dist < max_rel); +// sink_logit[h]: virtual sink token (logit=sink, value=0) -> adds exp(sink-m) +// to the softmax denominator only; +// gate_attn[h, d]: output *= sigmoid(gate) per dim. +// Two-pass softmax over the windowed range, f32 throughout. + +__global__ void k_flash_swa_gqa_decode(const float* __restrict__ q, + const float* __restrict__ k, + const float* __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; // [n_win] + float* red = smem + n_win; // [nt] + const float* qh = q + (size_t)h * hd; + const float* kh = k + (size_t)kvh * seq * hd; + const float* 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 float* ks = kh + (size_t)s * hd; + float dot = 0.f; + for (int d = 0; d < hd; ++d) dot += qh[d] * 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 * 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(const float* q, const float* k, const float* 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<<>>(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);