This repository has been archived on 2026-11-24. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
radiance-sycl/libxe2/xe2_attn_fast.cpp
T
claudeandClaude Opus 5.5 c0497e040e libxe2: attention scores a key a lane with 16-byte loads -- decode 32 -> 55 tok/s
Each sub-group now takes sixteen keys a step, one a lane: the lane scores its key in full against
the query in local memory, one max and one sum update the flash state, and the value rows are added
with each key's weight taken from its lane. bf16 cache rows are read 16 bytes at a time, and each
row's own visible span is split evenly 32 ways on the device instead of the context limit (which
left most partitions empty at a short context).

rad-kbench 138/138 and 132/132; KL against libref mean 5.7e-4, p99 3.1e-3, top-1 98.6%.
MiniCPM5-2B on the B65: decode 55 tok/s at a short context and 49 tok/s after a 1797-token prompt
(was 32 and 30); that prompt's prefill 1.62 s, 1109 tok/s (was 4.61 s).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
2026-10-23 20:58:52 +02:00

280 lines
15 KiB
C++

/* 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.
*
* 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
* sixteen at a time, one key a lane: the lane scores its key in full against the query in local
* memory (q . (k * k_descale), scaled), one max and one sum over the sub-group update the flash
* state (max m, sum l), and the lanes -- which split head_dim for the value rows -- add each key's
* value row weighted by that key's exp(s - m), taken from its lane. Per key that is no reduction and
* no exp on the lanes that do not own it (the first version reduced and exponentiated once a key on
* every lane, 27% of a 1.8k-context decode step). 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 each row's visible keys evenly 32 ways, on the device from the row's own context, 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: 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"
#include <cmath>
namespace xe2 {
namespace {
constexpr int kSgs = 8;
constexpr size_t kWg = kSgs * kSub;
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 kMaxParts = 32; /* a row's visible keys split this many ways at most */
int64_t row_stride(const RadTensor* t, int64_t cols) {
if (!t || t->rank < 2) return cols;
int64_t span = 1;
for (int i = (int)t->rank - 1; i >= 0; --i) {
span *= t->shape[i];
if (span == cols) return (i > 0) ? t->stride[i - 1] : cols;
if (span > cols) break;
}
return t->stride[t->rank - 2];
}
} // 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;
const RadTensor *Q = &a->t[0], *KV = &a->t[1], *BT = &a->t[2], *SU = &a->t[3], *O = &a->t[7];
const RadTensor* KD = rad_arg_in(a, 4);
const RadTensor* VD = rad_arg_in(a, 5);
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 || 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->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->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);
const int64_t rows = rad_tensor_numel(Q) / (q_heads * head_dim);
if (n_seq <= 0 || rows <= 0) return RAD_E_SHAPE;
if (!CU && rows % n_seq != 0) return RAD_E_SHAPE;
if (CU && rad_tensor_numel(CU) != n_seq + 1) return RAD_E_SHAPE;
const int64_t q_len_all = CU ? 0 : rows / n_seq;
if (rad_tensor_numel(O) < rows * q_heads * head_dim) return RAD_E_SHAPE;
if (KV->shape[2] != block_size || KV->shape[3] < 2 * head_dim) return RAD_E_SHAPE;
if (!rad_tensor_is_contiguous(SU) || (CU && !rad_tensor_is_contiguous(CU)) ||
(KD && !rad_tensor_is_contiguous(KD)) || (VD && !rad_tensor_is_contiguous(VD)))
return attn_paged(a, st);
const int64_t max_blocks = BT->rank >= 2 ? BT->shape[BT->rank - 1] : rad_tensor_numel(BT) / n_seq;
const int64_t bt_rs = BT->rank >= 2 ? BT->stride[BT->rank - 2] : max_blocks;
const int64_t bt_cs = BT->rank >= 2 ? BT->stride[BT->rank - 1] : 1;
const int64_t sb = KV->stride[0], sh = KV->stride[1], so = KV->stride[2], sd = KV->stride[3];
const int64_t q_ds = Q->rank >= 2 ? Q->stride[Q->rank - 1] : 1;
const int64_t q_hs = Q->rank >= 3 ? Q->stride[Q->rank - 2] : head_dim * q_ds;
const int64_t q_rs = row_stride(Q, q_heads * head_dim);
const int64_t o_ds = O->rank >= 2 ? O->stride[O->rank - 1] : 1;
const int64_t o_hs = O->rank >= 3 ? O->stride[O->rank - 2] : head_dim * o_ds;
const int64_t o_rs = row_stride(O, q_heads * head_dim);
const float scale = (float)rad_args_getf_or(a, "scale", (double)(1.0f / std::sqrt((float)head_dim)));
const int64_t jcap = max_blocks * block_size;
const int per = (int)(head_dim / kSub);
/* bf16 cache rows read 16 bytes at a time when every row start is 16-byte aligned. */
const bool vec_kv = KV->dtype == RAD_BF16 && sd == 1 && head_dim % 8 == 0 && sb % 8 == 0 &&
sh % 8 == 0 && so % 8 == 0 && rad_ptr_aligned(KV->data, 16);
/* The partitions: as many as the scratch holds for these rows, at most kMaxParts. Each row's
* own visible span is split evenly on the device, so every partition has keys whatever the
* context limit (splitting the limit instead left most partitions empty at a short context and
* the merge walking all of them). */
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(fit, kMaxParts);
if (P < 1) P = 1;
}
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;
char* ob = (char*)O->data;
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;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
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);
float* qloc = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[kSgs * kSub * kMaxPer]>(
it.get_group());
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);
}
if (P > 1) {
const int64_t span = sycl::max(jhi - jlo, (int64_t)0);
const int64_t ch = (span + P - 1) / P;
jlo += p * ch;
jhi = sycl::min(jhi, jlo + ch);
}
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;
}
/* The query in local memory, so a lane can score a whole key by itself. */
float* qs = qloc + (size_t)s * kSub * kMaxPer;
for (int e = 0; e < per; ++e) qs[lane * per + e] = qv[e];
sycl::group_barrier(sg);
float m = -INFINITY, l = 0.0f;
/* Sixteen keys a step, one a lane: the lane's own dot, then one max and one sum
* over the sub-group, and the value rows accumulated with each key's weight taken
* from its lane. */
for (int64_t j0 = jlo; j0 < jhi; j0 += kSub) {
const int64_t j = j0 + lane;
int64_t kb = -1;
float sc = -INFINITY;
if (j < jhi) {
const int64_t blk = ld_index(btdt, btb, sq * bt_rs + (j / block_size) * bt_cs);
if (blk >= 0) {
kb = blk * sb + kh * sh + (j % block_size) * so;
float dot = 0.0f;
if (vec_kv) {
/* A bf16 key row, 16 bytes at a time. */
const uint16_t* kr = (const uint16_t*)cb + kb;
for (int64_t d = 0; d < head_dim; d += 8) {
const sycl::vec<uint16_t, 8> kk = *(const sycl::vec<uint16_t, 8>*)(kr + d);
for (int u = 0; u < 8; ++u)
dot += qs[d + u] * (rad_bf16_to_f32(kk[u]) * kds);
}
} else {
for (int64_t d = 0; d < head_dim; ++d)
dot += qs[d] * (rad_load_f32(cb, cdt, kb + d * sd) * kds);
}
sc = dot * scale;
}
}
const float bm = sycl::reduce_over_group(sg, sc, sycl::maximum<float>());
if (bm == -INFINITY) continue; /* uniform: no visible key in this step */
const float mn = sycl::fmax(m, bm);
const float corr = sycl::exp(m - mn);
const float w = kb >= 0 ? sycl::exp(sc - mn) : 0.0f;
l = l * corr + sycl::reduce_over_group(sg, w, sycl::plus<float>());
for (int e = 0; e < per; ++e) acc[e] *= corr;
for (int jj = 0; jj < kSub; ++jj) {
const int64_t kbj = sycl::select_from_group(sg, kb, jj);
if (kbj < 0) continue; /* uniform */
const float wj = sycl::select_from_group(sg, w, jj);
if (vec_kv && per == 8) {
const sycl::vec<uint16_t, 8> vv = *(const sycl::vec<uint16_t, 8>*)(
(const uint16_t*)cb + kbj + head_dim + lane * 8);
for (int e = 0; e < 8; ++e) acc[e] += wj * (rad_bf16_to_f32(vv[e]) * vds);
} else {
for (int e = 0; e < per; ++e)
acc[e] += wj * (rad_load_f32(cb, cdt, kbj + (head_dim + lane * per + e) * sd) * vds);
}
}
m = mn;
}
sycl::group_barrier(sg);
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];
}
}
});
});
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;
}
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);
});
});
}
} // namespace xe2