/* 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 #include #include 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; 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; 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 row(sycl::range<1>((size_t)chunk), hd); sycl::local_accessor 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; if (K == 128 && V % 32 == 0 && chunk == 64 && !std::getenv("XE2_GDN_SCAN1")) { /* A work-group of 256 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. */ constexpr int CB = 32, CK = 64, KK = 128, WG = 256; 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; return submit([&] { qu->submit([&](sycl::handler& hd) { sycl::local_accessor 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(); 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 ? h0s.ld(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] = ks.ld(at3(kv, tj, hk, d)); qc[j * KP + d] = qs.ld(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] = vs.ld(at3(vv, bos + c0 + j, h, e0 + e)); } if (t < L) { const int64_t tj = bos + c0 + t; gc[t] = gs.ld(at2(gv, tj, h)); bc[t] = bs.ld(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 ? As.ld(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]; 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; hts.st(at4(htv, sn, h, e0 + e, d), St[idx]); } }); }); }); } 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 St(sycl::range<1>((size_t)(K * V)), hd); sycl::local_accessor 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(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; int launch_recurrent_reg(sycl::queue& qu, const RecIO& r, int64_t n_seq, float* orow, const float* gates); 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; 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 St(sycl::range<1>((size_t)(K * kCb)), hd); sycl::local_accessor 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 work-group a (token, head) */ return submit([&] { qu.submit([&](sycl::handler& hd) { sycl::local_accessor 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()); 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 rows, loaded and stored a work-group's 16 rows at a time through local * memory (coalesced) rather than a row a lane. 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. */ template int launch_recurrent_reg_t(sycl::queue& qu, const RecIO& r, int64_t n_seq, float* orow, const float* gates) { 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; for (int phase = r.anchor ? 0 : 1; phase <= 1 && rc >= 0; ++phase) rc = submit([&] { qu.submit([&](sycl::handler& hd) { sycl::local_accessor tr(sycl::range<1>(COAL ? (size_t)kCb * (kRegK + 1) : 1), hd); hd.parallel_for(sycl::nd_range<1>{(size_t)(n_seq * Hv * nblk) * kCb, (size_t)kCb}, 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) return rad_bf16_to_f32(((const uint16_t*)d.p)[o]); else if constexpr (std::is_same_v) 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 = gid % nblk, nh = gid / nblk; const int64_t n = nh / Hv, h = nh % Hv, hk = h / r.grp; const int l = (int)it.get_local_id(0); 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 (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) { const float* base = (const float*)sp + at4(r.stv, slot, h, e0, 0); for (int i = 0; i < kCb * K / kSub; ++i) { const int idx = i * kSub + l; tr[(idx / K) * (K + 1) + idx % K] = base[idx]; } sycl::group_barrier(sg); for (int d = 0; d < K; ++d) st[d] = tr[l * (K + 1) + d]; sycl::group_barrier(sg); } 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) { for (int d = 0; d < K; ++d) tr[l * (K + 1) + d] = st[d]; sycl::group_barrier(sg); float* base = (float*)sp + at4(r.stv, slot, h, e0, 0); for (int i = 0; i < kCb * K / kSub; ++i) { const int idx = i * kSub + l; base[idx] = tr[(idx / K) * (K + 1) + idx % K]; } sycl::group_barrier(sg); } 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 && 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]); return; } if (r.anchor && blk == 0 && l == 0) for (int c = 0; c < 3; ++c) SS(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]; 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); 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 */ } }); }); }); return rc; } int launch_recurrent_reg(sycl::queue& qu, const RecIO& r, int64_t n_seq, float* orow, const float* gates) { const bool coal = r.state.dt == RAD_F32 && r.stv.s3 == 1 && r.stv.s2 == kRegK && r.V % kCb == 0 && !std::getenv("XE2_GDN_GENERIC"); 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(qu, r, n_seq, orow, gates) : launch_recurrent_reg_t(qu, r, n_seq, orow, gates); if (same && qd == RAD_F32) return coal ? launch_recurrent_reg_t(qu, r, n_seq, orow, gates) : launch_recurrent_reg_t(qu, r, n_seq, orow, gates); return launch_recurrent_reg_t(qu, r, n_seq, orow, gates); } 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; 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