libxe2: fused gated-attention prologue (qk_norm_rope_gate, qk_norm_rope_gate_kv_store)

The one-launch prologue that the qwen35 family (Qwen3.5, Qwen3.8), Qwen4-Exp, FishOmni and the MTP
heads request where a kernel library declares it (libr4d did; libxe2 did not, so those models ran
q_norm, k_norm, rope_q, rope_k and kv_store: five launches an attention layer). It splits the
interleaved [q|gate] projection per head, norms q and k, applies the partial NeoX rotary from the
cos/sin table rope_table already fills each step, and with _kv_store stores k and v.

docs/OPS.md requires it byte-identical to the unfused chain, so each step is libxe2's own:
xe2_rmsnorm's bf16 head-row norm (XE2_EXACT=1: libref's ascending sum, as xe2_rmsnorm then takes),
the bf16 rounding the norm stores, cos/sin as xe2_rope_table wrote them (xe2_rope's arithmetic), and
xe2_kv_store's conversion. A sub-group a (token, head), as qkv_norm_rope; that kernel is untouched.
The schemas are libr4d's. The _kv_store row declares its chain (qk_norm_rope_gate, kv_store) and both
rows describe their operands, so rad-kbench draws them and checks the fold byte for byte.
XE2_NO_FUSED_PROLOGUE=1 now hides these two rows as well: the A/B and an escape hatch.

rad-kbench fusion oracle: 28/28 byte-identical on Qwen3.5-9B and on Qwen3.8-27B; default fixture
2144/2144. Greedy A/B (400-token story, 2.4k and 382-token prompts), twice each, spec off: outputs
identical; Qwen3.5-9B w4a16 decode 58.3 -> 58.9 tok/s, Qwen3.8-27B int4 30.1 -> 30.4. Prefill
unchanged (the fused rows serve steps up to 64 tokens).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
aneinanderandClaude Opus 5.5 committed 2026-11-09 11:50:39 +01:00
1 parent 47d1a952e9
commit 9aef29661b
3 files changed
+463 -2

No files matched your search

+2
View File
@@ -30,6 +30,8 @@ int pool_rows(const RadArgs* a, RadStream s);
int qk_norm_rope(const RadArgs* a, RadStream s);
int qkv_norm_rope(const RadArgs* a, RadStream s);
int qkv_norm_rope_kv_store(const RadArgs* a, RadStream s);
int qk_norm_rope_gate(const RadArgs* a, RadStream s);
int qk_norm_rope_gate_kv_store(const RadArgs* a, RadStream s);
int conv1d_dw(const RadArgs* a, RadStream s);
int conv2d(const RadArgs* a, RadStream s);
int attn_local_rel(const RadArgs* a, RadStream s);
+245
View File
@@ -596,6 +596,251 @@ int qkv_norm_rope_impl(const RadArgs* a, RadStream st, bool store) {
int qkv_norm_rope(const RadArgs* a, RadStream st) { return qkv_norm_rope_impl(a, st, false); }
int qkv_norm_rope_kv_store(const RadArgs* a, RadStream st) { return qkv_norm_rope_impl(a, st, true); }
/* qk_norm_rope_gate / qk_norm_rope_gate_kv_store: the gated-attention prologue (the qwen35 family,
* Qwen4-Exp, FishOmni, the MTP heads) in one launch. It splits the interleaved [q|gate] projection
* per head, applies the q and k norms and partial NeoX rotaries from a precomputed cos/sin table
* (`rope_table`), optionally copies the gate, and with _kv_store also stores k and v. docs/OPS.md
* requires it byte-identical to the unfused chain, and each step is libxe2's own:
* - the norm is xe2_rmsnorm's bf16 head-row form, as qkv_norm_rope above takes it;
* - the rotation reads cos and sin as xe2_rope_table wrote them, which is xe2_rope's arithmetic;
* - the store converts as xe2_kv_store does.
* Four or five launches per attention layer become one. A position outside the table is clamped
* into it, as libr4d's row does. */
namespace {
int qk_norm_rope_gate_impl(const RadArgs* a, RadStream st, bool store) {
enum { QG = 0, KI, CS, POSI, WQ, WK, QO, KO, GO, VI, SMI, KVI };
if (!a || a->n_t < (store ? 12 : 8)) return RAD_E_INVAL;
const RadTensor *QGT = rad_arg_in(a, QG), *K = rad_arg_in(a, KI), *CST = rad_arg_in(a, CS);
const RadTensor *POS = rad_arg_in(a, POSI), *QW = rad_arg_in(a, WQ), *KW = rad_arg_in(a, WK);
const RadTensor *QOT = rad_arg_in(a, QO), *KOT = rad_arg_in(a, KO), *GOT = rad_arg_in(a, GO);
const int64_t hd = rad_args_geti_or(a, "head_dim", 0);
const int64_t nq = rad_args_geti_or(a, "n_head", 0);
const int64_t nkv = rad_args_geti_or(a, "n_head_kv", 0);
const int64_t rot = rad_args_geti_or(a, "rot", 0);
if (!K || !CST || !POS || !KW || !KOT) return RAD_E_INVAL;
if (nq < 0 || nkv <= 0) return RAD_E_SHAPE;
if (nq > 0 && (!QGT || !QW || !QOT)) return RAD_E_INVAL;
if (hd != 128 && hd != 256 && hd != 512) return refuse("qk_norm_rope_gate: head_dim %lld", (long long)hd);
if (rot < 2 || (rot & 1) || rot > hd) return RAD_E_SHAPE;
if ((nq && (QGT->dtype != RAD_BF16 || QOT->dtype != RAD_BF16)) || K->dtype != RAD_BF16 ||
KOT->dtype != RAD_BF16 || (GOT && GOT->dtype != RAD_BF16))
return refuse("qk_norm_rope_gate: q, gate and k must be bf16");
if ((QW && QW->dtype != KW->dtype) || (KW->dtype != RAD_BF16 && KW->dtype != RAD_F32))
return refuse("qk_norm_rope_gate: gains must both be bf16 or f32");
if (rad_tensor_numel(KW) < hd || (QW && rad_tensor_numel(QW) < hd)) return RAD_E_SHAPE;
if (KW->rank && KW->stride[KW->rank - 1] != 1) return RAD_E_STRIDE;
if (QW && QW->rank && QW->stride[QW->rank - 1] != 1) return RAD_E_STRIDE;
if (CST->dtype != RAD_F32 && CST->dtype != RAD_BF16) return RAD_E_DTYPE;
if (!rad_tensor_is_contiguous(CST) || !rad_tensor_is_contiguous(POS)) return RAD_E_STRIDE;
const int64_t cs_rows = rad_tensor_numel(CST) / rot;
if (cs_rows < 1 || rad_tensor_numel(CST) % rot) return RAD_E_SHAPE;
const float eps = (float)rad_args_getf_or(a, "eps", 1e-6);
const float wadd = (float)rad_args_getf_or(a, "wadd", 0.0);
Rows qg{}, qo{}, go{}, k{}, ko{}, v{};
if (nq) {
if (int rc = rows_view(QGT, 2 * nq * hd, &qg, "qk_norm_rope_gate q_gate"); rc < 0) return rc;
if (int rc = rows_view(QOT, nq * hd, &qo, "qk_norm_rope_gate q_out"); rc < 0) return rc;
if (GOT) {
if (int rc = rows_view(GOT, nq * hd, &go, "qk_norm_rope_gate gate_out"); rc < 0) return rc;
}
}
if (int rc = rows_view(K, nkv * hd, &k, "qk_norm_rope_gate k"); rc < 0) return rc;
if (int rc = rows_view(KOT, nkv * hd, &ko, "qk_norm_rope_gate k_out"); rc < 0) return rc;
const int64_t M = nq ? qg.rows : k.rows;
if (M <= 0 || k.rows < M || ko.rows < M || (nq && (qo.rows < M || (GOT && go.rows < M))))
return RAD_E_SHAPE;
const int64_t npos = rad_tensor_numel(POS);
if (npos < M) return RAD_E_SHAPE;
auto vec_ok = [](const Rows& r) { return r.pitch % 8 == 0 && rad_ptr_aligned(r.base, 16); };
if ((nq && (!vec_ok(qg) || !vec_ok(qo) || (GOT && !vec_ok(go)))) || !vec_ok(k) || !vec_ok(ko))
return refuse("qk_norm_rope_gate: rows not 16-byte aligned");
/* the cache, as xe2_kv_store reads it (qkv_norm_rope_impl's checks) */
const char* sm = nullptr;
uint32_t smdt = 0;
int64_t nslot = 0, bs = 0, nblk = 0, csb = 0, csh = 0, cso = 0, csd = 1;
char* cb = nullptr;
uint32_t cdt = 0;
float kinv = 1.0f, vinv = 1.0f;
if (store) {
const RadTensor *V = rad_arg_in(a, VI), *SM = rad_arg_in(a, SMI), *KV = rad_arg_in(a, KVI);
if (!V || !SM || !KV) return RAD_E_INVAL;
if (V->dtype != RAD_BF16) return refuse("qk_norm_rope_gate_kv_store: v must be bf16");
if (int rc = rows_view(V, nkv * hd, &v, "qk_norm_rope_gate_kv_store v"); rc < 0) return rc;
if (v.rows < M) return RAD_E_SHAPE;
if (!vec_ok(v)) return refuse("qk_norm_rope_gate_kv_store: v rows not 16-byte aligned");
if (!rad_tensor_is_contiguous(SM)) return refuse("qk_norm_rope_gate_kv_store: slot_mapping not contiguous");
bs = rad_args_geti_or(a, "block_size", 0);
if (bs <= 0) return RAD_E_SHAPE;
nslot = rad_tensor_numel(SM);
if (nslot <= 0 || nslot > M) return RAD_E_SHAPE;
if (KV->rank == 4) {
if (KV->shape[1] != nkv || KV->shape[2] != bs || KV->shape[3] < 2 * hd) return RAD_E_SHAPE;
nblk = KV->shape[0];
csb = KV->stride[0]; csh = KV->stride[1]; cso = KV->stride[2]; csd = KV->stride[3];
} else {
cso = 2 * hd; csh = bs * cso; csb = nkv * csh;
}
const bool fp8 = KV->dtype == RAD_F8E4M3 || KV->dtype == RAD_F8E5M2;
kinv = fp8 ? 1.0f / (float)rad_args_getf_or(a, "k_scale", 1.0) : 1.0f;
vinv = fp8 ? 1.0f / (float)rad_args_getf_or(a, "v_scale", 1.0) : 1.0f;
sm = (const char*)SM->data;
smdt = SM->dtype;
cb = (char*)KV->data;
cdt = KV->dtype;
}
/* tasks: q heads, k heads, and with the store the v heads (copied to the cache only) */
const int64_t heads = nq + nkv + (store ? nkv : 0);
const int64_t total = M * heads;
const bool exact = exact_only();
const int nv = (int)(hd / 128); /* 16-byte vectors a lane */
const char* qwb = QW ? (const char*)QW->data : nullptr;
const char* kwb = (const char*)KW->data;
const bool wf32 = KW->dtype == RAD_F32;
const char* csp = (const char*)CST->data;
const bool cs32 = CST->dtype == RAD_F32;
const char* pb = (const char*)POS->data;
const uint32_t pdt = POS->dtype;
const bool gate = GOT != nullptr;
sycl::queue* qu = queue_of(st);
if (!qu) return RAD_E_DEVICE;
using V8 = sycl::vec<uint16_t, 8>;
const size_t wg = (size_t)kQnrSg * kSub;
const size_t groups = (size_t)((total + kQnrSg - 1) / kQnrSg);
return submit([&] {
syclex::nd_launch(*qu, sycl::nd_range<1>{groups * wg, wg},
[=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] {
const sycl::sub_group sg = it.get_sub_group();
const int sgi = (int)sg.get_group_linear_id();
float* lbuf = *sycl::ext::oneapi::group_local_memory_for_overwrite<float[kQnrSg * 512]>(it.get_group());
float* buf = lbuf + sgi * 512;
const int64_t task = (int64_t)it.get_group(0) * kQnrSg + sgi;
if (task >= total) return; /* uniform over the sub-group */
const int64_t m = task / heads, hh = task % heads;
const int l = (int)sg.get_local_linear_id();
const int per = nv * 8; /* contiguous elements a lane */
auto load = [&](const char* base, int64_t off, float* x) {
for (int u = 0; u < 4; ++u) {
if (u >= nv) break;
const V8 w = *(const V8*)((const uint16_t*)base + off + (l * nv + u) * 8);
for (int j = 0; j < 8; ++j) x[u * 8 + j] = sycl::bit_cast<float>((uint32_t)w[j] << 16);
}
};
/* xe2_rmsnorm on one head row: y = bf16(x * s * gw * mult), mult 1 */
auto norm = [&](const float* x, const char* gb, float* y) {
float ss = 0.0f;
if (!exact) {
for (int e = 0; e < 32; ++e) {
if (e >= per) break;
ss += x[e] * x[e];
}
ss = sycl::reduce_over_group(sg, ss, sycl::plus<float>());
} else {
for (int L = 0; L < kSub; ++L)
for (int e = 0; e < 32; ++e) {
if (e >= per) break;
const float xv = sycl::select_from_group(sg, x[e], L);
ss += xv * xv;
}
}
const float s = 1.0f / sycl::sqrt(ss / (float)hd + eps);
const float mult = 1.0f;
for (int e = 0; e < 32; ++e) {
if (e >= per) break;
const int64_t i = (int64_t)l * per + e;
const float gw = (wf32 ? ((const float*)gb)[i]
: sycl::bit_cast<float>((uint32_t)((const uint16_t*)gb)[i] << 16)) + wadd;
y[e] = rad_bf16_to_f32(rad_f32_to_bf16(x[e] * s * gw * mult));
}
};
auto put = [&](char* base, int64_t off, const float* y) {
for (int u = 0; u < 4; ++u) {
if (u >= nv) break;
V8 o;
for (int j = 0; j < 8; ++j) o[j] = rad_f32_to_bf16(y[u * 8 + j]);
*(V8*)((uint16_t*)base + off + (l * nv + u) * 8) = o;
}
};
int64_t cbase = -1;
if (store && m < nslot) {
const int64_t slot = ld_index(smdt, sm, m);
if (slot >= 0) {
const int64_t blk = slot / bs, off = slot % bs;
if (nblk <= 0 || blk < nblk) cbase = blk * csb + off * cso;
}
}
auto cache = [&](int64_t h, int64_t col0, const float* y, float inv) {
if (cbase < 0) return;
for (int e = 0; e < 32; ++e) {
if (e >= per) break;
const int64_t d = (int64_t)l * per + e;
rad_store_f32(cb, cdt, cbase + h * csh + (col0 + d) * csd, y[e] * inv);
}
};
float x[32], y[32];
if (hh >= nq + nkv) { /* a value head: kv_store's v half, as it is */
const int64_t h = hh - nq - nkv;
load(v.base, m * v.pitch + h * hd, x);
cache(h, hd, x, vinv);
return;
}
const bool isq = hh < nq;
const int64_t h = isq ? hh : hh - nq;
if (isq) {
const int64_t src = m * qg.pitch + h * 2 * hd;
if (gate) { /* the gate half, bit for bit */
for (int u = 0; u < 4; ++u) {
if (u >= nv) break;
*(V8*)((uint16_t*)go.base + m * go.pitch + h * hd + (l * nv + u) * 8) =
*(const V8*)((const uint16_t*)qg.base + src + hd + (l * nv + u) * 8);
}
}
load(qg.base, src, x);
} else {
load(k.base, m * k.pitch + h * hd, x);
}
norm(x, isq ? qwb : kwb, y);
for (int e = 0; e < 32; ++e) {
if (e >= per) break;
buf[l * per + e] = y[e];
}
sycl::group_barrier(sg);
int64_t pp = ld_index(pdt, pb, m);
pp = pp < 0 ? 0 : (pp < cs_rows ? pp : cs_rows - 1);
const int64_t half = rot / 2, co = pp * rot;
for (int64_t i = l; i < half; i += kSub) {
const float cs = cs32 ? ((const float*)csp)[co + i]
: sycl::bit_cast<float>((uint32_t)((const uint16_t*)csp)[co + i] << 16);
const float sn = cs32 ? ((const float*)csp)[co + half + i]
: sycl::bit_cast<float>((uint32_t)((const uint16_t*)csp)[co + half + i] << 16);
const float x0 = buf[i], x1 = buf[i + half];
buf[i] = rad_bf16_to_f32(rad_f32_to_bf16(x0 * cs - x1 * sn));
buf[i + half] = rad_bf16_to_f32(rad_f32_to_bf16(x0 * sn + x1 * cs));
}
sycl::group_barrier(sg);
for (int e = 0; e < 32; ++e) {
if (e >= per) break;
y[e] = buf[l * per + e];
}
if (isq) {
put(qo.base, m * qo.pitch + h * hd, y);
} else {
put(ko.base, m * ko.pitch + h * hd, y);
cache(h, 0, y, kinv);
}
});
});
}
} // namespace
int qk_norm_rope_gate(const RadArgs* a, RadStream st) { return qk_norm_rope_gate_impl(a, st, false); }
int qk_norm_rope_gate_kv_store(const RadArgs* a, RadStream st) { return qk_norm_rope_gate_impl(a, st, true); }
/* rope_table: cos and sin rows for each position, cs[pos * rot + i] and cs[pos * rot + half + i],
* as libref's ref_rope_table (a position outside the table is skipped). */
int rope_table(const RadArgs* a, RadStream st) {
+216 -2
View File
@@ -8,9 +8,11 @@
*/
#include <cstdlib>
#include <cstring>
#include <initializer_list>
#include <vector>
#include "rad_abi.h"
#include "rad_abi_layout.h"
#include "rad_plugin.h"
#include "xe2_ops.h"
namespace {
@@ -22,6 +24,8 @@ const RadConstraint cFloatDtype[] = { RAD_CIN("dtype", "bf16 f16 fp16 f32 fp32")
const RadConstraint cBf16[] = { RAD_CIN("dtype", "bf16") };
/* the fused attention prologue: bf16 heads of 128, 256 or 512 */
const RadConstraint cQnr[] = { RAD_CIN("dtype", "bf16"), RAD_CDIV("head_dim", 128), RAD_CLE("head_dim", 512) };
/* the gated prologue: the same heads, its dtype key is q_dtype */
const RadConstraint cQkg[] = { RAD_CIN("q_dtype", "bf16"), RAD_CDIV("head_dim", 128), RAD_CLE("head_dim", 512) };
/* The decode band of the skinny bf16 GEMV (xe2_gemv.cpp). */
const RadConstraint cGemvBf16[] = { RAD_CIN("dtype", "bf16"), RAD_CLE("M", 16) };
/* The prefill band of the bf16 XMX GEMM (xe2_gemm_xmx.cpp). */
@@ -47,6 +51,131 @@ const RadConstraint cM2Gemv[] = { RAD_CIN("dtype", "m2xfp4"), RAD_CLE("M", 16) }
/* Its prefill band (bf16 XMX, xe2_gemv_m2.cpp). */
const RadConstraint cM2Xmx[] = { RAD_CIN("dtype", "m2xfp4"), RAD_CGE("M", 17) };
/* Operand descriptions for the gated prologue, for rad-kbench (libr4d's r4d_shapes.cpp: the same
* shapes, so both libraries are drawn alike). A non-positive extent declines the whole list. */
RadOpdDesc opd(uint32_t dt, int64_t d0, int64_t d1 = 0, int64_t d2 = 0, int64_t d3 = 0) {
RadOpdDesc d{};
d.dtype = dt;
d.fill = RAD_FILL_NORMAL;
d.idx_const = -1;
const int64_t e[4] = { d0, d1, d2, d3 };
for (int i = 0; i < 4 && e[i] != 0; ++i) d.shape[d.rank++] = e[i];
return d;
}
RadOpdDesc opd_idx(int64_t d0, int64_t idx_max, uint32_t flags = 0) {
RadOpdDesc d = opd((uint32_t)RAD_I32, d0);
d.fill = RAD_FILL_INDEX;
d.idx_max = idx_max;
d.flags = flags;
return d;
}
RadOpdDesc opd_none() {
RadOpdDesc d{};
d.idx_const = -1;
d.flags = RAD_OPD_F_ABSENT;
return d;
}
template <int N>
int pick(RadOpdDesc* out, int operand, const RadOpdDesc (&list)[N]) {
if (!out) return RAD_E_INVAL;
for (const RadOpdDesc& d : list) {
if (d.flags & RAD_OPD_F_ABSENT) continue;
if (d.rank == 0 || d.rank > RAD_MAX_RANK) return RAD_E_UNSUPPORTED;
for (uint32_t i = 0; i < d.rank; ++i)
if (d.shape[i] <= 0) return RAD_E_UNSUPPORTED;
}
if (operand < 0 || operand >= N) return RAD_E_SHAPE;
*out = list[operand];
return RAD_OK;
}
uint32_t dt_act(const RadParam* p, int n_p, const char* key) {
const char* s = nullptr;
for (int i = 0; i < n_p; ++i)
if (p[i].kind == RAD_P_STR && p[i].key && !std::strcmp(p[i].key, key)) s = p[i].sval;
const uint32_t dt = s ? rad_dtype_parse(s) : (uint32_t)RAD_DT_INVALID;
return dt == (uint32_t)RAD_DT_INVALID ? (uint32_t)RAD_BF16 : dt;
}
/* [q|gate] interleaved per head, k, the [rows, rot] cos/sin table (a position is a lookup into it,
* so the draw is bounded by its rows), positions, f32 gains as every arch declares them, q_out,
* k_out; no gate_out, as the gated attention block passes none. */
int shape_qk_norm_rope_gate(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = rad_param_getdim(p, n_p, "M", 0), hd = rad_param_getdim(p, n_p, "head_dim", 0);
const int64_t nq = rad_param_getdim(p, n_p, "n_head", 0), nkv = rad_param_getdim(p, n_p, "n_head_kv", 0);
const int64_t rot = rad_param_getdim(p, n_p, "rot", 0);
const uint32_t Q = dt_act(p, n_p, "q_dtype");
const uint32_t CS = rad_param_getdim(p, n_p, "cs_f32", 0) ? (uint32_t)RAD_F32 : (uint32_t)RAD_BF16;
const RadOpdDesc l[] = {
nq ? opd(Q, M, nq * 2 * hd) : opd_none(),
opd(Q, M, nkv * hd),
opd(CS, M, rot),
opd_idx(M, M),
nq ? opd((uint32_t)RAD_F32, hd) : opd_none(),
opd((uint32_t)RAD_F32, hd),
nq ? opd(Q, M, nq * hd) : opd_none(),
opd(Q, M, nkv * hd),
opd_none(),
};
return pick(out, operand, l);
}
/* then kv_store's v, unique slots and the paged cache at kv_store's own shapes */
int shape_qk_norm_rope_gate_kv_store(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
if (operand < 9) return shape_qk_norm_rope_gate(p, n_p, operand, out);
const int64_t M = rad_param_getdim(p, n_p, "M", 0), hd = rad_param_getdim(p, n_p, "head_dim", 0);
const int64_t kvh = rad_param_getdim(p, n_p, "n_head_kv", 0), bs = rad_param_getdim(p, n_p, "block_size", 0);
const uint32_t KV = dt_act(p, n_p, "kv_dtype");
if (M <= 0 || bs <= 0) return RAD_E_UNSUPPORTED;
const int64_t nb = (M + bs - 1) / bs + 2;
const RadOpdDesc l[] = {
opd_none(), opd_none(), opd_none(), opd_none(), opd_none(), opd_none(), opd_none(),
opd_none(), opd_none(),
opd((uint32_t)RAD_BF16, M, kvh, hd),
opd_idx(M, nb * bs, RAD_OPD_F_IDX_UNIQUE),
opd(KV, nb, kvh, bs, 2 * hd),
};
return pick(out, operand, l);
}
/* The chain xe2_qk_norm_rope_gate_kv_store replaces (libr4d's r4d_fuse.cpp, the same wiring):
* qk_norm_rope_gate, then kv_store of its k_out and v. rad-kbench's fusion oracle runs both steps
* on libxe2's own rows and compares the bytes. The plain prologue declares no chain, as libr4d's
* does not: its q norm is an rmsnorm over T * n_head strided rows, which no step can express.
*
* Operands: [0] q_gate? [1] k [2] cos_sin [3] positions [4] q_w? [5] k_w [6] q_out?
* [7] k_out [8] gate_out? [9] v [10] slot_mapping [11] kv_cache */
int fuse_qk_norm_rope_gate_kv_store(const RadParam* p, int n_p, uint64_t present, int step,
RadFuseStep* out) {
if (!out) return RAD_E_INVAL;
*out = RadFuseStep{};
bool ok = true;
auto mirror = [&](const char* key, bool req) {
const RadParam* f = rad_param_find(p, n_p, key);
if (!f) { ok = ok && !req; return; }
if (out->n_p >= RAD_MAX_FUSE_PARAMS) { ok = false; return; }
out->p[out->n_p++] = *f;
};
auto opt = [present](int i) { return RAD_FUSE_HAS(present, i) ? (int16_t)i : (int16_t)RAD_FUSE_NONE; };
auto wire = [&](std::initializer_list<int16_t> from) {
if (!ok) return (int)RAD_E_UNSUPPORTED;
for (int16_t v : from) out->from[out->n_from++] = v;
return (int)RAD_OK;
};
switch (step) {
case 0:
out->op = "qk_norm_rope_gate";
for (const char* k : { "M", "head_dim", "n_head", "n_head_kv", "rot", "q_dtype" }) mirror(k, true);
for (const char* k : { "eps", "wadd", "cs_f32", "pos_i64" }) mirror(k, false);
return wire({ opt(0), 1, 2, 3, opt(4), 5, opt(6), 7, opt(8) });
case 1:
out->op = "kv_store";
for (const char* k : { "M", "head_dim", "n_head_kv", "block_size", "kv_dtype" }) mirror(k, true);
for (const char* k : { "k_scale", "v_scale" }) mirror(k, false);
return wire({ 7, 9, 10, 11 }); /* k (k_out), v, slot_mapping, kv_cache */
default:
return RAD_E_NOTFOUND;
}
}
/* Rows by field name (C++20 designated initialisers must follow declaration order, so the compiler
* checks it), unlike a positional table where a shifted field can still compile. */
const RadKernelInfo kKernels[] = {
@@ -140,6 +269,20 @@ const RadKernelInfo kKernels[] = {
.shape = "as xe2_qkv_norm_rope; any paged cache xe2_kv_store takes",
.dtypes = "bf16 q, k, v; a bf16 or fp8 cache",
.domain = RAD_DOMAIN_DEVICE, .constraints = cQnr, .n_constraints = 3, .launch = xe2::qkv_norm_rope_kv_store },
{ .name = "xe2_qk_norm_rope_gate", .op = "qk_norm_rope_gate", .family = "rope",
.computes = "the [q|gate] split, the q and k rmsnorms, partial NeoX rotaries from the cos/sin table and the "
"gate copy in one launch, byte-identical to libxe2's rmsnorm, rope_table + rope (its bf16 head-row "
"norm; XE2_EXACT=1 libref's order)",
.shape = "head_dim 128, 256 or 512; rot even, <= head_dim; rows 16-byte aligned; n_head 0 is the k-only form",
.dtypes = "bf16 q_gate, k, outputs; bf16 or f32 gains; f32 or bf16 cos/sin",
.domain = RAD_DOMAIN_DEVICE, .constraints = cQkg, .n_constraints = 3, .launch = xe2::qk_norm_rope_gate,
.opd_shape = shape_qk_norm_rope_gate },
{ .name = "xe2_qk_norm_rope_gate_kv_store", .op = "qk_norm_rope_gate_kv_store", .family = "rope",
.computes = "xe2_qk_norm_rope_gate, then xe2_kv_store of the rotated k and the v heads from the same launch",
.shape = "as xe2_qk_norm_rope_gate; any paged cache xe2_kv_store takes",
.dtypes = "bf16 q_gate, k, v; a bf16 or fp8 cache",
.domain = RAD_DOMAIN_DEVICE, .constraints = cQkg, .n_constraints = 3, .launch = xe2::qk_norm_rope_gate_kv_store,
.opd_shape = shape_qk_norm_rope_gate_kv_store, .replaces = fuse_qk_norm_rope_gate_kv_store },
{ .name = "xe2_conv1d_dw", .op = "conv1d_dw", .family = "conv",
.computes = "causal depthwise conv over time within cu segments, f32 in tap order, + bias, one rounding",
.shape = "rows of n, k taps", .dtypes = "any float dtype",
@@ -617,6 +760,63 @@ const RadOperandSpec oQkvNormRopeKv[] = {
};
/* libr4d's schemas for the gated prologue (r4d_rows.cpp), which the loader requires to agree. Not
* docs/OPS.md's qk_norm_rope: [q|gate] split per head, three destinations, and a precomputed
* cos/sin table in place of `theta`. */
const RadParamSpec pQkNormRopeGate[] = {
{ "M", RAD_P_INT, RAD_REQUIRED },
{ "head_dim", RAD_P_INT, RAD_REQUIRED },
{ "n_head", RAD_P_INT, RAD_REQUIRED },
{ "n_head_kv", RAD_P_INT, RAD_REQUIRED },
{ "rot", RAD_P_INT, RAD_REQUIRED },
{ "q_dtype", RAD_P_STR, RAD_REQUIRED },
{ "eps", RAD_P_F64, RAD_OPTIONAL },
{ "wadd", RAD_P_F64, RAD_OPTIONAL },
{ "cs_f32", RAD_P_INT, RAD_OPTIONAL },
{ "pos_i64", RAD_P_INT, RAD_OPTIONAL },
};
const RadOperandSpec oQkNormRopeGate[] = {
{ "q_gate", RAD_OPD_IN, 1 },
{ "k", RAD_OPD_IN, 0 },
{ "cos_sin", RAD_OPD_IN, 0 },
{ "positions", RAD_OPD_IN, 0 },
{ "q_w", RAD_OPD_WEIGHT, 1 },
{ "k_w", RAD_OPD_WEIGHT, 0 },
{ "q_out", RAD_OPD_OUT, 1 },
{ "k_out", RAD_OPD_OUT, 0 },
{ "gate_out", RAD_OPD_OUT, 1 },
};
const RadParamSpec pQkNormRopeGateKv[] = {
{ "M", RAD_P_INT, RAD_REQUIRED },
{ "head_dim", RAD_P_INT, RAD_REQUIRED },
{ "n_head", RAD_P_INT, RAD_REQUIRED },
{ "n_head_kv", RAD_P_INT, RAD_REQUIRED },
{ "rot", RAD_P_INT, RAD_REQUIRED },
{ "q_dtype", RAD_P_STR, RAD_REQUIRED },
{ "eps", RAD_P_F64, RAD_OPTIONAL },
{ "wadd", RAD_P_F64, RAD_OPTIONAL },
{ "cs_f32", RAD_P_INT, RAD_OPTIONAL },
{ "pos_i64", RAD_P_INT, RAD_OPTIONAL },
{ "block_size", RAD_P_INT, RAD_REQUIRED },
{ "kv_dtype", RAD_P_STR, RAD_REQUIRED },
{ "k_scale", RAD_P_F64, RAD_OPTIONAL },
{ "v_scale", RAD_P_F64, RAD_OPTIONAL },
};
const RadOperandSpec oQkNormRopeGateKv[] = {
{ "q_gate", RAD_OPD_IN, 1 },
{ "k", RAD_OPD_IN, 0 },
{ "cos_sin", RAD_OPD_IN, 0 },
{ "positions", RAD_OPD_IN, 0 },
{ "q_w", RAD_OPD_WEIGHT, 1 },
{ "k_w", RAD_OPD_WEIGHT, 0 },
{ "q_out", RAD_OPD_OUT, 1 },
{ "k_out", RAD_OPD_OUT, 0 },
{ "gate_out", RAD_OPD_OUT, 1 },
{ "v", RAD_OPD_IN, 0 },
{ "slot_mapping", RAD_OPD_IN, 0 },
{ "kv_cache", RAD_OPD_INOUT, 0 },
};
const RadOpSchema kSchemas[] = {
{ "add_rmsnorm", pAddRmsNorm, (int)(sizeof pAddRmsNorm / sizeof pAddRmsNorm[0]), oAddRmsNorm,
(int)(sizeof oAddRmsNorm / sizeof oAddRmsNorm[0]),
@@ -631,6 +831,19 @@ const RadOpSchema kSchemas[] = {
oQkvNormRopeKv, (int)(sizeof oQkvNormRopeKv / sizeof oQkvNormRopeKv[0]),
"qkv_norm_rope, then kv_store of the finished k and v heads into the paged cache, in one "
"launch." },
{ "qk_norm_rope_gate", pQkNormRopeGate, (int)(sizeof pQkNormRopeGate / sizeof pQkNormRopeGate[0]),
oQkNormRopeGate, (int)(sizeof oQkNormRopeGate / sizeof oQkNormRopeGate[0]),
"split [q|gate] per head, QK RMS norm over the head, partial NeoX RoPE and the gate "
"copy, in one pass. Not docs/OPS.md's qk_norm_rope: different operands, and a "
"precomputed cos/sin table instead of theta. `n_head` 0 is the K-ONLY FORM -- no "
"`q_gate`, no `q_w`, no `q_out` -- for an input that is already one plain head per "
"`head_dim` columns with nothing interleaved. The QSA indexer's query heads are that "
"shape, and it is how its `heads` norms plus a rope become one launch." },
{ "qk_norm_rope_gate_kv_store", pQkNormRopeGateKv, (int)(sizeof pQkNormRopeGateKv / sizeof pQkNormRopeGateKv[0]),
oQkNormRopeGateKv, (int)(sizeof oQkNormRopeGateKv / sizeof oQkNormRopeGateKv[0]),
"qk_norm_rope_gate followed by kv_store, in one launch: each k head's block also writes "
"its rotated k and its v into the paged cache at the token's slot. The `k` kv_store "
"reads is `k_out`, so the tail adds only `v`, `slot_mapping` and `kv_cache`." },
};
const RadPluginInfo kInfo = {
@@ -639,11 +852,12 @@ const RadPluginInfo kInfo = {
"intel_gpu_bmg_g31",
};
/* XE2_NO_FUSED_PROLOGUE=1 leaves the fused attention prologue undeclared, so an architecture takes
/* XE2_NO_FUSED_PROLOGUE=1 leaves the fused attention prologues (plain and gated) undeclared, so an architecture takes
* its unfused chain: the A/B for its byte-identity, and an escape hatch. */
bool hidden(const char* op) {
static const bool off = std::getenv("XE2_NO_FUSED_PROLOGUE") != nullptr;
return off && (!std::strcmp(op, "qkv_norm_rope") || !std::strcmp(op, "qkv_norm_rope_kv_store"));
return off && (!std::strcmp(op, "qkv_norm_rope") || !std::strcmp(op, "qkv_norm_rope_kv_store") ||
!std::strcmp(op, "qk_norm_rope_gate") || !std::strcmp(op, "qk_norm_rope_gate_kv_store"));
}
const std::vector<const RadKernelInfo*>& kernels() {
static const std::vector<const RadKernelInfo*> v = [] {