libxe2: split-KV attention -- a kv head's keys read once for its query heads, decode across the card

The long-context decode profile was 70% attention: one work-group a (row, head) left most of the
card idle at one row and read each kv head eight times. xe2_attn_paged now splits a row's keys into
partitions of 32 or more across work-groups, each work-group a (row, kv head, partition) whose
sub-groups are the kv head's query heads, the partial softmax states merged from 64 MiB of scratch
(the scratch hook); prefill-sized row counts take one partition and write directly.

rad-kbench 138/138 and 132/132, KL against libref mean 5.8e-4, p99 3.2e-3, top-1 98.5%. Decode
after a 1797-token prompt 16.2 -> 29.8 tok/s; short-context decode 32 tok/s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
This commit is contained in:
claudeandClaude Opus 5.5 committed 2026-10-23 20:42:38 +02:00
1 parent 96b3e1be83
commit b57c2db60c
4 files changed
+143 -85

No files matched your search

+13
View File
@@ -399,6 +399,19 @@ the rest under 1.5% each.
head) on a 160-engine card, and each kv head is read by 8 query heads. Next: split the keys across
work-groups and share a kv head's reads across its query heads.
## Phase 4, step 3 (2026-10-23): split-KV attention
Long-context decode profile (1.8k-token prompt, 64 steps): attn_paged 69.9%, gemm_nt 11.1%,
rmsnorm_quant_fp8 9.3%, gated_quant_fp8 4.1%. `xe2_attn_paged` is now flash-decoding: a work-group a
(row, kv head, key partition) whose sub-groups are the kv head's query heads (each key read once for
all 8), partitions of 32+ keys merged from 64 MiB of scratch; P = 1 for prefill-sized row counts.
A first try at 256-key partitions halved short-context decode (all keys in one partition, each
sub-group walking every key for its head): 32 keys fixed it.
- rad-kbench 138/138 and 132/132 (worst rel_l2 2.9e-4); KL mean 5.8e-4, p99 3.2e-3, top-1 98.5%.
- **Decode after a 1797-token prompt: 16.2 -> 29.8 tok/s**; short-context decode 32.0 tok/s;
1797-token prefill 4.61 s.
## Next steps
1. ~~Milestone B, part 2: `minicpm5-2b-fp8.rad`~~ **Dropped by the user (2026-10-23): "instead of the
+124 -81
View File
@@ -1,17 +1,23 @@
/* xe2_attn_fast.cpp -- Phase 4's paged attention: one pass over the keys with an online softmax,
* the keys spread over the work-group, for decode and prefill alike.
/* xe2_attn_fast.cpp -- Phase 4's paged attention: split-KV with an online softmax ("flash
* decoding"), a kv head's keys read once for all its query heads.
*
* One work-group a (query row, head), eight 16-lane sub-groups. Sub-group s takes keys s, s + 8,
* s + 16, ... of the row's visible span; its lanes split head_dim (head_dim / 16 elements each), so
* a key's score is a sub-group reduction of q . (k * k_descale), scaled. Each sub-group keeps the
* flash-attention running state -- max m, sum l, and its lanes' slice of the weighted value sum --
* rescaling by exp(m_old - m_new) as the max grows; at the end the eight states are merged through
* local memory and lane d's slice is divided by the merged sum.
* Pass 1: a work-group a (query row, kv head, key partition). Its sub-groups are the kv head's
* query heads (sub-group s takes heads s, s + 8, ...); each walks the partition's visible keys in
* order, its lanes splitting head_dim, so a key's score is a sub-group reduction of
* q . (k * k_descale), scaled, and the sub-group keeps the flash state: max m, sum l and its lanes'
* slice of the weighted value sum, rescaled by exp(m_old - m_new) as the max grows. The eight query
* heads read the same key and value rows, so the bytes come from memory once a work-group.
*
* The partition count P is chosen at launch from the rows: a decode step (one row, a few heads)
* splits the keys into partitions of 32 or more so the whole card works on one token; a
* prefill step has parallelism in its rows and takes P = 1. With P > 1 each partition's state goes
* to scratch (64 MiB, the `scratch` hook) and pass 2 -- a sub-group a (row, query head) -- merges
* them; with P = 1 pass 1 writes the normalised output itself.
*
* Same mask, window, ragged batches (cu_seqlens), fp8 descales and zero row for no visible key as
* libref's attn_paged and xe2_attn_paged_ref. Not libref's order (it takes the max first and sums
* in key order): held to rad-kbench's attention tolerance and the KL bound (D13). XE2_EXACT=1, or a
* head_dim that is not a multiple of 16 up to 256, sends the launch to xe2_attn_paged_ref.
* libref's attn_paged and xe2_attn_paged_ref. Not libref's order: held to rad-kbench's attention
* tolerance and the KL bound (D13). XE2_EXACT=1, a head_dim that is not a multiple of 16 up to 256,
* or a rank-3 cache, sends the launch to xe2_attn_paged_ref.
*/
#include "xe2_common.h"
#include "xe2_ops.h"
@@ -24,7 +30,10 @@ namespace {
constexpr int kSgs = 8;
constexpr size_t kWg = kSgs * kSub;
constexpr int kMaxPer = 16; /* head_dim / 16, up to head_dim 256 */
constexpr int kMaxPer = 16; /* head_dim / 16, up to head_dim 256 */
constexpr int64_t kScratch = (int64_t)64 << 20; /* pass 1's partial states */
constexpr int64_t kPartKeys = 32; /* the finest partition */
constexpr int64_t kMaxParts = 1024;
int64_t row_stride(const RadTensor* t, int64_t cols) {
if (!t || t->rank < 2) return cols;
@@ -39,6 +48,8 @@ int64_t row_stride(const RadTensor* t, int64_t cols) {
} // namespace
int64_t attn_paged_scratch(const RadArgs*) { return kScratch; }
int attn_paged_fast(const RadArgs* a, RadStream st) {
if (exact_only()) return attn_paged(a, st);
if (!a || a->n_t < 8) return RAD_E_INVAL;
@@ -48,14 +59,15 @@ int attn_paged_fast(const RadArgs* a, RadStream st) {
const RadTensor* CU = rad_arg_in(a, 6);
if (!Q->data || !KV->data || !BT->data || !SU->data || !O->data) return RAD_E_INVAL;
const int64_t head_dim = rad_args_geti_or(a, "head_dim", Q->rank >= 3 ? Q->shape[Q->rank - 1] : 0);
if (head_dim <= 0 || head_dim % kSub || head_dim / kSub > kMaxPer) return attn_paged(a, st);
if (head_dim <= 0 || head_dim % kSub || head_dim / kSub > kMaxPer || KV->rank != 4)
return attn_paged(a, st);
const int64_t gqa = rad_args_geti_or(a, "gqa", 1);
const int64_t block_size = rad_args_geti_or(a, "block_size", KV->rank == 4 ? KV->shape[2] : 0);
const int64_t block_size = rad_args_geti_or(a, "block_size", KV->shape[2]);
const int causal = (int)rad_args_geti_or(a, "causal", 1);
const int64_t window = rad_args_geti_or(a, "window", 0);
if (gqa <= 0 || block_size <= 0) return RAD_E_SHAPE;
const int64_t kv_heads = KV->rank == 4 ? KV->shape[1] : 0;
if (kv_heads <= 0 || KV->rank != 4) return RAD_E_SHAPE;
const int64_t kv_heads = KV->shape[1];
if (kv_heads <= 0) return RAD_E_SHAPE;
const int64_t q_heads = gqa * kv_heads;
if (Q->rank >= 3 && Q->shape[Q->rank - 2] != q_heads) return RAD_E_SHAPE;
const int64_t n_seq = rad_tensor_numel(SU);
@@ -84,6 +96,17 @@ int attn_paged_fast(const RadArgs* a, RadStream st) {
const int64_t jcap = max_blocks * block_size;
const int per = (int)(head_dim / kSub);
/* The partitions: as many as the scratch holds for these rows, none finer than kPartKeys. */
const int64_t state = 2 + head_dim; /* floats a partial state: m, l, acc[head_dim] */
int64_t P = 1;
if (a->scratch && a->scratch_bytes > 0) {
const int64_t fit = a->scratch_bytes / (rows * q_heads * state * (int64_t)sizeof(float));
P = sycl::min(sycl::min(fit, kMaxParts), (jcap + kPartKeys - 1) / kPartKeys);
if (P < 1) P = 1;
}
const int64_t chunk = (jcap + P - 1) / P;
float* part = (float*)a->scratch;
const char *qb = (const char*)Q->data, *cb = (const char*)KV->data, *btb = (const char*)BT->data;
const char *sub = (const char*)SU->data, *cub = CU ? (const char*)CU->data : nullptr;
const char *kdb = KD ? (const char*)KD->data : nullptr, *vdb = VD ? (const char*)VD->data : nullptr;
@@ -91,60 +114,56 @@ int attn_paged_fast(const RadArgs* a, RadStream st) {
const uint32_t qdt = Q->dtype, cdt = KV->dtype, btdt = BT->dtype, sudt = SU->dtype;
const uint32_t cudt = CU ? CU->dtype : 0, kddt = KD ? KD->dtype : 0, vddt = VD ? VD->dtype : 0;
const uint32_t odt = O->dtype;
const int64_t total = rows * q_heads;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
return submit([&] {
q->submit([&](sycl::handler& h) {
/* Each sub-group's final state: m, l, and its head_dim-wide accumulator. */
sycl::local_accessor<float, 1> sm(sycl::range<1>(kSgs), h);
sycl::local_accessor<float, 1> sl(sycl::range<1>(kSgs), h);
sycl::local_accessor<float, 1> sacc(sycl::range<1>((size_t)kSgs * kSub * kMaxPer), h);
h.parallel_for(sycl::nd_range<1>{(size_t)total * kWg, kWg},
[=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] {
const int64_t idx = (int64_t)it.get_group(0);
const sycl::sub_group sg = it.get_sub_group();
const int s = (int)sg.get_group_linear_id();
const int lane = (int)sg.get_local_linear_id();
const int64_t hq = idx % q_heads, tok = idx / q_heads;
int64_t sq = 0, qlen = q_len_all, i = 0;
if (cub) {
while (sq + 1 < n_seq && ld_index(cudt, cub, sq + 1) <= tok) ++sq;
qlen = ld_index(cudt, cub, sq + 1) - ld_index(cudt, cub, sq);
i = tok - ld_index(cudt, cub, sq);
} else {
sq = tok / q_len_all;
i = tok - sq * q_len_all;
}
if (qlen <= 0) return; /* uniform across the group */
const int64_t kh = hq / gqa;
const int64_t ctx = ld_index(sudt, sub, sq);
const int64_t pos = ctx - qlen + i;
const float kds = kdb ? rad_load_f32(kdb, kddt, sq * kv_heads + kh) : 1.0f;
const float vds = vdb ? rad_load_f32(vdb, vddt, sq * kv_heads + kh) : 1.0f;
const int64_t jend = sycl::min(ctx, jcap);
/* The keys this row sees: [jlo, jhi) before the block table is consulted. */
int64_t jlo = 0, jhi = causal ? sycl::min(jend, pos + 1) : jend;
if (window > 0) {
jlo = sycl::max((int64_t)0, pos - window + 1);
if (!causal) jhi = sycl::min(jend, pos + window);
}
const int64_t qoff = tok * q_rs + hq * q_hs, ooff = tok * o_rs + hq * o_hs;
int rc = submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{(size_t)(rows * kv_heads * P) * kWg, kWg},
[=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] {
const int64_t g = (int64_t)it.get_group(0);
const int64_t p = g % P, kh = (g / P) % kv_heads, tok = g / (P * kv_heads);
const sycl::sub_group sg = it.get_sub_group();
const int s = (int)sg.get_group_linear_id();
const int lane = (int)sg.get_local_linear_id();
int64_t sq = 0, qlen = q_len_all, i = 0;
if (cub) {
while (sq + 1 < n_seq && ld_index(cudt, cub, sq + 1) <= tok) ++sq;
qlen = ld_index(cudt, cub, sq + 1) - ld_index(cudt, cub, sq);
i = tok - ld_index(cudt, cub, sq);
} else {
sq = tok / q_len_all;
i = tok - sq * q_len_all;
}
if (qlen <= 0) return;
const int64_t ctx = ld_index(sudt, sub, sq);
const int64_t pos = ctx - qlen + i;
const float kds = kdb ? rad_load_f32(kdb, kddt, sq * kv_heads + kh) : 1.0f;
const float vds = vdb ? rad_load_f32(vdb, vddt, sq * kv_heads + kh) : 1.0f;
const int64_t jend = sycl::min(ctx, jcap);
int64_t jlo = 0, jhi = causal ? sycl::min(jend, pos + 1) : jend;
if (window > 0) {
jlo = sycl::max((int64_t)0, pos - window + 1);
if (!causal) jhi = sycl::min(jend, pos + window);
}
jlo = sycl::max(jlo, p * chunk);
jhi = sycl::min(jhi, (p + 1) * chunk);
for (int64_t hl = s; hl < gqa; hl += kSgs) {
const int64_t hq = kh * gqa + hl;
const int64_t qoff = tok * q_rs + hq * q_hs;
float qv[kMaxPer], acc[kMaxPer];
for (int e = 0; e < kMaxPer; ++e) {
qv[e] = e < per ? rad_load_f32(qb, qdt, qoff + (lane * per + e) * q_ds) : 0.0f;
acc[e] = 0.0f;
}
float m = -INFINITY, l = 0.0f;
for (int64_t j = jlo + s; j < jhi; j += kSgs) {
for (int64_t j = jlo; j < jhi; ++j) {
const int64_t blk = ld_index(btdt, btb, sq * bt_rs + (j / block_size) * bt_cs);
if (blk < 0) continue; /* uniform across the sub-group */
if (blk < 0) continue;
const int64_t kb = blk * sb + kh * sh + (j % block_size) * so;
float part = 0.0f;
float pp = 0.0f;
for (int e = 0; e < per; ++e)
part += qv[e] * (rad_load_f32(cb, cdt, kb + (lane * per + e) * sd) * kds);
const float sc = sycl::reduce_over_group(sg, part, sycl::plus<float>()) * scale;
pp += qv[e] * (rad_load_f32(cb, cdt, kb + (lane * per + e) * sd) * kds);
const float sc = sycl::reduce_over_group(sg, pp, sycl::plus<float>()) * scale;
const float mn = sycl::fmax(m, sc);
const float corr = sycl::exp(m - mn), w = sycl::exp(sc - mn);
l = l * corr + w;
@@ -153,31 +172,55 @@ int attn_paged_fast(const RadArgs* a, RadStream st) {
w * (rad_load_f32(cb, cdt, kb + (head_dim + lane * per + e) * sd) * vds);
m = mn;
}
if (lane == 0) {
sm[s] = m;
sl[s] = l;
if (P == 1) {
const int64_t ooff = tok * o_rs + hq * o_hs;
const float inv = l > 0.0f ? 1.0f / l : 0.0f; /* no visible key: zero row */
for (int e = 0; e < per; ++e)
rad_store_f32(ob, odt, ooff + (lane * per + e) * o_ds, acc[e] * inv);
} else {
float* ps = part + ((tok * q_heads + hq) * P + p) * state;
if (lane == 0) {
ps[0] = m;
ps[1] = l;
}
for (int e = 0; e < per; ++e) ps[2 + lane * per + e] = acc[e];
}
for (int e = 0; e < per; ++e) sacc[((size_t)s * kSub + lane) * kMaxPer + e] = acc[e];
sycl::group_barrier(it.get_group());
if (s != 0) return; /* sub-group 0 merges and stores */
float M = -INFINITY;
for (int t = 0; t < kSgs; ++t) M = sycl::fmax(M, sm[t]);
if (M == -INFINITY) {
for (int e = 0; e < per; ++e) rad_store_f32(ob, odt, ooff + (lane * per + e) * o_ds, 0.0f);
return;
}
});
});
if (rc < 0 || P == 1) return rc;
/* Pass 2: merge the partitions of each (row, query head). */
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{(size_t)(rows * q_heads) * kSub, (size_t)kSub},
[=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] {
const int64_t g = (int64_t)it.get_group(0);
const int64_t hq = g % q_heads, tok = g / q_heads;
const int lane = (int)it.get_local_id(0);
int64_t sq = 0, qlen = q_len_all;
if (cub) {
while (sq + 1 < n_seq && ld_index(cudt, cub, sq + 1) <= tok) ++sq;
qlen = ld_index(cudt, cub, sq + 1) - ld_index(cudt, cub, sq);
}
if (qlen <= 0) return;
const float* ps = part + (tok * q_heads + hq) * P * state;
float M = -INFINITY;
for (int64_t p = 0; p < P; ++p)
if (ps[p * state + 1] > 0.0f) M = sycl::fmax(M, ps[p * state]);
const int64_t ooff = tok * o_rs + hq * o_hs;
float L = 0.0f, out[kMaxPer];
for (int e = 0; e < kMaxPer; ++e) out[e] = 0.0f;
if (M != -INFINITY)
for (int64_t p = 0; p < P; ++p) {
const float* q0 = ps + p * state;
if (!(q0[1] > 0.0f)) continue; /* an empty partition */
const float f = sycl::exp(q0[0] - M);
L += q0[1] * f;
for (int e = 0; e < per; ++e) out[e] += q0[2 + lane * per + e] * f;
}
float L = 0.0f, out[kMaxPer];
for (int e = 0; e < kMaxPer; ++e) out[e] = 0.0f;
for (int t = 0; t < kSgs; ++t) {
if (sm[t] == -INFINITY) continue;
const float f = sycl::exp(sm[t] - M);
L += sl[t] * f;
for (int e = 0; e < per; ++e) out[e] += sacc[((size_t)t * kSub + lane) * kMaxPer + e] * f;
}
const float inv = L > 0.0f ? 1.0f / L : 0.0f;
for (int e = 0; e < per; ++e)
rad_store_f32(ob, odt, ooff + (lane * per + e) * o_ds, out[e] * inv);
});
const float inv = L > 0.0f ? 1.0f / L : 0.0f;
for (int e = 0; e < per; ++e)
rad_store_f32(ob, odt, ooff + (lane * per + e) * o_ds, out[e] * inv);
});
});
}
+1
View File
@@ -53,6 +53,7 @@ int logits_gemm_gemv(const RadArgs* a, RadStream s);
int gemm_nt_xmx(const RadArgs* a, RadStream s);
int logits_gemm_xmx(const RadArgs* a, RadStream s);
int attn_paged_fast(const RadArgs* a, RadStream s);
int64_t attn_paged_scratch(const RadArgs* a);
int gemm_zp_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel,
const RadTensor* planes, int n, RadLayout* out);
int gemm_zp_relayout(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
+5 -4
View File
@@ -127,13 +127,14 @@ const RadKernelInfo kKernels[] = {
.dtypes = "bf16 k and v, bf16 or E4M3 cache",
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::kv_store },
{ .name = "xe2_attn_paged", .op = "attn_paged", .family = "attn",
.computes = "paged attention in one pass with an online softmax: a work-group a (row, head), "
"keys over eight sub-groups, head_dim over lanes (not libref's order). "
"XE2_EXACT=1 runs xe2_attn_paged_ref instead",
.computes = "split-KV paged attention with an online softmax: a work-group a (row, kv head, "
"key partition), its sub-groups the kv head's query heads, partitions merged from "
"scratch (not libref's order). XE2_EXACT=1 runs xe2_attn_paged_ref instead",
.shape = "head_dim a multiple of 16 up to 256 (else the exact kernel); any gqa, causal or "
"not, sliding window, ragged batches",
.dtypes = "bf16 query, bf16 or E4M3 cache with per-(seq, head) descales, bf16 out",
.domain = RAD_DOMAIN_DEVICE, .priority = 10, .launch = xe2::attn_paged_fast },
.domain = RAD_DOMAIN_DEVICE, .priority = 10, .launch = xe2::attn_paged_fast,
.scratch = xe2::attn_paged_scratch },
{ .name = "xe2_attn_paged_ref", .op = "attn_paged", .family = "attn",
.computes = "paged attention, one work-group a (row, head), libref's order: serial dots, "
"keys summed in order; the correctness-first form",