diff --git a/crates/vetta-infer-hip/src/lib.rs b/crates/vetta-infer-hip/src/lib.rs index bd38202..adeec3e 100644 --- a/crates/vetta-infer-hip/src/lib.rs +++ b/crates/vetta-infer-hip/src/lib.rs @@ -46,6 +46,10 @@ 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_gemm_bf16_wmma( + 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_router_gemv( x: *const c_float, w: *const u16, y: *mut c_float, n: c_int, k: c_int, stream: *mut c_void, @@ -404,8 +408,14 @@ pub fn embed_bf16_gather(table: &DeviceBuf, tokens: &DeviceBuf, out: &DeviceBuf, } /// Launch k_gemm_bf16: y[m,n] = x[m,k] @ w[n,k]^T (BF16 in, f32 accumulate). +/// Prefill (m>=16, k%64==0) dispatches the BF16 WMMA tensor-core kernel (P1 b6); +/// decode (m<16) keeps the tiled-LDS scalar kernel. VETTA_NO_BF16_WMMA=1 forces +/// scalar everywhere (A/B baseline). WMMA changes f32 accumulation order (~1e-3). #[cfg(feature = "hip")] pub fn gemm_bf16(x: &DeviceBuf, w: &DeviceBuf, y: &DeviceBuf, m: i32, n: i32, k: i32) -> Result<(), String> { + if m >= 16 && k % 64 == 0 && std::env::var("VETTA_NO_BF16_WMMA").is_err() { + return gemm_bf16_wmma(x, w, y, m, n, k); + } let rc = unsafe { ffi::vetta_gemm_bf16(x.ptr as *const u16, w.ptr as *const u16, y.ptr as *mut f32, m, n, k, std::ptr::null_mut()) }; @@ -413,6 +423,16 @@ pub fn gemm_bf16(x: &DeviceBuf, w: &DeviceBuf, y: &DeviceBuf, m: i32, n: i32, k: Ok(()) } +/// Launch k_gemm_bf16_wmma: BF16 WMMA tensor-core dense GEMM (same I/O as gemm_bf16). +#[cfg(feature = "hip")] +pub fn gemm_bf16_wmma(x: &DeviceBuf, w: &DeviceBuf, y: &DeviceBuf, m: i32, n: i32, k: i32) -> Result<(), String> { + let rc = unsafe { + ffi::vetta_gemm_bf16_wmma(x.ptr as *const u16, w.ptr as *const u16, y.ptr as *mut f32, m, n, k, std::ptr::null_mut()) + }; + if rc != 0 { return Err("gemm_bf16_wmma launch failed".into()); } + Ok(()) +} + /// Launch k_router_gemv: y[n] = x_f32[k] @ w_bf16[n,k]^T (F32 router input). #[cfg(feature = "hip")] pub fn router_gemv(x: &DeviceBuf, w: &DeviceBuf, y: &DeviceBuf, n: i32, k: i32) -> Result<(), String> { @@ -1022,6 +1042,40 @@ mod gpu_tests { } } + #[test] + #[ignore] + fn gemm_bf16_wmma_parity() { + // P1 b6: BF16 WMMA vs serial-K CPU oracle. Accumulation order differs => + // numeric tolerance on the GLOBAL signal scale (per-entry rel explodes on + // near-zero outputs); greedy-vs-reference is the blocking gate downstream. + // (17,130,64) exercises partial M and N tiles. + for &(m, n, k) in &[(20usize, 128usize, 128usize), (256, 256, 256), (17, 130, 64)] { + let x: Vec = (0..m * k).map(|i| f32_to_bf16(((i % 41) as f32 - 20.0) * 0.05)).collect(); + let w: Vec = (0..n * k).map(|i| f32_to_bf16(((i % 29) as f32 - 14.0) * 0.06)).collect(); + let mut want = vec![0f32; m * n]; + for mi in 0..m { + for ni in 0..n { + let mut acc = 0f32; + for kk in 0..k { acc += bf16_to_f32(x[mi * k + kk]) * bf16_to_f32(w[ni * k + kk]); } + want[mi * n + ni] = acc; + } + } + let dx = DeviceBuf::alloc(x.len() * 2).unwrap(); + let dw = DeviceBuf::alloc(w.len() * 2).unwrap(); + let dy = DeviceBuf::alloc(want.len() * 4).unwrap(); + dx.h2d_bytes(bytemuck_u16(&x)).unwrap(); + dw.h2d_bytes(bytemuck_u16(&w)).unwrap(); + gemm_bf16_wmma(&dx, &dw, &dy, m as i32, n as i32, k as i32).unwrap(); + let mut got = vec![0f32; want.len()]; + dy.d2h(&mut got).unwrap(); + let scale = want.iter().fold(0f32, |a, v| a.max(v.abs())).max(1e-6); + let mut max_rel = 0f32; + for (g, wnt) in got.iter().zip(want.iter()) { max_rel = max_rel.max((g - wnt).abs() / scale); } + eprintln!("gemm_bf16_wmma m={m} n={n} k={k} max_rel_err={max_rel:.3e}"); + assert!(max_rel < 3e-3, "gemm_bf16_wmma parity failed: {max_rel}"); + } + } + 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]; diff --git a/kernels/hip/vetta_kernels.hip b/kernels/hip/vetta_kernels.hip index 176c93d..9cb83a7 100644 --- a/kernels/hip/vetta_kernels.hip +++ b/kernels/hip/vetta_kernels.hip @@ -932,6 +932,18 @@ __device__ __forceinline__ v_f8 wmma_f16_g11(v_h16 a, v_h16 b, v_f8 c) { // gfx11 accumulator lane mapping: lane l holds col (l&15), rows {2r+(l>>4)}. __device__ __forceinline__ int wmma_acc_m11(int r, int lane) { return 2*r + (lane>>4); } __device__ __forceinline__ int wmma_acc_n11(int lane) { return lane & 15; } +// BF16 WMMA operand (gfx11): same 16x16-bit lane layout as f16, bf16 bit pattern. +typedef short v_bf16 __attribute__((ext_vector_type(16))); +__device__ __forceinline__ v_bf16 wmma_ld_bf16(const uint16_t* p) { + const uint4 a = *reinterpret_cast(p); + const uint4 b = *reinterpret_cast(p + 8); + typedef unsigned u32x8 __attribute__((ext_vector_type(8))); + const u32x8 v = {a.x,a.y,a.z,a.w,b.x,b.y,b.z,b.w}; + return __builtin_bit_cast(v_bf16, v); +} +__device__ __forceinline__ v_f8 wmma_bf16_g11(v_bf16 a, v_bf16 b, v_f8 c) { + return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a, b, c); +} // ---- 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. @@ -2413,4 +2425,83 @@ extern "C" int vetta_moe_reduce_buckets_masked(const float* bucket_y, k_moe_reduce_buckets_masked<<>>(bucket_y, slotk_to_bidx, tk_w, out, B, top_k, D); HIP_CHECK(hipGetLastError()); return 0; +} + +// ---- k_gemm_bf16_wmma: BF16 WMMA tensor-core dense GEMM (P1 b6) ------------- +// Drop-in for k_gemm_bf16 (same bf16 X[M,K]/W[N,K], f32 Y[M,N]). BM16/BN128 +// (8 waves, one 16x16 N tile each)/BK64 K-slab staged in LDS. bf16 operands feed +// the matrix core directly (no dequant); f32 accumulation order differs from the +// serial-K scalar kernel => ~1e-3 (P1 budget; greedy-vs-reference is the gate). +#define GB_BM 16 +#define GB_BN 128 +#define GB_BK 64 +#define GB_LD (GB_BK + 8) +__global__ void __launch_bounds__(256) k_gemm_bf16_wmma( + const uint16_t* __restrict__ x, + const uint16_t* __restrict__ w, + float* __restrict__ y, int M, int N, int K) { + __shared__ uint16_t sX[GB_BM * GB_LD]; + __shared__ uint16_t sW[GB_BN * GB_LD]; + const int tid = threadIdx.x; + const int wave = tid >> 5; // 0..7 -> one 16-wide N tile + const int lane = tid & 31; + const int l16 = lane & 15; + const int m0 = blockIdx.y * GB_BM; + const int n0 = blockIdx.x * GB_BN; + const int tm = (M - m0 < GB_BM) ? (M - m0) : GB_BM; + v_f8 acc = v_f8_zero(); + for (int k0 = 0; k0 < K; k0 += GB_BK) { + // X [16, BK] bf16: 128 threads x uint4 + if (tid < 128) { + const int xr = tid >> 3, xc = tid & 7; + const int gm = m0 + xr, gk = k0 + xc * 8; + uint16_t* dst = &sX[xr * GB_LD + xc * 8]; + if (xr < tm && gk + 8 <= K) { + *reinterpret_cast(dst) = *reinterpret_cast(x + (size_t)gm * K + gk); + } else { + #pragma unroll + for (int j = 0; j < 8; ++j) + dst[j] = (xr < tm && gk + j < K) ? x[(size_t)gm * K + gk + j] : (uint16_t)0; + } + } + // W [BN, BK] bf16: 256 threads x 4 uint4 + #pragma unroll + for (int it = 0; it < 4; ++it) { + const int idx = it * 256 + tid; + const int r = idx >> 3, c = (idx & 7) * 8; + const int gn = n0 + r, gk = k0 + c; + uint16_t* dst = &sW[r * GB_LD + c]; + if (gn < N && gk + 8 <= K) { + *reinterpret_cast(dst) = *reinterpret_cast(w + (size_t)gn * K + gk); + } else { + #pragma unroll + for (int j = 0; j < 8; ++j) + dst[j] = (gn < N && gk + j < K) ? w[(size_t)gn * K + gk + j] : (uint16_t)0; + } + } + __syncthreads(); + #pragma unroll + for (int kk = 0; kk < 4; ++kk) { + v_bf16 a = wmma_ld_bf16(&sX[l16 * GB_LD + kk * 16]); + v_bf16 b = wmma_ld_bf16(&sW[(wave * 16 + l16) * GB_LD + kk * 16]); + acc = wmma_bf16_g11(a, b, acc); + } + __syncthreads(); + } + const int gn = n0 + wave * 16 + wmma_acc_n11(lane); + #pragma unroll + for (int r = 0; r < 8; ++r) { + const int lm = wmma_acc_m11(r, lane); + if (lm < tm && gn < N) y[(size_t)(m0 + lm) * N + gn] = acc[r]; + } +} + +extern "C" int vetta_gemm_bf16_wmma(const uint16_t* x, const uint16_t* w, float* y, + int M, int N, int K, vetta_stream_t stream) { + if (M <= 0 || N <= 0 || K <= 0 || (K % GB_BK) != 0) return 1; + hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; + dim3 grid((N + GB_BN - 1) / GB_BN, (M + GB_BM - 1) / GB_BM); + k_gemm_bf16_wmma<<>>(x, w, y, M, N, K); + HIP_CHECK(hipGetLastError()); + return 0; } \ No newline at end of file