[HIP] P1 b7: FlashAttention-2 WMMA prefill (kills global scores_scratch)
k_flash_swa_gqa_prefill_wmma: tiled FA2 on contiguous FP16 KV, same semantics as the scalar two-pass prefill (causal + SWA window + rel_bias + sink + sigmoid gate). BQ=64/BK=64/HD=128, 128 threads; Q scaled->f16 held in registers, K tiles reuse the Q LDS union, V loaded transposed for the PV B-operand, online softmax in registers, P staged in LDS => NO global scores_scratch alloc per batch. QK^T and PV via __builtin_amdgcn_wmma_f32_16x16x16_f16_w32. flash_swa_gqa_prefill_f16 binding dispatches WMMA for hd==128; VETTA_NO_FLASH_WMMA=1 forces scalar (A/B + scalar test). Parity vs scalar prefill on same fp16 KV (global-scale): 1.12e-3 (f16 P/Q rounding). gw serve_gen 4/4 EXACT; ld forward_batch argmax 111==111; forward_batch internal bound normalized to global logit scale (<1e-2) per P1 policy (f16 P compounds ~5e-3). MEASURED prefill 2048 A/B: flash scalar 27.6s -> flash WMMA 12.9s (-53%). Cumulative prefill 60 -> 12.9s (-78%); reference ~4.5s, gap ~2.9x. Suite GREEN: hip36 ld23 gw4 GPU serial, CPU -D warnings 23, Lean 6/6 0sorryAx.
This commit is contained in:
1 parent
216983abae
commit
cfa5586447
3 files changed
+276
-6
No files matched your search
@@ -78,6 +78,12 @@ mod ffi {
|
|||||||
sink_logit: *const c_float, gate: *const c_float, scores_scratch: *mut c_float,
|
sink_logit: *const c_float, gate: *const c_float, scores_scratch: *mut c_float,
|
||||||
n_win_max: c_int, m: c_int, stream: *mut c_void,
|
n_win_max: c_int, m: c_int, stream: *mut c_void,
|
||||||
) -> c_int;
|
) -> c_int;
|
||||||
|
pub fn vetta_flash_swa_gqa_prefill_wmma(
|
||||||
|
q: *const c_float, k: *const u16, v: *const u16, 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, pos: *const c_int, rel_bias: *const c_float, max_rel: c_int,
|
||||||
|
sink_logit: *const c_float, gate: *const c_float, m: c_int, stream: *mut c_void,
|
||||||
|
) -> c_int;
|
||||||
pub fn vetta_moe_router_topk(
|
pub fn vetta_moe_router_topk(
|
||||||
logits: *const c_float, bias: *const c_float, topk_ids: *mut i32, topk_weights: *mut c_float,
|
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,
|
m: c_int, n_experts: c_int, k_top: c_int, route_scale: c_float, stream: *mut c_void,
|
||||||
@@ -518,6 +524,14 @@ pub fn flash_swa_gqa_prefill_f16(q: &DeviceBuf, k: &DeviceBuf, v: &DeviceBuf, ou
|
|||||||
let rb = rel_bias.map(|b| b.ptr as *const f32).unwrap_or(std::ptr::null());
|
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 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 gt = gate.map(|b| b.ptr as *const f32).unwrap_or(std::ptr::null());
|
||||||
|
// P1 b7: FA2 WMMA prefill (hd==128) keeps P in LDS -> no global scores_scratch.
|
||||||
|
if hd == 128 && std::env::var("VETTA_NO_FLASH_WMMA").is_err() {
|
||||||
|
let rc = unsafe {
|
||||||
|
ffi::vetta_flash_swa_gqa_prefill_wmma(q.ptr as *const f32, k.ptr as *const u16, v.ptr as *const u16, out.ptr as *mut f32, n_head, n_kv, seq, hd, scale, swa_window, pos.ptr as *const i32, rb, max_rel, sk, gt, m, std::ptr::null_mut())
|
||||||
|
};
|
||||||
|
if rc != 0 { return Err("flash_swa_gqa_prefill_wmma launch failed".into()); }
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
let n_win_max = if swa_window > 0 && max_pos >= swa_window { swa_window } else { max_pos + 1 };
|
let n_win_max = if swa_window > 0 && max_pos >= swa_window { swa_window } else { max_pos + 1 };
|
||||||
let scratch = DeviceBuf::alloc_unpooled((m as usize) * (n_head as usize) * (n_win_max as usize) * 4)?;
|
let scratch = DeviceBuf::alloc_unpooled((m as usize) * (n_head as usize) * (n_win_max as usize) * 4)?;
|
||||||
let rc = unsafe {
|
let rc = unsafe {
|
||||||
@@ -1076,6 +1090,60 @@ mod gpu_tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[ignore]
|
||||||
|
fn flash_swa_gqa_prefill_wmma_parity() {
|
||||||
|
// P1 b7: FA2 WMMA prefill vs the scalar two-pass prefill on the SAME fp16 KV
|
||||||
|
// (internal parity gate; greedy-vs-reference validates end-to-end downstream).
|
||||||
|
// f16 P/Q rounding + WMMA order => global-scale tolerance. M=70 crosses BQ=64.
|
||||||
|
let (n_head, n_kv, seq, hd, m) = (8usize, 2usize, 128usize, 128usize, 70usize);
|
||||||
|
let base = (seq - m) as i32;
|
||||||
|
let max_rel = 32usize;
|
||||||
|
let scale = 1.0f32 / (hd as f32).sqrt();
|
||||||
|
for &window in &[64i32, 0] {
|
||||||
|
let q: Vec<f32> = (0..m * n_head * hd).map(|i| ((i % 23) as f32 - 11.0) * 0.04).collect();
|
||||||
|
let kf: Vec<f32> = (0..n_kv * seq * hd).map(|i| ((i % 31) as f32 - 15.0) * 0.03).collect();
|
||||||
|
let vf: Vec<f32> = (0..n_kv * seq * hd).map(|i| ((i % 17) as f32 - 8.0) * 0.05).collect();
|
||||||
|
let rb: Vec<f32> = (0..m * n_head * max_rel).map(|i| ((i % 13) as f32 - 6.0) * 0.02).collect();
|
||||||
|
let sink: Vec<f32> = (0..m * n_head).map(|i| (i as f32) * 0.01 - 1.0).collect();
|
||||||
|
let gate: Vec<f32> = (0..m * n_head * hd).map(|i| ((i % 29) as f32 - 14.0) * 0.1).collect();
|
||||||
|
let pos: Vec<i32> = (0..m).map(|i| base + i as i32).collect();
|
||||||
|
let dq = DeviceBuf::alloc(q.len() * 4).unwrap();
|
||||||
|
let dkf = DeviceBuf::alloc(kf.len() * 4).unwrap();
|
||||||
|
let dvf = DeviceBuf::alloc(vf.len() * 4).unwrap();
|
||||||
|
let dk = DeviceBuf::alloc(kf.len() * 2).unwrap();
|
||||||
|
let dv = DeviceBuf::alloc(vf.len() * 2).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();
|
||||||
|
let dpos = DeviceBuf::alloc(pos.len() * 4).unwrap();
|
||||||
|
let dy = DeviceBuf::alloc(m * n_head * hd * 4).unwrap();
|
||||||
|
let dy2 = DeviceBuf::alloc(m * n_head * hd * 4).unwrap();
|
||||||
|
dq.h2d(&q).unwrap(); dkf.h2d(&kf).unwrap(); dvf.h2d(&vf).unwrap();
|
||||||
|
cast_f32_f16(&dkf, &dk, kf.len()).unwrap();
|
||||||
|
cast_f32_f16(&dvf, &dv, vf.len()).unwrap();
|
||||||
|
drb.h2d(&rb).unwrap(); dsk.h2d(&sink).unwrap(); dgt.h2d(&gate).unwrap();
|
||||||
|
dpos.h2d_bytes(&pos.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>()).unwrap();
|
||||||
|
// WMMA path (default dispatch, hd==128)
|
||||||
|
flash_swa_gqa_prefill_f16(&dq, &dk, &dv, &dy, n_head as i32, n_kv as i32, seq as i32, hd as i32, scale, window, &dpos, pos[m - 1], Some(&drb), max_rel as i32, Some(&dsk), Some(&dgt), m as i32).unwrap();
|
||||||
|
// scalar path (direct ffi + global scratch)
|
||||||
|
let n_win_max = if window > 0 && pos[m - 1] >= window { window } else { pos[m - 1] + 1 };
|
||||||
|
let scratch = DeviceBuf::alloc_unpooled(m * n_head * (n_win_max as usize) * 4).unwrap();
|
||||||
|
let rc = unsafe {
|
||||||
|
crate::ffi::vetta_flash_swa_gqa_prefill_f16(dq.ptr as *const f32, dk.ptr as *const u16, dv.ptr as *const u16, dy2.ptr as *mut f32, n_head as i32, n_kv as i32, seq as i32, hd as i32, scale, window, dpos.ptr as *const i32, drb.ptr as *const f32, max_rel as i32, dsk.ptr as *const f32, dgt.ptr as *const f32, scratch.ptr as *mut f32, n_win_max, m as i32, std::ptr::null_mut())
|
||||||
|
};
|
||||||
|
assert_eq!(rc, 0);
|
||||||
|
let mut gw = vec![0f32; m * n_head * hd];
|
||||||
|
let mut gs = vec![0f32; m * n_head * hd];
|
||||||
|
dy.d2h(&mut gw).unwrap(); dy2.d2h(&mut gs).unwrap();
|
||||||
|
let gscale = gs.iter().fold(0f32, |a, v| a.max(v.abs())).max(1e-6);
|
||||||
|
let mut max_rel = 0f32;
|
||||||
|
for (a, b) in gw.iter().zip(gs.iter()) { max_rel = max_rel.max((a - b).abs() / gscale); }
|
||||||
|
eprintln!("flash_prefill_wmma window={window} max_rel_err={max_rel:.3e}");
|
||||||
|
assert!(max_rel < 3e-3, "flash_prefill_wmma parity failed: {max_rel}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn cpu_attn(q: &[f32], k: &[f32], v: &[f32], n_head: usize, n_kv: usize, seq: usize, hd: usize, scale: f32) -> Vec<f32> {
|
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 group = n_head / n_kv;
|
||||||
let mut out = vec![0f32; n_head * hd];
|
let mut out = vec![0f32; n_head * hd];
|
||||||
@@ -1698,6 +1766,9 @@ mod gpu_tests {
|
|||||||
#[test]
|
#[test]
|
||||||
#[ignore]
|
#[ignore]
|
||||||
fn flash_swa_gqa_prefill_f16_parity() {
|
fn flash_swa_gqa_prefill_f16_parity() {
|
||||||
|
// This test gates the SCALAR prefill kernel's batched==sequential consistency
|
||||||
|
// (tight 1e-5); force the scalar path so the P1 WMMA dispatch doesn't apply.
|
||||||
|
unsafe { std::env::set_var("VETTA_NO_FLASH_WMMA", "1") };
|
||||||
let (n_head, n_kv, hd, seq, b) = (24usize, 8usize, 128usize, 15usize, 8usize);
|
let (n_head, n_kv, hd, seq, b) = (24usize, 8usize, 128usize, 15usize, 8usize);
|
||||||
let (base, win, max_rel) = (5i32, 1024i32, 1024usize);
|
let (base, win, max_rel) = (5i32, 1024i32, 1024usize);
|
||||||
let scale = 1.0f32 / (hd as f32).sqrt();
|
let scale = 1.0f32 / (hd as f32).sqrt();
|
||||||
@@ -1722,6 +1793,7 @@ mod gpu_tests {
|
|||||||
let dout_p = DeviceBuf::alloc(b * n_head * hd * 4).unwrap();
|
let dout_p = DeviceBuf::alloc(b * n_head * hd * 4).unwrap();
|
||||||
flash_swa_gqa_prefill_f16(&dq, &dk, &dv, &dout_p, n_head as i32, n_kv as i32, seq as i32, hd as i32, scale, win, &dpos, max_pos, Some(&drb), max_rel as i32, Some(&dsk), Some(&dgt), b as i32).unwrap();
|
flash_swa_gqa_prefill_f16(&dq, &dk, &dv, &dout_p, n_head as i32, n_kv as i32, seq as i32, hd as i32, scale, win, &dpos, max_pos, Some(&drb), max_rel as i32, Some(&dsk), Some(&dgt), b as i32).unwrap();
|
||||||
let mut got_p = vec![0f32; b * n_head * hd]; dout_p.d2h(&mut got_p).unwrap();
|
let mut got_p = vec![0f32; b * n_head * hd]; dout_p.d2h(&mut got_p).unwrap();
|
||||||
|
unsafe { std::env::remove_var("VETTA_NO_FLASH_WMMA") };
|
||||||
let dq1 = DeviceBuf::alloc(n_head * hd * 4).unwrap();
|
let dq1 = DeviceBuf::alloc(n_head * hd * 4).unwrap();
|
||||||
let drb1 = DeviceBuf::alloc(n_head * max_rel * 4).unwrap();
|
let drb1 = DeviceBuf::alloc(n_head * max_rel * 4).unwrap();
|
||||||
let dsk1 = DeviceBuf::alloc(n_head * 4).unwrap();
|
let dsk1 = DeviceBuf::alloc(n_head * 4).unwrap();
|
||||||
|
|||||||
@@ -1757,15 +1757,17 @@ mod tests {
|
|||||||
let args = ls.iter().enumerate().max_by(|a, c| a.1.partial_cmp(c.1).unwrap()).unwrap().0;
|
let args = ls.iter().enumerate().max_by(|a, c| a.1.partial_cmp(c.1).unwrap()).unwrap().0;
|
||||||
let mut max_abs = 0f32; let mut max_rel = 0f32;
|
let mut max_abs = 0f32; let mut max_rel = 0f32;
|
||||||
for (g, w) in lb.iter().zip(ls.iter()) { max_abs = max_abs.max((g - w).abs()); max_rel = max_rel.max((g - w).abs() / w.abs().max(1.0)); }
|
for (g, w) in lb.iter().zip(ls.iter()) { max_abs = max_abs.max((g - w).abs()); max_rel = max_rel.max((g - w).abs() / w.abs().max(1.0)); }
|
||||||
eprintln!("forward_batch B={b} argmax batch={argb} seq={args} max_abs={max_abs:.3e} max_rel={max_rel:.3e}");
|
let gscale = ls.iter().fold(0f32, |a, v| a.max(v.abs())).max(1e-6);
|
||||||
|
eprintln!("forward_batch B={b} argmax batch={argb} seq={args} max_abs={max_abs:.3e} max_rel={max_rel:.3e} global_rel={:.3e}", max_abs / gscale);
|
||||||
set_kv_f16(false);
|
set_kv_f16(false);
|
||||||
unsafe { std::env::remove_var("VETTA_DEVICE_MOE") };
|
unsafe { std::env::remove_var("VETTA_DEVICE_MOE") };
|
||||||
assert_eq!(argb, args, "forward_batch argmax must match sequential (greedy gate)");
|
assert_eq!(argb, args, "forward_batch argmax must match sequential (greedy gate)");
|
||||||
// P1 tolerance: prefill MoE uses FP16 WMMA (tensor-core f32 accumulation
|
// P1 tolerance: prefill uses FP16 WMMA MoE (tensor-core f32 accumulation
|
||||||
// order) while M=1 decode uses serial fdot2. The ~1e-4 per-expert difference
|
// order) + FA2 flash prefill (f16 P/Q rounding) while M=1 decode uses serial
|
||||||
// amplifies through 24 layers to ~7e-2 absolute on softcap-bounded (+/-30)
|
// fdot2 + f32 two-pass softmax. Per-kernel ~1e-4..1e-3 compounds through 24
|
||||||
// logits (~2e-3 relative). The argmax above + gw serve_gen_multi_token_parity
|
// layers to ~5e-3 of the GLOBAL logit scale (per-entry rel explodes on
|
||||||
|
// near-zero logits). The argmax above + gw serve_gen_multi_token_parity
|
||||||
// (greedy-vs-reference EXACT) are the blocking production gates.
|
// (greedy-vs-reference EXACT) are the blocking production gates.
|
||||||
assert!(max_abs < 0.15, "forward_batch logits parity failed: max_abs={max_abs}");
|
assert!(max_abs / gscale < 1e-2, "forward_batch logits parity failed: global_rel={}", max_abs / gscale);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2504,4 +2504,200 @@ extern "C" int vetta_gemm_bf16_wmma(const uint16_t* x, const uint16_t* w, float*
|
|||||||
k_gemm_bf16_wmma<<<grid, 256, 0, s>>>(x, w, y, M, N, K);
|
k_gemm_bf16_wmma<<<grid, 256, 0, s>>>(x, w, y, M, N, K);
|
||||||
HIP_CHECK(hipGetLastError());
|
HIP_CHECK(hipGetLastError());
|
||||||
return 0;
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- k_flash_swa_gqa_prefill_wmma: FlashAttention-2 WMMA prefill (P1 b7) ----
|
||||||
|
// Same semantics as k_flash_swa_gqa_prefill_f16 (causal + SWA window + rel_bias +
|
||||||
|
// sink + gate) but tiled FA2 with FP16 WMMA for QK^T and PV, online softmax in
|
||||||
|
// registers, P staged in LDS (NO global scores_scratch). Contiguous FP16 KV
|
||||||
|
// [n_kv,seq,hd]. BQ=64 queries/block, BK=64 keys/tile, HD=128. Q scaled->f16 once
|
||||||
|
// and held in registers; K tiles reuse the Q LDS union; V loaded transposed for
|
||||||
|
// the PV B-operand. f16 P/Q rounding + WMMA accumulation order => ~1e-3 (P1 budget;
|
||||||
|
// greedy-vs-reference is the gate). grid (n_head, ceil(M/64)), 128 threads.
|
||||||
|
#define FQ_BQ 64
|
||||||
|
#define FQ_BK 64
|
||||||
|
#define FQ_HD 128
|
||||||
|
#define FQ_LDK (FQ_HD + 8)
|
||||||
|
#define FQ_LDV (FQ_BK + 8)
|
||||||
|
#define FQ_LDP (FQ_BK + 8)
|
||||||
|
__device__ __forceinline__ uint16_t fq_f2h(float f) { return __builtin_bit_cast(uint16_t, __float2half_rn(f)); }
|
||||||
|
__global__ void __launch_bounds__(128) k_flash_swa_gqa_prefill_wmma(
|
||||||
|
const float* __restrict__ q,
|
||||||
|
const uint16_t* __restrict__ k,
|
||||||
|
const uint16_t* __restrict__ v,
|
||||||
|
float* __restrict__ out,
|
||||||
|
int n_head, int n_kv, int seq, int hd,
|
||||||
|
float scale, int swa_window,
|
||||||
|
const int32_t* __restrict__ pos,
|
||||||
|
const float* __restrict__ rel_bias, int max_rel,
|
||||||
|
const float* __restrict__ sink_logit,
|
||||||
|
const float* __restrict__ gate, int M) {
|
||||||
|
__shared__ union {
|
||||||
|
alignas(16) uint16_t sK[FQ_BQ * FQ_LDK]; // Q init then K tiles [64,136]
|
||||||
|
alignas(16) uint16_t sVt[FQ_HD * FQ_LDV]; // transposed V [128,72]
|
||||||
|
} kv;
|
||||||
|
__shared__ alignas(16) uint16_t sP[FQ_BQ * FQ_LDP];
|
||||||
|
const int tid = threadIdx.x;
|
||||||
|
const int wave = tid >> 5; // 0..3 -> 16 query rows each
|
||||||
|
const int lane = tid & 31;
|
||||||
|
const int l16 = lane & 15;
|
||||||
|
const int qh = blockIdx.x;
|
||||||
|
const int q_blk = blockIdx.y * FQ_BQ;
|
||||||
|
if (qh >= n_head || q_blk >= M) return;
|
||||||
|
const int kvh = qh / (n_head / n_kv);
|
||||||
|
// 1. Q[64,128] scaled -> f16 LDS, then wave's [16,128] into registers
|
||||||
|
for (int idx = tid; idx < FQ_BQ * (FQ_HD / 4); idx += 128) {
|
||||||
|
const int r = idx >> 5, c4 = idx & 31;
|
||||||
|
const int gm = q_blk + r;
|
||||||
|
uint16_t* dst = &kv.sK[r * FQ_LDK + c4 * 4];
|
||||||
|
if (gm < M) {
|
||||||
|
const float4 qv = *reinterpret_cast<const float4*>(q + ((size_t)gm * n_head + qh) * hd + c4 * 4);
|
||||||
|
dst[0] = fq_f2h(qv.x * scale); dst[1] = fq_f2h(qv.y * scale);
|
||||||
|
dst[2] = fq_f2h(qv.z * scale); dst[3] = fq_f2h(qv.w * scale);
|
||||||
|
} else { dst[0]=0; dst[1]=0; dst[2]=0; dst[3]=0; }
|
||||||
|
}
|
||||||
|
__syncthreads();
|
||||||
|
v_h16 q_frag[8];
|
||||||
|
#pragma unroll
|
||||||
|
for (int d = 0; d < 8; ++d) q_frag[d] = wmma_ld_h16(&kv.sK[(wave * 16 + l16) * FQ_LDK + d * 16]);
|
||||||
|
__syncthreads();
|
||||||
|
// 2. online-softmax state (per-query sink) + f32 O accumulators
|
||||||
|
v_f8 o_acc[8];
|
||||||
|
#pragma unroll
|
||||||
|
for (int d = 0; d < 8; ++d) o_acc[d] = v_f8_zero();
|
||||||
|
float row_max[8], row_sum[8];
|
||||||
|
int row_gm[8], row_pos[8];
|
||||||
|
const float* rb_ptrs[8];
|
||||||
|
#pragma unroll
|
||||||
|
for (int r = 0; r < 8; ++r) {
|
||||||
|
const int gm = q_blk + wave * 16 + wmma_acc_m11(r, lane);
|
||||||
|
row_gm[r] = gm;
|
||||||
|
row_pos[r] = (gm < M) ? pos[gm] : 0;
|
||||||
|
rb_ptrs[r] = (rel_bias && gm < M) ? (rel_bias + ((size_t)gm * n_head + qh) * max_rel) : nullptr;
|
||||||
|
if (sink_logit && gm < M) { row_max[r] = sink_logit[(size_t)gm * n_head + qh]; row_sum[r] = 1.0f; }
|
||||||
|
else { row_max[r] = -1e30f; row_sum[r] = 0.0f; }
|
||||||
|
}
|
||||||
|
const int q_min_pos = pos[q_blk];
|
||||||
|
const int q_max_pos = pos[(q_blk + FQ_BQ - 1 < M - 1) ? (q_blk + FQ_BQ - 1) : (M - 1)];
|
||||||
|
const int k_begin = (swa_window > 0 && q_min_pos >= swa_window) ? (q_min_pos - swa_window + 1) : 0;
|
||||||
|
const int k_blk_start = (k_begin / FQ_BK) * FQ_BK;
|
||||||
|
// 3. FA2 loop over KV blocks
|
||||||
|
for (int kb = k_blk_start; kb <= q_max_pos; kb += FQ_BK) {
|
||||||
|
// 3A. K[64,128] f16 -> kv.sK (contiguous)
|
||||||
|
for (int idx = tid; idx < FQ_BK * (FQ_HD / 4); idx += 128) {
|
||||||
|
const int r = idx >> 5, c4 = idx & 31;
|
||||||
|
const int kp = kb + r;
|
||||||
|
uint16_t* dst = &kv.sK[r * FQ_LDK + c4 * 4];
|
||||||
|
if (kp <= q_max_pos && kp < seq) {
|
||||||
|
*reinterpret_cast<uint2*>(dst) = *reinterpret_cast<const uint2*>(k + ((size_t)kvh * seq + kp) * hd + c4 * 4);
|
||||||
|
} else { *reinterpret_cast<uint2*>(dst) = make_uint2(0u, 0u); }
|
||||||
|
}
|
||||||
|
__syncthreads();
|
||||||
|
// 3B. S[16,64] = Q[16,128] @ K[64,128]^T (8 d-tiles x 4 kt)
|
||||||
|
v_f8 s_acc[4];
|
||||||
|
#pragma unroll
|
||||||
|
for (int kt = 0; kt < 4; ++kt) s_acc[kt] = v_f8_zero();
|
||||||
|
#pragma unroll
|
||||||
|
for (int d = 0; d < 8; ++d) {
|
||||||
|
#pragma unroll
|
||||||
|
for (int kt = 0; kt < 4; ++kt) {
|
||||||
|
v_h16 k_f = wmma_ld_h16(&kv.sK[(kt * 16 + l16) * FQ_LDK + d * 16]);
|
||||||
|
s_acc[kt] = wmma_f16_g11(q_frag[d], k_f, s_acc[kt]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
__syncthreads();
|
||||||
|
// 3C. register online softmax + causal/SWA mask + rel_bias -> f16 P LDS
|
||||||
|
const int col16 = wmma_acc_n11(lane);
|
||||||
|
#pragma unroll
|
||||||
|
for (int r = 0; r < 8; ++r) {
|
||||||
|
const int gm = row_gm[r];
|
||||||
|
const int qp = row_pos[r];
|
||||||
|
const float* rbr = rb_ptrs[r];
|
||||||
|
float sv[4];
|
||||||
|
float lmax = -1e30f;
|
||||||
|
#pragma unroll
|
||||||
|
for (int kt = 0; kt < 4; ++kt) {
|
||||||
|
const int kp = kb + kt * 16 + col16;
|
||||||
|
const int dist = qp - kp;
|
||||||
|
if (gm < M && kp <= qp && (swa_window <= 0 || dist < swa_window)) {
|
||||||
|
float val = s_acc[kt][r];
|
||||||
|
if (rbr && dist < max_rel) val += rbr[dist];
|
||||||
|
sv[kt] = val;
|
||||||
|
lmax = fmaxf(lmax, val);
|
||||||
|
} else { sv[kt] = -1e30f; }
|
||||||
|
}
|
||||||
|
lmax = fmaxf(lmax, __shfl_xor(lmax, 8, 32));
|
||||||
|
lmax = fmaxf(lmax, __shfl_xor(lmax, 4, 32));
|
||||||
|
lmax = fmaxf(lmax, __shfl_xor(lmax, 2, 32));
|
||||||
|
lmax = fmaxf(lmax, __shfl_xor(lmax, 1, 32));
|
||||||
|
const float nm = fmaxf(row_max[r], lmax);
|
||||||
|
const float alpha = (row_sum[r] > 0.0f) ? __expf(row_max[r] - nm) : 0.0f;
|
||||||
|
#pragma unroll
|
||||||
|
for (int d = 0; d < 8; ++d) o_acc[d][r] *= alpha;
|
||||||
|
row_sum[r] *= alpha;
|
||||||
|
row_max[r] = nm;
|
||||||
|
float lsum = 0.0f;
|
||||||
|
const int local_row = wave * 16 + wmma_acc_m11(r, lane);
|
||||||
|
#pragma unroll
|
||||||
|
for (int kt = 0; kt < 4; ++kt) {
|
||||||
|
const float pv = (sv[kt] > -1e20f) ? __expf(sv[kt] - nm) : 0.0f;
|
||||||
|
lsum += pv;
|
||||||
|
sP[local_row * FQ_LDP + kt * 16 + col16] = fq_f2h(pv);
|
||||||
|
}
|
||||||
|
lsum += __shfl_xor(lsum, 8, 32);
|
||||||
|
lsum += __shfl_xor(lsum, 4, 32);
|
||||||
|
lsum += __shfl_xor(lsum, 2, 32);
|
||||||
|
lsum += __shfl_xor(lsum, 1, 32);
|
||||||
|
row_sum[r] += lsum;
|
||||||
|
}
|
||||||
|
__syncthreads();
|
||||||
|
// 3D. V transposed [128,64] -> kv.sVt (overwrites the K union)
|
||||||
|
for (int idx = tid; idx < FQ_HD * FQ_BK; idx += 128) {
|
||||||
|
const int d = idx >> 6, c = idx & 63;
|
||||||
|
const int kp = kb + c;
|
||||||
|
kv.sVt[d * FQ_LDV + c] = (kp <= q_max_pos && kp < seq) ? v[((size_t)kvh * seq + kp) * hd + d] : (uint16_t)0;
|
||||||
|
}
|
||||||
|
__syncthreads();
|
||||||
|
// 3E. O[16,128] += P[16,64] @ V[64,128] (4 kt x 8 d-tiles)
|
||||||
|
#pragma unroll
|
||||||
|
for (int kt = 0; kt < 4; ++kt) {
|
||||||
|
v_h16 p_f = wmma_ld_h16(&sP[(wave * 16 + l16) * FQ_LDP + kt * 16]);
|
||||||
|
#pragma unroll
|
||||||
|
for (int d = 0; d < 8; ++d) {
|
||||||
|
v_h16 v_f = wmma_ld_h16(&kv.sVt[(d * 16 + l16) * FQ_LDV + kt * 16]);
|
||||||
|
o_acc[d] = wmma_f16_g11(p_f, v_f, o_acc[d]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
__syncthreads();
|
||||||
|
}
|
||||||
|
// 4. epilogue: O / row_sum, optional sigmoid gate
|
||||||
|
#pragma unroll
|
||||||
|
for (int r = 0; r < 8; ++r) {
|
||||||
|
const int gm = row_gm[r];
|
||||||
|
if (gm >= M) continue;
|
||||||
|
const float inv = 1.0f / fmaxf(row_sum[r], 1e-30f);
|
||||||
|
#pragma unroll
|
||||||
|
for (int d = 0; d < 8; ++d) {
|
||||||
|
const int col = d * 16 + wmma_acc_n11(lane);
|
||||||
|
float acc = o_acc[d][r] * inv;
|
||||||
|
if (gate) acc *= 1.0f / (1.0f + __expf(-gate[((size_t)gm * n_head + qh) * hd + col]));
|
||||||
|
out[((size_t)gm * n_head + qh) * hd + col] = acc;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
extern "C" int vetta_flash_swa_gqa_prefill_wmma(const float* q, const uint16_t* k, const uint16_t* v,
|
||||||
|
float* out, int n_head, int n_kv, int seq, int hd,
|
||||||
|
float scale, int swa_window, const int32_t* pos,
|
||||||
|
const float* rel_bias, int max_rel,
|
||||||
|
const float* sink_logit, const float* gate, int M,
|
||||||
|
vetta_stream_t stream) {
|
||||||
|
if (n_head <= 0 || n_kv <= 0 || seq <= 0 || hd != FQ_HD || (n_head % n_kv) != 0 || M <= 0) return 1;
|
||||||
|
hipStream_t s = stream ? (hipStream_t)stream : (hipStream_t)0;
|
||||||
|
dim3 grid(n_head, (M + FQ_BQ - 1) / FQ_BQ);
|
||||||
|
k_flash_swa_gqa_prefill_wmma<<<grid, 128, 0, s>>>(q, k, v, out, n_head, n_kv, seq, hd,
|
||||||
|
scale, swa_window, pos, rel_bias, max_rel,
|
||||||
|
sink_logit, gate, M);
|
||||||
|
HIP_CHECK(hipGetLastError());
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user