From b6113b549a10b0085409ce531f32f555e68f841b Mon Sep 17 00:00:00 2001 From: iz0eyj Date: Tue, 1 Dec 2026 23:35:55 +0100 Subject: [PATCH] [HIP] reduce_buckets_masked: scatter-back + weighted reduce per token (batched MoE closed) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit k_moe_reduce_buckets_masked (exact strata semantics): bucket_y [total,D] in bucket order + slotk_to_bidx maps pair (b*top_k+kk) -> bucket position; out[b,d] = sum_kk tk_w[b*top_k+kk]*bucket_y[s2b[b*top_k+kk]*D+d]. grid (D tiles, B). This CLOSES the batched MoE compute path: bucket CSR (count/prefix/scatter) -> grouped expert GEMM (W amortized MT-fold) -> reduce_buckets_masked (scatter-back + weighted reduce). All device-side, no host round-trip. Parity vs CPU oracle: max_rel 1.75e-5 (f32 FMA accumulation noise, threshold 1e-4). Additive — decode default unchanged. Remaining for batched PREFILL: batched SiTU (M=total), batched attention (flash causal M=B + ShortConv prefill + attn_res_mix M=B + kv_store B), batched depth-blocks/controllers/bank, forward_batch + serve wiring + EXACT parity. Verified: hip GPU 23 green, workspace CPU -D warnings green, 6 Lean 0 sorryAx. --- crates/vetta-infer-hip/src/lib.rs | 56 +++++++++++++++++++++++++++++++ kernels/hip/vetta_kernels.hip | 32 ++++++++++++++++++ 2 files changed, 88 insertions(+) diff --git a/crates/vetta-infer-hip/src/lib.rs b/crates/vetta-infer-hip/src/lib.rs index 1110b73..aa62cd9 100644 --- a/crates/vetta-infer-hip/src/lib.rs +++ b/crates/vetta-infer-hip/src/lib.rs @@ -104,6 +104,7 @@ 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_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; pub fn vetta_attn_res_mix(blocks: *const c_float, cur: *const c_float, queries: *const c_float, out: *mut c_float, n_blocks: c_int, m: c_int, n_queries: c_int, d: c_int, eps: c_float, stream: *mut c_void) -> c_int; @@ -563,6 +564,17 @@ pub fn nvfp4_grouped_gemv_f16(arena_packed: &DeviceBuf, arena_scales: &DeviceBuf 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")] +pub fn moe_reduce_buckets_masked(bucket_y: &DeviceBuf, slotk_to_bidx: &DeviceBuf, tk_w: &DeviceBuf, out: &DeviceBuf, b: i32, top_k: i32, d: i32) -> Result<(), String> { + let rc = unsafe { + ffi::vetta_moe_reduce_buckets_masked(bucket_y.ptr as *const f32, slotk_to_bidx.ptr as *const i32, tk_w.ptr as *const f32, out.ptr as *mut f32, b, top_k, d, std::ptr::null_mut()) + }; + if rc != 0 { return Err("moe_reduce_buckets_masked launch failed".into()); } + Ok(()) +} + /// Launch k_shortconv4_decode (static): updates `hist` ring in place. #[cfg(feature = "hip")] pub fn shortconv4_decode(cur: &DeviceBuf, static_w: &DeviceBuf, hist: &DeviceBuf, out: &DeviceBuf, slot_ids: &DeviceBuf, m: i32, c: i32) -> Result<(), String> { @@ -1228,6 +1240,50 @@ mod gpu_tests { assert!(max_rel < 2e-3, "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] + #[ignore] + fn moe_reduce_buckets_masked_parity() { + let (b, top_k, d) = (20usize, 8usize, 64usize); + let total = b * top_k; + let ids: Vec = (0..total).map(|i| ((i * 7 + (i / top_k) * 13) % 128) as i32).collect(); + let ids_bytes: Vec = 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 by: Vec = (0..total * d).map(|i| ((i % 43) as f32 - 21.0) * 0.02).collect(); + let w: Vec = (0..total).map(|i| 0.5 + (i % 7) as f32 * 0.1).collect(); + let dby = DeviceBuf::alloc(total * d * 4).unwrap(); dby.h2d(&by).unwrap(); + let dw = DeviceBuf::alloc(total * 4).unwrap(); dw.h2d(&w).unwrap(); + let dout = DeviceBuf::alloc(b * d * 4).unwrap(); + moe_reduce_buckets_masked(&dby, &ds2b, &dw, &dout, b as i32, top_k as i32, d as i32).unwrap(); + let mut got = vec![0f32; b * d]; dout.d2h(&mut got).unwrap(); + let mut s2b_b = vec![0u8; total * 4]; ds2b.d2h_bytes(&mut s2b_b).unwrap(); + let s2b: Vec = s2b_b.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect(); + let mut want = vec![0f32; b * d]; + for bb in 0..b { + for dd in 0..d { + let mut acc = 0f32; + for kk in 0..top_k { + let pair = bb * top_k + kk; + acc += w[pair] * by[s2b[pair] as usize * d + dd]; + } + want[bb * d + dd] = acc; + } + } + let mut max_rel = 0f32; + for (g, wt) in got.iter().zip(want.iter()) { max_rel = max_rel.max((g - wt).abs() / wt.abs().max(1e-3)); } + eprintln!("moe_reduce_buckets_masked B={b} top_k={top_k} D={d} max_rel_err={max_rel:.3e}"); + assert!(max_rel < 1e-4, "reduce_buckets_masked parity failed: {max_rel}"); + } + #[test] #[ignore] fn shortconv4_multistep_parity() { diff --git a/kernels/hip/vetta_kernels.hip b/kernels/hip/vetta_kernels.hip index f07b1ca..a99ce5a 100644 --- a/kernels/hip/vetta_kernels.hip +++ b/kernels/hip/vetta_kernels.hip @@ -1657,4 +1657,36 @@ extern "C" int vetta_nvfp4_grouped_gemv_f16(const uint8_t* arena_packed, arena_packed, arena_scales, outer_arena, exp_off, bucket_tok, X, Y, N, K, w_stride, sc_stride); HIP_CHECK(hipGetLastError()); return 0; +} + +// ---- k_moe_reduce_buckets_masked: scatter-back + weighted reduce per token -- +// Exact strata k_moe_reduce_buckets_masked. bucket_y is [total_pairs, D] in +// bucket order; slotk_to_bidx maps pair (b*top_k+kk) -> bucket position. For each +// token b: out[b,d] = sum_kk tk_w[b*top_k+kk] * bucket_y[s2b[b*top_k+kk]*D+d]. +__global__ void k_moe_reduce_buckets_masked( + const float* __restrict__ bucket_y, + const int* __restrict__ slotk_to_bidx, + const float* __restrict__ tk_w, + float* __restrict__ out, int B, int top_k, int D) { + const int d = blockIdx.x * blockDim.x + threadIdx.x; + const int b = blockIdx.y; + if (d >= D || b >= B) return; + float acc = 0.f; + for (int kk = 0; kk < top_k; ++kk) { + const int pair = b * top_k + kk; + const int bp = slotk_to_bidx[pair]; + acc += tk_w[pair] * bucket_y[(size_t)bp * D + d]; + } + out[(size_t)b * D + d] = acc; +} + +extern "C" int vetta_moe_reduce_buckets_masked(const float* bucket_y, + const int* slotk_to_bidx, const float* tk_w, float* out, + int B, int top_k, int D, vetta_stream_t stream) { + if (B <= 0 || top_k <= 0 || D <= 0) return 1; + hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; + dim3 grid((D + 255) / 256, B); + k_moe_reduce_buckets_masked<<>>(bucket_y, slotk_to_bidx, tk_w, out, B, top_k, D); + HIP_CHECK(hipGetLastError()); + return 0; } \ No newline at end of file