diff --git a/crates/vetta-infer-hip/src/lib.rs b/crates/vetta-infer-hip/src/lib.rs index e838a22..5a8a63b 100644 --- a/crates/vetta-infer-hip/src/lib.rs +++ b/crates/vetta-infer-hip/src/lib.rs @@ -102,6 +102,8 @@ mod ffi { ) -> c_int; pub fn vetta_situ(gu: *const c_float, act: *mut c_float, inter: c_int, beta: c_float, lb: c_float, stream: *mut c_void) -> c_int; pub fn vetta_situ_f16(gu: *const c_float, act: *mut u16, inter: c_int, beta: c_float, lb: c_float, stream: *mut c_void) -> c_int; + pub fn vetta_situ_f16_batched(gu: *const c_float, act: *mut u16, inter: c_int, beta: c_float, lb: c_float, m: c_int, stream: *mut c_void) -> c_int; + pub fn vetta_mxfp8_grouped_gemv_f16(arena_weights: *const u8, arena_scales: *const u8, exp_off: *const c_int, bucket_tok: *const c_int, x: *const u16, y: *mut c_float, n: c_int, k: c_int, n_experts: c_int, w_stride: c_long, sc_stride: c_long, stream: *mut c_void) -> c_int; 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_moe_count_buckets(topk_ids: *const c_int, exp_cnt: *mut c_int, total: c_int, stream: *mut c_void) -> c_int; pub fn vetta_moe_prefix_buckets(exp_cnt: *const c_int, exp_off: *mut c_int, exp_cur: *mut c_int, stream: *mut c_void) -> c_int; @@ -547,6 +549,27 @@ pub fn situ_f16(gu: &DeviceBuf, act: &DeviceBuf, inter: i32, beta: f32, lb: f32) Ok(()) } +/// Batched SiTU (M rows): gu [M,2*inter] interleaved gate/up -> act [M,inter] FP16. +#[cfg(feature = "hip")] +pub fn situ_f16_batched(gu: &DeviceBuf, act: &DeviceBuf, inter: i32, beta: f32, lb: f32, m: i32) -> Result<(), String> { + let rc = unsafe { ffi::vetta_situ_f16_batched(gu.ptr as *const f32, act.ptr as *mut u16, inter, beta, lb, m, std::ptr::null_mut()) }; + if rc != 0 { return Err("situ_f16_batched launch failed".into()); } + Ok(()) +} + +/// Grouped MXFP8 expert GEMM (layers 20-23): grid (N, n_experts), bucket-indexed, +/// 32-byte E4M3 group dequantized once per MT=8 token tile (UE8M0 scale, no outer). +/// X [B,K] f16 -> Y [total_pairs,N] f32 bucket order. +#[cfg(feature = "hip")] +#[allow(clippy::too_many_arguments)] +pub fn mxfp8_grouped_gemv_f16(arena_weights: &DeviceBuf, arena_scales: &DeviceBuf, exp_off: &DeviceBuf, bucket_tok: &DeviceBuf, x: &DeviceBuf, y: &DeviceBuf, n: i32, k: i32, n_experts: i32, w_stride: i64, sc_stride: i64) -> Result<(), String> { + let rc = unsafe { + ffi::vetta_mxfp8_grouped_gemv_f16(arena_weights.ptr as *const u8, arena_scales.ptr as *const u8, exp_off.ptr as *const i32, bucket_tok.ptr as *const i32, x.ptr as *const u16, y.ptr as *mut f32, n, k, n_experts, w_stride, sc_stride, std::ptr::null_mut()) + }; + if rc != 0 { return Err("mxfp8_grouped_gemv_f16 launch failed".into()); } + Ok(()) +} + /// Launch k_moe_reduce: out[d] = sum_e tk_w[e]*y_part[e,d]. #[cfg(feature = "hip")] pub fn moe_reduce(y_part: &DeviceBuf, tk_w: &DeviceBuf, out: &DeviceBuf, top_k: i32, hidden: i32) -> Result<(), String> { @@ -1469,6 +1492,83 @@ mod gpu_tests { eprintln!("kv_store_f16_batched B={b} n_kv={n_kv} hd={hd}: K/V caches byte-identical"); } + /// Batched SiTU (M rows) must be byte-identical to M sequential situ_f16 calls. + #[test] + #[ignore] + fn situ_f16_batched_parity() { + let (m, inter) = (20usize, 64usize); + let (beta, lb) = (4.0f32, 25.0f32); + let gu: Vec = (0..m * 2 * inter).map(|i| ((i % 61) as f32 - 30.0) * 0.3).collect(); + let dgu = DeviceBuf::alloc(gu.len() * 4).unwrap(); dgu.h2d(&gu).unwrap(); + let da_b = DeviceBuf::alloc(m * inter * 2).unwrap(); + situ_f16_batched(&dgu, &da_b, inter as i32, beta, lb, m as i32).unwrap(); + let mut ab = vec![0u8; m * inter * 2]; da_b.d2h_bytes(&mut ab).unwrap(); + let dgu1 = DeviceBuf::alloc(2 * inter * 4).unwrap(); + let da1 = DeviceBuf::alloc(inter * 2).unwrap(); + for r in 0..m { + dgu1.h2d(&gu[r * 2 * inter..(r + 1) * 2 * inter]).unwrap(); + situ_f16(&dgu1, &da1, inter as i32, beta, lb).unwrap(); + let mut o = vec![0u8; inter * 2]; da1.d2h_bytes(&mut o).unwrap(); + assert_eq!(&ab[r * inter * 2..(r + 1) * inter * 2], &o[..], "situ batched row {r} must be byte-identical"); + } + eprintln!("situ_f16_batched M={m} inter={inter}: byte-identical to sequential"); + } + + /// Grouped MXFP8 expert GEMM parity vs a CPU dequant oracle per (token,expert) + /// pair. UE8M0 scales kept in a realistic exponent range [120,135] (2^-7..2^8) + /// to avoid f32 overflow. Integer activations exact in f16. + #[test] + #[ignore] + fn mxfp8_grouped_gemv_f16_parity() { + let (b, top_k, n_exp, n, k) = (20usize, 8usize, 4usize, 16usize, 128usize); + let total = b * top_k; + let w_stride = n * k; + let sc_stride = n * (k / 32); + let weights: Vec = (0..n_exp * w_stride).map(|i| (i % 256) as u8).collect(); + let scales: Vec = (0..n_exp * sc_stride).map(|i| (120 + (i * 7 + 3) % 16) as u8).collect(); + let ids: Vec = (0..total).map(|i| ((i * 7 + (i / top_k) * 13) % n_exp) as i32).collect(); + let xf: Vec = (0..b * k).map(|i| (i % 29) as f32 - 14.0).collect(); + let aw = DeviceBuf::alloc(weights.len()).unwrap(); aw.h2d_bytes(&weights).unwrap(); + let asc = DeviceBuf::alloc(scales.len()).unwrap(); asc.h2d_bytes(&scales).unwrap(); + let dxf = DeviceBuf::alloc(b * k * 4).unwrap(); dxf.h2d(&xf).unwrap(); + let dxh = DeviceBuf::alloc(b * k * 2).unwrap(); cast_f32_f16(&dxf, &dxh, b * k).unwrap(); + let ids_bytes: Vec = ids.iter().flat_map(|x| x.to_le_bytes()).collect(); + let dids = DeviceBuf::alloc(total * 4).unwrap(); dids.h2d_bytes(&ids_bytes).unwrap(); + let dcnt = DeviceBuf::alloc(129 * 4).unwrap(); dcnt.h2d_bytes(&vec![0u8; 129 * 4]).unwrap(); + let doff = DeviceBuf::alloc(129 * 4).unwrap(); + let dcur = DeviceBuf::alloc(128 * 4).unwrap(); + let dbtk = DeviceBuf::alloc(total * 4).unwrap(); + let ds2b = DeviceBuf::alloc(total * 4).unwrap(); + moe_count_buckets(&dids, &dcnt, total as i32).unwrap(); + moe_prefix_buckets(&dcnt, &doff, &dcur).unwrap(); + moe_scatter_buckets(&dids, &dcur, &dbtk, &ds2b, total as i32, top_k as i32).unwrap(); + let dy = DeviceBuf::alloc(total * n * 4).unwrap(); + mxfp8_grouped_gemv_f16(&aw, &asc, &doff, &dbtk, &dxh, &dy, n as i32, k as i32, n_exp as i32, w_stride as i64, sc_stride as i64).unwrap(); + let mut got = vec![0f32; total * n]; dy.d2h(&mut got).unwrap(); + let mut s2b_b = vec![0u8; total * 4]; ds2b.d2h_bytes(&mut s2b_b).unwrap(); + let s2b: Vec = s2b_b.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect(); + let ue8m0 = |bb: u8| ((bb as i32 - 127) as f32).exp2(); + let mut max_rel = 0f32; + for i in 0..total { + let tok = i / top_k; + let e = ids[i] as usize; + let bp = s2b[i] as usize; + for ni in 0..n { + let mut acc = 0f32; + for bb in 0..k / 32 { + let sc = ue8m0(scales[e * sc_stride + ni * (k / 32) + bb]); + let mut d = 0f32; + for j in 0..32 { d += xf[tok * k + bb * 32 + j] * e4m3(weights[e * w_stride + ni * k + bb * 32 + j]); } + acc = d.mul_add(sc, acc); + } + let g = got[bp * n + ni]; + max_rel = max_rel.max((g - acc).abs() / acc.abs().max(1e-3)); + } + } + eprintln!("mxfp8_grouped_gemv_f16 B={b} experts={n_exp} pairs={total} max_rel_err={max_rel:.3e}"); + assert!(max_rel < 2e-3, "grouped MXFP8 GEMM parity failed: {max_rel}"); + } + #[test] #[ignore] fn shortconv4_multistep_parity() { diff --git a/kernels/hip/vetta_kernels.hip b/kernels/hip/vetta_kernels.hip index 62cb7a2..eec8e4f 100644 --- a/kernels/hip/vetta_kernels.hip +++ b/kernels/hip/vetta_kernels.hip @@ -1188,6 +1188,105 @@ extern "C" int vetta_situ_f16(const float* gu, uint16_t* act, int inter, float b return 0; } +// ---- k_situ_f16_batched: SiTU over M rows (gu [M,2*inter] -> act [M,inter]) -- +// Same double-softcap SiTU, one row per blockIdx.y. For the grouped MoE the w13 +// GEMM emits gu [total_pairs, 2*inter]; this activates all rows in one launch. +__global__ void k_situ_f16_batched(const float* __restrict__ gu, uint16_t* __restrict__ act, + int inter, float beta, float lb, int M) { + const int j = blockIdx.x * blockDim.x + threadIdx.x; + const int m = blockIdx.y; + if (j >= inter || m >= M) return; + const float* g = gu + (size_t)m * 2 * inter; + act[(size_t)m * inter + j] = __half_as_ushort(__float2half_rn(situ_f32(g[2 * j], g[2 * j + 1], beta, lb))); +} + +extern "C" int vetta_situ_f16_batched(const float* gu, uint16_t* act, int inter, float beta, + float lb, int M, vetta_stream_t stream) { + if (inter <= 0 || M <= 0) return 1; + const int nt = 256; + dim3 grid((inter + nt - 1) / nt, M); + hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; + k_situ_f16_batched<<>>(gu, act, inter, beta, lb, M); + HIP_CHECK(hipGetLastError()); + return 0; +} + +// ---- k_mxfp8_grouped_gemv_f16: grouped MXFP8 expert GEMM (layers 20-23) ----- +// MXFP8 analogue of k_nvfp4_grouped_gemv_f16: grid (N, n_experts); expert eid +// processes its bucket tokens [exp_off[eid],exp_off[eid+1]) via bucket_tok. The +// 32-byte E4M3 group is dequantized once per MT-token tile (UE8M0 scale, no outer), +// amortizing weight bandwidth MT-fold. X [B,K] f16 -> Y [total_pairs,N] f32 bucket +// order. Block reduction (256 threads) per token, MT=8 register tile. +template +__global__ void __launch_bounds__(256) k_mxfp8_grouped_gemv_f16( + const uint8_t* __restrict__ arena_weights, + const uint8_t* __restrict__ arena_scales, + const int* __restrict__ exp_off, + const int* __restrict__ bucket_tok, + const uint16_t* __restrict__ X, + float* __restrict__ Y, int N, int K, + long w_stride, long sc_stride) { + const int n = blockIdx.x; + const int eid = blockIdx.y; + const int beg = exp_off[eid]; + const int end = exp_off[eid + 1]; + const int m_e = end - beg; + if (n >= N || m_e <= 0) return; + const int tid = threadIdx.x; + const int nt = blockDim.x; + const uint8_t* wp = arena_weights + (long)eid * w_stride + (size_t)n * K; + const uint8_t* ws = arena_scales + (long)eid * sc_stride + (size_t)n * (K >> 5); + const int nblk = K >> 5; + __shared__ float red[256]; + for (int t0 = 0; t0 < m_e; t0 += MT) { + float acc[MT]; + #pragma unroll + for (int m = 0; m < MT; ++m) acc[m] = 0.f; + for (int b = tid; b < nblk; b += nt) { + const float sc = ue8m0_to_f32(ws[b]); + const int k0 = b << 5; + float wv[32]; + #pragma unroll + for (int j = 0; j < 32; ++j) wv[j] = e4m3fn_to_f32(wp[k0 + j]); + #pragma unroll + for (int m = 0; m < MT; ++m) { + if (t0 + m < m_e) { + const int tok = bucket_tok[beg + t0 + m]; + const uint16_t* xr = X + (size_t)tok * K + k0; + float d = 0.f; + #pragma unroll + for (int j = 0; j < 32; ++j) d += f16_to_f32(xr[j]) * wv[j]; + acc[m] = fmaf(d, sc, acc[m]); + } + } + } + #pragma unroll + for (int m = 0; m < MT; ++m) { + if (t0 + m < m_e) { + red[tid] = acc[m]; + __syncthreads(); + for (int s = nt / 2; s > 0; s >>= 1) { if (tid < s) red[tid] += red[tid + s]; __syncthreads(); } + if (tid == 0) Y[(size_t)(beg + t0 + m) * N + n] = red[0]; + __syncthreads(); + } + } + } +} + +extern "C" int vetta_mxfp8_grouped_gemv_f16(const uint8_t* arena_weights, + const uint8_t* arena_scales, const int* exp_off, + const int* bucket_tok, const uint16_t* X, float* Y, + int N, int K, int n_experts, long w_stride, long sc_stride, + vetta_stream_t stream) { + if (N <= 0 || K <= 0 || (K % 32) != 0 || n_experts <= 0) return 1; + constexpr int MT = 8; + dim3 grid(N, n_experts); + hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; + k_mxfp8_grouped_gemv_f16<<>>(arena_weights, arena_scales, exp_off, bucket_tok, X, Y, N, K, w_stride, sc_stride); + HIP_CHECK(hipGetLastError()); + return 0; +} + // ---- k_moe_reduce: out[d] = sum_e tk_w[e] * y_part[e, d] ------------------- __global__ void k_moe_reduce(const float* __restrict__ y_part,