[HIP] flash SWA GQA decode kernel — Inkling attention parity (window+relpos+sink+gate)
- k_flash_swa_gqa_decode / vetta_flash_swa_gqa_decode: exact strata
k3_flash_swa_gqa semantics on a contiguous f32 KV cache:
* SWA window: k_start = (window>0 && cur_pos>=window) ? cur_pos-window+1 : 0;
* relpos bias rel_bias[h,dist] added to the score (dist=cur_pos-s, <max_rel);
* attention sink_logit[h]: virtual sink token (value 0) contributing
exp(sink-m) to the softmax denominator only;
* sigmoid gate_attn[h,d] applied per output dim.
Two-pass softmax over the windowed range, f32 throughout. rel_bias /
sink_logit / gate are optional (NULL disables each).
- Parity test vs a CPU oracle across 4 configs (window on/off x relpos x sink
x gate): max_rel_err 9.4e-7 .. 3.6e-6. The Inkling-specific attention math
(local window, relative position, sink, gate) is verified.
With ShortConv4, this covers the defining Inkling attention mechanisms; the
AttnRes block-mix deep residual is the remaining parity piece.
Verified: RUSTFLAGS="-D warnings" cargo test --workspace = 97/97 PASS;
lean proofs (4 files, 42 theorems) green; GPU 12/12 (--features hip).
This commit is contained in:
1 parent
e060862660
commit
aea1c437d4
3 files changed
+201
No files matched your search
@@ -44,6 +44,12 @@ mod ffi {
|
||||
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_flash_swa_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,
|
||||
swa_window: c_int, cur_pos: c_int, rel_bias: *const c_float, max_rel: c_int,
|
||||
sink_logit: *const c_float, gate: *const 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,
|
||||
@@ -188,6 +194,21 @@ pub fn flash_gqa_decode(q: &DeviceBuf, k: &DeviceBuf, v: &DeviceBuf, out: &Devic
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Launch k_flash_swa_gqa_decode: Inkling SWA window + relpos + sink + gate.
|
||||
/// `rel_bias`, `sink_logit`, `gate` are optional (None -> NULL).
|
||||
#[cfg(feature = "hip")]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn flash_swa_gqa_decode(q: &DeviceBuf, k: &DeviceBuf, v: &DeviceBuf, out: &DeviceBuf, n_head: i32, n_kv: i32, seq: i32, hd: i32, scale: f32, swa_window: i32, cur_pos: i32, rel_bias: Option<&DeviceBuf>, max_rel: i32, sink_logit: Option<&DeviceBuf>, gate: Option<&DeviceBuf>) -> Result<(), String> {
|
||||
let rb = rel_bias.map(|b| b.ptr as *const f32).unwrap_or(std::ptr::null());
|
||||
let sk = sink_logit.map(|b| b.ptr as *const f32).unwrap_or(std::ptr::null());
|
||||
let gt = gate.map(|b| b.ptr as *const f32).unwrap_or(std::ptr::null());
|
||||
let rc = unsafe {
|
||||
ffi::vetta_flash_swa_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, swa_window, cur_pos, rb, max_rel, sk, gt, std::ptr::null_mut())
|
||||
};
|
||||
if rc != 0 { return Err("flash_swa_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> {
|
||||
@@ -406,6 +427,75 @@ mod gpu_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn cpu_swa_attn(q: &[f32], k: &[f32], v: &[f32], n_head: usize, n_kv: usize, seq: usize, hd: usize, scale: f32, window: i32, cur_pos: i32, rb: Option<&[f32]>, max_rel: usize, sink: Option<&[f32]>, gate: Option<&[f32]>) -> Vec<f32> {
|
||||
let k_start = if window > 0 && cur_pos >= window { (cur_pos - window + 1) as usize } else { 0 };
|
||||
let mut out = vec![0f32; n_head * hd];
|
||||
for h in 0..n_head {
|
||||
let kvh = h / (n_head / n_kv);
|
||||
let sink_v = sink.map(|s| s[h]);
|
||||
let mut m = sink_v.unwrap_or(f32::NEG_INFINITY);
|
||||
let mut scores = Vec::new();
|
||||
let mut positions = Vec::new();
|
||||
for s in k_start..=(cur_pos as usize) {
|
||||
let mut dot = 0f32;
|
||||
for d in 0..hd { dot += q[h * hd + d] * k[(kvh * seq + s) * hd + d]; }
|
||||
dot *= scale;
|
||||
let dist = cur_pos as usize - s;
|
||||
if let Some(rb) = rb { if dist < max_rel { dot += rb[h * max_rel + dist]; } }
|
||||
scores.push(dot);
|
||||
positions.push(s);
|
||||
m = m.max(dot);
|
||||
}
|
||||
let exps: Vec<f32> = scores.iter().map(|sc| (sc - m).exp()).collect();
|
||||
let mut denom = sink_v.map(|sv| (sv - m).exp()).unwrap_or(0.0);
|
||||
denom += exps.iter().sum::<f32>();
|
||||
let inv = 1.0 / denom.max(1e-30);
|
||||
for d in 0..hd {
|
||||
let mut acc = 0f32;
|
||||
for (i, &s) in positions.iter().enumerate() { acc += exps[i] * inv * v[(kvh * seq + s) * hd + d]; }
|
||||
if let Some(g) = gate { acc *= 1.0 / (1.0 + (-g[h * hd + d]).exp()); }
|
||||
out[h * hd + d] = acc;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn flash_swa_gqa_parity_vs_cpu() {
|
||||
// (window, use_relpos, use_sink, use_gate)
|
||||
for &(window, ur, us, ug) in &[(4i32, true, true, true), (0, true, true, true), (6, false, false, false), (3, true, false, true)] {
|
||||
let (n_head, n_kv, seq, hd) = (8usize, 2usize, 32usize, 64usize);
|
||||
let cur_pos = (seq - 1) as i32;
|
||||
let max_rel = 32usize;
|
||||
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 rb: Vec<f32> = (0..n_head * max_rel).map(|i| ((i % 13) as f32 - 6.0) * 0.02).collect();
|
||||
let sink: Vec<f32> = (0..n_head).map(|i| (i as f32) * 0.3 - 1.0).collect();
|
||||
let gate: Vec<f32> = (0..n_head * hd).map(|i| ((i % 29) as f32 - 14.0) * 0.1).collect();
|
||||
let want = cpu_swa_attn(&q, &k, &v, n_head, n_kv, seq, hd, scale, window, cur_pos, ur.then_some(rb.as_slice()), max_rel, us.then_some(sink.as_slice()), ug.then_some(gate.as_slice()));
|
||||
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();
|
||||
let drb = DeviceBuf::alloc(rb.len() * 4).unwrap();
|
||||
let dsk = DeviceBuf::alloc(sink.len() * 4).unwrap();
|
||||
let dgt = DeviceBuf::alloc(gate.len() * 4).unwrap();
|
||||
dq.h2d(&q).unwrap(); dk.h2d(&k).unwrap(); dv.h2d(&v).unwrap();
|
||||
drb.h2d(&rb).unwrap(); dsk.h2d(&sink).unwrap(); dgt.h2d(&gate).unwrap();
|
||||
flash_swa_gqa_decode(&dq, &dk, &dv, &dy, n_head as i32, n_kv as i32, seq as i32, hd as i32, scale, window, cur_pos, ur.then_some(&drb), max_rel as i32, us.then_some(&dsk), ug.then_some(&dgt)).unwrap();
|
||||
let mut got = vec![0f32; want.len()];
|
||||
dy.d2h(&mut got).unwrap();
|
||||
let mut max_rel_err = 0f32;
|
||||
for (g, w) in got.iter().zip(want.iter()) { max_rel_err = max_rel_err.max((g - w).abs() / w.abs().max(1e-3)); }
|
||||
eprintln!("flash_swa window={window} rel={ur} sink={us} gate={ug} max_rel_err={max_rel_err:.3e}");
|
||||
assert!(max_rel_err < 1e-4, "flash_swa parity failed: {max_rel_err}");
|
||||
}
|
||||
}
|
||||
|
||||
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];
|
||||
|
||||
Reference in new issue
Block a user