[HIP] Batched router_gemv (f32) + relpos_bias + ctrl_pack (M=B): last attention/MoE prep kernels

k_router_gemv_batched: f32 router logits x[M,K]·w[N,K]bf16 -> y[M,N], grid(N,M)
(router reads F32 mlpin, exact strata launch_f32_linear).
k_relpos_bias_batched: r[M,n_head,d_rel] -> rel_bias[M,n_head,rel_extent], grid
(n_head,M), lim[m]=min(pos[m]+1,rel_extent) per token.
k_ctrl_pack_batched: cur/msg[M,D] -> packed[M,2D]bf16, grid M (controller input).

Parity vs M sequential: router 0.0, relpos 0.0, ctrl_pack BYTE-IDENTICAL (M=20).

Additive — decode default unchanged. With these, ALL per-layer kernels needed by
a batched forward now support M=B (gemm_bf16/rms_norm/attn_res_mix/router_topk
already did). Remaining: device-resident depth-block arena + batched layer
orchestration (SWA+full) + forward_batch + serve wiring + EXACT parity.

Verified: hip GPU 31 green, workspace CPU -D warnings green, 6 Lean 0 sorryAx.
This commit is contained in:
adm committed 2026-12-01 23:49:18 +01:00
1 parent 708a40d91b
commit 388e9108e5
2 files changed
+219

No files matched your search

+113
View File
@@ -47,6 +47,7 @@ mod ffi {
x: *const c_float, w: *const u16, y: *mut c_float,
n: c_int, k: c_int, stream: *mut c_void,
) -> c_int;
pub fn vetta_router_gemv_batched(x: *const c_float, w: *const u16, y: *mut c_float, n: c_int, k: c_int, m: c_int, stream: *mut c_void) -> c_int;
pub fn vetta_flash_gqa_decode(
q: *const c_float, k: *const c_float, v: *const c_float, out: *mut c_float,
n_head: c_int, n_kv: c_int, seq: c_int, hd: c_int, scale: c_float, stream: *mut c_void,
@@ -121,11 +122,13 @@ mod ffi {
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;
pub fn vetta_l2_clip(x: *mut c_float, scale: *const c_float, rows: c_int, hd: c_int, clip: c_float, apply_tau: c_int, pos: c_int, stream: *mut c_void) -> c_int;
pub fn vetta_relpos_bias(r: *const c_float, rel_proj: *const c_float, rel_bias: *mut c_float, n_head: c_int, d_rel: c_int, rel_extent: c_int, lim: c_int, stream: *mut c_void) -> c_int;
pub fn vetta_relpos_bias_batched(r: *const c_float, rel_proj: *const c_float, rel_bias: *mut c_float, pos: *const c_int, n_head: c_int, d_rel: c_int, rel_extent: c_int, m: c_int, stream: *mut c_void) -> c_int;
pub fn vetta_kv_store(k_in: *const c_float, v_in: *const c_float, k_cache: *mut c_float, v_cache: *mut c_float, pos: c_int, n_kv: c_int, hd: c_int, seq: c_int, rms_eps: c_float, stream: *mut c_void) -> c_int;
pub fn vetta_kv_store_f16(k_in: *const c_float, v_in: *const c_float, k_cache: *mut u16, v_cache: *mut u16, pos: c_int, n_kv: c_int, hd: c_int, seq: c_int, rms_eps: c_float, stream: *mut c_void) -> c_int;
pub fn vetta_kv_store_f16_batched(k_in: *const c_float, v_in: *const c_float, k_cache: *mut u16, v_cache: *mut u16, pos: *const c_int, n_kv: c_int, hd: c_int, seq: c_int, rms_eps: c_float, m: c_int, stream: *mut c_void) -> c_int;
pub fn vetta_softcap(x: *const c_float, y: *mut c_float, n: usize, cap: c_float, stream: *mut c_void) -> c_int;
pub fn vetta_ctrl_pack(cur: *const c_float, msg: *const c_float, packed: *mut u16, d: c_int, eps: c_float, stream: *mut c_void) -> c_int;
pub fn vetta_ctrl_pack_batched(cur: *const c_float, msg: *const c_float, packed: *mut u16, d: c_int, eps: c_float, m: c_int, stream: *mut c_void) -> c_int;
pub fn vetta_ctrl_apply(cur: *const c_float, msg: *const c_float, gain: *const c_float, forget: *const c_float, out: *mut c_float, n: usize, stream: *mut c_void) -> c_int;
}
}
@@ -346,6 +349,14 @@ pub fn router_gemv(x: &DeviceBuf, w: &DeviceBuf, y: &DeviceBuf, n: i32, k: i32)
Ok(())
}
/// Batched f32 router GEMM (M=B): x [M,K] f32, w [N,K] bf16 -> y [M,N].
#[cfg(feature = "hip")]
pub fn router_gemv_batched(x: &DeviceBuf, w: &DeviceBuf, y: &DeviceBuf, n: i32, k: i32, m: i32) -> Result<(), String> {
let rc = unsafe { ffi::vetta_router_gemv_batched(x.ptr as *const f32, w.ptr as *const u16, y.ptr as *mut f32, n, k, m, std::ptr::null_mut()) };
if rc != 0 { return Err("router_gemv_batched launch failed".into()); }
Ok(())
}
/// Launch k_flash_gqa_decode: single-token GQA attention over a f32 KV cache.
#[cfg(feature = "hip")]
pub fn flash_gqa_decode(q: &DeviceBuf, k: &DeviceBuf, v: &DeviceBuf, out: &DeviceBuf, n_head: i32, n_kv: i32, seq: i32, hd: i32, scale: f32) -> Result<(), String> {
@@ -689,6 +700,16 @@ pub fn relpos_bias(r: &DeviceBuf, rel_proj: &DeviceBuf, rel_bias: &DeviceBuf, n_
Ok(())
}
/// 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.
#[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> {
let rc = unsafe { ffi::vetta_relpos_bias_batched(r.ptr as *const f32, rel_proj.ptr as *const f32, rel_bias.ptr as *mut f32, pos.ptr as *const i32, n_head, d_rel, rel_extent, m, std::ptr::null_mut()) };
if rc != 0 { return Err("relpos_bias_batched launch failed".into()); }
Ok(())
}
/// Launch k_kv_store: K (pre-clipped) as-is + V RMS-normalized into f32 cache.
#[cfg(feature = "hip")]
#[allow(clippy::too_many_arguments)]
@@ -733,6 +754,14 @@ pub fn ctrl_pack(cur: &DeviceBuf, msg: &DeviceBuf, packed: &DeviceBuf, d: i32, e
Ok(())
}
/// Batched controller input pack (M=B): cur/msg [M,D] -> packed [M,2D] bf16.
#[cfg(feature = "hip")]
pub fn ctrl_pack_batched(cur: &DeviceBuf, msg: &DeviceBuf, packed: &DeviceBuf, d: i32, eps: f32, m: i32) -> Result<(), String> {
let rc = unsafe { ffi::vetta_ctrl_pack_batched(cur.ptr as *const f32, msg.ptr as *const f32, packed.ptr as *mut u16, d, eps, m, std::ptr::null_mut()) };
if rc != 0 { return Err("ctrl_pack_batched launch failed".into()); }
Ok(())
}
/// Launch k_ctrl_apply: out = (1-tanh(forget))*cur + tanh(gain)*msg.
#[cfg(feature = "hip")]
pub fn ctrl_apply(cur: &DeviceBuf, msg: &DeviceBuf, gain: &DeviceBuf, forget: &DeviceBuf, out: &DeviceBuf, n: usize) -> Result<(), String> {
@@ -1569,6 +1598,90 @@ mod gpu_tests {
assert!(max_rel < 2e-3, "grouped MXFP8 GEMM parity failed: {max_rel}");
}
/// Batched f32 router GEMM (M=B) vs M sequential router_gemv (same block
/// reduction order => bit-exact).
#[test]
#[ignore]
fn router_gemv_batched_parity() {
let (m, n, k) = (20usize, 16usize, 128usize);
let x: Vec<f32> = (0..m * k).map(|i| ((i % 29) as f32 - 14.0) * 0.03).collect();
let w: Vec<u16> = (0..n * k).map(|i| f32_to_bf16(((i % 23) as f32 - 11.0) * 0.04)).collect();
let dx = DeviceBuf::alloc(m * k * 4).unwrap(); dx.h2d(&x).unwrap();
let dw = DeviceBuf::alloc(n * k * 2).unwrap(); dw.h2d_bytes(bytemuck_u16(&w)).unwrap();
let dy_b = DeviceBuf::alloc(m * n * 4).unwrap();
router_gemv_batched(&dx, &dw, &dy_b, n as i32, k as i32, m as i32).unwrap();
let mut yb = vec![0f32; m * n]; dy_b.d2h(&mut yb).unwrap();
let dx1 = DeviceBuf::alloc(k * 4).unwrap();
let dy1 = DeviceBuf::alloc(n * 4).unwrap();
let mut max_rel = 0f32;
for mi in 0..m {
dx1.h2d(&x[mi * k..(mi + 1) * k]).unwrap();
router_gemv(&dx1, &dw, &dy1, n as i32, k as i32).unwrap();
let mut o = vec![0f32; n]; dy1.d2h(&mut o).unwrap();
for ni in 0..n { max_rel = max_rel.max((yb[mi * n + ni] - o[ni]).abs() / o[ni].abs().max(1e-3)); }
}
eprintln!("router_gemv_batched M={m} N={n} K={k} max_rel_err={max_rel:.3e}");
assert!(max_rel < 1e-6, "router batched parity failed: {max_rel}");
}
/// Batched relpos bias (M=B, lim per token) vs M sequential relpos_bias.
#[test]
#[ignore]
fn relpos_bias_batched_parity() {
let (m, n_head, d_rel, rel_extent, base) = (20usize, 8usize, 16usize, 64usize, 10i32);
let r: Vec<f32> = (0..m * n_head * d_rel).map(|i| ((i % 17) as f32 - 8.0) * 0.05).collect();
let rp: Vec<f32> = (0..d_rel * rel_extent).map(|i| ((i % 13) as f32 - 6.0) * 0.02).collect();
let pos: Vec<i32> = (0..m).map(|mi| base + mi as i32).collect();
let dr = DeviceBuf::alloc(r.len() * 4).unwrap(); dr.h2d(&r).unwrap();
let drp = DeviceBuf::alloc(rp.len() * 4).unwrap(); drp.h2d(&rp).unwrap();
let pos_bytes: Vec<u8> = pos.iter().flat_map(|x| x.to_le_bytes()).collect();
let dpos = DeviceBuf::alloc(m * 4).unwrap(); dpos.h2d_bytes(&pos_bytes).unwrap();
let row = n_head * rel_extent;
let zeros = vec![0f32; m * row];
let db_b = DeviceBuf::alloc(zeros.len() * 4).unwrap(); db_b.h2d(&zeros).unwrap();
relpos_bias_batched(&dr, &drp, &db_b, &dpos, n_head as i32, d_rel as i32, rel_extent as i32, m as i32).unwrap();
let mut bb = vec![0f32; zeros.len()]; db_b.d2h(&mut bb).unwrap();
let dr1 = DeviceBuf::alloc(n_head * d_rel * 4).unwrap();
let db1 = DeviceBuf::alloc(row * 4).unwrap();
let mut max_rel = 0f32;
for mi in 0..m {
dr1.h2d(&r[mi * n_head * d_rel..(mi + 1) * n_head * d_rel]).unwrap();
db1.h2d(&vec![0f32; row]).unwrap();
let lim = (pos[mi] + 1).min(rel_extent as i32);
relpos_bias(&dr1, &drp, &db1, n_head as i32, d_rel as i32, rel_extent as i32, lim).unwrap();
let mut o = vec![0f32; row]; db1.d2h(&mut o).unwrap();
for j in 0..row { max_rel = max_rel.max((bb[mi * row + j] - o[j]).abs() / o[j].abs().max(1e-3)); }
}
eprintln!("relpos_bias_batched M={m} n_head={n_head} max_rel_err={max_rel:.3e}");
assert!(max_rel < 1e-5, "relpos batched parity failed: {max_rel}");
}
/// Batched ctrl_pack (M=B) byte-identical to M sequential ctrl_pack.
#[test]
#[ignore]
fn ctrl_pack_batched_parity() {
let (m, d) = (20usize, 128usize);
let eps = 1e-6f32;
let cur: Vec<f32> = (0..m * d).map(|i| ((i % 31) as f32 - 15.0) * 0.04).collect();
let msg: Vec<f32> = (0..m * d).map(|i| ((i % 27) as f32 - 13.0) * 0.03).collect();
let dc = DeviceBuf::alloc(m * d * 4).unwrap(); dc.h2d(&cur).unwrap();
let dm = DeviceBuf::alloc(m * d * 4).unwrap(); dm.h2d(&msg).unwrap();
let dp_b = DeviceBuf::alloc(m * 2 * d * 2).unwrap();
ctrl_pack_batched(&dc, &dm, &dp_b, d as i32, eps, m as i32).unwrap();
let mut pb = vec![0u8; m * 2 * d * 2]; dp_b.d2h_bytes(&mut pb).unwrap();
let dc1 = DeviceBuf::alloc(d * 4).unwrap();
let dm1 = DeviceBuf::alloc(d * 4).unwrap();
let dp1 = DeviceBuf::alloc(2 * d * 2).unwrap();
for mi in 0..m {
dc1.h2d(&cur[mi * d..(mi + 1) * d]).unwrap();
dm1.h2d(&msg[mi * d..(mi + 1) * d]).unwrap();
ctrl_pack(&dc1, &dm1, &dp1, d as i32, eps).unwrap();
let mut o = vec![0u8; 2 * d * 2]; dp1.d2h_bytes(&mut o).unwrap();
assert_eq!(&pb[mi * 2 * d * 2..(mi + 1) * 2 * d * 2], &o[..], "ctrl_pack batched row {mi}");
}
eprintln!("ctrl_pack_batched M={m} D={d}: byte-identical to sequential");
}
#[test]
#[ignore]
fn shortconv4_multistep_parity() {