[HIP] Batched NVFP4 f16 GEMM (M>1) for prefill: weight dequant amortized MT-fold

Port strata k_sf4_gemv<MT> multi-token path: k_nvfp4_gemv_f16_mt<MT=16>, one wave
per output row, the W group is dequantized ONCE and reused across MT tokens
(fdot2 per token), M tiled by blockIdx.y. X [M,K] f16 -> Y [M,N] f32. This is the
expert-GEMM foundation for batched prefill: reading each expert weight once per
MT tokens instead of once per token amortizes the dominant NVFP4 weight bandwidth
MT-fold. For M=1 the math reduces to the decode GEMV (same fdot2 + scale-fma).

Parity vs CPU dequant oracle [M,N]: M=37 (exercises 2 full MT tiles + 5-token
remainder) max_rel_err 1.75e-6. Additive — decode default unchanged.

Verified: hip GPU green (incl. new mt parity), workspace CPU -D warnings green,
6 Lean proofs 0 sorryAx. Next: batched MoE (router M=B + grouped expert GEMM +
reduce M=B) and batched attention/depth-blocks -> forward_batch for prefill.
This commit is contained in:
adm committed 2026-12-01 22:49:55 +01:00
1 parent 0914fae8c8
commit bfdd665434
2 files changed
+132

No files matched your search

+56
View File
@@ -83,6 +83,10 @@ mod ffi {
ids: *const c_int, slot: c_int, x: *const u16, y: *mut c_float, ids: *const c_int, slot: c_int, x: *const u16, y: *mut c_float,
n: c_int, k: c_int, w_stride: c_long, sc_stride: c_long, y_offset: c_long, stream: *mut c_void, n: c_int, k: c_int, w_stride: c_long, sc_stride: c_long, y_offset: c_long, stream: *mut c_void,
) -> c_int; ) -> c_int;
pub fn vetta_nvfp4_gemv_f16_mt(
packed: *const u8, scales: *const u8, outer_scale: c_float, x: *const u16, y: *mut c_float,
m: c_int, n: c_int, k: c_int, stream: *mut c_void,
) -> c_int;
pub fn vetta_mxfp8_gemv(weights: *const u8, scales: *const u8, x: *const c_float, y: *mut c_float, n: c_int, k: c_int, stream: *mut c_void) -> c_int; pub fn vetta_mxfp8_gemv(weights: *const u8, scales: *const u8, x: *const c_float, y: *mut c_float, n: c_int, k: c_int, stream: *mut c_void) -> c_int;
pub fn vetta_mxfp8_gemv_f16(weights: *const u8, scales: *const u8, x: *const u16, y: *mut c_float, n: c_int, k: c_int, stream: *mut c_void) -> c_int; pub fn vetta_mxfp8_gemv_f16(weights: *const u8, scales: *const u8, x: *const u16, y: *mut c_float, n: c_int, k: c_int, stream: *mut c_void) -> c_int;
pub fn vetta_mxfp8_gemv_f16_indirect( pub fn vetta_mxfp8_gemv_f16_indirect(
@@ -465,6 +469,18 @@ pub fn nvfp4_gemv_f16_indirect(arena_packed: &DeviceBuf, arena_scales: &DeviceBu
Ok(()) Ok(())
} }
/// Batched (M>1) NVFP4 f16 GEMM for prefill: X [M,K] f16, Y [M,N] f32. The W
/// group is dequantized once and reused across MT=16 tokens (M tiled by
/// blockIdx.y), amortizing expert weight bandwidth MT-fold vs the M=1 GEMV.
#[cfg(feature = "hip")]
pub fn nvfp4_gemv_f16_mt(packed: &DeviceBuf, scales: &DeviceBuf, outer_scale: f32, x: &DeviceBuf, y: &DeviceBuf, m: i32, n: i32, k: i32) -> Result<(), String> {
let rc = unsafe {
ffi::vetta_nvfp4_gemv_f16_mt(packed.ptr as *const u8, scales.ptr as *const u8, outer_scale, x.ptr as *const u16, y.ptr as *mut f32, m, n, k, std::ptr::null_mut())
};
if rc != 0 { return Err("nvfp4_gemv_f16_mt launch failed".into()); }
Ok(())
}
/// Launch k_mxfp8_gemv_f16: MXFP8 GEMV reading FP16 activations (strata B=1 path). /// Launch k_mxfp8_gemv_f16: MXFP8 GEMV reading FP16 activations (strata B=1 path).
#[cfg(feature = "hip")] #[cfg(feature = "hip")]
pub fn mxfp8_gemv_f16(weights: &DeviceBuf, scales: &DeviceBuf, x: &DeviceBuf, y: &DeviceBuf, n: i32, k: i32) -> Result<(), String> { pub fn mxfp8_gemv_f16(weights: &DeviceBuf, scales: &DeviceBuf, x: &DeviceBuf, y: &DeviceBuf, n: i32, k: i32) -> Result<(), String> {
@@ -972,6 +988,46 @@ mod gpu_tests {
eprintln!("nvfp4_gemv_f16_indirect: bit-exact vs direct over {} routed slots", ids_vec.len()); eprintln!("nvfp4_gemv_f16_indirect: bit-exact vs direct over {} routed slots", ids_vec.len());
} }
/// Batched (M>1) NVFP4 f16 GEMM parity vs a CPU dequant oracle over [M,N].
/// M=37 exercises the MT=16 tiling (2 full tiles + a 5-token remainder).
/// Integer activations are exact in f16, so the oracle uses them directly.
#[test]
#[ignore]
fn nvfp4_gemv_f16_mt_parity() {
let (m, n, k) = (37usize, 16usize, 128usize);
let outer = 0.5f32;
let packed: Vec<u8> = (0..n * (k / 2)).map(|i| (i % 256) as u8).collect();
let scales: Vec<u8> = (0..n * (k / 16)).map(|i| ((i * 7 + 3) % 251) as u8).collect();
let xf: Vec<f32> = (0..m * k).map(|i| (i % 29) as f32 - 14.0).collect();
let dp = DeviceBuf::alloc(packed.len()).unwrap(); dp.h2d_bytes(&packed).unwrap();
let ds = DeviceBuf::alloc(scales.len()).unwrap(); ds.h2d_bytes(&scales).unwrap();
let dxf = DeviceBuf::alloc(m * k * 4).unwrap(); dxf.h2d(&xf).unwrap();
let dxh = DeviceBuf::alloc(m * k * 2).unwrap(); cast_f32_f16(&dxf, &dxh, m * k).unwrap();
let dy = DeviceBuf::alloc(m * n * 4).unwrap();
nvfp4_gemv_f16_mt(&dp, &ds, outer, &dxh, &dy, m as i32, n as i32, k as i32).unwrap();
let mut got = vec![0f32; m * n]; dy.d2h(&mut got).unwrap();
let mut want = vec![0f32; m * n];
for mi in 0..m {
for ni in 0..n {
let mut acc = 0f32;
for b in 0..k / 16 {
let sc = e4m3(scales[ni * (k / 16) + b]) * outer;
let mut d = 0f32;
for j in 0..8 {
let byte = packed[ni * (k / 2) + b * 8 + j];
d += xf[mi * k + b * 16 + j * 2] * e2m1(byte & 15) + xf[mi * k + b * 16 + j * 2 + 1] * e2m1(byte >> 4);
}
acc = d.mul_add(sc, acc);
}
want[mi * n + ni] = acc;
}
}
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_f16_mt m={m} n={n} k={k} max_rel_err={max_rel:.3e}");
assert!(max_rel < 2e-3, "batched NVFP4 f16 GEMM parity failed: {max_rel}");
}
#[test] #[test]
#[ignore] #[ignore]
fn situ_parity_vs_cpu() { fn situ_parity_vs_cpu() {
+76
View File
@@ -838,6 +838,82 @@ extern "C" int vetta_nvfp4_gemv_f16(const uint8_t* packed, const uint8_t* scales
return 0; return 0;
} }
// ---- k_nvfp4_gemv_f16_mt: batched (M>1) NVFP4 f16 GEMM for PREFILL ----------
// Exact strata k_sf4_gemv<MT> multi-token path: one wave per output row, the W
// group is dequantized ONCE and reused across MT tokens (fdot2 per token), so
// the expert weight bandwidth is amortized MT-fold vs the M=1 decode GEMV. M is
// tiled by blockIdx.y (m_blk = blockIdx.y*MT); X is [M,K] f16, Y is [M,N] f32.
// For M=1 this reduces to the decode kernel math (same fdot2 + scale-fma).
template <int MT>
__global__ void __launch_bounds__(256) k_nvfp4_gemv_f16_mt(
const uint8_t* __restrict__ packed,
const uint8_t* __restrict__ scales,
float outer_scale, const uint16_t* __restrict__ X,
float* __restrict__ Y, int M, int N, int K) {
const int wave = threadIdx.x >> 5;
const int lane = threadIdx.x & 31;
const int row = blockIdx.x * 8 + wave;
if (row >= N) return;
const int m_blk = blockIdx.y * MT;
const uint8_t* wp = packed + (size_t)row * (K >> 1);
const uint8_t* ws = scales + (size_t)row * (K >> 4);
const __half* xh = reinterpret_cast<const __half*>(X);
const int nblk16 = K >> 4;
float acc[MT];
#pragma unroll
for (int m = 0; m < MT; ++m) acc[m] = 0.f;
for (int b = lane; b < nblk16; b += 32) {
const float sc = e4m3fn_to_f32(ws[b]) * outer_scale;
const uint2 raw = *reinterpret_cast<const uint2*>(wp + b * 8);
uint32_t w2[8];
#pragma unroll
for (int i = 0; i < 4; ++i) {
const uint32_t byte0 = (raw.x >> (i * 8)) & 0xFFu;
const uint32_t byte1 = (raw.y >> (i * 8)) & 0xFFu;
const __half2 h0 = __halves2half2(sf4_e2m1_f16(byte0 & 15u), sf4_e2m1_f16(byte0 >> 4));
const __half2 h1 = __halves2half2(sf4_e2m1_f16(byte1 & 15u), sf4_e2m1_f16(byte1 >> 4));
w2[i] = __builtin_bit_cast(uint32_t, h0);
w2[4 + i] = __builtin_bit_cast(uint32_t, h1);
}
const int k0 = b << 4;
#pragma unroll
for (int m = 0; m < MT; ++m) {
if (m_blk + m < M) {
const size_t xo = (size_t)(m_blk + m) * K + k0;
const uint4 x0 = *reinterpret_cast<const uint4*>(xh + xo);
const uint4 x1 = *reinterpret_cast<const uint4*>(xh + xo + 8);
float d = 0.f;
d = fdot2_f32(w2[0], x0.x, d);
d = fdot2_f32(w2[1], x0.y, d);
d = fdot2_f32(w2[2], x0.z, d);
d = fdot2_f32(w2[3], x0.w, d);
d = fdot2_f32(w2[4], x1.x, d);
d = fdot2_f32(w2[5], x1.y, d);
d = fdot2_f32(w2[6], x1.z, d);
d = fdot2_f32(w2[7], x1.w, d);
acc[m] = fmaf(d, sc, acc[m]);
}
}
}
#pragma unroll
for (int m = 0; m < MT; ++m) {
const float sum = wave32_sum(acc[m]);
if (lane == 0 && m_blk + m < M) Y[(size_t)(m_blk + m) * N + row] = sum;
}
}
extern "C" int vetta_nvfp4_gemv_f16_mt(const uint8_t* packed, const uint8_t* scales,
float outer_scale, const uint16_t* X, float* Y,
int M, int N, int K, vetta_stream_t stream) {
if (M <= 0 || N <= 0 || K <= 0 || (K % 16) != 0) return 1;
constexpr int MT = 16;
hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0;
dim3 grid((N + 7) / 8, (M + MT - 1) / MT);
k_nvfp4_gemv_f16_mt<MT><<<grid, 256, 0, s>>>(packed, scales, outer_scale, X, Y, M, N, K);
HIP_CHECK(hipGetLastError());
return 0;
}
// ---- k_mxfp8_gemv (M=1 decode): MXFP8 experts (layers 20..23) -------------- // ---- k_mxfp8_gemv (M=1 decode): MXFP8 experts (layers 20..23) --------------
// Exact strata MX8: y[N] = sum_k e4m3fn(W[n,k]) * ue8m0(scale[n,k/32]) * x[k]. // Exact strata MX8: y[N] = sum_k e4m3fn(W[n,k]) * ue8m0(scale[n,k/32]) * x[k].
// W [N,K] F8_E4M3 bytes (full K), scale [N,K/32] U8 UE8M0, NO outer scale. // W [N,K] F8_E4M3 bytes (full K), scale [N,K/32] U8 UE8M0, NO outer scale.