From f25cd27cf0ba1ca015a7d35a593a87cfa012fd58 Mon Sep 17 00:00:00 2001 From: iz0eyj Date: Wed, 2 Dec 2026 01:40:20 +0100 Subject: [PATCH] [HIP] eliminate per-visit sync h2d: rel_bias in-kernel zero + async memset + grouped identity Peer review (strata-ctl coder) flagged ~13.3 GB of blocking host zero-fill copies per prompt: rel_bias [B,n_head,rel_extent] (25 MB at B=256) was h2d-zeroed every layer visit, plus moe_batched dcnt/didx sync h2d drained the GPU queue each layer. - k_relpos_bias / k_relpos_bias_batched now write 0.0f for dist>=lim (full rel_extent in-kernel); callers drop the host zero vec + sync h2d (M=1 too). - vetta_buf_zero_async (hipMemsetAsync) + DeviceBuf::zero_async for dcnt. - grouped gemv bucket_tok nullable: w2 passes None (tok=beg+t0+m identity in kernel), removing the didx identity h2d. moe_launch 2054ms -> 8ms per chunk. Prefill 2048: 56 -> 52.3 s; parity EXACT (ld 23, hip 33, gw 4, Lean 6/6). Enables host/device pipelining + is a graph-capture prerequisite. Big perf gap remains the scalar GEMM/flash (WMMA next). --- crates/vetta-infer-hip/src/lib.rs | 26 +++++++++++++----- crates/vetta-infer-ld/src/layer.rs | 24 +++++++---------- crates/vetta-infer-ld/src/packer.rs | 2 +- kernels/hip/vetta_kernels.hip | 42 ++++++++++++++++++++--------- 4 files changed, 59 insertions(+), 35 deletions(-) diff --git a/crates/vetta-infer-hip/src/lib.rs b/crates/vetta-infer-hip/src/lib.rs index 24cf6f6..b59be33 100644 --- a/crates/vetta-infer-hip/src/lib.rs +++ b/crates/vetta-infer-hip/src/lib.rs @@ -33,6 +33,7 @@ mod ffi { pub fn vetta_buf_copy2d(dst: *mut c_void, dpitch: usize, src: *const c_void, spitch: usize, width: usize, height: usize) -> c_int; pub fn vetta_synchronize() -> c_int; pub fn vetta_vram_used(out: *mut usize) -> c_int; + pub fn vetta_buf_zero_async(dst: *mut c_void, bytes: usize, stream: *mut c_void) -> c_int; pub fn vetta_rms_norm_f32( x: *const c_float, w: *const c_float, y: *mut c_float, rows: c_int, d: c_int, eps: c_float, stream: *mut c_void, @@ -316,6 +317,14 @@ impl DeviceBuf { if rc != 0 { return Err("d2d copy2d failed".into()); } Ok(()) } + /// Async zero-fill of the whole buffer on the default stream (hipMemsetAsync): + /// ordered before later kernels with NO blocking host round-trip. Replaces a + /// sync `h2d(&vec![0; n])` that would drain the GPU queue every layer visit. + pub fn zero_async(&self) -> Result<(), String> { + let rc = unsafe { ffi::vetta_buf_zero_async(self.ptr, self.bytes, std::ptr::null_mut()) }; + if rc != 0 { return Err("memset async failed".into()); } + Ok(()) + } } #[cfg(feature = "hip")] @@ -631,9 +640,10 @@ pub fn situ_f16_batched(gu: &DeviceBuf, act: &DeviceBuf, inter: i32, beta: f32, /// X [B,K] f16 -> Y [total_pairs,N] f32 bucket order. #[cfg(feature = "hip")] #[allow(clippy::too_many_arguments)] -pub fn mxfp8_grouped_gemv_f16(arena_weights: &DeviceBuf, arena_scales: &DeviceBuf, exp_off: &DeviceBuf, bucket_tok: &DeviceBuf, x: &DeviceBuf, y: &DeviceBuf, n: i32, k: i32, n_experts: i32, w_stride: i64, sc_stride: i64) -> Result<(), String> { +pub fn mxfp8_grouped_gemv_f16(arena_weights: &DeviceBuf, arena_scales: &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_mxfp8_grouped_gemv_f16(arena_weights.ptr as *const u8, arena_scales.ptr as *const u8, exp_off.ptr as *const i32, bucket_tok.ptr as *const i32, x.ptr as *const u16, y.ptr as *mut f32, n, k, n_experts, w_stride, sc_stride, std::ptr::null_mut()) + ffi::vetta_mxfp8_grouped_gemv_f16(arena_weights.ptr as *const u8, arena_scales.ptr as *const u8, 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("mxfp8_grouped_gemv_f16 launch failed".into()); } Ok(()) @@ -677,9 +687,10 @@ pub fn moe_scatter_buckets(topk_ids: &DeviceBuf, exp_cur: &DeviceBuf, bucket_tok /// amortized MT-fold. X [B,K] f16, Y [total_pairs,N] f32 in bucket order. #[cfg(feature = "hip")] #[allow(clippy::too_many_arguments)] -pub fn nvfp4_grouped_gemv_f16(arena_packed: &DeviceBuf, arena_scales: &DeviceBuf, outer_arena: &DeviceBuf, exp_off: &DeviceBuf, bucket_tok: &DeviceBuf, x: &DeviceBuf, y: &DeviceBuf, n: i32, k: i32, n_experts: i32, w_stride: i64, sc_stride: i64) -> Result<(), String> { +pub fn nvfp4_grouped_gemv_f16(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_gemv_f16(arena_packed.ptr as *const u8, arena_scales.ptr as *const u8, outer_arena.ptr as *const f32, exp_off.ptr as *const i32, bucket_tok.ptr as *const i32, x.ptr as *const u16, y.ptr as *mut f32, n, k, n_experts, w_stride, sc_stride, std::ptr::null_mut()) + ffi::vetta_nvfp4_grouped_gemv_f16(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_gemv_f16 launch failed".into()); } Ok(()) @@ -774,7 +785,8 @@ pub fn relpos_bias(r: &DeviceBuf, rel_proj: &DeviceBuf, rel_bias: &DeviceBuf, n_ } /// Batched relpos bias (M=B): r [M,n_head,d_rel] -> rel_bias [M,n_head,rel_extent], -/// lim[m]=min(pos[m]+1,rel_extent). Caller zero-fills rel_bias. +/// lim[m]=min(pos[m]+1,rel_extent). Kernel writes the full rel_extent (0.0f beyond +/// lim), so the caller need NOT host zero-fill (no sync h2d). #[cfg(feature = "hip")] #[allow(clippy::too_many_arguments)] pub fn relpos_bias_batched(r: &DeviceBuf, rel_proj: &DeviceBuf, rel_bias: &DeviceBuf, pos: &DeviceBuf, n_head: i32, d_rel: i32, rel_extent: i32, m: i32) -> Result<(), String> { @@ -1395,7 +1407,7 @@ mod gpu_tests { 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_gemv_f16(&ap, &asc, &ao, &doff, &dbtk, &dxh, &dy, n as i32, k as i32, n_exp as i32, w_stride as i64, sc_stride as i64).unwrap(); + nvfp4_grouped_gemv_f16(&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 = s2b_b.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect(); @@ -1645,7 +1657,7 @@ mod gpu_tests { 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(); - mxfp8_grouped_gemv_f16(&aw, &asc, &doff, &dbtk, &dxh, &dy, n as i32, k as i32, n_exp as i32, w_stride as i64, sc_stride as i64).unwrap(); + mxfp8_grouped_gemv_f16(&aw, &asc, &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 = s2b_b.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect(); diff --git a/crates/vetta-infer-ld/src/layer.rs b/crates/vetta-infer-ld/src/layer.rs index 05768b3..1ee6056 100644 --- a/crates/vetta-infer-ld/src/layer.rs +++ b/crates/vetta-infer-ld/src/layer.rs @@ -342,8 +342,7 @@ pub fn layer_forward_swa( let slot0 = DeviceBuf::alloc(4)?; slot0.h2d_bytes(&0i32.to_le_bytes())?; let k_cv = DeviceBuf::alloc(kv_dim * 4)?; let v_cv = DeviceBuf::alloc(kv_dim * 4)?; - let rel_bias = DeviceBuf::alloc(d.n_head * d.rel_extent * 4)?; - rel_bias.h2d(&vec![0f32; d.n_head * d.rel_extent])?; + let rel_bias = DeviceBuf::alloc(d.n_head * d.rel_extent * 4)?; // kernel writes all rel_extent (0.0f beyond lim): no sync host zero-fill let aout = DeviceBuf::alloc(q_dim * 4)?; let aout_bf = DeviceBuf::alloc(q_dim * 2)?; let oproj = DeviceBuf::alloc(h * 4)?; @@ -497,8 +496,7 @@ fn layer_forward_swa_batched( let bu = b as usize; let k_cv = DeviceBuf::alloc(bu * kv_dim * 4)?; let v_cv = DeviceBuf::alloc(bu * kv_dim * 4)?; - let rel_bias = DeviceBuf::alloc(bu * d.n_head * d.rel_extent * 4)?; - rel_bias.h2d(&vec![0f32; bu * d.n_head * d.rel_extent])?; + let rel_bias = DeviceBuf::alloc(bu * d.n_head * d.rel_extent * 4)?; // kernel writes all rel_extent (0.0f beyond lim): no sync host zero-fill let aout = DeviceBuf::alloc(bu * q_dim * 4)?; let aout_bf = DeviceBuf::alloc(bu * q_dim * 2)?; let oproj = DeviceBuf::alloc(bu * h * 4)?; @@ -773,7 +771,7 @@ fn moe_batched( let mlpin16 = DeviceBuf::alloc((b as usize) * h * 2)?; vetta_infer_hip::cast_f32_f16(mlpin, &mlpin16, (b as usize) * h)?; // Bucket CSR (device-side). - let dcnt = DeviceBuf::alloc(129 * 4)?; dcnt.h2d_bytes(&vec![0u8; 129 * 4])?; + let dcnt = DeviceBuf::alloc(129 * 4)?; dcnt.zero_async()?; let doff = DeviceBuf::alloc(129 * 4)?; let dcur = DeviceBuf::alloc(128 * 4)?; let dbtk = DeviceBuf::alloc(total * 4)?; @@ -783,15 +781,13 @@ fn moe_batched( vetta_infer_hip::moe_scatter_buckets(ids, &dcur, &dbtk, &ds2b, total as i32, top_k as i32)?; // w13 grouped GEMM: gather input tokens via bucket_tok -> gu [total, 2*inter]. let gu = DeviceBuf::alloc(total * 2 * inter * 4)?; - expert_arena_grouped_gemv_f16(&w13, &doff, &dbtk, &mlpin16, &gu)?; + expert_arena_grouped_gemv_f16(&w13, &doff, Some(&dbtk), &mlpin16, &gu)?; let act16 = DeviceBuf::alloc(total * inter * 2)?; vetta_infer_hip::situ_f16_batched(&gu, &act16, inter as i32, d.beta, d.lb, total as i32)?; - // w2 grouped GEMM: SiTU output is already bucket-ordered -> identity index. - let idx: Vec = (0..total as i32).collect(); - let idx_bytes: Vec = idx.iter().flat_map(|x| x.to_le_bytes()).collect(); - let didx = DeviceBuf::alloc(total * 4)?; didx.h2d_bytes(&idx_bytes)?; + // w2 grouped GEMM: SiTU output is already bucket-ordered -> identity index + // (bucket_tok=None reads tok = beg+t0+m in-kernel; no host identity h2d sync). let y_part = DeviceBuf::alloc(total * h * 4)?; - expert_arena_grouped_gemv_f16(&w2, &doff, &didx, &act16, &y_part)?; + expert_arena_grouped_gemv_f16(&w2, &doff, None, &act16, &y_part)?; // Scatter-back + weighted reduce per token. let moeout = DeviceBuf::alloc((b as usize) * h * 4)?; vetta_infer_hip::moe_reduce_buckets_masked(&y_part, &ds2b, weights, &moeout, b, top_k as i32, h as i32)?; @@ -1151,8 +1147,7 @@ pub fn layer_forward_full( vetta_infer_hip::l2_clip(&q, Some(&w.q_sc), d.n_head as i32, d.hd as i32, d.qk_clip, true, pos)?; vetta_infer_hip::l2_clip(&r_raw, Some(&w.r_sc), d.n_head as i32, d.d_rel as i32, d.rel_clip, true, pos)?; vetta_infer_hip::l2_clip(&k_cv, None, d.n_kv as i32, d.hd as i32, d.qk_clip, false, pos)?; - let rel_bias = DeviceBuf::alloc(d.n_head * d.rel_extent * 4)?; - rel_bias.h2d(&vec![0f32; d.n_head * d.rel_extent])?; + let rel_bias = DeviceBuf::alloc(d.n_head * d.rel_extent * 4)?; // kernel writes all rel_extent (0.0f beyond lim): no sync host zero-fill let lim = (pos + 1).min(d.rel_extent as i32); vetta_infer_hip::relpos_bias(&r_raw, &w.rel_proj, &rel_bias, d.n_head as i32, d.d_rel as i32, d.rel_extent as i32, lim)?; if f16_kv() { @@ -1278,8 +1273,7 @@ fn layer_forward_full_batched( vetta_infer_hip::l2_clip_batched(&q, Some(&w.q_sc), (b as usize * d.n_head) as i32, d.hd as i32, d.qk_clip, true, 0, d.n_head as i32, Some(pos))?; vetta_infer_hip::l2_clip_batched(&r_raw, Some(&w.r_sc), (b as usize * d.n_head) as i32, d.d_rel as i32, d.rel_clip, true, 0, d.n_head as i32, Some(pos))?; vetta_infer_hip::l2_clip_batched(&k_cv, None, (b as usize * d.n_kv) as i32, d.hd as i32, d.qk_clip, false, 0, d.n_kv as i32, None)?; - let rel_bias = DeviceBuf::alloc(bu * d.n_head * d.rel_extent * 4)?; - rel_bias.h2d(&vec![0f32; bu * d.n_head * d.rel_extent])?; + let rel_bias = DeviceBuf::alloc(bu * d.n_head * d.rel_extent * 4)?; // kernel writes all rel_extent (0.0f beyond lim): no sync host zero-fill vetta_infer_hip::relpos_bias_batched(&r_raw, &w.rel_proj, &rel_bias, pos, d.n_head as i32, d.d_rel as i32, d.rel_extent as i32, b)?; vetta_infer_hip::kv_store_f16_batched(&k_cv, &v_cv, &st.k_cache[pass], &st.v_cache[pass], pos, d.n_kv as i32, d.hd as i32, st.max_seq as i32, d.eps, b)?; let aout = DeviceBuf::alloc(bu * q_dim * 4)?; diff --git a/crates/vetta-infer-ld/src/packer.rs b/crates/vetta-infer-ld/src/packer.rs index 8eb7523..4a8f6f1 100644 --- a/crates/vetta-infer-ld/src/packer.rs +++ b/crates/vetta-infer-ld/src/packer.rs @@ -202,7 +202,7 @@ pub fn expert_arena_gemv_f16(a: &ExpertArena, ids: &DeviceBuf, slot: i32, x: &De /// expert eid processes its bucket tokens [exp_off[eid],exp_off[eid+1]) indexed /// by `bucket_tok`. X [B,K] f16 (gathered) or [total,K] f16 (bucket order, pass an /// identity index). Y [total_pairs,N] f32 in bucket order. Dispatches NVFP4/MXFP8. -pub fn expert_arena_grouped_gemv_f16(a: &ExpertArena, exp_off: &DeviceBuf, bucket_tok: &DeviceBuf, x: &DeviceBuf, y: &DeviceBuf) -> Result<(), String> { +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 { diff --git a/kernels/hip/vetta_kernels.hip b/kernels/hip/vetta_kernels.hip index a92be5d..f67840d 100644 --- a/kernels/hip/vetta_kernels.hip +++ b/kernels/hip/vetta_kernels.hip @@ -95,6 +95,14 @@ extern "C" int vetta_vram_used(size_t* out) { if (out) *out = total_b - free_b; return 0; } +// Async device zero-fill (hipMemsetAsync on the stream): ordered before subsequent +// kernels WITHOUT a blocking host round-trip (replaces sync h2d of a host zero vec). +extern "C" int vetta_buf_zero_async(void* dst, size_t bytes, vetta_stream_t stream) { + if (!dst || bytes == 0) return 0; + hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0; + HIP_CHECK(hipMemsetAsync(dst, 0, bytes, s)); + return 0; +} // ---- k_rms_norm (kernel #2): y = x * rsqrt(mean(x^2)+eps) * w -------------- // One block per row; block-wide reduction over D. f32 in/out. @@ -1333,7 +1341,7 @@ __global__ void __launch_bounds__(256) k_mxfp8_grouped_gemv_f16( #pragma unroll for (int m = 0; m < MT; ++m) { if (t0 + m < m_e) { - const int tok = bucket_tok[beg + t0 + m]; + const int tok = bucket_tok ? bucket_tok[beg + t0 + m] : (beg + t0 + m); const uint16_t* xr = X + (size_t)tok * K + k0; float d = 0.f; #pragma unroll @@ -1681,7 +1689,8 @@ extern "C" int vetta_l2_clip(float* x, const float* scale, int rows, int hd, // ---- k_relpos_bias: rel_bias[h,dist] = sum_rc R[h,rc]*rel_proj[rc,dist] ---- // R already L2-clipped [n_head,d_rel]; rel_proj [d_rel,rel_extent]; output -// rel_bias [n_head,rel_extent] for dist < lim = min(pos+1, rel_extent). +// rel_bias [n_head,rel_extent] for dist < lim = min(pos+1, rel_extent); entries +// dist >= lim are written 0.0f in-kernel (no caller host zero-fill / sync h2d). __global__ void k_relpos_bias(const float* __restrict__ r, const float* __restrict__ rel_proj, float* __restrict__ rel_bias, int n_head, int d_rel, @@ -1692,10 +1701,14 @@ __global__ void k_relpos_bias(const float* __restrict__ r, const float* __restri const int nt = blockDim.x; const float* rh = r + (size_t)h * d_rel; float* dst = rel_bias + (size_t)h * rel_extent; - for (int dist = tid; dist < lim; dist += nt) { - float acc = 0.f; - for (int rc = 0; rc < d_rel; ++rc) acc += rh[rc] * rel_proj[(size_t)rc * rel_extent + dist]; - dst[dist] = acc; + for (int dist = tid; dist < rel_extent; dist += nt) { + if (dist < lim) { + float acc = 0.f; + for (int rc = 0; rc < d_rel; ++rc) acc += rh[rc] * rel_proj[(size_t)rc * rel_extent + dist]; + dst[dist] = acc; + } else { + dst[dist] = 0.f; + } } } @@ -1711,7 +1724,8 @@ extern "C" int vetta_relpos_bias(const float* r, const float* rel_proj, float* r // ---- k_relpos_bias_batched: relpos bias for M tokens (lim per token) -------- // r [M,n_head,d_rel], rel_bias [M,n_head,rel_extent]; grid (n_head, M). Each token -// m writes dist < lim[m] = min(pos[m]+1, rel_extent). Caller zero-fills rel_bias. +// m writes dist < lim[m] = min(pos[m]+1, rel_extent) and 0.0f for dist >= lim[m] +// (full rel_extent written in-kernel; no caller host zero-fill / sync h2d). __global__ void k_relpos_bias_batched(const float* __restrict__ r, const float* __restrict__ rel_proj, float* __restrict__ rel_bias, const int32_t* __restrict__ pos, int n_head, int d_rel, int rel_extent, int M) { @@ -1723,10 +1737,14 @@ __global__ void k_relpos_bias_batched(const float* __restrict__ r, const float* const float* rh = r + ((size_t)m * n_head + h) * d_rel; float* dst = rel_bias + ((size_t)m * n_head + h) * rel_extent; const int lim = (pos[m] + 1 < rel_extent) ? (pos[m] + 1) : rel_extent; - for (int dist = tid; dist < lim; dist += nt) { - float acc = 0.f; - for (int rc = 0; rc < d_rel; ++rc) acc += rh[rc] * rel_proj[(size_t)rc * rel_extent + dist]; - dst[dist] = acc; + for (int dist = tid; dist < rel_extent; dist += nt) { + if (dist < lim) { + float acc = 0.f; + for (int rc = 0; rc < d_rel; ++rc) acc += rh[rc] * rel_proj[(size_t)rc * rel_extent + dist]; + dst[dist] = acc; + } else { + dst[dist] = 0.f; + } } } @@ -2104,7 +2122,7 @@ __global__ void __launch_bounds__(256) k_nvfp4_grouped_gemv_f16( #pragma unroll for (int m = 0; m < MT; ++m) { if (t0 + m < m_e) { - const int tok = bucket_tok[beg + t0 + m]; + const int tok = bucket_tok ? bucket_tok[beg + t0 + m] : (beg + t0 + m); const size_t xo = (size_t)tok * K + k0; const uint4 x0 = *reinterpret_cast(xh + xo); const uint4 x1 = *reinterpret_cast(xh + xo + 8);