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_gdn.cpp
T
claudeandClaude Opus 5.5 e6f4862c7e libxe2: gdn_conv_prep's convolution eight channels a work-item
The (token, channel) form spent ~1.8 ms a 2048-token chunk in int64 divides and per-channel
branches. A work-item now takes eight channels of one head in 32-bit index math with 16-byte
loads and one 16-byte store, each output computed tap for tap as before; the scalar form
remains for other layouts (XE2_GDN_SCALAR_CONV=1 forces it).

2234-token prompt 877 -> 960 tok/s, its 96-token greedy continuation identical to the scalar
form's; greedy set 8/8 identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 04:08:52 +01:00

2229 lines
122 KiB
C++

/* xe2_gdn.cpp -- the gated delta net (Qwen3.5 / Qwen3.8's linear-attention layers): the conv
* preamble, the chunk preamble, the chunked scan, the recurrent update and the gated norm.
*
* Correctness first: libref's ref_gdn.cpp (the algorithm and the layouts are in its header), each
* of its parallel loops one work-item an iteration running the loop's body as libref writes it --
* the same sums in the same order, ref_exp / log1p in double rounded once, the l2 and RMS norms as
* 1 / sqrt -- so the outputs are libref's. The per-(sequence, head) workspaces libref takes from
* ws_get are slices of one device workspace (xe2_common.h).
*
* The sequence boundaries `cu` live on the card, so the host takes the token count from the
* operand shapes (q, k or v as [T, heads, width]) and each work-item reads its own cu entries;
* libref's host-side checks of cu, state_idx and num_accepted against each other are the engine's
* to keep (it builds them), and an out-of-range slot is skipped on the card as libref skips it.
*/
#include "xe2_common.h"
#include "xe2_ops.h"
#include <algorithm>
#include <cstring>
#include <type_traits>
namespace xe2 {
namespace {
constexpr int kHistMax = 16; /* REF_CONV_HIST_MAX */
/* An operand as a device-side reader / writer (libref's ldt / stt). */
struct DT {
char* p = nullptr;
uint32_t dt = 0;
float ld(int64_t o) const { return rad_load_f32(p, dt, o); }
void st(int64_t o, float v) const { rad_store_f32(p, dt, o, v); }
int64_t li(int64_t o) const { return ld_index(dt, p, o); }
};
DT dt_of(const RadTensor* t) { return t && t->data ? DT{ (char*)t->data, t->dtype } : DT{}; }
int64_t laststride(const RadTensor* t) { return t->rank ? t->stride[t->rank - 1] : 1; }
struct V3 { int64_t s0, s1, s2; };
struct V2 { int64_t s0, s1; };
struct V4 { int64_t s0, s1, s2, s3; };
V3 v3(const RadTensor* t, int64_t d1, int64_t d2) {
V3 v{ d1 * d2, d2, 1 };
if (t->rank >= 3) { v.s0 = t->stride[t->rank - 3]; v.s1 = t->stride[t->rank - 2]; v.s2 = t->stride[t->rank - 1]; }
return v;
}
V3 v3_rows(const RadTensor* t, int64_t d1, int64_t d2) {
if (t->rank != 2) return v3(t, d1, d2);
return V3{ t->stride[0], d2 * t->stride[1], t->stride[1] };
}
V2 v2(const RadTensor* t, int64_t d1) {
V2 v{ d1, 1 };
if (t->rank >= 2) { v.s0 = t->stride[t->rank - 2]; v.s1 = t->stride[t->rank - 1]; }
return v;
}
V4 v4(const RadTensor* t, int64_t d1, int64_t d2, int64_t d3) {
V4 v{ d1 * d2 * d3, d2 * d3, d3, 1 };
if (t->rank >= 4) {
v.s0 = t->stride[t->rank - 4]; v.s1 = t->stride[t->rank - 3];
v.s2 = t->stride[t->rank - 2]; v.s3 = t->stride[t->rank - 1];
}
return v;
}
inline int64_t at3(const V3& v, int64_t i, int64_t j, int64_t k) { return i * v.s0 + j * v.s1 + k * v.s2; }
inline int64_t at2(const V2& v, int64_t i, int64_t j) { return i * v.s0 + j * v.s1; }
inline int64_t at4(const V4& v, int64_t i, int64_t j, int64_t k, int64_t l) {
return i * v.s0 + j * v.s1 + k * v.s2 + l * v.s3;
}
inline float rexp(float x) { return (float)sycl::exp((double)x); }
inline float rlog1p(float x) { return (float)sycl::log1p((double)x); }
inline float sigm(float x) { return 1.0f / (1.0f + rexp(-x)); }
inline float silu(float x) { return x * sigm(x); }
inline float softplus(float x, float thr) {
if (x > thr) return x;
return x > 0.0f ? x + rlog1p(rexp(-x)) : rlog1p(rexp(x));
}
/* A 1-D integer operand read in logical order (libref's offlin + ld_int). */
struct IV {
Lin l;
bool on = false;
int64_t at(int64_t i) const { return ld_index(l.dtype, l.base, l.off(i)); }
};
IV iv_of(const RadTensor* t) {
IV v;
if (t && t->data) { v.l = Lin::of(t); v.on = true; }
return v;
}
/* The token count and head count of a [T, heads, width] operand. */
bool thw(const RadTensor* t, int64_t width, int64_t* T, int64_t* heads) {
if (!t || t->rank != 3 || t->shape[2] != width) return false;
*T = t->shape[0];
*heads = t->shape[1];
return *T > 0 && *heads > 0;
}
/* conv_channel's operands, by value for a kernel. */
struct ConvIO {
DT x, w, bias, q, k, v;
V3 qv, kv, vv;
V2 wv;
int64_t xrow, xcol, Hg, H, K, V, width, bias_s;
bool has_bias;
};
/* libref's conv_channel: channel `c` over one sequence's `slen` tokens from `bos`. */
inline void conv_channel(const ConvIO& io, int64_t c, int64_t bos, int64_t slen, const float* hist) {
const int64_t Hg = io.Hg, K = io.K, V = io.V, width = io.width;
DT out;
V3 ov;
int64_t oh, od;
if (c < Hg * K) {
out = io.q; ov = io.qv; oh = c / K; od = c % K;
} else if (c < 2 * Hg * K) {
out = io.k; ov = io.kv; oh = (c - Hg * K) / K; od = (c - Hg * K) % K;
} else {
out = io.v; ov = io.vv; oh = (c - 2 * Hg * K) / V; od = (c - 2 * Hg * K) % V;
}
const float bs = io.has_bias ? io.bias.ld(c * io.bias_s) : 0.0f;
for (int64_t t = 0; t < slen; ++t) {
float acc = bs;
for (int64_t j = 0; j < width; ++j) {
const int64_t src = t - (width - 1) + j;
const float val = src >= 0 ? io.x.ld((bos + src) * io.xrow + c * io.xcol) : hist[src + width - 1];
acc += val * io.w.ld(at2(io.wv, c, j));
}
out.st(at3(ov, bos + t, oh, od), silu(acc));
}
}
size_t groups_for(int64_t n, size_t wg) { return (size_t)((n + (int64_t)wg - 1) / (int64_t)wg); }
} // namespace
/* xe2_gdn_esimd.cpp */
int gdn_chunk_scan_dpas(sycl::queue& q, const uint16_t* qp, int64_t qs0, int64_t qs1, const uint16_t* kp, int64_t ks0,
int64_t ks1, const uint16_t* vp, int64_t vs0, int64_t vs1, const uint16_t* Ap, int64_t As0,
int64_t As1, const float* g, int64_t gs0, int64_t gs1, const float* beta, int64_t bs0,
int64_t bs1, uint16_t* op, int64_t os0, int64_t os1, const float* h0, const int64_t* h0s,
float* ht, const int64_t* hts, const RadTensor* cu, const char* si, uint32_t sidt, int64_t sw,
int64_t T, int64_t N, int64_t H, int64_t Hg, float scale);
int gdn_kkt_solve_dpas(sycl::queue& q, const uint16_t* kp, int64_t ks0, int64_t ks1, const float* g, int64_t gs0,
int64_t gs1, const float* beta, int64_t bs0, int64_t bs1, uint16_t* Ap, int64_t As0,
int64_t As1, const RadTensor* cu, int64_t T, int64_t N, int64_t H, int64_t Hg);
/* ------------------------------------------------------------------ gdn_conv_prep */
int gdn_conv_prep(const RadArgs* a, RadStream st) {
if (!a || a->n_t < 16) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *w = &a->t[1], *cs = &a->t[5], *cu = &a->t[6];
const RadTensor *q = &a->t[11], *k = &a->t[12], *v = &a->t[13];
const RadTensor *g = &a->t[14], *beta = &a->t[15];
const RadTensor* bias = rad_arg_in(a, 2);
const RadTensor* A_log = rad_arg_in(a, 3);
const RadTensor* dt_bias = rad_arg_in(a, 4);
const RadTensor* ta = rad_arg_in(a, 7);
const RadTensor* tb = rad_arg_in(a, 8);
const RadTensor* sidx = rad_arg_in(a, 9);
const RadTensor* hini = rad_arg_in(a, 10);
if (!x->data || !w->data || !cu->data || !q->data || !k->data || !v->data || !g->data || !beta->data)
return RAD_E_INVAL;
if ((ta != nullptr) != (tb != nullptr)) return RAD_E_INVAL;
const int64_t K = rad_args_geti_or(a, "head_k", 0), V = rad_args_geti_or(a, "head_v", 0);
const int64_t chunk = rad_args_geti_or(a, "chunk", 0), width = rad_args_geti_or(a, "conv_width", 0);
const float l2eps = (float)rad_args_getf_or(a, "l2_eps", 1e-6);
const float spthr = (float)rad_args_getf_or(a, "softplus_thr", 20.0);
if (K <= 0 || V <= 0 || chunk <= 0 || width <= 0) return RAD_E_SHAPE;
if (width - 1 > kHistMax) return RAD_E_UNSUPPORTED;
const int64_t N = rad_tensor_numel(cu) - 1;
if (N <= 0) return RAD_E_SHAPE;
int64_t T = 0, Hg = 0, Tv = 0, H = 0;
if (!thw(q, K, &T, &Hg) || !thw(v, V, &Tv, &H) || Tv != T)
return refuse("gdn_conv_prep: q and v must be [T, heads, width] views");
if (H % Hg != 0) return RAD_E_SHAPE;
const int64_t conv_dim = 2 * Hg * K + H * V;
if (rad_tensor_numel(w) < conv_dim * width) return RAD_E_SHAPE;
if (rad_tensor_numel(g) < T * H || rad_tensor_numel(beta) < T * H) return RAD_E_SHAPE;
const int64_t xrow = x->rank >= 2 ? x->stride[x->rank - 2] : (conv_dim + (ta ? 0 : 2 * H));
const int64_t xcol = laststride(x);
const int64_t xneed = conv_dim + (ta ? 0 : 2 * H);
if (x->rank >= 2) {
if (x->shape[x->rank - 1] < xneed || x->shape[x->rank - 2] < T) return RAD_E_SHAPE;
} else if (rad_tensor_numel(x) < (T - 1) * xrow + xneed) {
return RAD_E_SHAPE;
}
if (ta && (rad_tensor_numel(ta) < T * H || rad_tensor_numel(tb) < T * H)) return RAD_E_SHAPE;
const int64_t state_len = cs->rank >= 3 ? cs->shape[cs->rank - 1] : (width > 1 ? width - 1 : 1);
const V3 cvs = v3(cs, conv_dim, state_len);
if (cs->data && state_len < width - 1) return RAD_E_SHAPE;
ConvIO io{};
io.x = dt_of(x); io.w = dt_of(w); io.bias = dt_of(bias); io.q = dt_of(q); io.k = dt_of(k); io.v = dt_of(v);
io.qv = v3(q, Hg, K); io.kv = v3(k, Hg, K); io.vv = v3(v, H, V); io.wv = v2(w, width);
io.xrow = xrow; io.xcol = xcol; io.Hg = Hg; io.H = H; io.K = K; io.V = V; io.width = width;
io.has_bias = bias && bias->data;
io.bias_s = io.has_bias ? laststride(bias) : 0;
const DT xs = dt_of(x), css = dt_of(cs), gs = dt_of(g), bts = dt_of(beta), tas = dt_of(ta), tbs = dt_of(tb);
const DT alg = dt_of(A_log), dtb = dt_of(dt_bias);
const int64_t alg_s = A_log ? laststride(A_log) : 0, dtb_s = dt_bias ? laststride(dt_bias) : 0;
const bool has_cs = cs->data != nullptr, has_ta = ta != nullptr;
const V2 gv = v2(g, H), bv = v2(beta, H);
const V2 av = ta ? v2(ta, H) : V2{ 0, 0 }, bgv = tb ? v2(tb, H) : V2{ 0, 0 };
const IV cuv = iv_of(cu), siv = iv_of(sidx), hiv = iv_of(hini);
const V3 qv = io.qv, kv = io.kv;
sycl::queue* qu = queue_of(st);
if (!qu) return RAD_E_DEVICE;
const size_t wg = 128;
return submit([&] {
const bool allbf = io.x.dt == RAD_BF16 && io.w.dt == RAD_BF16 && io.q.dt == RAD_BF16 && io.k.dt == RAD_BF16 &&
io.v.dt == RAD_BF16 && (!has_cs || css.dt == RAD_BF16) && io.xcol == 1 && io.wv.s1 == 1 &&
!std::getenv("XE2_GDN_GENERIC");
/* phase 1, vectorised: a work-item a (token, eight channels) in 32-bit index math, the
* eight in one head (K and V multiples of 8) and stored as one 16-byte write. Each output
* is the scalar form's, tap for tap (the int64 divides and the per-channel branches of
* the form below made it ~1.8 ms a 2048-token chunk, all ALU) */
const bool vec8 = allbf && K % 8 == 0 && V % 8 == 0 && conv_dim % 8 == 0 && io.xrow % 8 == 0 &&
io.qv.s2 == 1 && io.kv.s2 == 1 && io.vv.s2 == 1 && io.qv.s0 % 8 == 0 && io.qv.s1 % 8 == 0 &&
io.kv.s0 % 8 == 0 && io.kv.s1 % 8 == 0 && io.vv.s0 % 8 == 0 && io.vv.s1 % 8 == 0 &&
rad_ptr_aligned(io.x.p, 16) && rad_ptr_aligned(io.q.p, 16) && rad_ptr_aligned(io.k.p, 16) &&
rad_ptr_aligned(io.v.p, 16) && T * conv_dim < (int64_t)1 << 31 && width <= 8 &&
!std::getenv("XE2_GDN_SCALAR_CONV");
if (vec8) {
const int c8n = (int)(conv_dim / 8);
const size_t wg8 = 64;
qu->parallel_for(sycl::nd_range<2>{{(size_t)T, groups_for(c8n, wg8) * wg8}, {1, wg8}}, [=](sycl::nd_item<2> it) {
const int c8 = (int)it.get_global_id(1);
if (c8 >= c8n) return;
const int tok = (int)it.get_global_id(0);
int64_t n = 0;
while (n + 1 < N && cuv.at(n + 1) <= tok) ++n;
const int64_t bos = cuv.at(n), slen = cuv.at(n + 1) - bos;
if (slen <= 0 || tok >= bos + slen) return;
const int t = (int)(tok - bos);
const int64_t slot = siv.on ? siv.at(n) : n;
const bool warm = !hiv.on || hiv.at(n) != 0;
const int c = c8 * 8, HK = (int)(io.Hg * io.K), Ki = (int)io.K, Vi = (int)io.V;
uint16_t* op;
if (c < HK) op = (uint16_t*)io.q.p + (int64_t)tok * io.qv.s0 + (c / Ki) * io.qv.s1 + c % Ki;
else if (c < 2 * HK) op = (uint16_t*)io.k.p + (int64_t)tok * io.kv.s0 + ((c - HK) / Ki) * io.kv.s1 + (c - HK) % Ki;
else op = (uint16_t*)io.v.p + (int64_t)tok * io.vv.s0 + ((c - 2 * HK) / Vi) * io.vv.s1 + (c - 2 * HK) % Vi;
float acc[8];
#pragma unroll
for (int e = 0; e < 8; ++e) acc[e] = io.has_bias ? io.bias.ld((int64_t)(c + e) * io.bias_s) : 0.0f;
const uint16_t* xp = (const uint16_t*)io.x.p;
const uint16_t* wp = (const uint16_t*)io.w.p;
const uint16_t* sp = (const uint16_t*)css.p;
const int wd = (int)width;
for (int j = 0; j < wd; ++j) {
const int src = t - (wd - 1) + j;
float val[8];
if (src >= 0) {
const sycl::vec<uint16_t, 8> u = *(const sycl::vec<uint16_t, 8>*)(xp + (bos + src) * io.xrow + c);
#pragma unroll
for (int e = 0; e < 8; ++e) val[e] = rad_bf16_to_f32(u[e]);
} else {
#pragma unroll
for (int e = 0; e < 8; ++e)
val[e] = warm && has_cs && slot >= 0 ? rad_bf16_to_f32(sp[at3(cvs, slot, c + e, src + wd - 1)]) : 0.0f;
}
#pragma unroll
for (int e = 0; e < 8; ++e) acc[e] += val[e] * rad_bf16_to_f32(wp[(int64_t)(c + e) * io.wv.s0 + j]);
}
sycl::vec<uint16_t, 8> o;
#pragma unroll
for (int e = 0; e < 8; ++e) {
float s = acc[e] * sigmoid_fexp(acc[e]);
if (near_bf16_tie(s)) s = silu(acc[e]);
o[e] = rad_f32_to_bf16(s);
}
*(sycl::vec<uint16_t, 8>*)op = o;
});
} else
/* phase 1: the convolution, straight into q / k / v: a work-item a (token, channel) --
* each output is conv_channel's for that token, its window from x or the conv state
* (a channel walked its tokens in turn here: 10240 chains of 1882 at a prefill) */
qu->parallel_for(sycl::nd_range<1>{groups_for(T * conv_dim, wg) * wg, wg}, [=](sycl::nd_item<1> it) {
const int64_t tc = (int64_t)it.get_global_id(0);
if (tc >= T * conv_dim) return;
const int64_t tok = tc / conv_dim, c = tc % conv_dim;
int64_t n = 0;
while (n + 1 < N && cuv.at(n + 1) <= tok) ++n;
const int64_t bos = cuv.at(n), slen = cuv.at(n + 1) - bos;
if (slen <= 0 || tok >= bos + slen) return;
const int64_t t = tok - bos;
const int64_t slot = siv.on ? siv.at(n) : n;
const bool warm = !hiv.on || hiv.at(n) != 0;
const int64_t Hg_ = io.Hg, K_ = io.K, V_ = io.V;
DT out;
V3 ov;
int64_t oh, od;
if (c < Hg_ * K_) {
out = io.q; ov = io.qv; oh = c / K_; od = c % K_;
} else if (c < 2 * Hg_ * K_) {
out = io.k; ov = io.kv; oh = (c - Hg_ * K_) / K_; od = (c - Hg_ * K_) % K_;
} else {
out = io.v; ov = io.vv; oh = (c - 2 * Hg_ * K_) / V_; od = (c - 2 * Hg_ * K_) % V_;
}
float acc = io.has_bias ? io.bias.ld(c * io.bias_s) : 0.0f;
if (allbf) { /* the engine's bf16 operands, typed */
const uint16_t* xp = (const uint16_t*)io.x.p;
const uint16_t* wp = (const uint16_t*)io.w.p + c * io.wv.s0;
const uint16_t* sp = (const uint16_t*)css.p;
for (int64_t j = 0; j < width; ++j) {
const int64_t src = t - (width - 1) + j;
const float val = src >= 0 ? rad_bf16_to_f32(xp[(bos + src) * io.xrow + c])
: (warm && has_cs && slot >= 0 ? rad_bf16_to_f32(sp[at3(cvs, slot, c, src + width - 1)]) : 0.0f);
acc += val * rad_bf16_to_f32(wp[j]);
}
/* silu with a float exp, libref's double one only near a bf16 tie (xe2_common.h) */
float s = acc * sigmoid_fexp(acc);
if (near_bf16_tie(s)) s = silu(acc);
((uint16_t*)out.p)[at3(ov, bos + t, oh, od)] = rad_f32_to_bf16(s);
return;
}
for (int64_t j = 0; j < width; ++j) {
const int64_t src = t - (width - 1) + j;
const float val = src >= 0 ? io.x.ld((bos + src) * io.xrow + c * io.xcol)
: (warm && has_cs && slot >= 0 ? css.ld(at3(cvs, slot, c, src + width - 1)) : 0.0f);
acc += val * io.w.ld(at2(io.wv, c, j));
}
out.st(at3(ov, bos + t, oh, od), silu(acc));
});
/* phase 2: the l2 norm over each q and k head, reading the rounded conv output: a sub-group
* a (token, head) when the head is 128 bf16 contiguous -- its values loaded 8 a lane, the
* squares added in d order by lane broadcasts (libref's chain) -- else a work-item a head */
const bool l2v = K == 128 && io.q.dt == RAD_BF16 && io.k.dt == RAD_BF16 && qv.s2 == 1 && kv.s2 == 1 &&
!std::getenv("XE2_GDN_GENERIC");
if (l2v)
qu->parallel_for(sycl::nd_range<1>{(size_t)(T * Hg * 2) * kSub, (size_t)kSub},
[=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] {
const sycl::sub_group sg = it.get_sub_group();
const int lane = (int)sg.get_local_linear_id();
const int64_t th = (int64_t)it.get_group(0);
const int64_t which = th / (T * Hg), rest = th % (T * Hg);
const int64_t t = rest / Hg, h = rest % Hg;
uint16_t* zp = (uint16_t*)(which ? io.k.p : io.q.p) + at3(which ? kv : qv, t, h, 0);
sycl::vec<uint16_t, 8> u8 = *(const sycl::vec<uint16_t, 8>*)(zp + lane * 8);
float u[8];
for (int e = 0; e < 8; ++e) u[e] = rad_bf16_to_f32(u8[e]);
float ss = 0.0f;
for (int l = 0; l < kSub; ++l)
for (int e = 0; e < 8; ++e) {
const float w = sycl::select_from_group(sg, u[e], l);
ss += w * w;
}
const float inv = 1.0f / sycl::sqrt(ss + l2eps);
for (int e = 0; e < 8; ++e) u8[e] = rad_f32_to_bf16(u[e] * inv);
*(sycl::vec<uint16_t, 8>*)(zp + lane * 8) = u8;
});
else
qu->parallel_for(sycl::nd_range<1>{groups_for(T * Hg * 2, wg) * wg, wg}, [=](sycl::nd_item<1> it) {
const int64_t th = (int64_t)it.get_global_id(0);
if (th >= T * Hg * 2) return;
const int64_t which = th / (T * Hg), rest = th % (T * Hg);
const int64_t t = rest / Hg, h = rest % Hg;
const DT z = which ? io.k : io.q;
const V3 zv = which ? kv : qv;
float ss = 0.0f;
for (int64_t d = 0; d < K; ++d) { const float u = z.ld(at3(zv, t, h, d)); ss += u * u; }
const float inv = 1.0f / sycl::sqrt(ss + l2eps);
for (int64_t d = 0; d < K; ++d) z.st(at3(zv, t, h, d), z.ld(at3(zv, t, h, d)) * inv);
});
/* phase 3: the gate, its per-chunk cumsum, and beta: a work-item a (sequence, head,
* chunk), since the sum restarts at every chunk (48 work-items walked 1882 tokens) */
const int64_t cmax = (T + chunk - 1) / chunk;
qu->parallel_for(sycl::nd_range<1>{groups_for(N * H * cmax, wg) * wg, wg}, [=](sycl::nd_item<1> it) {
const int64_t gid = (int64_t)it.get_global_id(0);
if (gid >= N * H * cmax) return;
const int64_t ci = gid % cmax, nh = gid / cmax;
const int64_t n = nh / H, h = nh % H;
const int64_t bos = cuv.at(n), slen = cuv.at(n + 1) - bos;
if (ci * chunk >= slen) return;
const float alog = alg.p ? alg.ld(h * alg_s) : 0.0f;
const float db = dtb.p ? dtb.ld(h * dtb_s) : 0.0f;
float run = 0.0f;
for (int64_t t = ci * chunk; t < sycl::min(slen, (ci + 1) * chunk); ++t) {
if (t % chunk == 0) run = 0.0f;
const float av_ = has_ta ? tas.ld(at2(av, bos + t, h)) : xs.ld((bos + t) * xrow + (conv_dim + h) * xcol);
const float bvl = has_ta ? tbs.ld(at2(bgv, bos + t, h)) : xs.ld((bos + t) * xrow + (conv_dim + H + h) * xcol);
run += -rexp(alog) * softplus(av_ + db, spthr);
gs.st(at2(gv, bos + t, h), run);
bts.st(at2(bv, bos + t, h), sigm(bvl));
}
});
/* phase 4: rewrite the conv state from the sequence's last width-1 tokens */
if (has_cs && width > 1)
qu->parallel_for(sycl::nd_range<1>{groups_for(N * conv_dim, wg) * wg, wg}, [=](sycl::nd_item<1> it) {
const int64_t nc = (int64_t)it.get_global_id(0);
if (nc >= N * conv_dim) return;
const int64_t n = nc / conv_dim, c = nc % conv_dim;
const int64_t bos = cuv.at(n), slen = cuv.at(n + 1) - bos;
const int64_t slot = siv.on ? siv.at(n) : n;
if (slen <= 0 || slot < 0) return;
const bool warm = !hiv.on || hiv.at(n) != 0;
float keep[kHistMax];
const int64_t sl = width - 1;
for (int64_t i = 0; i < sl; ++i) {
const int64_t src = slen - (width - 1) + i;
keep[i] = src >= 0 ? xs.ld((bos + src) * xrow + c * xcol)
: (warm ? css.ld(at3(cvs, slot, c, src + width - 1)) : 0.0f);
}
for (int64_t i = 0; i < sl; ++i) css.st(at3(cvs, slot, c, i), keep[i]);
});
});
}
/* ------------------------------------------------------------------ gdn_conv_update */
int gdn_conv_update(const RadArgs* a, RadStream st) {
if (!a || a->n_t < 10) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *w = &a->t[1], *cs = &a->t[3], *cu = &a->t[6];
const RadTensor *q = &a->t[7], *k = &a->t[8], *v = &a->t[9];
const RadTensor* bias = rad_arg_in(a, 2);
const RadTensor* sidx = rad_arg_in(a, 4);
const RadTensor* nacc = rad_arg_in(a, 5);
if (!x->data || !w->data || !cs->data || !cu->data || !q->data || !k->data || !v->data)
return RAD_E_INVAL;
const int64_t K = rad_args_geti_or(a, "head_k", 0), V = rad_args_geti_or(a, "head_v", 0);
const int64_t width = rad_args_geti_or(a, "conv_width", 0);
if (K <= 0 || V <= 0 || width <= 0) return RAD_E_SHAPE;
if (width - 1 > kHistMax) return RAD_E_UNSUPPORTED;
const int64_t N = rad_tensor_numel(cu) - 1;
if (N <= 0) return RAD_E_SHAPE;
int64_t T = 0, Hg = 0, Tv = 0, H = 0;
if (!thw(q, K, &T, &Hg) || !thw(v, V, &Tv, &H) || Tv != T)
return refuse("gdn_conv_update: q and v must be [T, heads, width] views");
if (H % Hg != 0) return RAD_E_SHAPE;
const int64_t conv_dim = 2 * Hg * K + H * V;
if (rad_tensor_numel(w) < conv_dim * width) return RAD_E_SHAPE;
const int64_t xrow = x->rank >= 2 ? x->stride[x->rank - 2] : conv_dim;
const int64_t xcol = laststride(x);
const int64_t state_len = cs->rank >= 3 ? cs->shape[cs->rank - 1] : (width > 1 ? width - 1 : 1);
const V3 cvs = v3(cs, conv_dim, state_len);
ConvIO io{};
io.x = dt_of(x); io.w = dt_of(w); io.bias = dt_of(bias); io.q = dt_of(q); io.k = dt_of(k); io.v = dt_of(v);
io.qv = v3(q, Hg, K); io.kv = v3(k, Hg, K); io.vv = v3(v, H, V); io.wv = v2(w, width);
io.xrow = xrow; io.xcol = xcol; io.Hg = Hg; io.H = H; io.K = K; io.V = V; io.width = width;
io.has_bias = bias && bias->data;
io.bias_s = io.has_bias ? laststride(bias) : 0;
const DT xs = dt_of(x), css = dt_of(cs);
const IV cuv = iv_of(cu), siv = iv_of(sidx), nav = iv_of(nacc);
sycl::queue* qu = queue_of(st);
if (!qu) return RAD_E_DEVICE;
const size_t wg = 128;
const auto bf = [](const DT& d) { return d.dt == RAD_BF16; };
if (bf(io.x) && bf(io.w) && bf(css) && bf(io.q) && bf(io.k) && bf(io.v) && xcol == 1 &&
(!io.has_bias || bf(io.bias)) && io.wv.s1 == 1 && !std::getenv("XE2_GDN_GENERIC")) {
/* bf16 throughout (the engine's case): the same loop with typed loads and stores -- the
* generic accessors' dtype switch an element kept the loads from issuing together */
return submit([&] {
qu->parallel_for(sycl::nd_range<1>{groups_for(N * conv_dim, wg) * wg, wg}, [=](sycl::nd_item<1> it) {
const int64_t nc = (int64_t)it.get_global_id(0);
if (nc >= N * conv_dim) return;
const int64_t n = nc / conv_dim, c = nc % conv_dim;
const int64_t bos = cuv.at(n), slen = cuv.at(n + 1) - bos;
if (slen <= 0) return;
const int64_t slot = siv.on ? siv.at(n) : n;
if (slot < 0) return;
const int64_t off = nav.on ? nav.at(n) - 1 : 0;
if (off < 0 || off + width - 1 > state_len || (width > 1 && (width - 2) + slen > state_len)) return;
const uint16_t* xp = (const uint16_t*)xs.p;
uint16_t* sp = (uint16_t*)css.p;
const uint16_t* wp = (const uint16_t*)io.w.p + c * io.wv.s0;
float hist[kHistMax];
for (int64_t i = 0; i < width - 1; ++i) hist[i] = rad_bf16_to_f32(sp[at3(cvs, slot, c, off + i)]);
float wv[kHistMax + 1];
for (int64_t j = 0; j < width; ++j) wv[j] = rad_bf16_to_f32(wp[j]);
uint16_t* outp;
V3 ov;
int64_t oh, od;
if (c < io.Hg * io.K) {
outp = (uint16_t*)io.q.p; ov = io.qv; oh = c / io.K; od = c % io.K;
} else if (c < 2 * io.Hg * io.K) {
outp = (uint16_t*)io.k.p; ov = io.kv; oh = (c - io.Hg * io.K) / io.K; od = (c - io.Hg * io.K) % io.K;
} else {
outp = (uint16_t*)io.v.p; ov = io.vv; oh = (c - 2 * io.Hg * io.K) / io.V; od = (c - 2 * io.Hg * io.K) % io.V;
}
const float bs = io.has_bias ? rad_bf16_to_f32(((const uint16_t*)io.bias.p)[c * io.bias_s]) : 0.0f;
for (int64_t t = 0; t < slen; ++t) {
float acc = bs;
for (int64_t j = 0; j < width; ++j) {
const int64_t src = t - (width - 1) + j;
const float val = src >= 0 ? rad_bf16_to_f32(xp[(bos + src) * xrow + c]) : hist[src + width - 1];
acc += val * wv[j];
}
outp[at3(ov, bos + t, oh, od)] = rad_f32_to_bf16(silu(acc));
}
if (width > 1) {
for (int64_t i = 0; i + 1 < width - 1; ++i) sp[at3(cvs, slot, c, i)] = rad_f32_to_bf16(hist[i + 1]);
for (int64_t t = 0; t < slen; ++t) sp[at3(cvs, slot, c, t + width - 2)] = xp[(bos + t) * xrow + c];
}
});
});
}
return submit([&] {
qu->parallel_for(sycl::nd_range<1>{groups_for(N * conv_dim, wg) * wg, wg}, [=](sycl::nd_item<1> it) {
const int64_t nc = (int64_t)it.get_global_id(0);
if (nc >= N * conv_dim) return;
const int64_t n = nc / conv_dim, c = nc % conv_dim;
const int64_t bos = cuv.at(n), slen = cuv.at(n + 1) - bos;
if (slen <= 0) return;
const int64_t slot = siv.on ? siv.at(n) : n;
if (slot < 0) return;
const int64_t off = nav.on ? nav.at(n) - 1 : 0;
/* libref refuses these before any work; on the card the sequence is skipped. */
if (off < 0 || off + width - 1 > state_len || (width > 1 && (width - 2) + slen > state_len)) return;
float hist[kHistMax];
for (int64_t i = 0; i < width - 1; ++i) hist[i] = css.ld(at3(cvs, slot, c, off + i));
conv_channel(io, c, bos, slen, hist);
if (width > 1) {
for (int64_t i = 0; i + 1 < width - 1; ++i) css.st(at3(cvs, slot, c, i), hist[i + 1]);
for (int64_t t = 0; t < slen; ++t)
css.st(at3(cvs, slot, c, t + width - 2), xs.ld((bos + t) * xrow + c * xcol));
}
});
});
}
/* ------------------------------------------------------------------ gdn_kkt_solve */
int gdn_kkt_solve(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 5)) return RAD_E_INVAL;
const RadTensor *k = &a->t[0], *beta = &a->t[1], *g = &a->t[2], *cu = &a->t[3], *A = &a->t[4];
const int64_t K = rad_args_geti_or(a, "head_k", 0);
const int64_t chunk = rad_args_geti_or(a, "chunk", A->rank >= 3 ? A->shape[A->rank - 1] : 0);
if (K <= 0 || chunk <= 0) return RAD_E_SHAPE;
const int64_t N = rad_tensor_numel(cu) - 1;
if (N <= 0) return RAD_E_SHAPE;
int64_t T = 0, Hg = 0;
if (!thw(k, K, &T, &Hg)) return refuse("gdn_kkt_solve: k must be a [T, heads, head_k] view");
const int64_t H = rad_tensor_numel(beta) / T;
if (H <= 0 || H % Hg != 0) return RAD_E_SHAPE;
if (rad_tensor_numel(A) < T * H * chunk) return RAD_E_SHAPE;
const int64_t grp = H / Hg;
const V3 kv = v3(k, Hg, K), Av = v3(A, H, chunk);
const V2 gv = v2(g, H), bv = v2(beta, H);
const DT ks = dt_of(k), bs = dt_of(beta), gs = dt_of(g), As = dt_of(A);
const IV cuv = iv_of(cu);
sycl::queue* qu = queue_of(st);
if (!qu) return RAD_E_DEVICE;
/* The DPAS form (xe2_gdn_esimd.cpp) for the engine's operands: tolerance-held, so not under
* XE2_EXACT=1; it refuses a layout its 2D loads cannot take, and the exact kernels run. */
if (K == 128 && chunk == 64 && !exact_only() && !std::getenv("XE2_KKT_SERIAL") && ks.dt == RAD_BF16 &&
bs.dt == RAD_F32 && gs.dt == RAD_F32 && As.dt == RAD_BF16 && kv.s2 == 1 && Av.s2 == 1) {
const int rc = gdn_kkt_solve_dpas(*qu, (const uint16_t*)ks.p, kv.s0, kv.s1, (const float*)gs.p, gv.s0, gv.s1,
(const float*)bs.p, bv.s0, bv.s1, (uint16_t*)As.p, Av.s0, Av.s1, cu, T, N,
H, Hg);
if (rc != RAD_E_UNSUPPORTED) return rc;
}
if (chunk == 64 && K <= 128 && !std::getenv("XE2_KKT_SERIAL")) {
/* A work-group a (sequence, v head, chunk): chunks are independent here. The chunk's k rows
* (bf16, exact) in local memory; first every row term beta_i (k_i . k_j) e^{g_i - g_j},
* j < i -- each its sum over d in order -- spread over 256 work-items; then the solve, row
* by row: work-item j < 64 forms s[j] = delta - sum over l in order of row[l] A[l][j], all
* in local memory. libref's chains and order. The form below walked a head's chunks and rows
* in turn on 48 work-groups with its rows in global memory (31 ms a 1882-token call). */
constexpr int CK = 64, KMAX = 128;
constexpr int KR = KMAX + 2; /* k rows padded: neighbouring lanes read different rows */
constexpr int KWG = 512; /* the row terms spread over 512 work-items; the solve uses 64 */
const int64_t cmax = (T + CK - 1) / CK; /* a sequence has at most T tokens */
const bool typed = ks.dt == RAD_BF16 && bs.dt == RAD_F32 && gs.dt == RAD_F32 && As.dt == RAD_BF16 &&
!std::getenv("XE2_GDN_GENERIC");
auto launch = [&](auto ty) {
constexpr bool TY = decltype(ty)::value;
return submit([&] {
qu->submit([&](sycl::handler& hd) {
sycl::local_accessor<uint16_t, 1> kc(sycl::range<1>((size_t)(CK * KR)), hd);
sycl::local_accessor<float, 1> kt(sycl::range<1>((size_t)(CK * CK)), hd);
sycl::local_accessor<float, 1> am(sycl::range<1>((size_t)(CK * CK)), hd);
sycl::local_accessor<float, 1> gb(sycl::range<1>((size_t)(2 * CK)), hd);
hd.parallel_for(sycl::nd_range<1>{(size_t)(N * H * cmax) * KWG, (size_t)KWG}, [=](sycl::nd_item<1> it) {
const int64_t gid = (int64_t)it.get_group(0);
const int64_t ci = gid % cmax, nh = gid / cmax;
const int64_t n = nh / H, h = nh % H, hk = h / grp;
const int t = (int)it.get_local_id(0), j = t;
auto grpw = it.get_group();
const int64_t bos = cuv.at(n), slen = cuv.at(n + 1) - bos;
const int64_t c0 = ci * CK;
if (c0 >= slen) return; /* uniform */
const int L = (int)((c0 + CK < slen) ? CK : slen - c0);
auto LK = [&](int64_t o) -> uint16_t {
if constexpr (TY) return ((const uint16_t*)ks.p)[o];
else return rad_f32_to_bf16(ks.ld(o)); /* only bf16 k reaches here exactly */
};
auto LF = [&](const DT& d, int64_t o) -> float {
if constexpr (TY) return ((const float*)d.p)[o];
else return d.ld(o);
};
if (t < L) {
const int64_t tj = bos + c0 + t;
gb[t] = LF(gs, at2(gv, tj, h));
gb[CK + t] = LF(bs, at2(bv, tj, h));
}
for (int64_t e = t; e < (int64_t)L * K; e += KWG) { /* lanes along d: coalesced */
const int64_t jr = e / K, d = e % K;
kc[jr * KR + d] = LK(at3(kv, bos + c0 + jr, hk, d));
}
sycl::group_barrier(grpw);
for (int p = t; p < L * L; p += KWG) {
const int i = p / L, jj = p % L;
if (jj >= i) continue;
float rj = 0.0f;
for (int64_t d = 0; d < K; ++d)
rj += rad_bf16_to_f32(kc[i * KR + d]) * rad_bf16_to_f32(kc[jj * KR + d]);
kt[i * CK + jj] = gb[CK + i] * rj * rexp(gb[i] - gb[jj]);
}
sycl::group_barrier(grpw);
for (int i = 0; i < L; ++i) {
if (j < CK) {
float v = 0.0f;
if (j <= i) {
float sj = (i == j) ? 1.0f : 0.0f;
for (int l = j; l < i; ++l) sj -= kt[i * CK + l] * am[l * CK + j];
v = sj;
}
am[i * CK + j] = v;
const int64_t o = at3(Av, bos + c0 + i, h, j);
if constexpr (TY) ((uint16_t*)As.p)[o] = rad_f32_to_bf16(v);
else As.st(o, v);
}
sycl::group_barrier(grpw);
}
});
});
});
};
if (typed || ks.dt == RAD_BF16) return typed ? launch(std::true_type{}) : launch(std::false_type{});
}
if (chunk <= 256 && chunk % kSub == 0) {
/* A work-group a (sequence, v head), a work-item a column j of the chunk: for each row i,
* work-item j forms row[j] (its sum over d in order) and then column j of the inverse,
* s[j] = delta - sum over l of row[l] A[l][j] in l order -- libref's chains, spread over j. */
const int64_t need = chunk * chunk + chunk * K;
float* ws = workspace(*qu, (size_t)(N * H * need));
if (!ws) return RAD_E_DEVICE;
const size_t wg = (size_t)chunk;
return submit([&] {
qu->submit([&](sycl::handler& hd) {
sycl::local_accessor<float, 1> row(sycl::range<1>((size_t)chunk), hd);
sycl::local_accessor<float, 1> gcl(sycl::range<1>((size_t)chunk), hd);
hd.parallel_for(sycl::nd_range<1>{(size_t)(N * H) * wg, wg}, [=](sycl::nd_item<1> it) {
const int64_t nh = (int64_t)it.get_group(0);
const int64_t n = nh / H, h = nh % H, hk = h / grp;
const int64_t j = (int64_t)it.get_local_id(0);
auto grpw = it.get_group();
const int64_t bos = cuv.at(n), slen = cuv.at(n + 1) - bos;
float* Am = ws + nh * need;
float* kc = Am + chunk * chunk;
for (int64_t c0 = 0; c0 < slen; c0 += chunk) {
const int64_t L = (c0 + chunk < slen) ? chunk : slen - c0;
sycl::group_barrier(grpw);
if (j < L) {
const int64_t tj = bos + c0 + j;
gcl[j] = gs.ld(at2(gv, tj, h));
for (int64_t d = 0; d < K; ++d) kc[j * K + d] = ks.ld(at3(kv, tj, hk, d));
}
sycl::group_barrier(grpw);
for (int64_t i = 0; i < L; ++i) {
const int64_t ti = bos + c0 + i;
if (j < i) {
const float bi = bs.ld(at2(bv, ti, h));
float rj = 0.0f;
for (int64_t d = 0; d < K; ++d) rj += kc[i * K + d] * kc[j * K + d];
row[j] = bi * rj * rexp(gcl[i] - gcl[j]);
}
sycl::group_barrier(grpw);
if (j <= i) {
float sj = (i == j) ? 1.0f : 0.0f;
for (int64_t l = j; l < i; ++l) sj -= row[l] * Am[l * chunk + j];
Am[i * chunk + j] = sj;
} else {
Am[i * chunk + j] = 0.0f;
}
As.st(at3(Av, ti, h, j), Am[i * chunk + j]);
sycl::group_barrier(grpw);
}
}
});
});
});
}
const int64_t need = chunk * chunk + 3 * chunk + 2 * chunk * K;
float* ws = workspace(*qu, (size_t)(N * H * need));
if (!ws) return RAD_E_DEVICE;
const size_t wg = 32;
return submit([&] {
qu->parallel_for(sycl::nd_range<1>{groups_for(N * H, wg) * wg, wg}, [=](sycl::nd_item<1> it) {
const int64_t nh = (int64_t)it.get_global_id(0);
if (nh >= N * H) return;
const int64_t n = nh / H, h = nh % H, hk = h / grp;
const int64_t bos = cuv.at(n), slen = cuv.at(n + 1) - bos;
float* Am = ws + nh * need;
float* row = Am + chunk * chunk;
float* s = row + chunk;
float* gc = s + chunk;
float* kc = gc + chunk;
float* kT = kc + chunk * K;
for (int64_t c0 = 0; c0 < slen; c0 += chunk) {
const int64_t L = (c0 + chunk < slen) ? chunk : slen - c0;
for (int64_t j = 0; j < L; ++j) {
const int64_t tj = bos + c0 + j;
gc[j] = gs.ld(at2(gv, tj, h));
for (int64_t d = 0; d < K; ++d) {
kc[j * K + d] = ks.ld(at3(kv, tj, hk, d));
kT[d * chunk + j] = kc[j * K + d];
}
}
for (int64_t i = 0; i < L; ++i) {
const int64_t ti = bos + c0 + i;
const float bi = bs.ld(at2(bv, ti, h));
const float gi = gc[i];
for (int64_t j = 0; j < i; ++j) row[j] = 0.0f;
for (int64_t d = 0; d < K; ++d) {
const float kd = kc[i * K + d];
const float* kr = kT + d * chunk;
for (int64_t j = 0; j < i; ++j) row[j] += kd * kr[j];
}
for (int64_t j = 0; j < i; ++j) row[j] = bi * row[j] * rexp(gi - gc[j]);
for (int64_t j = 0; j <= i; ++j) s[j] = (i == j) ? 1.0f : 0.0f;
for (int64_t l = 0; l < i; ++l) {
const float rl = row[l];
const float* al = Am + l * chunk;
for (int64_t j = 0; j <= l; ++j) s[j] -= rl * al[j];
}
for (int64_t j = 0; j <= i; ++j) Am[i * chunk + j] = s[j];
for (int64_t j = i + 1; j < chunk; ++j) Am[i * chunk + j] = 0.0f;
for (int64_t j = 0; j < chunk; ++j) As.st(at3(Av, ti, h, j), Am[i * chunk + j]);
}
}
});
});
}
/* ------------------------------------------------------------------ gdn_chunk_scan */
int gdn_chunk_scan(const RadArgs* a, RadStream st) {
if (!a || a->n_t < 10) return RAD_E_INVAL;
const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *A = &a->t[3];
const RadTensor *g = &a->t[4], *beta = &a->t[5], *cu = &a->t[7];
const RadTensor *o = &a->t[8], *ht = &a->t[9];
const RadTensor* h0 = rad_arg_in(a, 6);
const RadTensor* sidx = rad_arg_in(a, 10);
if (!q->data || !k->data || !v->data || !A->data || !g->data || !beta->data || !cu->data || !o->data)
return RAD_E_INVAL;
const int64_t K = rad_args_geti_or(a, "head_k", 0), V = rad_args_geti_or(a, "head_v", 0);
const int64_t chunk = rad_args_geti_or(a, "chunk", A->rank >= 3 ? A->shape[A->rank - 1] : 0);
const float scale = (float)rad_args_getf_or(a, "scale", 1.0);
if (K <= 0 || V <= 0 || chunk <= 0) return RAD_E_SHAPE;
const int64_t N = rad_tensor_numel(cu) - 1;
if (N <= 0) return RAD_E_SHAPE;
int64_t T = 0, Hg = 0;
if (!thw(q, K, &T, &Hg)) return refuse("gdn_chunk_scan: q must be a [T, heads, head_k] view");
const int64_t H = rad_tensor_numel(beta) / T;
if (H <= 0 || H % Hg != 0) return RAD_E_SHAPE;
const int64_t grp = H / Hg;
if (rad_tensor_numel(o) < T * H * V || rad_tensor_numel(A) < T * H * chunk) return RAD_E_SHAPE;
if (!sidx) {
if (ht->data && rad_tensor_numel(ht) < N * H * V * K) return RAD_E_SHAPE;
if (h0 && h0->data && rad_tensor_numel(h0) < N * H * V * K) return RAD_E_SHAPE;
} else if (sidx->rank < 1 || sidx->shape[0] < N) {
return RAD_E_SHAPE;
}
const V3 qv = v3(q, Hg, K), kv = v3(k, Hg, K), vv = v3(v, H, V), ov = v3(o, H, V);
const V3 Av = v3(A, H, chunk);
const V2 gv = v2(g, H), bv = v2(beta, H);
const bool has_h0 = h0 && h0->data, has_ht = ht->data != nullptr;
const V4 h0v = has_h0 ? v4(h0, H, V, K) : V4{ 0, 0, 0, 0 };
const V4 htv = has_ht ? v4(ht, H, V, K) : V4{ 0, 0, 0, 0 };
const DT qs = dt_of(q), ks = dt_of(k), vs = dt_of(v), As = dt_of(A), gs = dt_of(g), bs = dt_of(beta);
const DT os = dt_of(o), h0s = dt_of(h0), hts = dt_of(ht), sis = dt_of(sidx);
const int64_t sw = sidx && sidx->rank >= 1 ? sidx->stride[0] : 1;
const bool has_si = sidx != nullptr;
const IV cuv = iv_of(cu);
sycl::queue* qu = queue_of(st);
if (!qu) return RAD_E_DEVICE;
/* The DPAS form (xe2_gdn_esimd.cpp) for the engine's operands: tolerance-held, so not under
* XE2_EXACT=1; it refuses a layout its 2D loads cannot take, and the exact kernels run. */
if (K == 128 && V == 128 && chunk == 64 && !exact_only() && !std::getenv("XE2_GDN_SCAN1") && qs.dt == RAD_BF16 &&
ks.dt == RAD_BF16 && vs.dt == RAD_BF16 && As.dt == RAD_BF16 && os.dt == RAD_BF16 && gs.dt == RAD_F32 &&
bs.dt == RAD_F32 && (!has_h0 || h0s.dt == RAD_F32) && (!has_ht || hts.dt == RAD_F32) && qv.s2 == 1 &&
kv.s2 == 1 && vv.s2 == 1 && Av.s2 == 1 && ov.s2 == 1) {
const int64_t h0st[4] = { h0v.s0, h0v.s1, h0v.s2, h0v.s3 }, htst[4] = { htv.s0, htv.s1, htv.s2, htv.s3 };
const int rc = gdn_chunk_scan_dpas(*qu, (const uint16_t*)qs.p, qv.s0, qv.s1, (const uint16_t*)ks.p, kv.s0, kv.s1,
(const uint16_t*)vs.p, vv.s0, vv.s1, (const uint16_t*)As.p, Av.s0, Av.s1,
(const float*)gs.p, gv.s0, gv.s1, (const float*)bs.p, bv.s0, bv.s1,
(uint16_t*)os.p, ov.s0, ov.s1, has_h0 ? (const float*)h0s.p : nullptr, h0st,
has_ht ? (float*)hts.p : nullptr, htst, cu, has_si ? sis.p : nullptr, sis.dt,
sw, T, N, H, Hg, scale);
if (rc != RAD_E_UNSUPPORTED) return rc;
}
if (K == 128 && V % 32 == 0 && chunk == 64 && !std::getenv("XE2_GDN_SCAN1")) {
/* A work-group of 1024 a (sequence, v head, block of 32 value columns), the chunk's k, q,
* the block's slices of v, S, W, V' and the sA rows R in local memory (~124 KB). Each phase
* of a chunk is a set of independent chains -- W[j][e], V'[i][e], R[i][j], O[i][e], S[d][e]
* -- each run by one work-item in libref's order, so the scan is libref's; the parallelism
* is the chains' (thousands a phase), not one column a work-item. R and the decays depend
* only on q, k, g, so each column block forms them again. Its ~124 KB of local memory
* leaves one work-group a Xe core, so the work-group is the core's 1024 work-items: 256
* left three quarters of its threads idle (2.68 -> 0.92 s over a 1882-token prefill). */
constexpr int CB = 32, CK = 64, KK = 128, WG = 1024;
constexpr int KP = KK + 1; /* k and q rows padded: the R phase's lanes read different rows */
const int64_t nblk = V / CB;
/* e^{g_i - g_j} for every (row i, chunk position j <= i of i's chunk), libref's double exp
* rounded once, a (token, head) row of 64: once here instead of once a column block. */
float* dec = workspace(*qu, (size_t)(T * H * CK + 64), 5);
if (!dec) return RAD_E_DEVICE;
if (int rc0 = submit([&] {
qu->parallel_for(sycl::range<1>((size_t)(T * H)), [=](sycl::id<1> id) {
const int64_t th = (int64_t)id[0];
const int64_t tok = th / H, h = th % H;
/* the token's sequence and its chunk start */
int64_t n = 0;
while (n + 1 < N && cuv.at(n + 1) <= tok) ++n;
const int64_t bos = cuv.at(n), c0 = bos + (tok - bos) / CK * CK;
const float gi = gs.ld(at2(gv, tok, h));
for (int64_t j = 0; j < CK; ++j) {
const int64_t tj = c0 + j;
dec[th * CK + j] = tj <= tok ? rexp(gi - gs.ld(at2(gv, tj, h))) : 0.0f;
}
});
});
rc0 < 0)
return rc0;
/* bf16 q, k, v, A and o with f32 g, beta and states (the engine's operands) take typed
* loads and stores: the generic accessors' dtype switch an element made this kernel ~3x
* its probe. The same arithmetic either way. */
const bool typed = qs.dt == RAD_BF16 && ks.dt == RAD_BF16 && vs.dt == RAD_BF16 && As.dt == RAD_BF16 &&
os.dt == RAD_BF16 && gs.dt == RAD_F32 && bs.dt == RAD_F32 &&
(!has_h0 || h0s.dt == RAD_F32) && (!has_ht || hts.dt == RAD_F32) &&
!std::getenv("XE2_GDN_GENERIC");
auto launch = [&](auto ty) {
constexpr bool TY = decltype(ty)::value;
return submit([&] {
qu->submit([&](sycl::handler& hd) {
sycl::local_accessor<float, 1> lm(sycl::range<1>((size_t)(2 * CK * KP + 3 * CK * CB + KK * CB + CK * CK + 4 * CK)), hd);
hd.parallel_for(sycl::nd_range<1>{(size_t)(N * H * nblk) * WG, (size_t)WG}, [=](sycl::nd_item<1> it) {
const int64_t gid = (int64_t)it.get_group(0);
const int64_t blk = gid % nblk, nh = gid / nblk;
const int64_t n = nh / H, h = nh % H, hk = h / grp;
const int64_t e0 = blk * CB;
const int t = (int)it.get_local_id(0);
auto gw = it.get_group();
auto bfl = [](const DT& d, int64_t o) { return rad_bf16_to_f32(((const uint16_t*)d.p)[o]); };
auto f3l = [](const DT& d, int64_t o) { return ((const float*)d.p)[o]; };
auto LB = [&](const DT& d, int64_t o) -> float { if constexpr (TY) return bfl(d, o); else return d.ld(o); };
auto LF = [&](const DT& d, int64_t o) -> float { if constexpr (TY) return f3l(d, o); else return d.ld(o); };
const int64_t bos = cuv.at(n), slen = cuv.at(n + 1) - bos;
const int64_t sn = has_si ? sis.li(n * sw) : n;
if (sn < 0) return; /* uniform */
float* kc = &lm[0]; /* [CK][KP] */
float* qc = kc + CK * KP; /* [CK][KP] */
float* vc = qc + CK * KP; /* [CK][CB] */
float* Wm = vc + CK * CB; /* [CK][CB] */
float* Vp = Wm + CK * CB; /* [CK][CB] */
float* St = Vp + CK * CB; /* [KK][CB] */
float* R = St + KK * CB; /* [CK][CK] */
float* gc = R + CK * CK; /* [CK] */
float* bc = gc + CK;
float* ge = bc + CK; /* e^{g_j} */
float* gsj = ge + CK; /* e^{g_last - g_j} */
for (int idx = t; idx < KK * CB; idx += WG) {
const int d = idx / CB, e = idx % CB;
St[idx] = has_h0 ? LF(h0s, at4(h0v, sn, h, e0 + e, d)) : 0.0f;
}
for (int64_t c0 = 0; c0 < slen; c0 += CK) {
const int64_t L = (c0 + CK < slen) ? CK : slen - c0;
sycl::group_barrier(gw);
for (int idx = t; idx < (int)L * KK; idx += WG) {
const int j = idx / KK, d = idx % KK;
const int64_t tj = bos + c0 + j;
kc[j * KP + d] = LB(ks, at3(kv, tj, hk, d));
qc[j * KP + d] = LB(qs, at3(qv, tj, hk, d));
}
for (int idx = t; idx < (int)L * CB; idx += WG) {
const int j = idx / CB, e = idx % CB;
vc[idx] = LB(vs, at3(vv, bos + c0 + j, h, e0 + e));
}
if (t < L) {
const int64_t tj = bos + c0 + t;
gc[t] = LF(gs, at2(gv, tj, h));
bc[t] = LF(bs, at2(bv, tj, h));
}
sycl::group_barrier(gw);
const float glast = gc[L - 1];
if (t < L) {
ge[t] = rexp(gc[t]);
gsj[t] = rexp(glast - gc[t]);
}
sycl::group_barrier(gw);
/* W[j][e] = beta_j (v[j][e] - e^{g_j} sum_d k[j][d] S[d][e]) */
for (int idx = t; idx < (int)L * CB; idx += WG) {
const int j = idx / CB, e = idx % CB;
float acc = 0.0f;
for (int d = 0; d < KK; ++d) acc += kc[j * KP + d] * St[d * CB + e];
Wm[idx] = bc[j] * (vc[idx] - ge[j] * acc);
}
/* the chunk's rows of A, widened into the R buffer (R is formed after V') */
for (int idx = t; idx < (int)(L * L); idx += WG) {
const int i = idx / (int)L, j = idx % (int)L;
R[i * CK + j] = j <= i ? LB(As, at3(Av, bos + c0 + i, h, j)) : 0.0f;
}
sycl::group_barrier(gw);
/* V'[i][e] = sum_{j <= i} A[i][j] W[j][e] */
for (int idx = t; idx < (int)L * CB; idx += WG) {
const int i = idx / CB, e = idx % CB;
float vp = 0.0f;
for (int j = 0; j <= i; ++j) vp += R[i * CK + j] * Wm[j * CB + e];
Vp[idx] = vp;
}
sycl::group_barrier(gw);
/* R[i][j] = scale e^{g_i - g_j} sum_d q[i][d] k[j][d], j <= i */
for (int idx = t; idx < (int)(L * L); idx += WG) {
const int i = idx / (int)L, j = idx % (int)L;
if (j > i) continue;
float rj = 0.0f;
for (int d = 0; d < KK; ++d) rj += qc[i * KP + d] * kc[j * KP + d];
R[i * CK + j] = scale * dec[((bos + c0 + i) * H + h) * CK + j] * rj;
}
sycl::group_barrier(gw);
/* O[i][e] = scale e^{g_i} sum_d q[i][d] S[d][e] + sum_{j <= i} R[i][j] V'[j][e] */
for (int idx = t; idx < (int)L * CB; idx += WG) {
const int i = idx / CB, e = idx % CB;
float inr = 0.0f;
for (int d = 0; d < KK; ++d) inr += qc[i * KP + d] * St[d * CB + e];
float acc = (scale * ge[i]) * inr;
for (int j = 0; j <= i; ++j) acc += R[i * CK + j] * Vp[j * CB + e];
if constexpr (TY) ((uint16_t*)os.p)[at3(ov, bos + c0 + i, h, e0 + e)] = rad_f32_to_bf16(acc);
else os.st(at3(ov, bos + c0 + i, h, e0 + e), acc);
}
sycl::group_barrier(gw);
/* k[j][d] *= e^{g_last - g_j}; S[d][e] = e^{g_last} S[d][e] + sum_j V'[j][e] k[j][d] */
for (int idx = t; idx < (int)L * KK; idx += WG) {
const int j = idx / KK, d = idx % KK;
kc[j * KP + d] = gsj[j] * kc[j * KP + d];
}
sycl::group_barrier(gw);
const float el = rexp(glast);
for (int idx = t; idx < KK * CB; idx += WG) {
const int d = idx / CB, e = idx % CB;
float sr = el * St[idx];
for (int j = 0; j < (int)L; ++j) sr += Vp[j * CB + e] * kc[j * KP + d];
St[idx] = sr;
}
}
sycl::group_barrier(gw);
if (has_ht)
for (int idx = t; idx < KK * CB; idx += WG) {
const int d = idx / CB, e = idx % CB;
if constexpr (TY) ((float*)hts.p)[at4(htv, sn, h, e0 + e, d)] = St[idx];
else hts.st(at4(htv, sn, h, e0 + e, d), St[idx]);
}
});
});
});
};
return typed ? launch(std::true_type{}) : launch(std::false_type{});
}
if (V % kSub == 0 && V <= 256 && chunk <= V && K * V <= 128 * 128) {
/* A work-group a (sequence, v head), a work-item a value column e (and, for the Q K^T
* rows, a chunk position j): the state in local memory, the chunk's widened operands in
* the workspace. Every element is libref's chain in libref's order: the sums over d for
* K S^T, Q S^T and the rows, over j for V' and O, and the state's decay then sum over j. */
const int64_t need = 3 * chunk * V + 2 * chunk * K + chunk * chunk;
float* ws = workspace(*qu, (size_t)(N * H * need));
if (!ws) return RAD_E_DEVICE;
const size_t wg = (size_t)V;
return submit([&] {
qu->submit([&](sycl::handler& hd) {
sycl::local_accessor<float, 1> St(sycl::range<1>((size_t)(K * V)), hd);
sycl::local_accessor<float, 1> gcb(sycl::range<1>((size_t)(2 * chunk)), hd);
hd.parallel_for(sycl::nd_range<1>{(size_t)(N * H) * wg, wg}, [=](sycl::nd_item<1> it) {
const int64_t nh = (int64_t)it.get_group(0);
const int64_t n = nh / H, h = nh % H, hk = h / grp;
const int64_t e = (int64_t)it.get_local_id(0);
auto gw = it.get_group();
const int64_t bos = cuv.at(n), slen = cuv.at(n + 1) - bos;
const int64_t sn = has_si ? sis.li(n * sw) : n;
if (sn < 0) return; /* uniform */
float* Wm = ws + nh * need;
float* Vp = Wm + chunk * V;
float* vc = Vp + chunk * V;
float* kc = vc + chunk * V;
float* qc = kc + chunk * K;
float* R = qc + chunk * K; /* [chunk, chunk]: row i of sA */
float* gc = &gcb[0];
float* bc = gc + chunk;
for (int64_t d = 0; d < K; ++d) St[d * V + e] = has_h0 ? h0s.ld(at4(h0v, sn, h, e, d)) : 0.0f;
for (int64_t c0 = 0; c0 < slen; c0 += chunk) {
const int64_t L = (c0 + chunk < slen) ? chunk : slen - c0;
sycl::group_barrier(gw);
for (int64_t j = 0; j < L; ++j) {
const int64_t tj = bos + c0 + j;
vc[j * V + e] = vs.ld(at3(vv, tj, h, e));
for (int64_t d = e; d < K; d += V) {
kc[j * K + d] = ks.ld(at3(kv, tj, hk, d));
qc[j * K + d] = qs.ld(at3(qv, tj, hk, d));
}
}
if (e < L) {
const int64_t tj = bos + c0 + e;
gc[e] = gs.ld(at2(gv, tj, h));
bc[e] = bs.ld(at2(bv, tj, h));
}
sycl::group_barrier(gw);
const float glast = gc[L - 1];
/* W = beta . (V - e^{g_j} . (K S^T)) */
for (int64_t j = 0; j < L; ++j) {
const float ge = rexp(gc[j]);
float acc = 0.0f;
for (int64_t d = 0; d < K; ++d) acc += kc[j * K + d] * St[d * V + e];
Wm[j * V + e] = bc[j] * (vc[j * V + e] - ge * acc);
}
/* V' = A W (lane e, sum over j <= i in order) */
for (int64_t i = 0; i < L; ++i) {
const int64_t ti = bos + c0 + i;
float vp = 0.0f;
for (int64_t j = 0; j <= i; ++j) vp += As.ld(at3(Av, ti, h, j)) * Wm[j * V + e];
Vp[i * V + e] = vp;
}
/* the sA rows, lane j: R[i][j] = scale e^{g_i - g_j} sum_d q_i k_j */
if (e < L)
for (int64_t i = e; i < L; ++i) {
float rj = 0.0f;
for (int64_t d = 0; d < K; ++d) rj += qc[i * K + d] * kc[e * K + d];
R[i * chunk + e] = scale * rexp(gc[i] - gc[e]) * rj;
}
sycl::group_barrier(gw);
/* O = scale . e^{g_i} . (Q S^T) + sA V' */
for (int64_t i = 0; i < L; ++i) {
const int64_t ti = bos + c0 + i;
const float sg = scale * rexp(gc[i]);
float inr = 0.0f;
for (int64_t d = 0; d < K; ++d) inr += qc[i * K + d] * St[d * V + e];
float acc = sg * inr;
for (int64_t j = 0; j <= i; ++j) acc += R[i * chunk + j] * Vp[j * V + e];
os.st(at3(ov, ti, h, e), acc);
}
sycl::group_barrier(gw);
/* S = e^{g_last} S + V'^T (e^{g_last - g_j} . K) */
for (int64_t j = 0; j < L; ++j) {
const float gsc = rexp(glast - gc[j]);
for (int64_t d = e; d < K; d += V) kc[j * K + d] = gsc * kc[j * K + d];
}
sycl::group_barrier(gw);
const float el = rexp(glast);
for (int64_t d = 0; d < K; ++d) {
float sr = el * St[d * V + e];
for (int64_t j = 0; j < L; ++j) sr += Vp[j * V + e] * kc[j * K + d];
St[d * V + e] = sr;
}
}
if (has_ht)
for (int64_t d = 0; d < K; ++d) hts.st(at4(htv, sn, h, e, d), St[d * V + e]);
});
});
});
}
const int64_t need = K * V + 3 * chunk * V + 3 * chunk * K + chunk * chunk + 3 * chunk + 2 * V;
float* ws = workspace(*qu, (size_t)(N * H * need));
if (!ws) return RAD_E_DEVICE;
const size_t wg = 16;
return submit([&] {
qu->parallel_for(sycl::nd_range<1>{groups_for(N * H, wg) * wg, wg}, [=](sycl::nd_item<1> it) {
const int64_t nh = (int64_t)it.get_global_id(0);
if (nh >= N * H) return;
const int64_t n = nh / H, h = nh % H, hk = h / grp;
const int64_t bos = cuv.at(n), slen = cuv.at(n + 1) - bos;
const int64_t sn = has_si ? sis.li(n * sw) : n;
if (sn < 0) return;
float* St = ws + nh * need;
float* Wm = St + K * V;
float* Vp = Wm + chunk * V;
float* vc = Vp + chunk * V;
float* kc = vc + chunk * V;
float* qc = kc + chunk * K;
float* kT = qc + chunk * K;
float* Ac = kT + chunk * K;
float* gc = Ac + chunk * chunk;
float* bc = gc + chunk;
float* row = bc + chunk;
float* acc = row + chunk;
float* inr = acc + V;
for (int64_t e = 0; e < V; ++e)
for (int64_t d = 0; d < K; ++d) St[d * V + e] = has_h0 ? h0s.ld(at4(h0v, sn, h, e, d)) : 0.0f;
for (int64_t c0 = 0; c0 < slen; c0 += chunk) {
const int64_t L = (c0 + chunk < slen) ? chunk : slen - c0;
for (int64_t j = 0; j < L; ++j) {
const int64_t tj = bos + c0 + j;
gc[j] = gs.ld(at2(gv, tj, h));
bc[j] = bs.ld(at2(bv, tj, h));
for (int64_t d = 0; d < K; ++d) {
kc[j * K + d] = ks.ld(at3(kv, tj, hk, d));
qc[j * K + d] = qs.ld(at3(qv, tj, hk, d));
kT[d * chunk + j] = kc[j * K + d];
}
for (int64_t e = 0; e < V; ++e) vc[j * V + e] = vs.ld(at3(vv, tj, h, e));
for (int64_t i = 0; i <= j; ++i) Ac[j * chunk + i] = As.ld(at3(Av, tj, h, i));
}
const float glast = gc[L - 1];
for (int64_t j = 0; j < L; ++j) {
const float ge = rexp(gc[j]);
for (int64_t e = 0; e < V; ++e) acc[e] = 0.0f;
for (int64_t d = 0; d < K; ++d) {
const float kd = kc[j * K + d];
const float* sr = St + d * V;
for (int64_t e = 0; e < V; ++e) acc[e] += kd * sr[e];
}
for (int64_t e = 0; e < V; ++e) Wm[j * V + e] = bc[j] * (vc[j * V + e] - ge * acc[e]);
}
for (int64_t i = 0; i < L; ++i) {
float* vp = Vp + i * V;
for (int64_t e = 0; e < V; ++e) vp[e] = 0.0f;
for (int64_t j = 0; j <= i; ++j) {
const float aij = Ac[i * chunk + j];
const float* wr = Wm + j * V;
for (int64_t e = 0; e < V; ++e) vp[e] += aij * wr[e];
}
}
for (int64_t i = 0; i < L; ++i) {
const int64_t ti = bos + c0 + i;
const float gi = gc[i];
const float ge = rexp(gi);
for (int64_t j = 0; j <= i; ++j) row[j] = 0.0f;
for (int64_t d = 0; d < K; ++d) {
const float qd = qc[i * K + d];
const float* kr = kT + d * chunk;
for (int64_t j = 0; j <= i; ++j) row[j] += qd * kr[j];
}
for (int64_t j = 0; j <= i; ++j) row[j] = scale * rexp(gi - gc[j]) * row[j];
for (int64_t e = 0; e < V; ++e) inr[e] = 0.0f;
for (int64_t d = 0; d < K; ++d) {
const float qd = qc[i * K + d];
const float* sr = St + d * V;
for (int64_t e = 0; e < V; ++e) inr[e] += qd * sr[e];
}
const float sg = scale * ge;
for (int64_t e = 0; e < V; ++e) acc[e] = sg * inr[e];
for (int64_t j = 0; j <= i; ++j) {
const float rj = row[j];
const float* vp = Vp + j * V;
for (int64_t e = 0; e < V; ++e) acc[e] += rj * vp[e];
}
for (int64_t e = 0; e < V; ++e) os.st(at3(ov, ti, h, e), acc[e]);
}
const float el = rexp(glast);
for (int64_t j = 0; j < L; ++j) {
const float gsc = rexp(glast - gc[j]);
for (int64_t d = 0; d < K; ++d) kc[j * K + d] = gsc * kc[j * K + d];
}
for (int64_t d = 0; d < K; ++d) {
float* sr = St + d * V;
for (int64_t e = 0; e < V; ++e) sr[e] = el * sr[e];
for (int64_t j = 0; j < L; ++j) {
const float gk = kc[j * K + d];
const float* vp = Vp + j * V;
for (int64_t e = 0; e < V; ++e) sr[e] += vp[e] * gk;
}
}
}
if (has_ht)
for (int64_t e = 0; e < V; ++e)
for (int64_t d = 0; d < K; ++d) hts.st(at4(htv, sn, h, e, d), St[d * V + e]);
});
});
}
/* ------------------------------------------------------------------ gdn_recurrent_update */
namespace {
/* libref's AnchorLayout (the state cache's replay factors, at libr4d's offsets). */
struct Anchor {
int64_t groups, fstr, vb, gb, tmax, mark;
};
Anchor anchor_layout(int64_t K, int64_t V) {
Anchor al;
al.groups = (V + 31) / 32;
al.fstr = al.groups * K + V + 2 * al.groups;
al.vb = al.groups * K;
al.gb = al.groups * K + V;
al.tmax = std::min<int64_t>(16, (V * K - 1) / al.fstr);
al.mark = al.tmax * al.fstr;
return al;
}
struct RecIO {
DT q, k, v, av, bv, state, o, alog, dtb, sidx, z, nw, oq, osc;
V3 qv, kv, vv, ov, zv;
V2 a2, b2, si;
V4 stv;
IV cu, nacc;
Anchor al;
int64_t K, V, Hv, grp, sw, alog_s, dtb_s, nw_s, oq_rs, oq_cs, osc_rs, osc_cs;
float scale, l2eps, neps, spthr;
int nact;
bool anchor, has_si, has_z, has_nw, has_q8;
};
/* One (sequence, v head) of libref's recurrent loop; `St` .. `sk2` its workspace. */
inline void recurrent(const RecIO& r, int64_t n, int64_t h, float* wsp) {
const int64_t K = r.K, V = r.V, hk = h / r.grp;
const int64_t bos = r.cu.at(n), q_len = r.cu.at(n + 1) - bos;
if (q_len <= 0 && !r.anchor) return;
const int64_t na = r.nacc.on ? r.nacc.at(n) : 1;
const int64_t rd = na > 0 ? na - 1 : 0;
int64_t col[6] = { 0, 0, 0, 0, 0, 0 };
int64_t slot_in = 0;
const Anchor& al = r.al;
if (r.anchor) {
if (q_len > al.tmax || na > al.tmax) return; /* libref refuses the launch */
for (int c = 0; c < 6; ++c) col[c] = r.sidx.li(at2(r.si, n, c));
bool pad = false;
for (int c = 0; c < 6; ++c) pad = pad || col[c] < 0;
if (pad) return;
const int64_t fb0 = at4(r.stv, col[4], h, 0, 0);
const int m = (int)(r.state.ld(fb0 + al.mark) + 0.5f) - 1;
slot_in = col[3 - ((m >= 0 && m <= 2) ? m : 1)];
} else {
slot_in = r.has_si ? r.sidx.li(at2(r.si, n, rd < r.sw ? rd : r.sw - 1)) : n;
if (slot_in < 0) return;
}
const int64_t fb = r.anchor ? at4(r.stv, col[4], h, 0, 0) : 0;
const int64_t fbs[3] = { r.anchor ? at4(r.stv, col[3], h, 0, 0) : 0, fb,
r.anchor ? at4(r.stv, col[5], h, 0, 0) : 0 };
const bool dup_f = r.anchor && (col[3] != col[4] || col[5] != col[4]);
float* St = wsp;
float* qn = St + V * K;
float* kn = qn + K;
float* uu = kn + K;
float* orow = uu + V;
float* sk2 = orow + V;
for (int64_t e = 0; e < V; ++e)
for (int64_t d = 0; d < K; ++d) St[d * V + e] = r.state.ld(at4(r.stv, slot_in, h, e, d));
const float alog = r.alog.p ? r.alog.ld(h * r.alog_s) : 0.0f;
const float dtb = r.dtb.p ? r.dtb.ld(h * r.dtb_s) : 0.0f;
auto update = [&](float g, float bt, auto vrow, int64_t e0, int64_t e1) {
const float dec = rexp(g);
for (int64_t e = e0; e < e1; ++e) sk2[e] = 0.0f;
for (int64_t d = 0; d < K; ++d) {
float* sr = St + d * V;
const float kd = kn[d];
for (int64_t e = e0; e < e1; ++e) {
sr[e] *= dec;
sk2[e] += sr[e] * kd;
}
}
for (int64_t e = e0; e < e1; ++e) uu[e] = bt * (vrow(e) - sk2[e]);
for (int64_t d = 0; d < K; ++d) {
float* sr = St + d * V;
const float kd = kn[d];
for (int64_t e = e0; e < e1; ++e) sr[e] += uu[e] * kd;
}
};
if (r.anchor) {
for (int64_t t = 0; t < na; ++t) {
const int64_t f = fb + t * al.fstr;
for (int64_t gi = 0; gi < al.groups; ++gi) {
for (int64_t d = 0; d < K; ++d) kn[d] = r.state.ld(f + gi * K + d);
update(r.state.ld(f + al.gb + 2 * gi), r.state.ld(f + al.gb + 2 * gi + 1),
[&](int64_t e) { return r.state.ld(f + al.vb + e); },
32 * gi, sycl::min(V, 32 * gi + 32));
}
}
for (int64_t e = 0; e < V; ++e)
for (int64_t d = 0; d < K; ++d) r.state.st(at4(r.stv, col[2], h, e, d), St[d * V + e]);
for (int c = 0; c < 3; ++c) r.state.st(fbs[c] + al.mark, (float)(c + 1));
}
for (int64_t t = 0; t < q_len; ++t) {
const int64_t tok = bos + t;
const float gv = -rexp(alog) * softplus(r.av.ld(at2(r.a2, tok, h)) + dtb, r.spthr);
const float bt = sigm(r.bv.ld(at2(r.b2, tok, h)));
float sq = 0.0f, sk = 0.0f;
for (int64_t d = 0; d < K; ++d) {
const float u = r.q.ld(at3(r.qv, tok, hk, d)), w = r.k.ld(at3(r.kv, tok, hk, d));
sq += u * u;
sk += w * w;
}
const float qs = 1.0f / sycl::sqrt(sq + r.l2eps) * r.scale;
const float ks = 1.0f / sycl::sqrt(sk + r.l2eps);
for (int64_t d = 0; d < K; ++d) {
qn[d] = r.q.ld(at3(r.qv, tok, hk, d)) * qs;
kn[d] = r.k.ld(at3(r.kv, tok, hk, d)) * ks;
}
update(gv, bt, [&](int64_t e) { return r.v.ld(at3(r.vv, tok, h, e)); }, 0, V);
for (int64_t e = 0; e < V; ++e) orow[e] = 0.0f;
for (int64_t d = 0; d < K; ++d) {
const float* sr = St + d * V;
const float qd = qn[d];
for (int64_t e = 0; e < V; ++e) orow[e] += sr[e] * qd;
}
if (r.anchor)
for (int c = 0; c < 3; ++c) {
if (c != 1 && !dup_f) continue;
const int64_t f = fbs[c] + t * al.fstr;
for (int64_t gi = 0; gi < al.groups; ++gi) {
for (int64_t d = 0; d < K; ++d) r.state.st(f + gi * K + d, kn[d]);
r.state.st(f + al.gb + 2 * gi, gv);
r.state.st(f + al.gb + 2 * gi + 1, bt);
}
for (int64_t e = 0; e < V; ++e) r.state.st(f + al.vb + e, r.v.ld(at3(r.vv, tok, h, e)));
}
float sq2 = 0.0f;
for (int64_t e = 0; e < V; ++e) sq2 += orow[e] * orow[e];
const float sc = 1.0f / sycl::sqrt(sq2 / (float)V + r.neps);
for (int64_t e = 0; e < V; ++e) {
float x = orow[e] * sc;
if (r.has_nw) x *= r.nw.ld(e * r.nw_s);
if (r.has_z) {
const float zz = r.z.ld(at3(r.zv, tok, h, e));
x *= (r.nact == 1 ? sigm(zz) : silu(zz));
}
r.o.st(at3(r.ov, tok, h, e), x);
}
if (r.has_q8) {
/* q8_group over the stored o, one group a (token, head), 448 for E4M3. */
const int64_t qb = tok * r.oq_rs + h * V * r.oq_cs;
float amax = 0.0f;
for (int64_t e = 0; e < V; ++e) {
const float m = sycl::fabs(r.o.ld(at3(r.ov, tok, h, e)));
if (m > amax) amax = m;
}
const float qsc = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f;
const float inv = 1.0f / qsc;
for (int64_t e = 0; e < V; ++e) {
float c = r.o.ld(at3(r.ov, tok, h, e)) * inv;
if (c > 448.0f) c = 448.0f;
if (c < -448.0f) c = -448.0f;
r.oq.st(qb + e * r.oq_cs, c);
}
r.osc.st(tok * r.osc_rs + h * r.osc_cs, qsc);
}
if (r.anchor) continue;
const int64_t so = r.has_si ? r.sidx.li(at2(r.si, n, t < r.sw ? t : r.sw - 1)) : n;
if (so >= 0)
for (int64_t e = 0; e < V; ++e)
for (int64_t d = 0; d < K; ++d) r.state.st(at4(r.stv, so, h, e, d), St[d * V + e]);
}
}
/* Builds RecIO from libref's operand list (q, k, v, a, b, A_log, dt_bias, state, state_idx,
* num_accepted, cu, z, norm_w, o[, o_q, o_scale]). */
int rec_io(const RadArgs* a, const RadTensor* t, int nt, RecIO* r, int64_t* n_seq, int64_t* tk_out) {
if (nt < 14) return RAD_E_INVAL;
const RadTensor *q = &t[0], *k = &t[1], *v = &t[2], *av = &t[3], *bvt = &t[4];
const RadTensor *state = &t[7], *o = &t[13];
auto in = [&](int i) -> const RadTensor* { return i < nt && t[i].data ? &t[i] : nullptr; };
const RadTensor *A_log = in(5), *dt_bias = in(6), *sidx = in(8), *nacc = in(9), *cu = in(10);
const RadTensor *z = in(11), *nw = in(12), *oq = in(14), *osc = in(15);
if (!q->data || !k->data || !v->data || !av->data || !bvt->data || !state->data || !o->data || !cu)
return RAD_E_INVAL;
const char* sf = rad_args_gets_or(a, "state_form", "per_candidate");
r->anchor = sf && std::strcmp(sf, "anchor") == 0;
if (!r->anchor && sf && std::strcmp(sf, "per_candidate") != 0) return RAD_E_UNSUPPORTED;
r->K = rad_args_geti_or(a, "head_k", 0);
r->V = rad_args_geti_or(a, "head_v", 0);
r->scale = (float)rad_args_getf_or(a, "scale", 1.0);
r->l2eps = (float)rad_args_getf_or(a, "l2_eps", 1e-6);
r->neps = (float)rad_args_getf_or(a, "eps", 1e-6);
r->spthr = (float)rad_args_getf_or(a, "softplus_thr", 20.0);
const char* act = rad_args_gets_or(a, "act", "silu");
if (!std::strcmp(act, "silu")) r->nact = 0;
else if (!std::strcmp(act, "sigmoid")) r->nact = 1;
else return RAD_E_INVAL;
const int64_t K = r->K, V = r->V;
if (K <= 0 || V <= 0) return RAD_E_SHAPE;
int64_t Hv = rad_args_geti_or(a, "n_head_v", 0);
if (Hv <= 0) Hv = v->rank >= 3 ? v->shape[v->rank - 2] : 0;
if (Hv <= 0) return RAD_E_SHAPE;
const int64_t Tk = rad_tensor_numel(v) / (Hv * V);
if (Tk <= 0) return RAD_E_SHAPE;
*tk_out = Tk;
const int64_t Hg = rad_tensor_numel(q) / (Tk * K);
if (Hg <= 0 || Hv % Hg != 0) return RAD_E_SHAPE;
r->Hv = Hv;
r->grp = Hv / Hg;
*n_seq = rad_tensor_numel(cu) - 1;
if (*n_seq <= 0) return RAD_E_SHAPE;
r->sw = sidx ? (sidx->rank >= 2 ? sidx->shape[sidx->rank - 1]
: (rad_tensor_numel(sidx) / *n_seq > 0 ? rad_tensor_numel(sidx) / *n_seq : 1))
: 1;
r->q = dt_of(q); r->k = dt_of(k); r->v = dt_of(v); r->av = dt_of(av); r->bv = dt_of(bvt);
r->state = dt_of(state); r->o = dt_of(o); r->alog = dt_of(A_log); r->dtb = dt_of(dt_bias);
r->sidx = dt_of(sidx); r->z = dt_of(z); r->nw = dt_of(nw); r->oq = dt_of(oq); r->osc = dt_of(osc);
r->qv = v3(q, Hg, K); r->kv = v3(k, Hg, K); r->vv = v3(v, Hv, V); r->ov = v3(o, Hv, V);
r->zv = z ? v3_rows(z, Hv, V) : r->vv;
r->a2 = v2(av, Hv); r->b2 = v2(bvt, Hv);
r->si = sidx ? v2(sidx, r->sw) : V2{ 0, 0 };
r->stv = v4(state, Hv, V, K);
r->cu = iv_of(cu); r->nacc = iv_of(nacc);
r->al = anchor_layout(K, V);
r->alog_s = A_log ? laststride(A_log) : 0;
r->dtb_s = dt_bias ? laststride(dt_bias) : 0;
r->nw_s = nw ? laststride(nw) : 0;
r->has_si = sidx != nullptr;
r->has_z = z != nullptr;
r->has_nw = nw != nullptr;
r->has_q8 = oq && osc;
if (r->has_q8) {
Rows qr, sr;
if (int rc = rows_view(oq, Hv * V, &qr, "gdn o_q"); rc < 0) return rc;
if (int rc = rows_view(osc, Hv, &sr, "gdn o_scale"); rc < 0) return rc;
r->oq_rs = qr.pitch; r->oq_cs = laststride(oq);
r->osc_rs = sr.pitch; r->osc_cs = laststride(osc);
}
if (r->anchor) {
if (!sidx || r->sw < 6) return RAD_E_SHAPE;
if (r->stv.s3 != 1 || r->stv.s2 != K) return RAD_E_STRIDE;
if (r->al.tmax < 1) return RAD_E_SHAPE;
}
return RAD_OK;
}
/* The same step spread over value columns. Kernel A: a 16-lane work-group a (sequence, v head,
* block of 16 columns e), its 128 x 16 slice of the state in local memory (read and written a
* state row at a time with the lanes along d, coalesced): every chain libref forms runs over d, so
* each column is libref's arithmetic, and the un-normalised output column goes to a scratch row.
* Kernel B: a work-group a (token, v head) for the gated RMS norm -- its sum over e serial in e
* order on one work-item, as libref's -- and the folded fp8 group. 384 work-groups a 27B layer
* instead of 48. */
constexpr int64_t kCb = 16; /* columns a work-group of kernel A */
/* Whether sequence n is stepped at all -- the early returns of libref's loop, which leave its o
* rows untouched. */
inline bool seq_active(const RecIO& r, int64_t n) {
const int64_t q_len = r.cu.at(n + 1) - r.cu.at(n);
if (q_len <= 0 && !r.anchor) return false;
const int64_t na = r.nacc.on ? r.nacc.at(n) : 1;
if (r.anchor) {
if (q_len > r.al.tmax || na > r.al.tmax) return false;
for (int c = 0; c < 6; ++c)
if (r.sidx.li(at2(r.si, n, c)) < 0) return false;
return true;
}
const int64_t rd = na > 0 ? na - 1 : 0;
const int64_t slot_in = r.has_si ? r.sidx.li(at2(r.si, n, rd < r.sw ? rd : r.sw - 1)) : n;
return slot_in >= 0;
}
constexpr int64_t kWgMaxV = 256;
constexpr int64_t kWgMaxK = 256;
constexpr int kRegK = 128;
constexpr int kBRegs = (int)(kWgMaxV / kSub); /* kernel B's columns a lane */
int launch_recurrent_reg(sycl::queue& qu, const RecIO& r, int64_t n_seq, float* orow, const float* gates);
int launch_recurrent_fused(sycl::queue& qu, const RecIO& r, int64_t n_seq, int64_t Tk);
int launch_recurrent_wg(sycl::queue& qu, const RecIO& r, int64_t n_seq, int64_t Tk) {
const int64_t K = r.K, V = r.V, Hv = r.Hv;
const int64_t nblk = V / kCb;
if (int rc = launch_recurrent_fused(qu, r, n_seq, Tk); rc != RAD_E_UNSUPPORTED) return rc;
float* orow = workspace(qu, (size_t)(Tk * Hv * V + 64), 3);
if (!orow) return RAD_E_DEVICE;
/* Each token's gate, beta and decay -- libref's double exp / log1p, which this card emulates --
* once a (token, head) here, not once a block below: [Tk][Hv][3]. */
float* gates = workspace(qu, (size_t)(Tk * Hv * 3 + 64), 4);
if (!gates) return RAD_E_DEVICE;
if (int rc0 = submit([&] {
qu.parallel_for(sycl::range<1>((size_t)(Tk * Hv)), [=](sycl::id<1> i) {
const int64_t tok = (int64_t)i[0] / Hv, h = (int64_t)i[0] % Hv;
const float alog = r.alog.p ? r.alog.ld(h * r.alog_s) : 0.0f;
const float dtb = r.dtb.p ? r.dtb.ld(h * r.dtb_s) : 0.0f;
const float gv = -rexp(alog) * softplus(r.av.ld(at2(r.a2, tok, h)) + dtb, r.spthr);
gates[i[0] * 3 + 0] = gv;
gates[i[0] * 3 + 1] = sigm(r.bv.ld(at2(r.b2, tok, h)));
gates[i[0] * 3 + 2] = rexp(gv);
});
});
rc0 < 0)
return rc0;
/* Under `anchor` the replay is its own launch (phase 0): every block reads the stamp and the
* previous step's factors before any block of the head overwrites them in phase 1. */
int rc = RAD_OK;
if (K == kRegK && !std::getenv("XE2_GDN_SLM")) {
rc = launch_recurrent_reg(qu, r, n_seq, orow, gates);
} else
for (int phase = r.anchor ? 0 : 1; phase <= 1 && rc >= 0; ++phase)
rc = submit([&] {
qu.submit([&](sycl::handler& hd) {
sycl::local_accessor<float, 1> St(sycl::range<1>((size_t)(K * kCb)), hd);
sycl::local_accessor<float, 1> vec(sycl::range<1>((size_t)(4 * K)), hd);
hd.parallel_for(sycl::nd_range<1>{(size_t)(n_seq * Hv * nblk) * kCb, (size_t)kCb},
[=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] {
const int64_t gid = (int64_t)it.get_group(0);
const int64_t blk = gid % nblk, nh = gid / nblk;
const int64_t n = nh / Hv, h = nh % Hv, hk = h / r.grp;
const int64_t l = (int64_t)it.get_local_id(0);
const int64_t e0 = blk * kCb, e = e0 + l;
auto grp = it.get_group();
float* qn = &vec[0];
float* kn = qn + K;
float* qraw = kn + K;
float* kraw = qraw + K;
const int64_t bos = r.cu.at(n), q_len = r.cu.at(n + 1) - bos;
if (q_len <= 0 && !r.anchor) return; /* uniform */
const int64_t na = r.nacc.on ? r.nacc.at(n) : 1;
const int64_t rd = na > 0 ? na - 1 : 0;
const Anchor& al = r.al;
int64_t col[6] = { 0, 0, 0, 0, 0, 0 };
int64_t slot_in = 0;
if (r.anchor) {
if (q_len > al.tmax || na > al.tmax) return;
for (int c = 0; c < 6; ++c) col[c] = r.sidx.li(at2(r.si, n, c));
bool pad = false;
for (int c = 0; c < 6; ++c) pad = pad || col[c] < 0;
if (pad) return;
if (phase == 0) {
const int64_t fb0 = at4(r.stv, col[4], h, 0, 0);
const int m = (int)(r.state.ld(fb0 + al.mark) + 0.5f) - 1;
slot_in = col[3 - ((m >= 0 && m <= 2) ? m : 1)];
} else {
slot_in = col[2]; /* the anchor phase 0 published */
}
} else {
slot_in = r.has_si ? r.sidx.li(at2(r.si, n, rd < r.sw ? rd : r.sw - 1)) : n;
if (slot_in < 0) return;
}
const int64_t fb = r.anchor ? at4(r.stv, col[4], h, 0, 0) : 0;
const int64_t fbs[3] = { r.anchor ? at4(r.stv, col[3], h, 0, 0) : 0, fb,
r.anchor ? at4(r.stv, col[5], h, 0, 0) : 0 };
const bool dup_f = r.anchor && (col[3] != col[4] || col[5] != col[4]);
auto load_state = [&](int64_t slot) {
for (int64_t ee = 0; ee < kCb; ++ee)
for (int64_t d = l; d < K; d += kCb) St[d * kCb + ee] = r.state.ld(at4(r.stv, slot, h, e0 + ee, d));
};
auto store_state = [&](int64_t slot) {
for (int64_t ee = 0; ee < kCb; ++ee)
for (int64_t d = l; d < K; d += kCb) r.state.st(at4(r.stv, slot, h, e0 + ee, d), St[d * kCb + ee]);
};
load_state(slot_in);
sycl::group_barrier(grp);
auto update_dec = [&](float dec, float bt, float ve) {
float sk2 = 0.0f;
for (int64_t d = 0; d < K; ++d) {
St[d * kCb + l] *= dec;
sk2 += St[d * kCb + l] * kn[d];
}
const float uu = bt * (ve - sk2);
for (int64_t d = 0; d < K; ++d) St[d * kCb + l] += uu * kn[d];
};
auto update_col = [&](float g, float bt, float ve) { update_dec(rexp(g), bt, ve); };
if (r.anchor && phase == 0) {
for (int64_t t = 0; t < na; ++t) {
const int64_t f = fb + t * al.fstr;
for (int64_t gi = 0; gi < al.groups; ++gi) {
sycl::group_barrier(grp);
for (int64_t d = l; d < K; d += kCb) kn[d] = r.state.ld(f + gi * K + d);
sycl::group_barrier(grp);
if (e >= 32 * gi && e < sycl::min(V, 32 * gi + 32))
update_col(r.state.ld(f + al.gb + 2 * gi), r.state.ld(f + al.gb + 2 * gi + 1),
r.state.ld(f + al.vb + e));
}
}
sycl::group_barrier(grp);
store_state(col[2]);
return;
}
if (r.anchor && blk == 0 && l == 0)
for (int c = 0; c < 3; ++c) r.state.st(fbs[c] + al.mark, (float)(c + 1));
for (int64_t t = 0; t < q_len; ++t) {
const int64_t tok = bos + t;
const float gv = gates[(tok * Hv + h) * 3 + 0];
const float bt = gates[(tok * Hv + h) * 3 + 1];
const float dec = gates[(tok * Hv + h) * 3 + 2];
sycl::group_barrier(grp);
for (int64_t d = l; d < K; d += kCb) {
qraw[d] = r.q.ld(at3(r.qv, tok, hk, d));
kraw[d] = r.k.ld(at3(r.kv, tok, hk, d));
}
sycl::group_barrier(grp);
float sq = 0.0f, sk = 0.0f; /* every work-item, the same chain */
for (int64_t d = 0; d < K; ++d) {
sq += qraw[d] * qraw[d];
sk += kraw[d] * kraw[d];
}
const float qs = 1.0f / sycl::sqrt(sq + r.l2eps) * r.scale;
const float ks = 1.0f / sycl::sqrt(sk + r.l2eps);
for (int64_t d = l; d < K; d += kCb) {
qn[d] = qraw[d] * qs;
kn[d] = kraw[d] * ks;
}
sycl::group_barrier(grp);
update_dec(dec, bt, r.v.ld(at3(r.vv, tok, h, e)));
float oe = 0.0f;
for (int64_t d = 0; d < K; ++d) oe += St[d * kCb + l] * qn[d];
orow[(tok * Hv + h) * V + e] = oe;
if (r.anchor)
for (int c = 0; c < 3; ++c) {
if (c != 1 && !dup_f) continue;
const int64_t f = fbs[c] + t * al.fstr;
if (blk == 0)
for (int64_t gi = 0; gi < al.groups; ++gi) {
for (int64_t d = l; d < K; d += kCb) r.state.st(f + gi * K + d, kn[d]);
if (l == 0) {
r.state.st(f + al.gb + 2 * gi, gv);
r.state.st(f + al.gb + 2 * gi + 1, bt);
}
}
r.state.st(f + al.vb + e, r.v.ld(at3(r.vv, tok, h, e)));
}
if (r.anchor) continue;
const int64_t so = r.has_si ? r.sidx.li(at2(r.si, n, t < r.sw ? t : r.sw - 1)) : n;
if (so >= 0) { /* uniform */
sycl::group_barrier(grp);
store_state(so);
}
}
});
});
});
if (rc < 0) return rc;
/* kernel B: the gated RMS norm and the fp8 group, a sub-group a (token, head), its V columns
* kSub apart in each lane's registers. The sum over e is libref's chain, lane by lane in e
* order; the amax is a maximum, exact in any order. One wave of Tk * Hv threads: a work-group
* of V work-items a (token, head), each a few dependent steps of latency, took ~2.4 waves of
* the card's threads: 31.8 -> 24.9 us a call at Tk = 8, Hv = 48. */
if (V % kSub == 0 && V / kSub <= kBRegs && !std::getenv("XE2_GDN_NORM_WG")) {
constexpr size_t kSgs = 8; /* sub-groups a work-group */
const int64_t rows = Tk * Hv;
return submit([&] {
qu.parallel_for(sycl::nd_range<1>{(size_t)((rows + kSgs - 1) / kSgs) * kSgs * kSub, kSgs * kSub},
[=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] {
const sycl::sub_group sg = it.get_sub_group();
const int64_t th = (int64_t)(it.get_global_id(0) / kSub);
if (th >= rows) return; /* uniform across the sub-group */
const int64_t tok = th / Hv, h = th % Hv;
const int l = (int)sg.get_local_linear_id();
const int nj = (int)(V / kSub);
int64_t n = 0;
while (n + 1 < n_seq && r.cu.at(n + 1) <= tok) ++n;
if (!seq_active(r, n)) return;
float ov[kBRegs];
for (int j = 0; j < kBRegs; ++j) ov[j] = j < nj ? orow[th * V + j * kSub + l] : 0.0f;
float sq2 = 0.0f;
for (int j = 0; j < kBRegs; ++j) {
if (j >= nj) break;
for (int i = 0; i < kSub; ++i) {
const float v = sycl::select_from_group(sg, ov[j], i);
sq2 += v * v;
}
}
const float sc = 1.0f / sycl::sqrt(sq2 / (float)V + r.neps);
float amax = 0.0f;
for (int j = 0; j < kBRegs; ++j) {
if (j >= nj) break;
const int64_t e = j * kSub + l;
float x = ov[j] * sc;
if (r.has_nw) x *= r.nw.ld(e * r.nw_s);
if (r.has_z) {
const float zz = r.z.ld(at3(r.zv, tok, h, e));
x *= (r.nact == 1 ? sigm(zz) : silu(zz));
}
r.o.st(at3(r.ov, tok, h, e), x);
if (r.has_q8) {
ov[j] = r.o.ld(at3(r.ov, tok, h, e));
amax = sycl::maximum<float>()(amax, sycl::fabs(ov[j]));
}
}
if (!r.has_q8) return;
amax = sycl::reduce_over_group(sg, amax, sycl::maximum<float>());
const float qsc = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f;
const float inv = 1.0f / qsc;
for (int j = 0; j < kBRegs; ++j) {
if (j >= nj) break;
const int64_t e = j * kSub + l;
float c = ov[j] * inv;
if (c > 448.0f) c = 448.0f;
if (c < -448.0f) c = -448.0f;
r.oq.st(tok * r.oq_rs + h * V * r.oq_cs + e * r.oq_cs, c);
}
if (l == 0) r.osc.st(tok * r.osc_rs + h * r.osc_cs, qsc);
});
});
}
return submit([&] {
qu.submit([&](sycl::handler& hd) {
sycl::local_accessor<float, 1> ob(sycl::range<1>((size_t)V), hd);
hd.parallel_for(sycl::nd_range<1>{(size_t)(Tk * Hv) * (size_t)V, (size_t)V}, [=](sycl::nd_item<1> it) {
const int64_t th = (int64_t)it.get_group(0);
const int64_t tok = th / Hv, h = th % Hv;
const int64_t e = (int64_t)it.get_local_id(0);
auto grp = it.get_group();
/* the token's sequence, and whether kernel A stepped it */
int64_t n = 0;
while (n + 1 < n_seq && r.cu.at(n + 1) <= tok) ++n;
if (!seq_active(r, n)) return; /* uniform: libref leaves these rows as they are */
const float oe = orow[th * V + e];
ob[e] = oe;
sycl::group_barrier(grp);
float sc = 0.0f;
if (e == 0) {
float sq2 = 0.0f;
for (int64_t i = 0; i < V; ++i) sq2 += ob[i] * ob[i];
sc = 1.0f / sycl::sqrt(sq2 / (float)V + r.neps);
}
sc = sycl::group_broadcast(grp, sc, 0);
float x = oe * sc;
if (r.has_nw) x *= r.nw.ld(e * r.nw_s);
if (r.has_z) {
const float zz = r.z.ld(at3(r.zv, tok, h, e));
x *= (r.nact == 1 ? sigm(zz) : silu(zz));
}
r.o.st(at3(r.ov, tok, h, e), x);
if (r.has_q8) {
const float stored = r.o.ld(at3(r.ov, tok, h, e));
const float amax = sycl::reduce_over_group(grp, sycl::fabs(stored), sycl::maximum<float>());
const float qsc = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f;
const float inv = 1.0f / qsc;
float c = stored * inv;
if (c > 448.0f) c = 448.0f;
if (c < -448.0f) c = -448.0f;
r.oq.st(tok * r.oq_rs + h * V * r.oq_cs + e * r.oq_cs, c);
if (e == 0) r.osc.st(tok * r.osc_rs + h * r.osc_cs, qsc);
}
});
});
});
}
/* Kernel A with the state in registers, for head_k = 128: a lane's value column of the block is
* st[0..127] (the large register file), k and q spread over the 16 lanes and read by compile-time
* broadcasts. Every chain is the one above (over d in order), so the result is the same, without
* the local-memory round trips a column's three passes over d cost there. */
/* QT: the staged q, k and v as stored (uint16_t bf16, float, or void for any dtype); COAL: an f32
* state with contiguous 16-byte aligned rows, a lane's row loaded and stored as 16-byte vectors.
* The generic accessors switch on the dtype at every element, which kept the 128 loads of a row
* from issuing together: 8x the probe's time. (Staging the block's 16 rows through local memory
* instead, coalesced, took 8.3 KB a 16-lane work-group: ~300 of the 384 fit the card at once, and
* the phase ran in two waves -- 39.6 against 24.7 us in probe rec2.cpp.) */
template <class QT, bool COAL, bool FUSED>
int launch_recurrent_reg_t(sycl::queue& qu, const RecIO& r, int64_t n_seq, float* orow, const float* gates,
int64_t Tk) {
const int64_t V = r.V, Hv = r.Hv;
const int64_t nblk = V / kCb;
namespace intelex = sycl::ext::intel::experimental;
syclex::properties props{intelex::grf_size<256>};
int rc = RAD_OK;
/* FUSED: one launch, both phases, the gates and kernel B's epilogue in it (see launch_recurrent_wg) */
for (int phase = (r.anchor && !FUSED) ? 0 : 1; phase <= 1 && rc >= 0; ++phase)
rc = submit([&] {
qu.submit([&](sycl::handler& hd) {
sycl::local_accessor<float, 1> os(sycl::range<1>(FUSED ? (size_t)(Tk * V) : 1), hd);
const size_t wg = FUSED ? (size_t)V : (size_t)kCb;
hd.parallel_for(sycl::nd_range<1>{(size_t)(n_seq * Hv * nblk) * kCb, wg}, props,
[=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] {
constexpr int K = kRegK;
char* const sp = r.state.p;
const uint32_t sdt = r.state.dt;
auto LS = [&](int64_t o) -> float {
if constexpr (COAL) return ((const float*)sp)[o];
else return rad_load_f32(sp, sdt, o);
};
auto SS = [&](int64_t o, float v) {
if constexpr (COAL) ((float*)sp)[o] = v;
else rad_store_f32(sp, sdt, o, v);
};
auto LQ = [&](const DT& d, int64_t o) -> float {
if constexpr (std::is_same_v<QT, uint16_t>) return rad_bf16_to_f32(((const uint16_t*)d.p)[o]);
else if constexpr (std::is_same_v<QT, float>) return ((const float*)d.p)[o];
else return d.ld(o);
};
const sycl::sub_group sg = it.get_sub_group();
const int64_t gid = (int64_t)it.get_group(0);
const int64_t blk = FUSED ? (int64_t)sg.get_group_linear_id() : gid % nblk;
const int64_t nh = FUSED ? gid : gid / nblk;
const int64_t n = nh / Hv, h = nh % Hv, hk = h / r.grp;
const int l = (int)sg.get_local_linear_id();
const int64_t e0 = blk * kCb, e = e0 + l;
const int64_t bos = r.cu.at(n), q_len = r.cu.at(n + 1) - bos;
if (q_len <= 0 && !r.anchor) return;
const int64_t na = r.nacc.on ? r.nacc.at(n) : 1;
const int64_t rd = na > 0 ? na - 1 : 0;
const Anchor& al = r.al;
int64_t col[6] = { 0, 0, 0, 0, 0, 0 };
int64_t slot_in = 0;
if (r.anchor) {
if (q_len > al.tmax || na > al.tmax) return;
for (int c = 0; c < 6; ++c) col[c] = r.sidx.li(at2(r.si, n, c));
bool pad = false;
for (int c = 0; c < 6; ++c) pad = pad || col[c] < 0;
if (pad) return;
if (FUSED || phase == 0) {
const int64_t fb0 = at4(r.stv, col[4], h, 0, 0);
const int m = (int)(LS(fb0 + al.mark) + 0.5f) - 1;
slot_in = col[3 - ((m >= 0 && m <= 2) ? m : 1)];
} else {
slot_in = col[2];
}
} else {
slot_in = r.has_si ? r.sidx.li(at2(r.si, n, rd < r.sw ? rd : r.sw - 1)) : n;
if (slot_in < 0) return;
}
const int64_t fb = r.anchor ? at4(r.stv, col[4], h, 0, 0) : 0;
const int64_t fbs[3] = { r.anchor ? at4(r.stv, col[3], h, 0, 0) : 0, fb,
r.anchor ? at4(r.stv, col[5], h, 0, 0) : 0 };
const bool dup_f = r.anchor && (col[3] != col[4] || col[5] != col[4]);
float st[K];
auto load_rows = [&](int64_t slot) {
if constexpr (COAL) {
/* the lane's own row, 512 contiguous bytes, as 16-byte loads */
const sycl::float4* row = (const sycl::float4*)((const float*)sp + at4(r.stv, slot, h, e, 0));
for (int i = 0; i < K / 4; ++i) {
const sycl::float4 x = row[i];
st[4 * i] = x[0]; st[4 * i + 1] = x[1]; st[4 * i + 2] = x[2]; st[4 * i + 3] = x[3];
}
} else {
for (int d = 0; d < K; ++d) st[d] = LS(at4(r.stv, slot, h, e, d));
}
};
auto store_rows = [&](int64_t slot) {
if constexpr (COAL) {
sycl::float4* row = (sycl::float4*)((float*)sp + at4(r.stv, slot, h, e, 0));
for (int i = 0; i < K / 4; ++i)
row[i] = sycl::float4(st[4 * i], st[4 * i + 1], st[4 * i + 2], st[4 * i + 3]);
} else {
for (int d = 0; d < K; ++d) SS(at4(r.stv, slot, h, e, d), st[d]);
}
};
load_rows(slot_in);
float knv[K / kSub]; /* kn[16 j + lane] */
auto kn_at = [&](int d) { return sycl::select_from_group(sg, knv[d / kSub], d % kSub); };
auto update = [&](float dec, float bt, float ve) {
float sk2 = 0.0f;
for (int d = 0; d < K; ++d) {
st[d] *= dec;
sk2 += st[d] * kn_at(d);
}
const float uu = bt * (ve - sk2);
for (int d = 0; d < K; ++d) st[d] += uu * kn_at(d);
};
if (r.anchor && (FUSED || phase == 0)) {
/* the block's 32-column group; its replay decays, one token a lane (the
* double exp is emulated: a chain of na of them was most of this phase) */
const int64_t gi = e0 / 32;
const float decl = l < na ? rexp(LS(fb + l * al.fstr + al.gb + 2 * gi)) : 0.0f;
for (int64_t t = 0; t < na; ++t) {
const int64_t f = fb + t * al.fstr;
for (int j = 0; j < K / kSub; ++j) knv[j] = LS(f + gi * K + j * kSub + l);
update(sycl::select_from_group(sg, decl, (int)t), LS(f + al.gb + 2 * gi + 1),
LS(f + al.vb + e));
}
store_rows(col[2]);
/* the head's replay reads the factors and the stamp that its token pass
* overwrites below: every block done reading first */
if constexpr (FUSED) sycl::group_barrier(it.get_group());
else return;
}
if (r.anchor && blk == 0 && l == 0)
for (int c = 0; c < 3; ++c) SS(fbs[c] + al.mark, (float)(c + 1));
float g_l[3] = { 0.0f, 0.0f, 0.0f }; /* FUSED: token (t & ~15) + lane's gates */
for (int64_t t = 0; t < q_len; ++t) {
const int64_t tok = bos + t;
float gv, bt, dec;
if constexpr (FUSED) {
/* the gates kernel's arithmetic, sixteen tokens at a time, a token a lane */
if ((t & 15) == 0 && t + l < q_len) {
const float alog = r.alog.p ? r.alog.ld(h * r.alog_s) : 0.0f;
const float dtb = r.dtb.p ? r.dtb.ld(h * r.dtb_s) : 0.0f;
g_l[0] = -rexp(alog) * softplus(r.av.ld(at2(r.a2, tok + l, h)) + dtb, r.spthr);
g_l[1] = sigm(r.bv.ld(at2(r.b2, tok + l, h)));
g_l[2] = rexp(g_l[0]);
}
gv = sycl::select_from_group(sg, g_l[0], (int)(t & 15));
bt = sycl::select_from_group(sg, g_l[1], (int)(t & 15));
dec = sycl::select_from_group(sg, g_l[2], (int)(t & 15));
} else {
gv = gates[(tok * Hv + h) * 3 + 0];
bt = gates[(tok * Hv + h) * 3 + 1];
dec = gates[(tok * Hv + h) * 3 + 2];
}
float qv[K / kSub], kv[K / kSub];
for (int j = 0; j < K / kSub; ++j) {
qv[j] = LQ(r.q, at3(r.qv, tok, hk, j * kSub + l));
kv[j] = LQ(r.k, at3(r.kv, tok, hk, j * kSub + l));
}
float sq = 0.0f, sk = 0.0f; /* libref's chains, d in order, in every lane */
for (int d = 0; d < K; ++d) {
const float u = sycl::select_from_group(sg, qv[d / kSub], d % kSub);
const float w = sycl::select_from_group(sg, kv[d / kSub], d % kSub);
sq += u * u;
sk += w * w;
}
const float qs = 1.0f / sycl::sqrt(sq + r.l2eps) * r.scale;
const float ks = 1.0f / sycl::sqrt(sk + r.l2eps);
float qnv[K / kSub];
for (int j = 0; j < K / kSub; ++j) {
qnv[j] = qv[j] * qs;
knv[j] = kv[j] * ks;
}
update(dec, bt, LQ(r.v, at3(r.vv, tok, h, e)));
float oe = 0.0f;
for (int d = 0; d < K; ++d) oe += st[d] * sycl::select_from_group(sg, qnv[d / kSub], d % kSub);
if constexpr (FUSED) os[t * V + e] = oe;
else orow[(tok * Hv + h) * V + e] = oe;
if (r.anchor)
for (int c = 0; c < 3; ++c) {
if (c != 1 && !dup_f) continue;
const int64_t f = fbs[c] + t * al.fstr;
if (blk == 0)
for (int64_t gi = 0; gi < al.groups; ++gi) {
for (int j = 0; j < K / kSub; ++j) SS(f + gi * K + j * kSub + l, knv[j]);
if (l == 0) {
SS(f + al.gb + 2 * gi, gv);
SS(f + al.gb + 2 * gi + 1, bt);
}
}
SS(f + al.vb + e, LQ(r.v, at3(r.vv, tok, h, e)));
}
if (r.anchor) continue;
const int64_t so = r.has_si ? r.sidx.li(at2(r.si, n, t < r.sw ? t : r.sw - 1)) : n;
if (so >= 0) store_rows(so); /* uniform */
}
if constexpr (FUSED) {
/* kernel B's epilogue, a sub-group a token, from the outputs in local memory */
sycl::group_barrier(it.get_group());
for (int64_t t = blk; t < q_len; t += nblk) {
const int64_t tok = bos + t;
float ov[K / kSub];
for (int j = 0; j < K / kSub; ++j) ov[j] = j < nblk ? os[t * V + j * kSub + l] : 0.0f;
float sq2 = 0.0f;
for (int j = 0; j < K / kSub; ++j) {
if (j >= nblk) break;
for (int i = 0; i < kSub; ++i) {
const float v = sycl::select_from_group(sg, ov[j], i);
sq2 += v * v;
}
}
const float sc = 1.0f / sycl::sqrt(sq2 / (float)V + r.neps);
float amax = 0.0f;
for (int j = 0; j < K / kSub; ++j) {
if (j >= nblk) break;
const int64_t ee = j * kSub + l;
float x = ov[j] * sc;
if (r.has_nw) x *= r.nw.ld(ee * r.nw_s);
if (r.has_z) {
const float zz = r.z.ld(at3(r.zv, tok, h, ee));
x *= (r.nact == 1 ? sigm(zz) : silu(zz));
}
r.o.st(at3(r.ov, tok, h, ee), x);
if (r.has_q8) {
ov[j] = r.o.ld(at3(r.ov, tok, h, ee));
amax = sycl::maximum<float>()(amax, sycl::fabs(ov[j]));
}
}
if (!r.has_q8) continue;
amax = sycl::reduce_over_group(sg, amax, sycl::maximum<float>());
const float qsc = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f;
const float inv = 1.0f / qsc;
for (int j = 0; j < K / kSub; ++j) {
if (j >= nblk) break;
const int64_t ee = j * kSub + l;
float c = ov[j] * inv;
if (c > 448.0f) c = 448.0f;
if (c < -448.0f) c = -448.0f;
r.oq.st(tok * r.oq_rs + h * V * r.oq_cs + ee * r.oq_cs, c);
}
if (l == 0) r.osc.st(tok * r.osc_rs + h * r.osc_cs, qsc);
}
}
});
});
});
return rc;
}
bool coal_state(const RecIO& r) {
return r.state.dt == RAD_F32 && r.stv.s3 == 1 && r.stv.s2 == kRegK && r.V % kCb == 0 &&
rad_ptr_aligned(r.state.p, 16) && r.stv.s1 % 4 == 0 && r.stv.s0 % 4 == 0 &&
!std::getenv("XE2_GDN_GENERIC");
}
/* The register kernel as one launch a step: a work-group a (sequence, v head), its V / 16
* sub-groups the column blocks, so the replay and the token pass are ordered by a work-group
* barrier instead of a launch boundary, the replayed state stays in registers rather than going
* to its slot and back, the gates are formed in the kernel, and kernel B's norm and fp8 group run
* at the end over the outputs kept in local memory. The same arithmetic as the split form. */
int launch_recurrent_fused(sycl::queue& qu, const RecIO& r, int64_t n_seq, int64_t Tk) {
if (r.K != kRegK || r.V > kRegK || r.V % kCb || !coal_state(r) || Tk * r.V > 8192 ||
std::getenv("XE2_GDN_SPLIT") || std::getenv("XE2_GDN_SLM"))
return RAD_E_UNSUPPORTED;
const uint32_t qd = r.q.dt;
if (r.k.dt != qd || r.v.dt != qd) return RAD_E_UNSUPPORTED;
if (qd == RAD_BF16) return launch_recurrent_reg_t<uint16_t, true, true>(qu, r, n_seq, nullptr, nullptr, Tk);
if (qd == RAD_F32) return launch_recurrent_reg_t<float, true, true>(qu, r, n_seq, nullptr, nullptr, Tk);
return RAD_E_UNSUPPORTED;
}
int launch_recurrent_reg(sycl::queue& qu, const RecIO& r, int64_t n_seq, float* orow, const float* gates) {
constexpr int64_t Tk = 0;
const bool coal = coal_state(r);
const uint32_t qd = r.q.dt;
const bool same = r.k.dt == qd && r.v.dt == qd;
if (same && qd == RAD_BF16)
return coal ? launch_recurrent_reg_t<uint16_t, true, false>(qu, r, n_seq, orow, gates, Tk)
: launch_recurrent_reg_t<uint16_t, false, false>(qu, r, n_seq, orow, gates, Tk);
if (same && qd == RAD_F32)
return coal ? launch_recurrent_reg_t<float, true, false>(qu, r, n_seq, orow, gates, Tk)
: launch_recurrent_reg_t<float, false, false>(qu, r, n_seq, orow, gates, Tk);
return launch_recurrent_reg_t<void, false, false>(qu, r, n_seq, orow, gates, Tk);
}
int launch_recurrent(sycl::queue& qu, const RecIO& r, int64_t n_seq, int64_t Tk) {
/* Kernel B covers every token row: a row no sequence owns this step (cu stops short of T) is
* normed from a stale scratch row, so the split form is taken only when cu covers all of T,
* which the engine's decode always does; otherwise the serial form below. */
if (r.V % kCb == 0 && r.V <= kWgMaxV && r.K <= kWgMaxK && Tk > 0) return launch_recurrent_wg(qu, r, n_seq, Tk);
const int64_t need = r.V * r.K + 2 * r.K + 3 * r.V;
const int64_t work = n_seq * r.Hv;
float* ws = workspace(qu, (size_t)(work * need));
if (!ws) return RAD_E_DEVICE;
const int64_t Hv = r.Hv;
const size_t wg = 16;
return submit([&] {
qu.parallel_for(sycl::nd_range<1>{groups_for(work, wg) * wg, wg}, [=](sycl::nd_item<1> it) {
const int64_t nh = (int64_t)it.get_global_id(0);
if (nh >= work) return;
recurrent(r, nh / Hv, nh % Hv, ws + nh * need);
});
});
}
} // namespace
int gdn_recurrent_update(const RadArgs* a, RadStream st) {
if (!a) return RAD_E_INVAL;
RecIO r{};
int64_t n_seq = 0, Tk = 0;
if (int rc = rec_io(a, a->t, a->n_t, &r, &n_seq, &Tk); rc < 0) return rc;
sycl::queue* qu = queue_of(st);
if (!qu) return RAD_E_DEVICE;
return launch_recurrent(*qu, r, n_seq, Tk);
}
/* ------------------------------------------------------------------ gdn_gated_rmsnorm */
int gdn_gated_rmsnorm(const RadArgs* a, RadStream st) {
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *z = &a->t[1], *w = &a->t[2], *o = &a->t[3];
const int64_t ch = rad_args_geti_or(a, "channels", w->rank ? w->shape[w->rank - 1] : 0);
const float eps = (float)rad_args_getf_or(a, "eps", 1e-6);
const char* act_s = rad_args_gets_or(a, "act", "silu");
int act = -1;
if (!std::strcmp(act_s, "silu")) act = 0;
else if (!std::strcmp(act_s, "sigmoid")) act = 1;
if (act < 0) return RAD_E_INVAL;
if (ch <= 0) return RAD_E_SHAPE;
const int64_t rows = rad_tensor_numel(x) / ch;
if (rows <= 0 || rad_tensor_numel(o) < rows * ch || rad_tensor_numel(z) < rows * ch ||
rad_tensor_numel(w) < ch)
return RAD_E_SHAPE;
Rows xr, orr;
if (int rc = rows_view(x, ch, &xr, "gdn_gated_rmsnorm x"); rc < 0) return rc;
if (int rc = rows_view(o, ch, &orr, "gdn_gated_rmsnorm o"); rc < 0) return rc;
/* libref's gate_rowoff: a column slice [tokens, heads * ch] of a wider row, or plain rows. */
const bool zslice = z->rank == 2 && z->shape[1] != ch && z->shape[1] % ch == 0;
int64_t zheads = 1, zs0 = 0, zs1 = 0, zpitch = 0;
if (zslice) {
zheads = z->shape[1] / ch; zs0 = z->stride[0]; zs1 = z->stride[1];
} else {
Rows zr;
if (int rc = rows_view(z, ch, &zr, "gdn_gated_rmsnorm z"); rc < 0) return rc;
zpitch = zr.pitch;
}
const int64_t zs = laststride(z), ws = laststride(w);
const DT zd = dt_of(z), wd = dt_of(w);
sycl::queue* qu = queue_of(st);
if (!qu) return RAD_E_DEVICE;
constexpr size_t wg = 128;
if (ch == 128 && orr.dtype == RAD_BF16 && !std::getenv("XE2_GDN_GENERIC")) {
/* A sub-group a row of 128 (a (token, head) of the prefill: ~98k rows at a 2048-token chunk,
* where a 128-item work-group a row left 127 items waiting on one's ordered sum): a lane its
* 8 consecutive values, the squares added in index order by lane broadcasts (libref's chain),
* and the gate with a float exp, libref's double one only near a bf16 tie (xe2_common.h). */
const DT xd = dt_of(x);
const bool xv = xr.dtype == RAD_BF16 && xr.pitch % 8 == 0 && rad_ptr_aligned(xr.base, 16);
return submit([&] {
syclex::nd_launch(*qu, sycl::nd_range<1>{(size_t)((rows + 7) / 8) * 128, 128},
[=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] {
const sycl::sub_group sg = it.get_sub_group();
const int64_t r = (int64_t)it.get_group(0) * 8 + (int64_t)sg.get_group_linear_id();
if (r >= rows) return; /* uniform over the sub-group */
const int lane = (int)sg.get_local_linear_id();
float u[8];
if (xv) {
const sycl::vec<uint16_t, 8> v8 = *(const sycl::vec<uint16_t, 8>*)((const uint16_t*)xr.base + r * xr.pitch + lane * 8);
for (int e = 0; e < 8; ++e) u[e] = rad_bf16_to_f32(v8[e]);
} else {
for (int e = 0; e < 8; ++e) u[e] = xd.ld(r * xr.pitch + lane * 8 + e);
}
float ss = 0.0f;
for (int l = 0; l < kSub; ++l)
for (int e = 0; e < 8; ++e) {
const float w = sycl::select_from_group(sg, u[e], l);
ss += w * w;
}
const float sc = 1.0f / sycl::sqrt(ss / (float)ch + eps);
const int64_t zb = zslice ? (r / zheads) * zs0 + (r % zheads) * ch * zs1 : r * zpitch;
sycl::vec<uint16_t, 8> o8;
for (int e = 0; e < 8; ++e) {
const int64_t i = lane * 8 + e;
const float zz = zd.ld(zb + i * zs);
const float base = u[e] * sc * wd.ld(i * ws);
const float sf = sigmoid_fexp(zz);
float y = base * (act == 1 ? sf : zz * sf);
if (near_bf16_tie(y)) y = base * (act == 1 ? sigm(zz) : silu(zz));
o8[e] = rad_f32_to_bf16(y);
}
uint16_t* op = (uint16_t*)orr.base + r * orr.pitch + lane * 8;
if (orr.pitch % 8 == 0 && rad_ptr_aligned(orr.base, 16)) *(sycl::vec<uint16_t, 8>*)op = o8;
else for (int e = 0; e < 8; ++e) op[e] = o8[e];
});
});
}
if (ch <= 1024) {
/* the row in local memory, read once by all work-items, then work-item 0's ordered sum
* from there (its serial walk over global memory was the kernel's time) */
return submit([&] {
qu->submit([&](sycl::handler& h) {
sycl::local_accessor<float, 1> xl(sycl::range<1>((size_t)ch), h);
h.parallel_for(sycl::nd_range<1>{(size_t)rows * wg, wg}, [=](sycl::nd_item<1> it) {
const int64_t r = (int64_t)it.get_group(0);
const int64_t t = (int64_t)it.get_local_id(0);
for (int64_t i = t; i < ch; i += (int64_t)wg) xl[i] = rad_load_f32(xr.base, xr.dtype, r * xr.pitch + i);
sycl::group_barrier(it.get_group());
float sc = 0.0f;
if (t == 0) {
float ss = 0.0f;
for (int64_t i = 0; i < ch; ++i) {
const float u = xl[i];
ss += u * u;
}
sc = 1.0f / sycl::sqrt(ss / (float)ch + eps);
}
sc = sycl::group_broadcast(it.get_group(), sc, 0);
const int64_t zb = zslice ? (r / zheads) * zs0 + (r % zheads) * ch * zs1 : r * zpitch;
for (int64_t i = t; i < ch; i += (int64_t)wg) {
const float zz = zd.ld(zb + i * zs);
rad_store_f32(orr.base, orr.dtype, r * orr.pitch + i,
xl[i] * sc * wd.ld(i * ws) * (act == 1 ? sigm(zz) : silu(zz)));
}
});
});
});
}
return submit([&] {
syclex::nd_launch(*qu, sycl::nd_range<1>{(size_t)rows * wg, wg}, [=](sycl::nd_item<1> it) {
const int64_t r = (int64_t)it.get_group(0);
const int64_t t = (int64_t)it.get_local_id(0);
float sc = 0.0f;
if (t == 0) {
float ss = 0.0f;
for (int64_t i = 0; i < ch; ++i) {
const float u = rad_load_f32(xr.base, xr.dtype, r * xr.pitch + i);
ss += u * u;
}
sc = 1.0f / sycl::sqrt(ss / (float)ch + eps);
}
sc = sycl::group_broadcast(it.get_group(), sc, 0);
const int64_t zb = zslice ? (r / zheads) * zs0 + (r % zheads) * ch * zs1 : r * zpitch;
for (int64_t i = t; i < ch; i += (int64_t)wg) {
const float zz = zd.ld(zb + i * zs);
rad_store_f32(orr.base, orr.dtype, r * orr.pitch + i,
rad_load_f32(xr.base, xr.dtype, r * xr.pitch + i) * sc * wd.ld(i * ws) *
(act == 1 ? sigm(zz) : silu(zz)));
}
});
});
}
/* ------------------------------------------------------------------ gdn_conv_recurrent_update */
/* gdn_conv_update into staging q, k and v (x's dtype, so they round as the unfused pair's stores
* do), then gdn_recurrent_update over them -- libref's definition of the fused op. */
int gdn_conv_recurrent_update(const RadArgs* a, RadStream st) {
if (!a || a->n_t < 16) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *o = &a->t[15];
if (!x->data || !o->data || o->rank != 3 || x->rank < 2) return RAD_E_SHAPE;
const int64_t K = rad_args_geti_or(a, "head_k", 0), V = rad_args_geti_or(a, "head_v", 0);
const int64_t T = o->shape[0], Hv = o->shape[1];
if (K <= 0 || V <= 0 || T <= 0 || Hv <= 0 || o->shape[2] != V) return RAD_E_SHAPE;
const int64_t conv_dim = x->shape[x->rank - 1];
if (conv_dim <= Hv * V || (conv_dim - Hv * V) % (2 * K)) return RAD_E_SHAPE;
const int64_t Hg = (conv_dim - Hv * V) / (2 * K);
sycl::queue* qu = queue_of(st);
if (!qu) return RAD_E_DEVICE;
const int64_t esz = (rad_dtype_bits(x->dtype) + 7) / 8;
const int64_t nq = T * Hg * K, nv = T * Hv * V;
/* The staging: q, k, v back to back, 16-byte aligned, in workspace slot 1 (the recurrence may
* take slot 0). */
auto up16 = [](int64_t b) { return (b + 15) / 16 * 16; };
const int64_t bq = up16(nq * esz), bv = up16(nv * esz);
char* stage = (char*)workspace(*qu, (size_t)((2 * bq + bv) / 4 + 4), 1);
if (!stage) return RAD_E_DEVICE;
auto mk = [&](char* d, int64_t h, int64_t w) {
RadTensor t{};
t.data = d; t.dtype = x->dtype; t.rank = 3;
t.shape[0] = T; t.shape[1] = h; t.shape[2] = w;
t.stride[0] = h * w; t.stride[1] = w; t.stride[2] = 1;
return t;
};
const RadTensor tq = mk(stage, Hg, K), tk = mk(stage + bq, Hg, K), tv = mk(stage + 2 * bq, Hv, V);
RadParam cp[4] = {};
const char* ck[4] = { "q_len", "head_k", "head_v", "conv_width" };
int rc = RAD_OK;
for (int i = 0; i < 4 && rc == RAD_OK; ++i) {
const RadParam* f = rad_param_find(a->p, a->n_p, ck[i]);
if (!f) rc = RAD_E_INVAL;
else cp[i] = *f;
}
if (rc == RAD_OK) {
RadTensor ct[10] = { a->t[0], a->t[1], a->t[2], a->t[3], a->t[4], a->t[11], a->t[12], tq, tk, tv };
RadArgs ca = *a;
ca.t = ct; ca.n_t = 10; ca.p = cp; ca.n_p = 4;
rc = gdn_conv_update(&ca, st);
}
if (rc == RAD_OK) {
RadTensor rt[16] = { tq, tk, tv, a->t[5], a->t[6], a->t[7], a->t[8], a->t[9], a->t[10],
a->t[11], a->t[12], a->t[13], a->t[14], a->t[15],
a->n_t > 16 ? a->t[16] : RadTensor{}, a->n_t > 17 ? a->t[17] : RadTensor{} };
RecIO r{};
int64_t n_seq = 0, Tk = 0;
rc = rec_io(a, rt, 16, &r, &n_seq, &Tk);
if (rc == RAD_OK) rc = launch_recurrent(*qu, r, n_seq, Tk);
}
return rc;
}
} // namespace xe2