[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:
1 parent
47f8b52070
commit
755626fae2
4 files changed
+253
-6
No files matched your search
@@ -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]
|
||||
|
||||
@@ -1598,7 +1598,7 @@ mod tests {
|
||||
let mut ids_b = vec![0u8; b * top_k * 4]; ids.d2h_bytes(&mut ids_b).unwrap();
|
||||
let ids_h: Vec<i32> = ids_b.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect();
|
||||
let mut weights_h = vec![0f32; b * top_k]; weights.d2h(&mut weights_h).unwrap();
|
||||
let mut max_rel = 0f32;
|
||||
let mut os_all = vec![0f32; b * h];
|
||||
for m in 0..b {
|
||||
let mlpin_m = DeviceBuf::alloc(h * 4).unwrap(); mlpin_m.h2d(&mlpin_h[m * h..(m + 1) * h]).unwrap();
|
||||
let ids_m = DeviceBuf::alloc(top_k * 4).unwrap();
|
||||
@@ -1607,8 +1607,14 @@ mod tests {
|
||||
let weights_m = DeviceBuf::alloc(top_k * 4).unwrap(); weights_m.h2d(&weights_h[m * top_k..(m + 1) * top_k]).unwrap();
|
||||
let moeout_s = moe_device(&cache, ip, &mlpin_m, &ids_m, &weights_m, &d, h).unwrap();
|
||||
let mut os = vec![0f32; h]; moeout_s.d2h(&mut os).unwrap();
|
||||
for j in 0..h { max_rel = max_rel.max((ob[m * h + j] - os[j]).abs() / os[j].abs().max(1e-3)); }
|
||||
os_all[m * h..(m + 1) * h].copy_from_slice(&os);
|
||||
}
|
||||
// Global-scale normalization: P1 WMMA (ip=0 NVFP4) vs serial fdot2 differs
|
||||
// ~1e-4 absolute, which explodes per-entry on near-zero expert outputs.
|
||||
// ip=20 MXFP8 uses the same Wave32 fdot2 on both paths => bit-exact.
|
||||
let scale = os_all.iter().fold(0f32, |mx, v| mx.max(v.abs())).max(1e-3);
|
||||
let mut max_rel = 0f32;
|
||||
for (g, w) in ob.iter().zip(os_all.iter()) { max_rel = max_rel.max((g - w).abs() / scale); }
|
||||
eprintln!("moe_batched ip={ip} B={b} max_rel_err={max_rel:.3e}");
|
||||
assert!(max_rel < 3e-3, "batched MoE parity failed at ip={ip}: {max_rel}");
|
||||
}
|
||||
@@ -1652,8 +1658,13 @@ mod tests {
|
||||
let mut o = vec![0f32; h]; cur_m.d2h(&mut o).unwrap();
|
||||
cs[m * h..(m + 1) * h].copy_from_slice(&o);
|
||||
}
|
||||
// Normalize by the GLOBAL cur scale, not per-entry: the P1 WMMA MoE differs
|
||||
// from serial fdot2 by ~1e-4 absolute, which explodes as a per-entry relative
|
||||
// error on near-zero residual entries. The KV cache stays byte-identical
|
||||
// (attention precedes MoE) — that is the strong correctness gate here.
|
||||
let cscale = cs.iter().fold(0f32, |m, v| m.max(v.abs())).max(1e-3);
|
||||
let mut max_rel = 0f32;
|
||||
for (g, wnt) in cb.iter().zip(cs.iter()) { max_rel = max_rel.max((g - wnt).abs() / wnt.abs().max(1e-3)); }
|
||||
for (g, wnt) in cb.iter().zip(cs.iter()) { max_rel = max_rel.max((g - wnt).abs() / cscale); }
|
||||
// KV cache byte-compare (f16).
|
||||
let kvn = d.n_kv * max_seq * d.hd * 2;
|
||||
let mut kb = vec![0u8; kvn]; st_b.k_cache[0].d2h_bytes(&mut kb).unwrap();
|
||||
@@ -1702,8 +1713,13 @@ mod tests {
|
||||
let mut o = vec![0f32; h]; cur_m.d2h(&mut o).unwrap();
|
||||
cs[m * h..(m + 1) * h].copy_from_slice(&o);
|
||||
}
|
||||
// Normalize by the GLOBAL cur scale, not per-entry: the P1 WMMA MoE differs
|
||||
// from serial fdot2 by ~1e-4 absolute, which explodes as a per-entry relative
|
||||
// error on near-zero residual entries. The KV cache stays byte-identical
|
||||
// (attention precedes MoE) — that is the strong correctness gate here.
|
||||
let cscale = cs.iter().fold(0f32, |m, v| m.max(v.abs())).max(1e-3);
|
||||
let mut max_rel = 0f32;
|
||||
for (g, wnt) in cb.iter().zip(cs.iter()) { max_rel = max_rel.max((g - wnt).abs() / wnt.abs().max(1e-3)); }
|
||||
for (g, wnt) in cb.iter().zip(cs.iter()) { max_rel = max_rel.max((g - wnt).abs() / cscale); }
|
||||
let kvn = d.n_kv * max_seq * d.hd * 2;
|
||||
let mut kb = vec![0u8; kvn]; st_b.k_cache[0].d2h_bytes(&mut kb).unwrap();
|
||||
let mut ks = vec![0u8; kvn]; st_s.k_cache[0].d2h_bytes(&mut ks).unwrap();
|
||||
@@ -1744,7 +1760,12 @@ mod tests {
|
||||
eprintln!("forward_batch B={b} argmax batch={argb} seq={args} max_abs={max_abs:.3e} max_rel={max_rel:.3e}");
|
||||
set_kv_f16(false);
|
||||
unsafe { std::env::remove_var("VETTA_DEVICE_MOE") };
|
||||
assert_eq!(argb, args, "forward_batch argmax must match sequential");
|
||||
assert!(max_abs < 1e-2, "forward_batch logits parity failed: max_abs={max_abs}");
|
||||
assert_eq!(argb, args, "forward_batch argmax must match sequential (greedy gate)");
|
||||
// P1 tolerance: prefill MoE uses FP16 WMMA (tensor-core f32 accumulation
|
||||
// order) while M=1 decode uses serial fdot2. The ~1e-4 per-expert difference
|
||||
// amplifies through 24 layers to ~7e-2 absolute on softcap-bounded (+/-30)
|
||||
// logits (~2e-3 relative). The argmax above + gw serve_gen_multi_token_parity
|
||||
// (greedy-vs-reference EXACT) are the blocking production gates.
|
||||
assert!(max_abs < 0.15, "forward_batch logits parity failed: max_abs={max_abs}");
|
||||
}
|
||||
}
|
||||
@@ -205,6 +205,12 @@ pub fn expert_arena_gemv_f16(a: &ExpertArena, ids: &DeviceBuf, slot: i32, x: &De
|
||||
pub fn expert_arena_grouped_gemv_f16(a: &ExpertArena, exp_off: &DeviceBuf, bucket_tok: Option<&DeviceBuf>, x: &DeviceBuf, y: &DeviceBuf) -> Result<(), String> {
|
||||
if a.mxfp8 {
|
||||
vetta_infer_hip::mxfp8_grouped_gemv_f16(&a.packed, &a.scales, exp_off, bucket_tok, x, y, a.n, a.k, a.n_exp as i32, a.w_stride, a.sc_stride)
|
||||
} else if a.k % 64 == 0 && std::env::var("VETTA_NO_MOE_WMMA").is_err() {
|
||||
// P1: FP16 WMMA tensor-core grouped GEMM (~8x fdot2 ALU throughput). NVFP4
|
||||
// E2M1 dequant is exact in f16; only the f32 accumulation order differs
|
||||
// (~1e-4 measured). K%64==0 required by the BK=64 LDS slab (Inkling w13
|
||||
// K=2304, w2 K=1152). VETTA_NO_MOE_WMMA=1 falls back to fdot2 for A/B.
|
||||
vetta_infer_hip::nvfp4_grouped_gemm_wmma(&a.packed, &a.scales, &a.outer, exp_off, bucket_tok, x, y, a.n, a.k, a.n_exp as i32, a.w_stride, a.sc_stride)
|
||||
} else {
|
||||
vetta_infer_hip::nvfp4_grouped_gemv_f16(&a.packed, &a.scales, &a.outer, exp_off, bucket_tok, x, y, a.n, a.k, a.n_exp as i32, a.w_stride, a.sc_stride)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user