diff --git a/crates/vetta-infer-hip/src/lib.rs b/crates/vetta-infer-hip/src/lib.rs index 93c22db..920cee1 100644 --- a/crates/vetta-infer-hip/src/lib.rs +++ b/crates/vetta-infer-hip/src/lib.rs @@ -40,6 +40,15 @@ mod ffi { x: *const u16, w: *const u16, y: *mut c_float, m: c_int, n: c_int, k: c_int, stream: *mut c_void, ) -> c_int; + pub fn vetta_flash_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, 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, + ) -> c_int; + pub fn vetta_vec_add(a: *const c_float, b: *const c_float, y: *mut c_float, n: usize, stream: *mut c_void) -> c_int; } } @@ -161,6 +170,35 @@ pub fn gemm_bf16(x: &DeviceBuf, w: &DeviceBuf, y: &DeviceBuf, m: i32, n: i32, k: Ok(()) } +/// Launch k_flash_gqa_decode: single-token GQA attention over a f32 KV cache. +#[cfg(feature = "hip")] +pub fn flash_gqa_decode(q: &DeviceBuf, k: &DeviceBuf, v: &DeviceBuf, out: &DeviceBuf, n_head: i32, n_kv: i32, seq: i32, hd: i32, scale: f32) -> Result<(), String> { + let rc = unsafe { + ffi::vetta_flash_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, std::ptr::null_mut()) + }; + if rc != 0 { return Err("flash_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> { + let bp = bias.map(|b| b.ptr as *const f32).unwrap_or(std::ptr::null()); + let rc = unsafe { + ffi::vetta_moe_router_topk(logits.ptr as *const f32, bp, ids.ptr as *mut i32, weights.ptr as *mut f32, m, n_experts, k_top, route_scale, std::ptr::null_mut()) + }; + if rc != 0 { return Err("router launch failed".into()); } + Ok(()) +} + +/// Launch k_vec_add: y = a + b elementwise. +#[cfg(feature = "hip")] +pub fn vec_add(a: &DeviceBuf, b: &DeviceBuf, y: &DeviceBuf, n: usize) -> Result<(), String> { + let rc = unsafe { ffi::vetta_vec_add(a.ptr as *const f32, b.ptr as *const f32, y.ptr as *mut f32, n, std::ptr::null_mut()) }; + if rc != 0 { return Err("vec_add launch failed".into()); } + Ok(()) +} + #[cfg(all(test, feature = "hip"))] mod gpu_tests { use super::*; @@ -269,6 +307,123 @@ mod gpu_tests { } } + fn cpu_attn(q: &[f32], k: &[f32], v: &[f32], n_head: usize, n_kv: usize, seq: usize, hd: usize, scale: f32) -> Vec { + let group = n_head / n_kv; + let mut out = vec![0f32; n_head * hd]; + for h in 0..n_head { + let kvh = h / group; + let qh = &q[h * hd..(h + 1) * hd]; + let mut scores = vec![0f32; seq]; + for s in 0..seq { + let ks = &k[(kvh * seq + s) * hd..(kvh * seq + s + 1) * hd]; + scores[s] = qh.iter().zip(ks).map(|(a, b)| a * b).sum::() * scale; + } + let m = scores.iter().cloned().fold(f32::NEG_INFINITY, f32::max); + let mut denom = 0f32; + for s in 0..seq { scores[s] = (scores[s] - m).exp(); denom += scores[s]; } + for d in 0..hd { + let mut acc = 0f32; + for s in 0..seq { acc += scores[s] / denom * v[(kvh * seq + s) * hd + d]; } + out[h * hd + d] = acc; + } + } + out + } + + #[test] + #[ignore] + fn flash_gqa_decode_parity_vs_cpu() { + for &(n_head, n_kv, seq, hd) in &[(8usize, 2usize, 32usize, 64usize), (24, 8, 128, 128), (4, 4, 16, 32)] { + 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 want = cpu_attn(&q, &k, &v, n_head, n_kv, seq, hd, scale); + 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(); + dq.h2d(&q).unwrap(); dk.h2d(&k).unwrap(); dv.h2d(&v).unwrap(); + flash_gqa_decode(&dq, &dk, &dv, &dy, n_head as i32, n_kv as i32, seq as i32, hd as i32, scale).unwrap(); + let mut got = vec![0f32; want.len()]; + dy.d2h(&mut got).unwrap(); + let mut max_rel = 0f32; + for (g, wnt) in got.iter().zip(want.iter()) { + max_rel = max_rel.max((g - wnt).abs() / wnt.abs().max(1e-3)); + } + eprintln!("flash_gqa nh={n_head} nkv={n_kv} seq={seq} hd={hd} max_rel_err={max_rel:.3e}"); + assert!(max_rel < 1e-4, "flash_gqa parity failed: {max_rel}"); + } + } + + 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]; + for mi in 0..m { + let prob: Vec = (0..n_experts).map(|e| 1.0 / (1.0 + (-logits[mi * n_experts + e]).exp())).collect(); + let mut score: Vec = (0..n_experts).map(|e| prob[e] + bias[e]).collect(); + let mut wsum = 0f32; + for k in 0..k_top { + let mut bv = f32::NEG_INFINITY; + let mut bi = 0usize; + for e in 0..n_experts { if score[e] > bv { bv = score[e]; bi = e; } } + ids[mi * k_top + k] = bi as i32; + weights[mi * k_top + k] = prob[bi]; + wsum += prob[bi]; + score[bi] = -1e30; + } + let inv = route_scale / (wsum + 1e-20); + for k in 0..k_top { weights[mi * k_top + k] *= inv; } + } + (ids, weights) + } + + fn read_i32(buf: &DeviceBuf, len: usize) -> Vec { + let mut bytes = vec![0u8; len * 4]; + buf.d2h_bytes(&mut bytes).unwrap(); + bytes.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect() + } + + #[test] + #[ignore] + fn moe_router_parity_vs_cpu() { + let (m, n_experts, k_top, route_scale) = (2usize, 128usize, 8usize, 8.0f32); + let logits: Vec = (0..m * n_experts).map(|i| ((i % 47) as f32 - 23.0) * 0.2).collect(); + let bias: Vec = (0..n_experts).map(|i| ((i % 19) as f32 - 9.0) * 0.03).collect(); + let (want_ids, want_w) = cpu_router(&logits, &bias, m, n_experts, k_top, route_scale); + let dl = DeviceBuf::alloc(logits.len() * 4).unwrap(); + let db = DeviceBuf::alloc(bias.len() * 4).unwrap(); + let di = DeviceBuf::alloc(want_ids.len() * 4).unwrap(); + let dw = DeviceBuf::alloc(want_w.len() * 4).unwrap(); + dl.h2d(&logits).unwrap(); db.h2d(&bias).unwrap(); + moe_router_topk(&dl, Some(&db), &di, &dw, m as i32, n_experts as i32, k_top as i32, route_scale).unwrap(); + let got_ids = read_i32(&di, want_ids.len()); + let mut got_w = vec![0f32; want_w.len()]; + dw.d2h(&mut got_w).unwrap(); + assert_eq!(got_ids, want_ids, "router top-k ids must match exactly"); + let mut max_rel = 0f32; + for (g, w) in got_w.iter().zip(want_w.iter()) { max_rel = max_rel.max((g - w).abs() / w.abs().max(1e-3)); } + eprintln!("router max_rel_err={max_rel:.3e}"); + assert!(max_rel < 1e-5, "router weights parity failed: {max_rel}"); + } + + #[test] + #[ignore] + fn vec_add_exact() { + let n = 10000usize; + let a: Vec = (0..n).map(|i| (i as f32) * 0.01).collect(); + let b: Vec = (0..n).map(|i| -(i as f32) * 0.003).collect(); + let want: Vec = a.iter().zip(&b).map(|(x, y)| x + y).collect(); + let da = DeviceBuf::alloc(n * 4).unwrap(); + let db = DeviceBuf::alloc(n * 4).unwrap(); + let dy = DeviceBuf::alloc(n * 4).unwrap(); + da.h2d(&a).unwrap(); db.h2d(&b).unwrap(); + vec_add(&da, &db, &dy, n).unwrap(); + let mut got = vec![0f32; n]; + dy.d2h(&mut got).unwrap(); + assert_eq!(got, want, "vec_add must be exact"); + } + 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 9088d26..6a3da0b 100644 --- a/kernels/hip/vetta_kernels.h +++ b/kernels/hip/vetta_kernels.h @@ -45,6 +45,21 @@ int vetta_embed_bf16_gather(const uint16_t* table, const int32_t* tokens, int vetta_gemm_bf16(const uint16_t* x, const uint16_t* w, float* y, int M, int N, int K, vetta_stream_t stream); +// k_flash_gqa_decode (base): single-token GQA attention over a f32 KV cache. +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_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, + int M, int n_experts, int K_top, + float route_scale, vetta_stream_t stream); + +// k_vec_add: y = a + b elementwise (residual stream). +int vetta_vec_add(const float* a, const float* b, float* y, size_t n, + 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 581b652..6de542a 100644 --- a/kernels/hip/vetta_kernels.hip +++ b/kernels/hip/vetta_kernels.hip @@ -164,4 +164,161 @@ extern "C" int vetta_gemm_bf16(const uint16_t* x, const uint16_t* w, float* y, k_gemm_bf16<<>>(x, w, y, M, N, K); HIP_CHECK(hipGetLastError()); return 0; +} + +// ---- k_flash_gqa_decode (kernel #8 base): single-token GQA attention ------- +// q f32 [n_head, hd]; k/v f32 cache [n_kv, seq, hd]; out f32 [n_head, hd]. +// Head h attends to KV head h/(n_head/n_kv) over all `seq` cached positions +// (decode is causal over the full cache). Two-pass softmax, f32 throughout. +// Correctness-first; SWA window / relpos bias / split-KV / WMMA are the +// performance + parity refinements layered on later. + +__global__ void k_flash_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) { + const int h = blockIdx.x; + const int kvh = h / (n_head / n_kv); + const int tid = threadIdx.x; + const int nt = blockDim.x; + extern __shared__ float smem[]; + float* scores = smem; // [seq] + float* red = smem + seq; // [nt] reduction scratch + 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; + + float lmax = -INFINITY; + for (int s = tid; s < seq; s += nt) { + 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; + scores[s] = 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 s = tid; s < seq; s += nt) { + float e = __expf(scores[s] - m); + scores[s] = 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 inv = 1.f / red[0]; + __syncthreads(); + + float* oh = out + (size_t)h * hd; + for (int d = tid; d < hd; d += nt) { + float acc = 0.f; + for (int s = 0; s < seq; ++s) acc += scores[s] * inv * vh[(size_t)s * hd + d]; + oh[d] = acc; + } +} + +extern "C" 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) { + if (n_head <= 0 || n_kv <= 0 || seq <= 0 || hd <= 0 || (n_head % n_kv) != 0) return 1; + const int nt = 256; + const size_t shmem = ((size_t)seq + nt) * sizeof(float); + hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; + k_flash_gqa_decode<<>>(q, k, v, out, n_head, n_kv, seq, hd, scale); + 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); +// top-K by score (strictly greater, smallest eid wins ties); +// weight[k] = p[chosen] (the sigmoid prob, NOT the score); +// weights *= route_scale / (sum(weights) + 1e-20). + +__global__ void k_moe_router_topk(const float* __restrict__ logits, + const float* __restrict__ bias, + int32_t* __restrict__ topk_ids, + float* __restrict__ topk_weights, + int M, int n_experts, int K_top, + float route_scale) { + const int m = blockIdx.x; + if (m >= M) return; + extern __shared__ float smem[]; + float* prob = smem; // [n_experts] + float* score = smem + n_experts; // [n_experts] + const int tid = threadIdx.x; + const int nt = blockDim.x; + for (int e = tid; e < n_experts; e += nt) { + float lg = logits[(size_t)m * n_experts + e]; + float p = 1.f / (1.f + __expf(-lg)); + if (!(p == p)) p = 0.f; + prob[e] = p; + float sc = p + (bias ? bias[e] : 0.f); + if (!(sc == sc)) sc = -1e29f; + score[e] = sc; + } + __syncthreads(); + if (tid == 0) { + float wsum = 0.f; + for (int k = 0; k < K_top; ++k) { + float bv = -INFINITY; + int bi = -1; + for (int e = 0; e < n_experts; ++e) { + if (score[e] > bv) { bv = score[e]; bi = e; } + } + topk_ids[(size_t)m * K_top + k] = bi; + float w = prob[bi]; + topk_weights[(size_t)m * K_top + k] = w; + wsum += w; + score[bi] = -1e30f; + } + float inv = route_scale / (wsum + 1e-20f); + for (int k = 0; k < K_top; ++k) topk_weights[(size_t)m * K_top + k] *= inv; + } +} + +extern "C" int vetta_moe_router_topk(const float* logits, const float* bias, + int32_t* topk_ids, float* topk_weights, + int M, int n_experts, int K_top, + float route_scale, vetta_stream_t stream) { + if (M <= 0 || n_experts <= 0 || K_top <= 0 || K_top > n_experts) return 1; + const size_t shmem = (size_t)2 * n_experts * sizeof(float); + hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; + k_moe_router_topk<<>>(logits, bias, topk_ids, topk_weights, M, n_experts, K_top, route_scale); + HIP_CHECK(hipGetLastError()); + return 0; +} + +// ---- k_vec_add: y = a + b elementwise (residual stream) -------------------- + +__global__ void k_vec_add(const float* __restrict__ a, const float* __restrict__ b, + float* __restrict__ y, size_t n) { + size_t i = (size_t)blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) y[i] = a[i] + b[i]; +} + +extern "C" int vetta_vec_add(const float* a, const float* b, float* y, size_t n, + vetta_stream_t stream) { + if (n == 0) return 0; + const int nt = 256; + const size_t grid = (n + nt - 1) / nt; + hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; + k_vec_add<<>>(a, b, y, n); + HIP_CHECK(hipGetLastError()); + return 0; } \ No newline at end of file