[HIP] attention + MoE router + vec_add kernels (GPU-verified, parity vs reference semantics)
- k_flash_gqa_decode: single-token GQA attention over a f32 KV cache, two-pass softmax, correctness-first base. Parity vs CPU oracle ~3e-6 on the real Inkling shape (24 heads / 8 KV, hd 128). SWA window / relpos bias / sinks / split-KV / WMMA are the later parity+performance refinements. - k_moe_router_topk: Inkling EXACT sigmoid router, semantics verified against strata k4_moe_router_topk — p=sigmoid(logit), score=p+bias, top-K by score (smallest eid wins ties), weight=p[chosen], renormalized to route_scale. Parity: top-k ids exact, weights ~1e-5 (128 experts, top-8, route_scale 8). - k_vec_add: y=a+b elementwise (residual stream), exact. - C ABI + safe Rust wrappers + DeviceBuf byte/i32 transfers + CPU-oracle tests. Six compute kernels now verified on gfx1150 (embed, rms_norm, gemm_bf16, flash_gqa, moe_router, vec_add); the base decode graph is covered except the NVFP4 expert GEMMs (w13/w2) + reduce. Approach: standard correctness-first math, Inkling-specific features ported from the measured reference (no invented attention variants); performance pass (WMMA/split-KV) comes after. Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS; lean proofs (4 files, 42 theorems) green; GPU parity 7/7 (--features hip).
This commit is contained in:
1 parent
356f9c458e
commit
b99d3a7a6a
3 files changed
+327
No files matched your search
@@ -40,6 +40,15 @@ mod ffi {
|
||||
x: *const u16, w: *const u16, y: *mut c_float,
|
||||
m: c_int, n: c_int, k: 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,
|
||||
) -> c_int;
|
||||
pub fn vetta_moe_router_topk(
|
||||
logits: *const c_float, bias: *const c_float, topk_ids: *mut i32, topk_weights: *mut c_float,
|
||||
m: c_int, n_experts: c_int, k_top: c_int, route_scale: c_float, stream: *mut c_void,
|
||||
) -> c_int;
|
||||
pub fn vetta_vec_add(a: *const c_float, b: *const c_float, y: *mut c_float, n: usize, stream: *mut c_void) -> c_int;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,6 +170,35 @@ pub fn gemm_bf16(x: &DeviceBuf, w: &DeviceBuf, y: &DeviceBuf, m: i32, n: i32, k:
|
||||
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> {
|
||||
let rc = unsafe {
|
||||
ffi::vetta_flash_gqa_decode(q.ptr as *const f32, k.ptr as *const f32, v.ptr as *const f32, out.ptr as *mut f32, n_head, n_kv, seq, hd, scale, std::ptr::null_mut())
|
||||
};
|
||||
if rc != 0 { return Err("flash_gqa launch failed".into()); }
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Launch k_moe_router_topk (Inkling exact sigmoid router).
|
||||
#[cfg(feature = "hip")]
|
||||
pub fn moe_router_topk(logits: &DeviceBuf, bias: Option<&DeviceBuf>, ids: &DeviceBuf, weights: &DeviceBuf, m: i32, n_experts: i32, k_top: i32, route_scale: f32) -> Result<(), String> {
|
||||
let bp = bias.map(|b| b.ptr as *const f32).unwrap_or(std::ptr::null());
|
||||
let rc = unsafe {
|
||||
ffi::vetta_moe_router_topk(logits.ptr as *const f32, bp, ids.ptr as *mut i32, weights.ptr as *mut f32, m, n_experts, k_top, route_scale, std::ptr::null_mut())
|
||||
};
|
||||
if rc != 0 { return Err("router launch failed".into()); }
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Launch k_vec_add: y = a + b elementwise.
|
||||
#[cfg(feature = "hip")]
|
||||
pub fn vec_add(a: &DeviceBuf, b: &DeviceBuf, y: &DeviceBuf, n: usize) -> Result<(), String> {
|
||||
let rc = unsafe { ffi::vetta_vec_add(a.ptr as *const f32, b.ptr as *const f32, y.ptr as *mut f32, n, std::ptr::null_mut()) };
|
||||
if rc != 0 { return Err("vec_add launch failed".into()); }
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(all(test, feature = "hip"))]
|
||||
mod gpu_tests {
|
||||
use super::*;
|
||||
@@ -269,6 +307,123 @@ mod gpu_tests {
|
||||
}
|
||||
}
|
||||
|
||||
fn cpu_attn(q: &[f32], k: &[f32], v: &[f32], n_head: usize, n_kv: usize, seq: usize, hd: usize, scale: f32) -> Vec<f32> {
|
||||
let group = n_head / n_kv;
|
||||
let mut out = vec![0f32; n_head * hd];
|
||||
for h in 0..n_head {
|
||||
let kvh = h / group;
|
||||
let qh = &q[h * hd..(h + 1) * hd];
|
||||
let mut scores = vec![0f32; seq];
|
||||
for s in 0..seq {
|
||||
let ks = &k[(kvh * seq + s) * hd..(kvh * seq + s + 1) * hd];
|
||||
scores[s] = qh.iter().zip(ks).map(|(a, b)| a * b).sum::<f32>() * scale;
|
||||
}
|
||||
let m = scores.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
|
||||
let mut denom = 0f32;
|
||||
for s in 0..seq { scores[s] = (scores[s] - m).exp(); denom += scores[s]; }
|
||||
for d in 0..hd {
|
||||
let mut acc = 0f32;
|
||||
for s in 0..seq { acc += scores[s] / denom * v[(kvh * seq + s) * hd + d]; }
|
||||
out[h * hd + d] = acc;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn flash_gqa_decode_parity_vs_cpu() {
|
||||
for &(n_head, n_kv, seq, hd) in &[(8usize, 2usize, 32usize, 64usize), (24, 8, 128, 128), (4, 4, 16, 32)] {
|
||||
let scale = 1.0f32 / (hd as f32).sqrt();
|
||||
let q: Vec<f32> = (0..n_head * hd).map(|i| ((i % 23) as f32 - 11.0) * 0.04).collect();
|
||||
let k: Vec<f32> = (0..n_kv * seq * hd).map(|i| ((i % 31) as f32 - 15.0) * 0.03).collect();
|
||||
let v: Vec<f32> = (0..n_kv * seq * hd).map(|i| ((i % 17) as f32 - 8.0) * 0.05).collect();
|
||||
let want = cpu_attn(&q, &k, &v, n_head, n_kv, seq, hd, scale);
|
||||
let dq = DeviceBuf::alloc(q.len() * 4).unwrap();
|
||||
let dk = DeviceBuf::alloc(k.len() * 4).unwrap();
|
||||
let dv = DeviceBuf::alloc(v.len() * 4).unwrap();
|
||||
let dy = DeviceBuf::alloc(want.len() * 4).unwrap();
|
||||
dq.h2d(&q).unwrap(); dk.h2d(&k).unwrap(); dv.h2d(&v).unwrap();
|
||||
flash_gqa_decode(&dq, &dk, &dv, &dy, n_head as i32, n_kv as i32, seq as i32, hd as i32, scale).unwrap();
|
||||
let mut got = vec![0f32; want.len()];
|
||||
dy.d2h(&mut got).unwrap();
|
||||
let mut max_rel = 0f32;
|
||||
for (g, wnt) in got.iter().zip(want.iter()) {
|
||||
max_rel = max_rel.max((g - wnt).abs() / wnt.abs().max(1e-3));
|
||||
}
|
||||
eprintln!("flash_gqa nh={n_head} nkv={n_kv} seq={seq} hd={hd} max_rel_err={max_rel:.3e}");
|
||||
assert!(max_rel < 1e-4, "flash_gqa parity failed: {max_rel}");
|
||||
}
|
||||
}
|
||||
|
||||
fn cpu_router(logits: &[f32], bias: &[f32], m: usize, n_experts: usize, k_top: usize, route_scale: f32) -> (Vec<i32>, Vec<f32>) {
|
||||
let mut ids = vec![0i32; m * k_top];
|
||||
let mut weights = vec![0f32; m * k_top];
|
||||
for mi in 0..m {
|
||||
let prob: Vec<f32> = (0..n_experts).map(|e| 1.0 / (1.0 + (-logits[mi * n_experts + e]).exp())).collect();
|
||||
let mut score: Vec<f32> = (0..n_experts).map(|e| prob[e] + bias[e]).collect();
|
||||
let mut wsum = 0f32;
|
||||
for k in 0..k_top {
|
||||
let mut bv = f32::NEG_INFINITY;
|
||||
let mut bi = 0usize;
|
||||
for e in 0..n_experts { if score[e] > bv { bv = score[e]; bi = e; } }
|
||||
ids[mi * k_top + k] = bi as i32;
|
||||
weights[mi * k_top + k] = prob[bi];
|
||||
wsum += prob[bi];
|
||||
score[bi] = -1e30;
|
||||
}
|
||||
let inv = route_scale / (wsum + 1e-20);
|
||||
for k in 0..k_top { weights[mi * k_top + k] *= inv; }
|
||||
}
|
||||
(ids, weights)
|
||||
}
|
||||
|
||||
fn read_i32(buf: &DeviceBuf, len: usize) -> Vec<i32> {
|
||||
let mut bytes = vec![0u8; len * 4];
|
||||
buf.d2h_bytes(&mut bytes).unwrap();
|
||||
bytes.chunks_exact(4).map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn moe_router_parity_vs_cpu() {
|
||||
let (m, n_experts, k_top, route_scale) = (2usize, 128usize, 8usize, 8.0f32);
|
||||
let logits: Vec<f32> = (0..m * n_experts).map(|i| ((i % 47) as f32 - 23.0) * 0.2).collect();
|
||||
let bias: Vec<f32> = (0..n_experts).map(|i| ((i % 19) as f32 - 9.0) * 0.03).collect();
|
||||
let (want_ids, want_w) = cpu_router(&logits, &bias, m, n_experts, k_top, route_scale);
|
||||
let dl = DeviceBuf::alloc(logits.len() * 4).unwrap();
|
||||
let db = DeviceBuf::alloc(bias.len() * 4).unwrap();
|
||||
let di = DeviceBuf::alloc(want_ids.len() * 4).unwrap();
|
||||
let dw = DeviceBuf::alloc(want_w.len() * 4).unwrap();
|
||||
dl.h2d(&logits).unwrap(); db.h2d(&bias).unwrap();
|
||||
moe_router_topk(&dl, Some(&db), &di, &dw, m as i32, n_experts as i32, k_top as i32, route_scale).unwrap();
|
||||
let got_ids = read_i32(&di, want_ids.len());
|
||||
let mut got_w = vec![0f32; want_w.len()];
|
||||
dw.d2h(&mut got_w).unwrap();
|
||||
assert_eq!(got_ids, want_ids, "router top-k ids must match exactly");
|
||||
let mut max_rel = 0f32;
|
||||
for (g, w) in got_w.iter().zip(want_w.iter()) { max_rel = max_rel.max((g - w).abs() / w.abs().max(1e-3)); }
|
||||
eprintln!("router max_rel_err={max_rel:.3e}");
|
||||
assert!(max_rel < 1e-5, "router weights parity failed: {max_rel}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn vec_add_exact() {
|
||||
let n = 10000usize;
|
||||
let a: Vec<f32> = (0..n).map(|i| (i as f32) * 0.01).collect();
|
||||
let b: Vec<f32> = (0..n).map(|i| -(i as f32) * 0.003).collect();
|
||||
let want: Vec<f32> = a.iter().zip(&b).map(|(x, y)| x + y).collect();
|
||||
let da = DeviceBuf::alloc(n * 4).unwrap();
|
||||
let db = DeviceBuf::alloc(n * 4).unwrap();
|
||||
let dy = DeviceBuf::alloc(n * 4).unwrap();
|
||||
da.h2d(&a).unwrap(); db.h2d(&b).unwrap();
|
||||
vec_add(&da, &db, &dy, n).unwrap();
|
||||
let mut got = vec![0f32; n];
|
||||
dy.d2h(&mut got).unwrap();
|
||||
assert_eq!(got, want, "vec_add must be exact");
|
||||
}
|
||||
|
||||
fn bytemuck_u16(v: &[u16]) -> &[u8] {
|
||||
unsafe { std::slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * 2) }
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user