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 3158324bdb libxe2: every op Qwen3.8-27B-PARO-M2XFP4 needs, correctness first -- the 27B serves on the B65
Kernels, each libref's arithmetic in libref's order:
- gemm_nt_q at m2xfp4 (xe2_gemm_m2.cpp) with libref's m2 layout hooks, and givens_dense_quant
  (xe2_givens.cpp, the rotation in double as libref's)
- the gated delta net (xe2_gdn.cpp): gdn_conv_prep, gdn_conv_update, gdn_kkt_solve, gdn_chunk_scan,
  gdn_recurrent_update (per-candidate and anchor state forms), gdn_gated_rmsnorm,
  gdn_conv_recurrent_update; each work-item one iteration of libref's parallel loop, the
  per-(sequence, head) workspaces in a shared device workspace (xe2_common: workspace())
- rope's multi-component modes (mrope, imrope, axial) and rope_table
- logits_gemm over an fp8 128x128 joined head, gemm_nt_bias with its epilogue
- mul, sigmoid, scatter_rows, layernorm, grid_embed, attn_dense (the vision tower)
- dflash_conv and logit_rerank (plain and joined head) for the DFlash2 drafter

libref's gemm_m2 gains the parts (pb1/pb2) every other ParoQuant grid and libr4d's mx_parts
already define -- weight rows [0, e1), [e1, e2), [e2, N) read activation copies 0, 1, 2 side by
side -- since this model's fused projections are rotated per piece and the oracle declined them;
its shape hook widens a and a_scale by the part count. Both m2 arms now take the stored
codes-then-meta blob as the engine describes it, u8 [N, K], beside the shape hook's rank-1 form
(libref refused the engine's launch; only libr4d had been run on it).

rad-kbench on the fixture: every new row at rel_l2 0 (90 gdn/givens cases, 108 rope, 80
elementwise, 20 attn_dense, the drafter's and the heads'). On the B65 the model starts with every
op on the card and answers "The capital of France is" -> " Paris.\nThe capital of Germany is
Berlin.\nThe capital of Italy is" (greedy), at 0.1 tok/s: the correctness-first kernels.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
2026-10-24 00:30:40 +02:00

949 lines
45 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>
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
/* ------------------------------------------------------------------ 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([&] {
/* phase 1: the convolution, straight into q / k / v */
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;
const bool warm = !hiv.on || hiv.at(n) != 0;
float hist[kHistMax];
for (int64_t i = 0; i < width - 1; ++i)
hist[i] = warm && has_cs && slot >= 0 ? css.ld(at3(cvs, slot, c, i)) : 0.0f;
conv_channel(io, c, bos, slen, hist);
});
/* phase 2: the l2 norm over each q and k head, reading the rounded conv output */
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 */
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;
const int64_t bos = cuv.at(n), slen = cuv.at(n + 1) - bos;
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 = 0; t < slen; ++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;
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;
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;
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) {
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;
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;
}
int launch_recurrent(sycl::queue& qu, const RecIO& r, int64_t n_seq) {
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;
if (int rc = rec_io(a, a->t, a->n_t, &r, &n_seq); rc < 0) return rc;
sycl::queue* qu = queue_of(st);
if (!qu) return RAD_E_DEVICE;
return launch_recurrent(*qu, r, n_seq);
}
/* ------------------------------------------------------------------ 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;
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 rides the workspace's tail-free head: q, k, v back to back, 16-byte aligned. */
auto up16 = [](int64_t b) { return (b + 15) / 16 * 16; };
const int64_t bq = up16(nq * esz), bv = up16(nv * esz);
char* stage = (char*)sycl::malloc_device(size_t(2 * bq + bv), *qu);
if (!stage) return refuse("gdn_conv_recurrent_update: no staging memory");
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;
rc = rec_io(a, rt, 16, &r, &n_seq);
if (rc == RAD_OK) rc = launch_recurrent(*qu, r, n_seq);
}
/* The staging is freed once the queue has passed the two launches. */
try {
qu->wait();
} catch (const sycl::exception& e) {
rc = refuse("SYCL: %s", e.what());
}
sycl::free(stage, *qu);
return rc;
}
} // namespace xe2