From bd49da5636d06579f1be20d43784b81c31eef332 Mon Sep 17 00:00:00 2001 From: iz0eyj Date: Tue, 1 Dec 2026 14:07:14 +0100 Subject: [PATCH] [HIP] NVFP4 expert GEMV kernel (exact E2M1+E4M3 dequant, GPU-verified ~4e-7) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - kernels/hip: NVFP4 (SF4) codecs ported exactly from strata ink_hip_common — sf4_e2m1_f32 (E2M1 nibble LUT {0,0.5,1,1.5,2,3,4,6,...}), e4m3fn_to_f32 (F8_E4M3FN: subnormal mant*2^-9, NaN->0, bias 7). Layout: packed_e2m1 [N,K/2] (low nib even col), scales_e4m3 [N,K/16], f32 outer_scale. - k_nvfp4_gemv (M=1 decode): y[N] = dequant(W)[N,K] @ x[K], one block/row, threads stride K/16 groups, f32 accumulate. Correctness-first; the Wave32 bandwidth-saturated path is the performance pass. This is the core of the MoE expert compute (w13/w2); the full direct path (SiTU activation + weighted reduce) builds on it. - C ABI + safe wrapper nvfp4_gemv + CPU-oracle parity test (Rust e2m1/e4m3 matching the kernel). Verified LIVE on gfx1150: nvfp4_gemv max_rel_err ~4e-7 across (8,64)/(16,256)/ (32,128). Eight compute kernels now verified. Default suite 97/97, lean 4 files green; GPU parity 8/8 (--features hip). --- crates/vetta-infer-hip/src/lib.rs | 68 ++++++++++++++++++++++++++++ kernels/hip/vetta_kernels.h | 6 +++ kernels/hip/vetta_kernels.hip | 75 +++++++++++++++++++++++++++++++ 3 files changed, 149 insertions(+) diff --git a/crates/vetta-infer-hip/src/lib.rs b/crates/vetta-infer-hip/src/lib.rs index 5ad7bbf..80c29dc 100644 --- a/crates/vetta-infer-hip/src/lib.rs +++ b/crates/vetta-infer-hip/src/lib.rs @@ -50,6 +50,10 @@ mod ffi { ) -> 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; pub fn vetta_cast_f32_bf16(x: *const c_float, y: *mut u16, n: usize, stream: *mut c_void) -> c_int; + pub fn vetta_nvfp4_gemv( + packed: *const u8, scales: *const u8, outer_scale: c_float, x: *const c_float, y: *mut c_float, + n: c_int, k: c_int, stream: *mut c_void, + ) -> c_int; } } @@ -208,6 +212,16 @@ pub fn cast_f32_bf16(x: &DeviceBuf, y: &DeviceBuf, n: usize) -> Result<(), Strin Ok(()) } +/// Launch k_nvfp4_gemv (M=1): y[n] = dequant(W)[n,k] @ x[k] (NVFP4). +#[cfg(feature = "hip")] +pub fn nvfp4_gemv(packed: &DeviceBuf, scales: &DeviceBuf, outer_scale: f32, x: &DeviceBuf, y: &DeviceBuf, n: i32, k: i32) -> Result<(), String> { + let rc = unsafe { + ffi::vetta_nvfp4_gemv(packed.ptr as *const u8, scales.ptr as *const u8, outer_scale, x.ptr as *const f32, y.ptr as *mut f32, n, k, std::ptr::null_mut()) + }; + if rc != 0 { return Err("nvfp4_gemv launch failed".into()); } + Ok(()) +} + #[cfg(all(test, feature = "hip"))] mod gpu_tests { use super::*; @@ -433,6 +447,60 @@ mod gpu_tests { assert_eq!(got, want, "vec_add must be exact"); } + fn e2m1(nib: u8) -> f32 { + const LUT: [f32; 16] = [0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, -0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0]; + LUT[(nib & 15) as usize] + } + fn e4m3(b: u8) -> f32 { + let sign = ((b & 0x80) as u32) << 24; + let exp = (b >> 3) & 0xF; + let mant = b & 7; + if exp == 0 { + if mant == 0 { return f32::from_bits(sign); } + let val = mant as f32 / 512.0; + return if b & 0x80 != 0 { -val } else { val }; + } else if exp == 15 && mant == 7 { return 0.0; } + f32::from_bits(sign | ((exp as u32 + 120) << 23) | ((mant as u32) << 20)) + } + + #[test] + #[ignore] + fn nvfp4_gemv_parity_vs_cpu() { + for &(n, k) in &[(8usize, 64usize), (16, 256), (32, 128)] { + let outer = 0.5f32; + let packed: Vec = (0..n * (k / 2)).map(|i| (i % 256) as u8).collect(); + let scales: Vec = (0..n * (k / 16)).map(|i| ((i * 7 + 3) % 251) as u8).collect(); + let x: Vec = (0..k).map(|i| ((i % 29) as f32 - 14.0) * 0.04).collect(); + // CPU oracle: dequant then dot, f32. + let mut want = vec![0f32; n]; + for ni in 0..n { + let mut acc = 0f32; + for b in 0..k / 16 { + let sc = e4m3(scales[ni * (k / 16) + b]) * outer; + for j in 0..8 { + let byte = packed[ni * (k / 2) + b * 8 + j]; + let w0 = e2m1(byte & 15) * sc; + let w1 = e2m1(byte >> 4) * sc; + acc += x[b * 16 + j * 2] * w0 + x[b * 16 + j * 2 + 1] * w1; + } + } + want[ni] = acc; + } + let dp = DeviceBuf::alloc(packed.len()).unwrap(); + let ds = DeviceBuf::alloc(scales.len()).unwrap(); + let dx = DeviceBuf::alloc(x.len() * 4).unwrap(); + let dy = DeviceBuf::alloc(n * 4).unwrap(); + dp.h2d_bytes(&packed).unwrap(); ds.h2d_bytes(&scales).unwrap(); dx.h2d(&x).unwrap(); + nvfp4_gemv(&dp, &ds, outer, &dx, &dy, n as i32, k as i32).unwrap(); + let mut got = vec![0f32; n]; + dy.d2h(&mut got).unwrap(); + let mut max_rel = 0f32; + for (g, w) in got.iter().zip(want.iter()) { max_rel = max_rel.max((g - w).abs() / w.abs().max(1e-3)); } + eprintln!("nvfp4_gemv n={n} k={k} max_rel_err={max_rel:.3e}"); + assert!(max_rel < 1e-4, "nvfp4 parity failed: {max_rel}"); + } + } + 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 f828b19..1e07f07 100644 --- a/kernels/hip/vetta_kernels.h +++ b/kernels/hip/vetta_kernels.h @@ -64,6 +64,12 @@ int vetta_vec_add(const float* a, const float* b, float* y, size_t n, int vetta_cast_f32_bf16(const float* x, uint16_t* y, size_t n, vetta_stream_t stream); +// k_nvfp4_gemv (M=1): y[N] = dequant(W)[N,K] @ x[K], NVFP4 (E2M1 + E4M3/16 + +// f32 outer_scale). packed [N,K/2], scales [N,K/16]. K % 16 == 0. +int vetta_nvfp4_gemv(const uint8_t* packed, const uint8_t* scales, + float outer_scale, const float* x, float* y, + int N, int K, 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 21e1785..8c34e11 100644 --- a/kernels/hip/vetta_kernels.hip +++ b/kernels/hip/vetta_kernels.hip @@ -343,4 +343,79 @@ extern "C" int vetta_cast_f32_bf16(const float* x, uint16_t* y, size_t n, k_cast_f32_bf16<<>>(x, y, n); HIP_CHECK(hipGetLastError()); return 0; +} + +// ---- NVFP4 (SF4) codecs — exact semantics from strata ink_hip_common ------- +// E2M1 nibble LUT; F8_E4M3FN group scale (16 weights/group); f32 outer_scale. +// Layout: packed_e2m1 [N, K/2] (low nib = even col, high nib = odd col), +// scales_e4m3 [N, K/16], outer_scale = amax/denom. + +__device__ __forceinline__ float sf4_e2m1_f32(uint32_t nib) { + static constexpr float kLut[16] = { + 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f, + -0.0f, -0.5f, -1.0f, -1.5f, -2.0f, -3.0f, -4.0f, -6.0f + }; + return kLut[nib & 15u]; +} + +__device__ __forceinline__ float e4m3fn_to_f32(uint8_t b) { + const uint32_t sign = (uint32_t)(b & 0x80u) << 24; + const uint32_t exp = (b >> 3) & 0x0Fu; + const uint32_t mant = b & 0x07u; + if (exp == 0) { + if (mant == 0) return __builtin_bit_cast(float, sign); + const float val = (float)mant * (1.0f / 512.0f); + return (b & 0x80u) ? -val : val; + } else if (exp == 15 && mant == 7) { + return 0.0f; // NaN -> 0 safely + } + uint32_t f = sign | ((exp + (127u - 7u)) << 23) | (mant << 20); + return __builtin_bit_cast(float, f); +} + +// ---- k_nvfp4_gemv (M=1 decode): y[N] = dequant(W)[N,K] @ x[K] -------------- +// One block per output row; threads stride over K/16 groups, f32 accumulate. +// Correctness-first; the Wave32 bandwidth-saturated path is the performance pass. + +__global__ void k_nvfp4_gemv(const uint8_t* __restrict__ packed, + const uint8_t* __restrict__ scales, + float outer_scale, const float* __restrict__ x, + float* __restrict__ y, int N, int K) { + const int n = blockIdx.x; + if (n >= N) return; + const int tid = threadIdx.x; + const int nt = blockDim.x; + const uint8_t* wp = packed + (size_t)n * (K >> 1); + const uint8_t* ws = scales + (size_t)n * (K >> 4); + const int nblk = K >> 4; + float acc = 0.f; + for (int b = tid; b < nblk; b += nt) { + const float sc = e4m3fn_to_f32(ws[b]) * outer_scale; + const int k0 = b << 4; + const uint8_t* w8 = wp + b * 8; + for (int j = 0; j < 8; ++j) { + uint8_t byte = w8[j]; + float w0 = sf4_e2m1_f32(byte & 15u) * sc; + float w1 = sf4_e2m1_f32(byte >> 4) * sc; + acc += x[k0 + j * 2] * w0 + x[k0 + j * 2 + 1] * w1; + } + } + __shared__ float red[256]; + red[tid] = acc; + __syncthreads(); + for (int s = nt / 2; s > 0; s >>= 1) { + if (tid < s) red[tid] += red[tid + s]; + __syncthreads(); + } + if (tid == 0) y[n] = red[0]; +} + +extern "C" int vetta_nvfp4_gemv(const uint8_t* packed, const uint8_t* scales, + float outer_scale, const float* x, float* y, + int N, int K, vetta_stream_t stream) { + if (N <= 0 || K <= 0 || (K % 16) != 0) return 1; + hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; + k_nvfp4_gemv<<>>(packed, scales, outer_scale, x, y, N, K); + HIP_CHECK(hipGetLastError()); + return 0; } \ No newline at end of file