diff --git a/crates/vetta-infer-hip/src/lib.rs b/crates/vetta-infer-hip/src/lib.rs index 38d2300..7ced5a8 100644 --- a/crates/vetta-infer-hip/src/lib.rs +++ b/crates/vetta-infer-hip/src/lib.rs @@ -63,6 +63,13 @@ 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, scores_scratch: *mut c_float, stream: *mut c_void, ) -> c_int; + pub fn vetta_flash_swa_gqa_prefill_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, pos: *const c_int, rel_bias: *const c_float, max_rel: c_int, + sink_logit: *const c_float, gate: *const c_float, scores_scratch: *mut c_float, + n_win_max: c_int, m: c_int, 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, @@ -393,6 +400,25 @@ pub fn flash_swa_gqa_decode_f16(q: &DeviceBuf, k: &DeviceBuf, v: &DeviceBuf, out Ok(()) } +/// Batched causal flash SWA GQA (M=B) on FP16 KV. `pos` [M] gives each query +/// token's cur_pos (causal); KV cache must already hold all B positions. +/// `max_pos` = largest pos in the batch (sizes the [M,n_head,n_win_max] scratch, +/// allocated unpooled since it varies per batch). q/out/gate [M,n_head,hd]. +#[cfg(feature = "hip")] +#[allow(clippy::too_many_arguments)] +pub fn flash_swa_gqa_prefill_f16(q: &DeviceBuf, k: &DeviceBuf, v: &DeviceBuf, out: &DeviceBuf, n_head: i32, n_kv: i32, seq: i32, hd: i32, scale: f32, swa_window: i32, pos: &DeviceBuf, max_pos: i32, rel_bias: Option<&DeviceBuf>, max_rel: i32, sink_logit: Option<&DeviceBuf>, gate: Option<&DeviceBuf>, m: i32) -> 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 n_win_max = if swa_window > 0 && max_pos >= swa_window { swa_window } else { max_pos + 1 }; + let scratch = DeviceBuf::alloc_unpooled((m as usize) * (n_head as usize) * (n_win_max as usize) * 4)?; + let rc = unsafe { + ffi::vetta_flash_swa_gqa_prefill_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, pos.ptr as *const i32, rb, max_rel, sk, gt, scratch.ptr as *mut f32, n_win_max, m, std::ptr::null_mut()) + }; + if rc != 0 { return Err("flash_swa_gqa_prefill_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> { @@ -1344,6 +1370,57 @@ mod gpu_tests { assert!(hmax < 1e-6, "update_hist parity failed: {hmax}"); } + /// Batched causal flash prefill (M=B) must equal B sequential decode flash f16 + /// calls (each cur_pos=base+m), same FP16 KV + rel_bias + sink + gate. win=16 + /// exercises windowing; base=10 so early tokens are unwindowed, later windowed. + #[test] + #[ignore] + fn flash_swa_gqa_prefill_f16_parity() { + let (n_head, n_kv, hd, seq, b) = (8usize, 2usize, 128usize, 64usize, 20usize); + let (base, win, max_rel) = (10i32, 16i32, 16usize); + let scale = 1.0f32 / (hd as f32).sqrt(); + let max_pos = base + (b as i32) - 1; + let kf: Vec = (0..n_kv * seq * hd).map(|i| ((i % 41) as f32 - 20.0) * 0.02).collect(); + let vf: Vec = (0..n_kv * seq * hd).map(|i| ((i % 37) as f32 - 18.0) * 0.02).collect(); + let dkf = DeviceBuf::alloc(kf.len() * 4).unwrap(); dkf.h2d(&kf).unwrap(); + let dk = DeviceBuf::alloc(kf.len() * 2).unwrap(); cast_f32_f16(&dkf, &dk, kf.len()).unwrap(); + let dvf = DeviceBuf::alloc(vf.len() * 4).unwrap(); dvf.h2d(&vf).unwrap(); + let dv = DeviceBuf::alloc(vf.len() * 2).unwrap(); cast_f32_f16(&dvf, &dv, vf.len()).unwrap(); + let qf: Vec = (0..b * n_head * hd).map(|i| ((i % 29) as f32 - 14.0) * 0.03).collect(); + let rb: Vec = (0..b * n_head * max_rel).map(|i| ((i % 13) as f32 - 6.0) * 0.01).collect(); + let sk: Vec = (0..b * n_head).map(|i| -2.0 + (i % 5) as f32 * 0.1).collect(); + let gt: Vec = (0..b * n_head * hd).map(|i| ((i % 17) as f32 - 8.0) * 0.05).collect(); + let dq = DeviceBuf::alloc(qf.len() * 4).unwrap(); dq.h2d(&qf).unwrap(); + let drb = DeviceBuf::alloc(rb.len() * 4).unwrap(); drb.h2d(&rb).unwrap(); + let dsk = DeviceBuf::alloc(sk.len() * 4).unwrap(); dsk.h2d(&sk).unwrap(); + let dgt = DeviceBuf::alloc(gt.len() * 4).unwrap(); dgt.h2d(>).unwrap(); + let pos: Vec = (0..b).map(|m| base + m as i32).collect(); + let pos_bytes: Vec = pos.iter().flat_map(|x| x.to_le_bytes()).collect(); + let dpos = DeviceBuf::alloc(b * 4).unwrap(); dpos.h2d_bytes(&pos_bytes).unwrap(); + let dout_p = DeviceBuf::alloc(b * n_head * hd * 4).unwrap(); + flash_swa_gqa_prefill_f16(&dq, &dk, &dv, &dout_p, n_head as i32, n_kv as i32, seq as i32, hd as i32, scale, win, &dpos, max_pos, Some(&drb), max_rel as i32, Some(&dsk), Some(&dgt), b as i32).unwrap(); + let mut got_p = vec![0f32; b * n_head * hd]; dout_p.d2h(&mut got_p).unwrap(); + let dq1 = DeviceBuf::alloc(n_head * hd * 4).unwrap(); + let drb1 = DeviceBuf::alloc(n_head * max_rel * 4).unwrap(); + let dsk1 = DeviceBuf::alloc(n_head * 4).unwrap(); + let dgt1 = DeviceBuf::alloc(n_head * hd * 4).unwrap(); + let dout1 = DeviceBuf::alloc(n_head * hd * 4).unwrap(); + let mut got_s = vec![0f32; b * n_head * hd]; + for m in 0..b { + dq1.h2d(&qf[m * n_head * hd..(m + 1) * n_head * hd]).unwrap(); + drb1.h2d(&rb[m * n_head * max_rel..(m + 1) * n_head * max_rel]).unwrap(); + dsk1.h2d(&sk[m * n_head..(m + 1) * n_head]).unwrap(); + dgt1.h2d(>[m * n_head * hd..(m + 1) * n_head * hd]).unwrap(); + flash_swa_gqa_decode_f16(&dq1, &dk, &dv, &dout1, n_head as i32, n_kv as i32, seq as i32, hd as i32, scale, win, pos[m], Some(&drb1), max_rel as i32, Some(&dsk1), Some(&dgt1)).unwrap(); + let mut o = vec![0f32; n_head * hd]; dout1.d2h(&mut o).unwrap(); + got_s[m * n_head * hd..(m + 1) * n_head * hd].copy_from_slice(&o); + } + let mut max_rel_err = 0f32; + for (g, w) in got_p.iter().zip(got_s.iter()) { max_rel_err = max_rel_err.max((g - w).abs() / w.abs().max(1e-3)); } + eprintln!("flash_swa_gqa_prefill_f16 B={b} n_head={n_head} win={win} max_rel_err={max_rel_err:.3e}"); + assert!(max_rel_err < 1e-5, "flash prefill parity failed: {max_rel_err}"); + } + #[test] #[ignore] fn shortconv4_multistep_parity() { diff --git a/kernels/hip/vetta_kernels.hip b/kernels/hip/vetta_kernels.hip index 1551611..68b6a8d 100644 --- a/kernels/hip/vetta_kernels.hip +++ b/kernels/hip/vetta_kernels.hip @@ -478,6 +478,112 @@ extern "C" int vetta_flash_swa_gqa_decode_f16(const float* q, const uint16_t* k, return 0; } +// ---- k_flash_swa_gqa_prefill_f16: batched causal flash SWA GQA (M=B) -------- +// Same two-pass softmax semantics as the decode f16 kernel, extended to M tokens: +// grid (n_head, M); each query token m uses cur_pos=pos[m] (causal: attends keys +// <= pos[m]), so the KV cache [n_kv,seq,hd] must already hold all B positions. +// q/out/gate [M,n_head,hd]; rel_bias [M,n_head,max_rel]; sink [M,n_head]; +// scores_scratch [M,n_head,n_win_max] (n_win_max = max window over the batch). +__global__ void k_flash_swa_gqa_prefill_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, + const int32_t* __restrict__ pos, + const float* __restrict__ rel_bias, int max_rel, + const float* __restrict__ sink_logit, + const float* __restrict__ gate, + float* __restrict__ scores_scratch, + int n_win_max, int M) { + const int h = blockIdx.x; + const int m = blockIdx.y; + if (h >= n_head || m >= M) return; + const int kvh = h / (n_head / n_kv); + const int tid = threadIdx.x; + const int nt = blockDim.x; + const int cur_pos = pos[m]; + 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 = scores_scratch + ((size_t)m * n_head + h) * n_win_max; + float* red = smem; + const float* qh = q + ((size_t)m * n_head + 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)m * n_head + h) * max_rel) : nullptr; + const float sink = sink_logit ? sink_logit[(size_t)m * n_head + 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 mx = red[0]; + __syncthreads(); + + float lsum = 0.f; + for (int p = tid; p < n_win; p += nt) { + float e = __expf(scores[p] - mx); + 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 - mx) : 0.f); + const float inv = 1.f / fmaxf(total, 1e-30f); + __syncthreads(); + + float* oh = out + ((size_t)m * n_head + h) * hd; + const float* gh = gate ? (gate + ((size_t)m * n_head + h) * hd) : nullptr; + 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 (gh) acc *= 1.f / (1.f + __expf(-gh[d])); + oh[d] = acc; + } +} + +extern "C" int vetta_flash_swa_gqa_prefill_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, const int32_t* pos, + const float* rel_bias, int max_rel, + const float* sink_logit, const float* gate, + float* scores_scratch, int n_win_max, int M, + vetta_stream_t stream) { + if (n_head <= 0 || n_kv <= 0 || seq <= 0 || hd <= 0 || (n_head % n_kv) != 0 || M <= 0) return 1; + if (n_win_max <= 0) return 1; + const int nt = 256; + const size_t shmem = (size_t)nt * sizeof(float); + dim3 grid(n_head, M); + hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; + k_flash_swa_gqa_prefill_f16<<>>(q, k, v, out, n_head, n_kv, seq, hd, + scale, swa_window, pos, rel_bias, max_rel, + sink_logit, gate, scores_scratch, n_win_max, M); + 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);