[HIP] P1: FP16 WMMA grouped NVFP4 MoE GEMM (tensor cores)

First P1 WMMA brick (Federico approved relaxing the bit-exact M=1-vs-M=B parity
to a numeric tolerance; greedy-vs-reference stays the blocking gate). Adds gfx11
(RDNA3.5) FP16 WMMA helpers (v_h16/v_f8, wmma_f32_16x16x16_f16_w32, acc lane map
2r+(lane>>4)) + k_nvfp4_grouped_gemm_wmma: a drop-in for the fdot2 grouped GEMM
with the same arena/CSR I/O. BM=16 (one M tile ~ tokens/expert at chunk 256),
BN=128 (8 waves, one 16x16 N tile each), BK=64 K-slab in LDS. NVFP4 E2M1 -> exact
FP16 prescaled e4m3*0.0625, WMMA f32 accumulation, epilogue *outer*16. Wired into
expert_arena_grouped_gemv_f16 for NVFP4 (K%64==0); VETTA_NO_MOE_WMMA=1 A/B fallback.
M=1 decode keeps fdot2 (WMMA needs M>=16 tiles).

Verified: WMMA-vs-CPU-oracle parity max_rel=1.2e-4; gw serve_gen greedy-vs-
reference EXACT (16 tokens + Paris + EOS, 4/4); forward_batch argmax batch==seq.
Relaxed the internal batched-vs-sequential tolerances to the P1 numeric budget
(global-scale normalization, not per-entry near-zero): forward_batch max_abs<0.15
(~2e-3 rel on +/-30 logits), single-layer cur + MoE global-scale <3e-3, KV cache
stays BYTE-IDENTICAL (attention precedes MoE). MEASURED prefill 2048tok A/B:
fdot2 41.6s -> WMMA 36.9s (-11%), moe_launch ~1888->1400ms (-26%). Gain bounded by
dequant/bandwidth (the reference INT8-fused sf4_i8 path is the further 2x axis).
Suite green: hip34 ld23 gw4 GPU serial, CPU -D warnings, Lean 0 sorryAx.
This commit is contained in:
adm committed 2026-12-02 03:04:58 +01:00
1 parent 47f8b52070
commit 755626fae2
4 files changed
+253 -6

No files matched your search

+81
View File
@@ -119,6 +119,11 @@ mod ffi {
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_nvfp4_grouped_gemm_wmma(
arena_packed: *const u8, arena_scales: *const u8, outer_arena: *const c_float,
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_buckets_masked(bucket_y: *const c_float, slotk_to_bidx: *const c_int, tk_w: *const c_float, out: *mut c_float, b: c_int, top_k: c_int, d: c_int, stream: *mut c_void) -> c_int;
pub fn vetta_shortconv4_decode(cur: *const c_float, static_w: *const c_float, hist: *mut c_float, out: *mut c_float, slot_ids: *const i32, m: c_int, c: c_int, stream: *mut c_void) -> c_int;
pub fn vetta_shortconv4_dyn_decode(cur: *const c_float, static_w: *const c_float, dyn_taps: *const c_float, hist: *mut c_float, out: *mut c_float, slot_ids: *const i32, m: c_int, c: c_int, n_heads: c_int, stream: *mut c_void) -> c_int;
@@ -735,6 +740,21 @@ pub fn nvfp4_grouped_gemv_f16(arena_packed: &DeviceBuf, arena_scales: &DeviceBuf
Ok(())
}
/// FP16 WMMA tensor-core grouped MoE GEMM (drop-in for nvfp4_grouped_gemv_f16).
/// Same arena/CSR I/O and Y[total,N] f32 bucket order; K must be a multiple of 64.
/// Matrix-core 16x16x16 tiles (~8x fdot2 ALU throughput). Accumulation order differs
/// from serial fdot2 => ~1e-3 (P1 tolerance; greedy-vs-reference is the blocking gate).
#[cfg(feature = "hip")]
#[allow(clippy::too_many_arguments)]
pub fn nvfp4_grouped_gemm_wmma(arena_packed: &DeviceBuf, arena_scales: &DeviceBuf, outer_arena: &DeviceBuf, exp_off: &DeviceBuf, bucket_tok: Option<&DeviceBuf>, x: &DeviceBuf, y: &DeviceBuf, n: i32, k: i32, n_experts: i32, w_stride: i64, sc_stride: i64) -> Result<(), String> {
let bt = bucket_tok.map(|b| b.ptr as *const i32).unwrap_or(std::ptr::null());
let rc = unsafe {
ffi::vetta_nvfp4_grouped_gemm_wmma(arena_packed.ptr as *const u8, arena_scales.ptr as *const u8, outer_arena.ptr as *const f32, exp_off.ptr as *const i32, bt, 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("nvfp4_grouped_gemm_wmma launch failed".into()); }
Ok(())
}
/// Scatter-back + weighted reduce per token from bucket-order expert outputs:
/// out[b,d] = sum_kk tk_w[b*top_k+kk] * bucket_y[slotk_to_bidx[b*top_k+kk]*D+d].
#[cfg(feature = "hip")]
@@ -1474,6 +1494,67 @@ mod gpu_tests {
assert!(max_rel < 2e-3, "grouped NVFP4 GEMM parity failed: {max_rel}");
}
/// FP16 WMMA grouped GEMM parity vs the same CPU oracle. N=128 exercises all 8
/// wave N-tiles; K=128 (multiple of BK=64). WMMA changes the f32 accumulation
/// order and prescales the dequantized weight in f16 (e4m3*0.0625 exact, E2M1*scale
/// rounded) => P1 numeric tolerance (~1e-3), not bit-exact. Greedy-vs-reference is
/// the blocking production gate (ld forward_batch_parity / gw serve_gen).
#[test]
#[ignore]
fn nvfp4_grouped_gemm_wmma_parity() {
let (b, top_k, n_exp, n, k) = (20usize, 8usize, 4usize, 128usize, 128usize);
let total = b * top_k;
let w_stride = n * (k / 2);
let sc_stride = n * (k / 16);
let packed: Vec<u8> = (0..n_exp * w_stride).map(|i| (i % 256) as u8).collect();
let scales: Vec<u8> = (0..n_exp * sc_stride).map(|i| ((i * 7 + 3) % 251) as u8).collect();
let outer: Vec<f32> = (0..n_exp).map(|i| 0.3 + 0.1 * i as f32).collect();
let ids: Vec<i32> = (0..total).map(|i| ((i * 7 + (i / top_k) * 13) % n_exp) as i32).collect();
let xf: Vec<f32> = (0..b * k).map(|i| (i % 29) as f32 - 14.0).collect();
let ap = DeviceBuf::alloc(packed.len()).unwrap(); ap.h2d_bytes(&packed).unwrap();
let asc = DeviceBuf::alloc(scales.len()).unwrap(); asc.h2d_bytes(&scales).unwrap();
let ao = DeviceBuf::alloc(n_exp * 4).unwrap(); ao.h2d(&outer).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<u8> = 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();
nvfp4_grouped_gemm_wmma(&ap, &asc, &ao, &doff, Some(&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<i32> = s2b_b.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect();
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 / 16 {
let sc = e4m3(scales[e * sc_stride + ni * (k / 16) + bb]) * outer[e];
let mut d = 0f32;
for j in 0..8 {
let byte = packed[e * w_stride + ni * (k / 2) + bb * 8 + j];
d += xf[tok * k + bb * 16 + j * 2] * e2m1(byte & 15) + xf[tok * k + bb * 16 + j * 2 + 1] * e2m1(byte >> 4);
}
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!("nvfp4_grouped_gemm_wmma B={b} experts={n_exp} pairs={total} N={n} K={k} max_rel_err={max_rel:.3e}");
assert!(max_rel < 5e-3, "WMMA grouped NVFP4 GEMM parity failed: {max_rel}");
}
/// reduce_buckets_masked parity: scatter-back from bucket order + weighted
/// reduce per token vs a CPU oracle using the same slotk_to_bidx map.
#[test]