feat: add RoPE, half-precision KV store and grouped-query attention with sinks to leleka-igpu (STRA-219)

RoPE uses the decoder's own rotation table; attention folds the softmax online over 32-key blocks for the
8 query heads of a KV head. Tested against the CPU decoder functions on full and sliding layers; one layer
over a 512-token batch ending at position 4096 takes about 0.52 s (0.02 s sliding) on the reference iGPU.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-14 23:52:33 +02:00
co-authored by Claude Sonnet 5.5
parent 762fca1842
commit dae6794ad8
4 changed files with 607 additions and 0 deletions
+50
View File
@@ -0,0 +1,50 @@
//! Speed of the GPU attention kernel on prefill-shaped work (gpt-oss: 64 query heads, 8 KV heads, head
//! dimension 64). Run: `cargo run --release -p leleka-igpu --example attn_bench`
//!
//! Reports milliseconds for one layer's attention over a batch of `m` tokens ending at position `end`.
use leleka_igpu::{AttentionShape, Gpu};
fn main() {
let gpu = Gpu::new().expect("a GPU");
println!("adapter: {}", gpu.adapter_name());
let (kw, qw) = (512usize, 4096usize);
let cap = 8192usize;
let kcache = gpu.zeros(cap * kw / 2);
let vcache = gpu.zeros(cap * kw / 2);
let sinks = gpu.zeros(64);
println!("{:>6} {:>6} {:>7} {:>10}", "end", "m", "window", "ms");
for (end, m, window) in [
(512usize, 512usize, 0usize),
(2048, 512, 0),
(4096, 512, 0),
(4096, 512, 128),
(8192, 512, 0),
] {
let q = gpu.zeros(m * qw);
let out = gpu.zeros(m * qw);
let shape = AttentionShape {
m,
pos0: end - m,
window,
kv_width: kw,
q_width: qw,
scale: 0.125,
};
let run = |count: usize| {
let mut rec = gpu.recorder();
for _ in 0..count {
rec.attention(shape, &q, &kcache, &vcache, &sinks, &out)
.unwrap();
}
rec.submit().unwrap();
};
run(1);
let start = std::time::Instant::now();
run(5);
println!(
"{end:>6} {m:>6} {window:>7} {:>10.2}",
start.elapsed().as_secs_f64() / 5.0 * 1e3
);
}
}
+185
View File
@@ -113,6 +113,9 @@ pub struct Gpu {
gemm_q8: wgpu::ComputePipeline,
gemm_mxfp4: wgpu::ComputePipeline,
rmsnorm_quant: wgpu::ComputePipeline,
rope: wgpu::ComputePipeline,
kv_store: wgpu::ComputePipeline,
attention: wgpu::ComputePipeline,
/// Stands in for the bias binding when a product has none.
no_bias: wgpu::Buffer,
/// Outputs per thread along the activation rows and the weight rows.
@@ -137,6 +140,49 @@ struct NormParams {
eps: f32,
}
/// What attention needs to know about its operands (see [`Recorder::attention`]).
#[derive(Clone, Copy, Debug)]
pub struct AttentionShape {
/// Tokens in this batch, at positions `pos0..pos0 + m`.
pub m: usize,
pub pos0: usize,
/// Sliding-window length, or 0 for full attention.
pub window: usize,
/// KV width (`kv heads * 64`) and query width (`heads * 64`).
pub kv_width: usize,
pub q_width: usize,
pub scale: f32,
}
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct AttentionParams {
m: u32,
pos0: u32,
window: u32,
kw: u32,
qw: u32,
scale: f32,
pad: [u32; 2],
}
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct Quad {
a: u32,
b: u32,
c: u32,
d: u32,
}
/// Workgroup counts for `threads` threads in workgroups of `wg`, split over two dimensions when the count
/// exceeds the 65535 limit of one (shaders recover the flat group index as `y * num_workgroups.x + x`).
fn groups_1d(threads: usize, wg: usize) -> (u32, u32, u32) {
let total = threads.div_ceil(wg).max(1);
let x = total.min(65535);
(x as u32, total.div_ceil(x) as u32, 1)
}
fn entry(binding: u32, buffer: &wgpu::Buffer) -> wgpu::BindGroupEntry<'_> {
wgpu::BindGroupEntry {
binding,
@@ -271,6 +317,9 @@ impl Gpu {
gemm_q8: pipeline("gemm q8_0", shaders::gemm(WeightKind::Q8_0, tm, tn)),
gemm_mxfp4: pipeline("gemm mxfp4", shaders::gemm(WeightKind::Mxfp4, tm, tn)),
rmsnorm_quant: pipeline("rmsnorm quant", shaders::RMSNORM_QUANT.to_owned()),
rope: pipeline("rope", shaders::ROPE.to_owned()),
kv_store: pipeline("kv store", shaders::KV_STORE.to_owned()),
attention: pipeline("attention", shaders::ATTENTION.to_owned()),
no_bias,
device,
queue,
@@ -648,6 +697,142 @@ impl Recorder<'_> {
Ok(())
}
/// Launch a kernel whose bindings are one uniform block followed by storage buffers 1, 2, ...
fn run_simple<T: bytemuck::Pod>(
&mut self,
pipeline: &wgpu::ComputePipeline,
params: &T,
buffers: &[&wgpu::Buffer],
groups: (u32, u32, u32),
) {
let uniform = self.uniform(params);
let mut entries = vec![entry(0, &uniform)];
entries.extend(
buffers
.iter()
.enumerate()
.map(|(i, b)| entry(i as u32 + 1, b)),
);
self.dispatch(pipeline, &entries, groups);
}
/// Rotate `m` tokens' `heads` heads of `hd` floats each in place with the per-token `(cos, sin)` table
/// `rot` (`[m][hd / 2][2]`).
pub fn rope(
&mut self,
x: &Buf,
rot: &Buf,
m: usize,
heads: usize,
hd: usize,
) -> Result<(), GpuError> {
if hd == 0 || !hd.is_multiple_of(2) || x.len < m * heads * hd || rot.len < m * hd {
return Err(GpuError::Shape(format!("rope of {m} x {heads} x {hd}")));
}
let gpu = self.gpu;
self.run_simple(
&gpu.rope,
&Quad {
a: m as u32,
b: heads as u32,
c: hd as u32,
d: 0,
},
&[&x.buffer, &rot.buffer],
groups_1d(m * heads * hd / 2, 256),
);
Ok(())
}
/// Store `m` rows of `kw` floats as half precision into `cache` at positions `pos0..`.
pub fn kv_store(
&mut self,
src: &Buf,
cache: &Buf,
m: usize,
kw: usize,
pos0: usize,
) -> Result<(), GpuError> {
if kw == 0 || !kw.is_multiple_of(2) || src.len < m * kw || cache.len < (pos0 + m) * kw / 2 {
return Err(GpuError::Shape(format!(
"kv store of {m} x {kw} at position {pos0}"
)));
}
let gpu = self.gpu;
self.run_simple(
&gpu.kv_store,
&Quad {
a: m as u32,
b: kw as u32,
c: pos0 as u32,
d: 0,
},
&[&src.buffer, &cache.buffer],
groups_1d(m * kw / 2, 256),
);
Ok(())
}
/// Causal sliding or full attention with sinks for `shape.m` tokens; head dimension 64, 8 query heads
/// per KV head. `queries` and `out` are `[m][q_width]`; the caches hold `[position][kv_width]` halves
/// (two per word) and must already contain the keys and values of positions up to `pos0 + m - 1`;
/// `sinks` has one logit per query head.
pub fn attention(
&mut self,
shape: AttentionShape,
queries: &Buf,
keys: &Buf,
values: &Buf,
sinks: &Buf,
out: &Buf,
) -> Result<(), GpuError> {
let AttentionShape {
m,
pos0,
window,
kv_width,
q_width,
scale,
} = shape;
let (kv_heads, heads) = (kv_width / 64, q_width / 64);
let positions = pos0 + m;
if kv_width == 0
|| !kv_width.is_multiple_of(64)
|| q_width != kv_heads * 8 * 64
|| queries.len < m * q_width
|| out.len < m * q_width
|| keys.len < positions * kv_width / 2
|| values.len < positions * kv_width / 2
|| sinks.len < heads
|| m == 0
|| m > 65535
{
return Err(GpuError::Shape(format!("attention shape {shape:?}")));
}
let gpu = self.gpu;
self.run_simple(
&gpu.attention,
&AttentionParams {
m: m as u32,
pos0: pos0 as u32,
window: window as u32,
kw: kv_width as u32,
qw: q_width as u32,
scale,
pad: [0; 2],
},
&[
&queries.buffer,
&keys.buffer,
&values.buffer,
&sinks.buffer,
&out.buffer,
],
(kv_heads as u32, m as u32, 1),
);
Ok(())
}
/// Submit everything recorded and wait for it to finish.
pub fn submit(self) -> Result<(), GpuError> {
self.gpu.queue.submit([self.encoder.finish()]);
+152
View File
@@ -212,3 +212,155 @@ fn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid
}
}
"#;
/// Rotary embedding in place: `x` is `[m][heads][hd]` floats, `rot` the `(cos, sin)` pairs of each token's
/// position (`[m][hd / 2][2]`, computed on the CPU by the decoder's own `Yarn::rotation`, so both sides use
/// the same table). NeoX layout: pair `i` is `(x[i], x[i + hd / 2])`.
///
/// Bindings: 0 params `{m, heads, hd, pad}`; 1 `x` (read-write); 2 `rot`. One thread per rotary pair.
pub const ROPE: &str = r#"
struct P { m: u32, heads: u32, hd: u32, pad: u32 }
@group(0) @binding(0) var<uniform> p: P;
@group(0) @binding(1) var<storage, read_write> x: array<f32>;
@group(0) @binding(2) var<storage, read> rot: array<f32>;
@compute @workgroup_size(256)
fn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>,
@builtin(num_workgroups) nwg: vec3<u32>) {
let flat = (wid.y * nwg.x + wid.x) * 256u + lid.x;
let half = p.hd / 2u;
if (flat >= p.m * p.heads * half) { return; }
let i = flat % half;
let head = (flat / half) % p.heads;
let t = flat / (half * p.heads);
let c = rot[(t * half + i) * 2u];
let s = rot[(t * half + i) * 2u + 1u];
let base = (t * p.heads + head) * p.hd + i;
let a = x[base];
let b = x[base + half];
x[base] = a * c - b * s;
x[base + half] = a * s + b * c;
}
"#;
/// Store `m` rows of `kw` floats into a half-precision cache at positions `pos0..` (two halves per word,
/// `[position][kw / 2]` words).
///
/// Bindings: 0 params `{m, kw, pos0, pad}`; 1 source floats; 2 cache words. One thread per word.
pub const KV_STORE: &str = r#"
struct P { m: u32, kw: u32, pos0: u32, pad: u32 }
@group(0) @binding(0) var<uniform> p: P;
@group(0) @binding(1) var<storage, read> src: array<f32>;
@group(0) @binding(2) var<storage, read_write> dst: array<u32>;
@compute @workgroup_size(256)
fn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>,
@builtin(num_workgroups) nwg: vec3<u32>) {
let flat = (wid.y * nwg.x + wid.x) * 256u + lid.x;
let hw = p.kw / 2u;
if (flat >= p.m * hw) { return; }
let t = flat / hw;
let j = flat % hw;
dst[(p.pos0 + t) * hw + j] = pack2x16float(vec2<f32>(src[t * p.kw + 2u * j], src[t * p.kw + 2u * j + 1u]));
}
"#;
/// Causal attention with a learned sink for `m` tokens at positions `pos0..` over a half-precision cache,
/// grouped-query: one workgroup per (token, KV head) serves the 8 query heads that share that KV head, so
/// each key and value block is read once for all 8 (the same blocking the CPU kernels use).
///
/// 256 threads = 8 heads x 32 lanes. A block of 32 keys at a time: the block's K and V are unpacked to shared
/// memory, lane `j` of head `h` scores key `j`, then an online softmax (running max starting at the sink
/// logit, running sum starting at 1 for the sink) folds the block in; lane `l` owns output dimensions
/// `2l, 2l + 1`. `window` is 0 for full attention or the sliding-window length.
///
/// Bindings: 0 params `{m, pos0, window, kw, qw, scale, pad, pad}`; 1 queries `[m][qw]`; 2 key cache words;
/// 3 value cache words; 4 sinks (per query head); 5 output `[m][qw]`. Head dimension 64, group 8.
pub const ATTENTION: &str = r#"
struct P { m: u32, pos0: u32, window: u32, kw: u32, qw: u32, scale: f32, pad0: u32, pad1: u32 }
@group(0) @binding(0) var<uniform> p: P;
@group(0) @binding(1) var<storage, read> q: array<f32>;
@group(0) @binding(2) var<storage, read> kc: array<u32>;
@group(0) @binding(3) var<storage, read> vc: array<u32>;
@group(0) @binding(4) var<storage, read> sinks: array<f32>;
@group(0) @binding(5) var<storage, read_write> o: array<f32>;
const G: u32 = 8u;
const HD: u32 = 64u;
const KB: u32 = 32u;
const KS: u32 = 65u; // padded row of the key block: lanes read different rows at the same column
var<workgroup> qs: array<f32, 512>;
var<workgroup> ks: array<f32, 2080>;
var<workgroup> vs: array<f32, 2048>;
var<workgroup> sc: array<f32, 256>;
var<workgroup> pr: array<f32, 256>;
@compute @workgroup_size(256)
fn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
let kvh = wid.x;
let t = wid.y;
let tid = lid.x;
let h = tid / 32u;
let lane = tid % 32u;
let pos = p.pos0 + t;
var first = 0u;
if (p.window != 0u && pos + 1u > p.window) { first = pos + 1u - p.window; }
let n = pos + 1u - first;
let head = kvh * G + h;
for (var i = tid; i < G * HD; i += 256u) {
qs[i] = q[t * p.qw + kvh * G * HD + i];
}
var m = sinks[head];
var l = 1.0;
var acc0 = 0.0;
var acc1 = 0.0;
for (var base = 0u; base < n; base += KB) {
workgroupBarrier();
for (var i = tid; i < KB * 32u; i += 256u) {
let j = i / 32u;
let w = i % 32u;
var kv = vec2<f32>(0.0, 0.0);
var vv = vec2<f32>(0.0, 0.0);
if (base + j < n) {
let widx = ((first + base + j) * p.kw + kvh * HD) / 2u + w;
kv = unpack2x16float(kc[widx]);
vv = unpack2x16float(vc[widx]);
}
ks[j * KS + 2u * w] = kv.x;
ks[j * KS + 2u * w + 1u] = kv.y;
vs[j * HD + 2u * w] = vv.x;
vs[j * HD + 2u * w + 1u] = vv.y;
}
workgroupBarrier();
var s = 0.0;
for (var k = 0u; k < HD; k++) {
s += qs[h * HD + k] * ks[lane * KS + k];
}
s *= p.scale;
if (base + lane >= n) { s = -3.0e38; }
sc[h * KB + lane] = s;
workgroupBarrier();
var mnew = m;
for (var j = 0u; j < KB; j++) { mnew = max(mnew, sc[h * KB + j]); }
let alpha = exp(m - mnew);
pr[h * KB + lane] = exp(s - mnew);
workgroupBarrier();
var sum = 0.0;
var a0 = 0.0;
var a1 = 0.0;
for (var j = 0u; j < KB; j++) {
let pv = pr[h * KB + j];
sum += pv;
a0 += pv * vs[j * HD + 2u * lane];
a1 += pv * vs[j * HD + 2u * lane + 1u];
}
l = l * alpha + sum;
acc0 = acc0 * alpha + a0;
acc1 = acc1 * alpha + a1;
m = mnew;
}
o[t * p.qw + head * HD + 2u * lane] = acc0 / l;
o[t * p.qw + head * HD + 2u * lane + 1u] = acc1 / l;
}
"#;
+220
View File
@@ -0,0 +1,220 @@
//! RoPE, the half-precision KV store and grouped-query attention with sinks on the GPU against the CPU
//! decoder's functions (`Yarn::rotation`, `rope_neox`, `attend_group_with_sink`).
//!
//! The attention reference reads the same half-precision cache; the GPU folds the softmax online and sums
//! in a different order, so values agree to float32 accumulation error, not bit for bit.
//!
//! Skipped (with a message) when the machine has no GPU adapter.
use leleka_cpu_kernels::Dispatch;
use leleka_gptoss::ops::{self, Group, KvRows, Yarn};
use leleka_igpu::{AttentionShape, Gpu};
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
fn unit(&mut self) -> f32 {
((self.next() >> 40) as f32 / (1u64 << 24) as f32 - 0.5) * 2.0
}
}
fn gpu() -> Option<Gpu> {
match Gpu::new() {
Ok(g) => Some(g),
Err(e) => {
eprintln!("skipped: {e}");
None
}
}
}
fn rotations(yarn: &Yarn, pos0: usize, m: usize, hd: usize) -> Vec<(f32, f32)> {
let mut all = Vec::new();
for t in 0..m {
let mut r = vec![(0.0f32, 0.0f32); hd / 2];
yarn.rotation((pos0 + t) as u32, hd, &mut r);
all.extend(r);
}
all
}
fn pack_halves(d: &Dispatch, x: &[f32]) -> (Vec<u16>, Vec<u32>) {
let mut halves = vec![0u16; x.len()];
d.f32_to_f16(x, &mut halves).unwrap();
let words = halves
.chunks(2)
.map(|p| u32::from(p[0]) | (u32::from(p[1]) << 16))
.collect();
(halves, words)
}
#[test]
fn rope_matches_the_decoders_rotation() {
let Some(gpu) = gpu() else { return };
let yarn = Yarn::gpt_oss(150_000.0, 32.0, 4096);
let (pos0, m, heads, hd) = (700usize, 9usize, 6usize, 64usize);
let mut rng = Rng(5);
let x: Vec<f32> = (0..m * heads * hd).map(|_| rng.unit() * 3.0).collect();
let table = rotations(&yarn, pos0, m, hd);
let flat: Vec<f32> = table.iter().flat_map(|(c, s)| [*c, *s]).collect();
let (xb, rb) = (gpu.buf_f32(&x), gpu.buf_f32(&flat));
let mut rec = gpu.recorder();
rec.rope(&xb, &rb, m, heads, hd).unwrap();
rec.submit().unwrap();
let got = gpu.read_f32(&xb).unwrap();
let mut want = x.clone();
for t in 0..m {
for h in 0..heads {
let at = (t * heads + h) * hd;
ops::rope_neox(&mut want[at..at + hd], &table[t * hd / 2..(t + 1) * hd / 2]);
}
}
for (i, (g, w)) in got.iter().zip(&want).enumerate() {
assert!(
(g - w).abs() <= 2e-6 * (1.0 + w.abs()),
"element {i}: gpu {g} vs cpu {w}"
);
}
}
#[test]
fn kv_store_rounds_to_half_like_the_cpu() {
let Some(gpu) = gpu() else { return };
let d = Dispatch::best();
let (m, kw, pos0) = (7usize, 128usize, 5usize);
let mut rng = Rng(6);
let x: Vec<f32> = (0..m * kw).map(|_| rng.unit() * 40.0).collect();
let (halves, _) = pack_halves(&d, &x);
let cache = gpu.zeros((pos0 + m + 2) * kw / 2);
let src = gpu.buf_f32(&x);
let mut rec = gpu.recorder();
rec.kv_store(&src, &cache, m, kw, pos0).unwrap();
rec.submit().unwrap();
let words = gpu.read_u32(&cache).unwrap();
assert!(words[..pos0 * kw / 2].iter().all(|w| *w == 0));
let mut off_by_one = 0;
for (i, h) in halves.iter().enumerate() {
let w = words[pos0 * kw / 2 + i / 2];
let g = if i % 2 == 0 { w & 0xFFFF } else { w >> 16 } as u16;
let diff = (i32::from(g) - i32::from(*h)).abs();
assert!(diff <= 1, "element {i}: gpu {g:#06x} vs cpu {h:#06x}");
off_by_one += usize::from(diff != 0);
}
eprintln!("{off_by_one} of {} halves differ by one ulp", halves.len());
assert!(words[(pos0 + m) * kw / 2..].iter().all(|w| *w == 0));
}
fn attention_case(gpu: &Gpu, pos0: usize, m: usize, window: usize, seed: u64) {
let d = Dispatch::best();
let (kv_heads, group, hd) = (2usize, 8usize, 64usize);
let (kw, qw) = (kv_heads * hd, kv_heads * group * hd);
let positions = pos0 + m;
let mut rng = Rng(seed);
let q: Vec<f32> = (0..m * qw).map(|_| rng.unit() * 1.5).collect();
let k: Vec<f32> = (0..positions * kw).map(|_| rng.unit() * 1.5).collect();
let v: Vec<f32> = (0..positions * kw).map(|_| rng.unit()).collect();
let sinks: Vec<f32> = (0..kv_heads * group).map(|_| rng.unit() * 2.0).collect();
let (kh, kwords) = pack_halves(&d, &k);
let (vh, vwords) = pack_halves(&d, &v);
let (qb, kb, vb, sb) = (
gpu.buf_f32(&q),
gpu.buf_u32(&kwords),
gpu.buf_u32(&vwords),
gpu.buf_f32(&sinks),
);
let out = gpu.zeros(m * qw);
let scale = 1.0 / (hd as f32).sqrt();
let mut rec = gpu.recorder();
rec.attention(
AttentionShape {
m,
pos0,
window,
kv_width: kw,
q_width: qw,
scale,
},
&qb,
&kb,
&vb,
&sb,
&out,
)
.unwrap();
rec.submit().unwrap();
let got = gpu.read_f32(&out).unwrap();
for t in 0..m {
let pos = pos0 + t;
let first = if window != 0 {
(pos + 1).saturating_sub(window)
} else {
0
};
let attended = pos + 1 - first;
for kvh in 0..kv_heads {
let mut scores = vec![0.0f32; group * attended];
let mut want = vec![0.0f32; group * hd];
let start = first * kw + kvh * hd;
let qs = t * qw + kvh * group * hd;
ops::attend_group_with_sink(
Group {
queries: &q[qs..qs + group * hd],
sinks: &sinks[kvh * group..(kvh + 1) * group],
scale,
},
KvRows {
keys: &kh[start..],
values: &vh[start..],
stride: kw,
},
attended,
&d,
&mut scores,
&mut want,
)
.unwrap();
for (i, w) in want.iter().enumerate() {
let g = got[qs + i];
assert!(
(g - w).abs() <= 2e-5 * (1.0 + w.abs()),
"pos0 {pos0} m {m} window {window}: token {t} kv head {kvh} element {i}: gpu {g} vs cpu {w}"
);
}
}
}
}
#[test]
fn attention_matches_the_cpu_for_full_and_sliding_layers() {
let Some(gpu) = gpu() else { return };
for (pos0, m) in [(0, 1), (0, 70), (33, 40), (100, 3), (0, 129)] {
for window in [0, 5, 40] {
attention_case(&gpu, pos0, m, window, 100 + (pos0 * 7 + m) as u64);
}
}
}
#[test]
fn attention_refuses_shapes_it_does_not_implement() {
let Some(gpu) = gpu() else { return };
let (q, c, s, o) = (gpu.zeros(512), gpu.zeros(64), gpu.zeros(8), gpu.zeros(512));
let mut rec = gpu.recorder();
let shape = |kv_width, q_width| AttentionShape {
m: 1,
pos0: 0,
window: 0,
kv_width,
q_width,
scale: 0.125,
};
assert!(rec.attention(shape(64, 512), &q, &c, &c, &s, &o).is_ok());
assert!(rec.attention(shape(64, 256), &q, &c, &c, &s, &o).is_err()); // group is not 8
assert!(rec.attention(shape(60, 480), &q, &c, &c, &s, &o).is_err()); // head dim is not 64
rec.submit().unwrap();
}