Archived
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
This commit is contained in:
1 parent
20ddb6aba1
commit
3158324bdb
15 files changed
+2251
-78
No files matched your search
+31
-15
@@ -384,27 +384,45 @@ static int gemm_zp(const ZpGrid& zg, const RadTensor* A, const RadTensor* as_,
|
||||
* multiplier k_s the meta byte's two-bit field [2s, 2s+2) over subgroups s of eight columns
|
||||
* (libr4d's r4d_m2xfp4.h folds the same law into its staging table); each product is one f32
|
||||
* multiply, each row one f32 accumulation in k order -- the exact decode's own arithmetic, since
|
||||
* the multipliers take the codes off the integer grid an mxfp4 group sub-sum would use. */
|
||||
* the multipliers take the codes off the integer grid an mxfp4 group sub-sum would use.
|
||||
*
|
||||
* Parts (`pb1`, `pb2`), as the other ParoQuant grids read them (gemm_zp, libr4d's mx_parts): weight
|
||||
* rows [0, e1), [e1, e2), [e2, N) meet copies 0, 1, 2 of the activation, side by side in `a`
|
||||
* ([M, parts * K]) and in `a_scale` ([M, parts * K/128]) -- a fused projection whose pieces were
|
||||
* rotated separately, each copy givens_dense_quant's for its own part. */
|
||||
static const float kM2E2M1[8] = { 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f };
|
||||
|
||||
static int gemm_m2(const RadArgs* a) {
|
||||
static int gemm_m2(const RadArgs* a, int64_t pb1, int64_t pb2) {
|
||||
if (a->n_t < 5) return RAD_E_INVAL;
|
||||
const RadTensor *A = &a->t[0], *B = &a->t[2], *Y = &a->t[4];
|
||||
const RadTensor *as_ = t_in(a, 1), *bs_ = t_in(a, 3);
|
||||
if (!A->data || !B->data || !Y->data) return RAD_E_INVAL;
|
||||
if (t_in(a, 5)) return RAD_E_UNSUPPORTED; /* a_sum belongs to the asym grids */
|
||||
if (A->dtype != RAD_F8E4M3 || B->dtype != RAD_U8 || B->rank != 1) return RAD_E_DTYPE;
|
||||
if (A->dtype != RAD_F8E4M3 || B->dtype != RAD_U8) return RAD_E_DTYPE;
|
||||
if (!as_ || !bs_ || bs_->dtype != RAD_E8M0 || bs_->rank < 2) return RAD_E_DTYPE;
|
||||
const int64_t K = p_int(a, "K", 0), N = p_int(a, "N", 0);
|
||||
if (K <= 0 || K % 32 || N <= 0) return RAD_E_SHAPE;
|
||||
const int64_t M = numel(Y) / N;
|
||||
if (M <= 0) return RAD_E_SHAPE;
|
||||
const int64_t kb = K / 32, akb = (K + 127) / 128;
|
||||
if (numel(A) < M * K || numel(B) != N * (K / 2 + kb) || numel(bs_) < N * kb ||
|
||||
numel(as_) < M * akb)
|
||||
const bool parted = pb1 > 0 || pb2 > 0;
|
||||
const int64_t e1 = pb1 > 0 ? std::min<int64_t>(pb1, N) : N;
|
||||
const int64_t e2 = pb2 > 0 ? std::max<int64_t>(e1, std::min<int64_t>(pb2, N)) : N;
|
||||
const int64_t parts = e2 < N ? 3 : (e1 < N ? 2 : 1);
|
||||
if (parted && ((e1 % 16) || (e2 % 16))) return RAD_E_SHAPE;
|
||||
if (parted && e1 == e2 && e2 < N) return RAD_E_SHAPE; /* an empty middle part has no copy */
|
||||
const int64_t acols = parts * K, scols = parts * akb;
|
||||
/* `b` is the stored codes-then-meta blob: a rank-1 u8 of its bytes (the shape hook's
|
||||
* description), or the weight's logical [N, K] u8 view of the same bytes (the engine's). */
|
||||
const bool blob = (B->rank == 1 && numel(B) == N * (K / 2 + kb)) ||
|
||||
(B->rank == 2 && B->shape[0] == N && B->shape[1] == K);
|
||||
if (!blob) return RAD_E_SHAPE;
|
||||
if (numel(A) < M * acols || numel(bs_) < N * kb ||
|
||||
numel(as_) < M * scols)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t ars = row_stride(A, K), acs = laststride(A);
|
||||
const int64_t srs = row_stride(as_, akb), scs = laststride(as_);
|
||||
if (A->rank >= 2 && A->shape[A->rank - 1] != acols) return RAD_E_SHAPE;
|
||||
const int64_t ars = row_stride(A, acols), acs = laststride(A);
|
||||
const int64_t srs = row_stride(as_, scols), scs = laststride(as_);
|
||||
const int64_t brs = row_stride(bs_, kb);
|
||||
const int64_t ys_r = row_stride(Y, N), ys_c = laststride(Y);
|
||||
const uint8_t* meta0 = (const uint8_t*)B->data + N * (K / 2);
|
||||
@@ -423,11 +441,12 @@ static int gemm_m2(const RadArgs* a) {
|
||||
const float km = 1.0f + 0.25f * (float)((meta[k >> 5] >> (2 * ((k & 31) >> 3))) & 3);
|
||||
w[(size_t)k] = cv * ev * km;
|
||||
}
|
||||
const int64_t part = n < e1 ? 0 : (n < e2 ? 1 : 2);
|
||||
for (int64_t m = 0; m < M; ++m) {
|
||||
const int64_t ab = m * ars;
|
||||
const int64_t ab = m * ars + part * K * acs, sb = m * srs + part * akb * scs;
|
||||
float acc = 0.0f;
|
||||
for (int64_t k = 0; k < K; ++k)
|
||||
acc += ldt(A, ab + k * acs) * ldt(as_, m * srs + (k >> 7) * scs) * w[(size_t)k];
|
||||
acc += ldt(A, ab + k * acs) * ldt(as_, sb + (k >> 7) * scs) * w[(size_t)k];
|
||||
stt(Y, m * ys_r + n * ys_c, acc);
|
||||
}
|
||||
}
|
||||
@@ -450,13 +469,10 @@ static int gemm_ntq_impl(const RadArgs* a, bool bias_operand) {
|
||||
const ZpGrid* zg = zp_grid(p_str(a, "dtype", nullptr));
|
||||
if (zg && bias_operand) return RAD_E_UNSUPPORTED;
|
||||
/* M2XFP4: the quantiser's own scheme, decoded by gemm_m2 from its concatenated planes.
|
||||
* Parts (pb1/pb2) are the rotated grids'; the m2 declare makes none, and a case carrying
|
||||
* them is declined rather than answered unsplit. */
|
||||
* Parts (pb1/pb2) are the rotated grids', a fused projection rotated per piece (gemm_m2). */
|
||||
if (!bias_operand && p_str(a, "dtype", nullptr) &&
|
||||
std::strcmp(p_str(a, "dtype", nullptr), "m2xfp4") == 0) {
|
||||
if (p_int(a, "pb1", 0) > 0 || p_int(a, "pb2", 0) > 0) return RAD_E_UNSUPPORTED;
|
||||
return gemm_m2(a);
|
||||
}
|
||||
std::strcmp(p_str(a, "dtype", nullptr), "m2xfp4") == 0)
|
||||
return gemm_m2(a, p_int(a, "pb1", 0), p_int(a, "pb2", 0));
|
||||
if (!bias_operand) {
|
||||
if (t_in(a, 5) && (!zg || zg->act != ZP_I8_ROW)) return RAD_E_UNSUPPORTED;
|
||||
if (t_in(a, 6) && B->dtype != RAD_FP4E2M1) return RAD_E_UNSUPPORTED;
|
||||
|
||||
+10
-2
@@ -1186,8 +1186,16 @@ int gemm_q_shape(const RadParam* p, int n_p, int operand, bool bias, RadOpdDesc*
|
||||
* reads back as the two planes' bytes concatenated (encoding.cpp) -- the codes rows, then
|
||||
* the meta rows -- which ref_gemm.cpp's own arm decodes against `b_scale`. */
|
||||
const int64_t akb = (mx || m2) ? (K + 127) / 128 : kb;
|
||||
o.t((uint32_t)((mx || m2) ? RAD_F8E4M3 : RAD_I8), { M, K }); /* a */
|
||||
o.t_fill((uint32_t)RAD_F32, { M, akb }, (uint32_t)RAD_FILL_SIGMOID, 0); /* a_scale */
|
||||
/* m2xfp4 parts (pb1/pb2, gemm_m2): one activation copy a part, side by side. */
|
||||
int64_t parts = 1;
|
||||
if (m2) {
|
||||
const int64_t pb1 = gi(p, n_p, "pb1", 0), pb2 = gi(p, n_p, "pb2", 0);
|
||||
const int64_t e1 = pb1 > 0 ? std::min<int64_t>(pb1, N) : N;
|
||||
const int64_t e2 = pb2 > 0 ? std::max<int64_t>(e1, std::min<int64_t>(pb2, N)) : N;
|
||||
parts = e2 < N ? 3 : (e1 < N ? 2 : 1);
|
||||
}
|
||||
o.t((uint32_t)((mx || m2) ? RAD_F8E4M3 : RAD_I8), { M, parts * K }); /* a */
|
||||
o.t_fill((uint32_t)RAD_F32, { M, parts * akb }, (uint32_t)RAD_FILL_SIGMOID, 0); /* a_scale */
|
||||
if (m2)
|
||||
o.t((uint32_t)RAD_U8, { N * (K / 2 + K / 32) }); /* b -- codes then meta bytes */
|
||||
else
|
||||
|
||||
@@ -263,4 +263,112 @@ int attn_paged(const RadArgs* a, RadStream st) {
|
||||
});
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ attn_dense */
|
||||
/* The vision tower's unpaged attention, libref's ref_attn_dense: segments [cu[s] / cu_div,
|
||||
* cu[s+1] / cu_div), optional causal mask, window (and window_right) and blocks. One work-item a
|
||||
* (query row, head), which finds its segment on the card and runs libref's two passes in its
|
||||
* order: the max over the visible keys' scaled dots, then w = exp(dot * scale - max) in double,
|
||||
* sum += w and acc += w * v in key order, out = acc * (1 / sum). */
|
||||
constexpr int kDenseHdMax = 256;
|
||||
|
||||
int attn_dense(const RadArgs* a, RadStream st) {
|
||||
if (!rad_args_have(a, 5)) return RAD_E_INVAL;
|
||||
const RadTensor *Q = &a->t[0], *K = &a->t[1], *V = &a->t[2], *CU = &a->t[3], *O = &a->t[4];
|
||||
const int64_t head_dim = rad_args_geti_or(a, "head_dim", Q->rank >= 3 ? Q->shape[Q->rank - 1] : 0);
|
||||
const int64_t gqa = rad_args_geti_or(a, "gqa", 1);
|
||||
const int causal = (int)rad_args_geti_or(a, "causal", 0);
|
||||
const int64_t window = rad_args_geti_or(a, "window", 0);
|
||||
const int64_t wright = rad_args_geti_or(a, "window_right", 0);
|
||||
const int64_t block = rad_args_geti_or(a, "block", 0);
|
||||
const int64_t cdiv = rad_args_geti_or(a, "cu_div", 1);
|
||||
if (head_dim <= 0 || gqa <= 0 || window < 0 || block < 0 || cdiv <= 0 || wright < 0 ||
|
||||
(wright > 0 && (causal || window == 0)))
|
||||
return RAD_E_SHAPE;
|
||||
if (head_dim > kDenseHdMax) return refuse("attn_dense: head_dim %lld over %d", (long long)head_dim, kDenseHdMax);
|
||||
const int64_t q_heads = Q->rank >= 3 ? Q->shape[Q->rank - 2] : (Q->rank == 2 ? Q->shape[1] / head_dim : 1);
|
||||
const int64_t kv_heads = q_heads / gqa;
|
||||
if (kv_heads <= 0 || q_heads % gqa != 0) return RAD_E_SHAPE;
|
||||
const int64_t n_seq = rad_tensor_numel(CU) - 1;
|
||||
if (n_seq <= 0) return RAD_E_SHAPE;
|
||||
const int64_t total_q = rad_tensor_numel(Q) / (q_heads * head_dim);
|
||||
if (total_q <= 0) return RAD_E_SHAPE;
|
||||
if (rad_tensor_numel(O) < total_q * q_heads * head_dim) return RAD_E_SHAPE;
|
||||
if (rad_tensor_numel(K) < total_q * kv_heads * head_dim) return RAD_E_SHAPE;
|
||||
if (rad_tensor_numel(V) < total_q * kv_heads * head_dim) return RAD_E_SHAPE;
|
||||
const int64_t q_ds = Q->rank >= 2 ? Q->stride[Q->rank - 1] : 1;
|
||||
const int64_t q_hs = Q->rank >= 3 ? Q->stride[Q->rank - 2] : head_dim * q_ds;
|
||||
const int64_t q_rs = row_stride(Q, q_heads * head_dim);
|
||||
const int64_t k_ds = K->rank >= 2 ? K->stride[K->rank - 1] : 1;
|
||||
const int64_t k_hs = K->rank >= 3 ? K->stride[K->rank - 2] : head_dim * k_ds;
|
||||
const int64_t k_rs = row_stride(K, kv_heads * head_dim);
|
||||
const int64_t v_ds = V->rank >= 2 ? V->stride[V->rank - 1] : 1;
|
||||
const int64_t v_hs = V->rank >= 3 ? V->stride[V->rank - 2] : head_dim * v_ds;
|
||||
const int64_t v_rs = row_stride(V, kv_heads * head_dim);
|
||||
const int64_t o_ds = O->rank >= 2 ? O->stride[O->rank - 1] : 1;
|
||||
const int64_t o_hs = O->rank >= 3 ? O->stride[O->rank - 2] : head_dim * o_ds;
|
||||
const int64_t o_rs = row_stride(O, q_heads * head_dim);
|
||||
const float scale = (float)rad_args_getf_or(a, "scale", (double)(1.0f / std::sqrt((float)head_dim)));
|
||||
const char *qb0 = (const char*)Q->data, *kb0 = (const char*)K->data, *vb0 = (const char*)V->data;
|
||||
char* ob0 = (char*)O->data;
|
||||
const uint32_t qdt = Q->dtype, kdt = K->dtype, vdt = V->dtype, odt = O->dtype;
|
||||
const Lin cu = Lin::of(CU);
|
||||
sycl::queue* q = queue_of(st);
|
||||
if (!q) return RAD_E_DEVICE;
|
||||
const int64_t total = total_q * q_heads;
|
||||
const size_t wg = 64;
|
||||
const size_t groups = (size_t)((total + (int64_t)wg - 1) / (int64_t)wg);
|
||||
return submit([&] {
|
||||
syclex::nd_launch(*q, sycl::nd_range<1>{groups * wg, wg}, [=](sycl::nd_item<1> it) {
|
||||
const int64_t g = (int64_t)it.get_global_id(0);
|
||||
if (g >= total) return;
|
||||
const int64_t i = g / q_heads, h = g % q_heads, kh = h / gqa;
|
||||
int64_t b0 = -1, b1 = -1;
|
||||
for (int64_t s = 0; s < n_seq; ++s) {
|
||||
const int64_t s0 = ld_index(cu.dtype, cu.base, cu.off(s)) / cdiv;
|
||||
const int64_t s1 = ld_index(cu.dtype, cu.base, cu.off(s + 1)) / cdiv;
|
||||
if (i >= s0 && i < s1) { b0 = s0; b1 = s1; break; }
|
||||
}
|
||||
if (b0 < 0) return; /* a row no segment covers is left as it is */
|
||||
const int64_t qb = i * q_rs + h * q_hs, ob = i * o_rs + h * o_hs;
|
||||
int64_t jbeg = b0, jend = causal ? (i + 1) : b1;
|
||||
if (window > 0) {
|
||||
jbeg = sycl::max(b0, i - window + 1);
|
||||
if (!causal) jend = sycl::min(b1, i + (wright > 0 ? wright : window));
|
||||
}
|
||||
if (block > 0) {
|
||||
const int64_t blk = b0 + (i - b0) / block * block;
|
||||
jbeg = sycl::max(jbeg, blk);
|
||||
jend = sycl::min(jend, blk + block);
|
||||
}
|
||||
float mx = -INFINITY;
|
||||
for (int64_t j = jbeg; j < jend; ++j) {
|
||||
const int64_t kb = j * k_rs + kh * k_hs;
|
||||
float dot = 0.0f;
|
||||
for (int64_t d = 0; d < head_dim; ++d)
|
||||
dot += rad_load_f32(qb0, qdt, qb + d * q_ds) * rad_load_f32(kb0, kdt, kb + d * k_ds);
|
||||
dot *= scale;
|
||||
if (dot > mx) mx = dot;
|
||||
}
|
||||
if (mx == -INFINITY) {
|
||||
for (int64_t d = 0; d < head_dim; ++d) rad_store_f32(ob0, odt, ob + d * o_ds, 0.0f);
|
||||
return;
|
||||
}
|
||||
float acc[kDenseHdMax];
|
||||
for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f;
|
||||
float sum = 0.0f;
|
||||
for (int64_t j = jbeg; j < jend; ++j) {
|
||||
const int64_t kb = j * k_rs + kh * k_hs, vb = j * v_rs + kh * v_hs;
|
||||
float dot = 0.0f;
|
||||
for (int64_t d = 0; d < head_dim; ++d)
|
||||
dot += rad_load_f32(qb0, qdt, qb + d * q_ds) * rad_load_f32(kb0, kdt, kb + d * k_ds);
|
||||
const float w = (float)sycl::exp((double)(dot * scale - mx));
|
||||
sum += w;
|
||||
for (int64_t d = 0; d < head_dim; ++d) acc[d] += w * rad_load_f32(vb0, vdt, vb + d * v_ds);
|
||||
}
|
||||
const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
|
||||
for (int64_t d = 0; d < head_dim; ++d) rad_store_f32(ob0, odt, ob + d * o_ds, acc[d] * inv);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
} // namespace xe2
|
||||
@@ -1,6 +1,9 @@
|
||||
/* xe2_common.cpp -- the shared helpers of xe2_common.h. */
|
||||
#include "xe2_common.h"
|
||||
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
|
||||
#include <cstdarg>
|
||||
|
||||
namespace xe2 {
|
||||
@@ -27,6 +30,27 @@ sycl::queue* queue_of(RadStream s) {
|
||||
return q;
|
||||
}
|
||||
|
||||
float* workspace(sycl::queue& q, size_t floats) {
|
||||
struct Ws { sycl::queue* q; float* p; size_t n; };
|
||||
static std::mutex mu;
|
||||
static std::vector<Ws> all;
|
||||
std::lock_guard<std::mutex> lk(mu);
|
||||
for (Ws& w : all) {
|
||||
if (w.q != &q) continue;
|
||||
if (w.n >= floats) return w.p;
|
||||
q.wait();
|
||||
sycl::free(w.p, q);
|
||||
w.p = sycl::malloc_device<float>(floats, q);
|
||||
w.n = w.p ? floats : 0;
|
||||
if (!w.p) refuse("workspace: %zu floats", floats);
|
||||
return w.p;
|
||||
}
|
||||
float* p = sycl::malloc_device<float>(floats, q);
|
||||
if (!p) { refuse("workspace: %zu floats", floats); return nullptr; }
|
||||
all.push_back({ &q, p, floats });
|
||||
return p;
|
||||
}
|
||||
|
||||
int rows_view(const RadTensor* t, int64_t n, Rows* out, const char* what) {
|
||||
if (!t || !t->data || n <= 0) return refuse("%s: missing operand or n <= 0", what);
|
||||
out->base = (char*)t->data;
|
||||
|
||||
@@ -47,6 +47,12 @@ int rows_view(const RadTensor* t, int64_t n, Rows* out, const char* what);
|
||||
/* The queue behind a launch's stream, or null with a reason (not a SYCL stream). */
|
||||
sycl::queue* queue_of(RadStream s);
|
||||
|
||||
/* A device workspace of at least `floats` floats for `q`, kept between launches and grown on
|
||||
* demand (libref's ws_get, for kernels whose work-items each need a scratch block). The queue is
|
||||
* in-order, so consecutive launches can share it; growing waits for the queue first. Null with a
|
||||
* reason when the allocation fails. */
|
||||
float* workspace(sycl::queue& q, size_t floats);
|
||||
|
||||
/* Runs `submit`, turning a SYCL exception into RAD_E_DEVICE with its message. */
|
||||
template <typename F>
|
||||
int submit(F&& f) {
|
||||
@@ -130,6 +136,17 @@ inline float key_value(uint64_t k) {
|
||||
return v;
|
||||
}
|
||||
|
||||
/* Stores an integer index in an integer dtype (the counterpart of ld_index). */
|
||||
inline void st_index(uint32_t dt, void* p, int64_t i, int64_t v) {
|
||||
switch (dt) {
|
||||
case RAD_I32: ((int32_t*)p)[i] = (int32_t)v; break;
|
||||
case RAD_U32: ((uint32_t*)p)[i] = (uint32_t)v; break;
|
||||
case RAD_I64: ((int64_t*)p)[i] = v; break;
|
||||
case RAD_I16: ((int16_t*)p)[i] = (int16_t)v; break;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
|
||||
/* Rounds `v` through a store and load of `dt`, as libref's round_dt does. */
|
||||
inline float round_dt(uint32_t dt, float v) {
|
||||
uint64_t buf = 0;
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
/* xe2_dflash.cpp -- the DFlash2 drafter's own ops: dflash_conv and logit_rerank.
|
||||
* Correctness first, libref's arithmetic (ref_qsa.cpp, ref_moe.cpp):
|
||||
*
|
||||
* dflash_conv: o[t][h] = sum over taps j (in order, the first term not added to zero) of
|
||||
* (bias[j][h] + delta[t][j][h / group]) * x[t - j][h], a tap skipped when it would reach back past
|
||||
* the start of t's block of `block_size` rows.
|
||||
* logit_rerank: R candidate ids a row rescored against the head, each a dot product summed in
|
||||
* double in k order, then emitted descending by score, ties to the lower id, pads (an id outside
|
||||
* this shard, or -1) last as id -1 and -inf -- row_topk's order. The head is plain or, in the
|
||||
* joined row, codes with a scale plane decoded element by element (code * scale).
|
||||
*/
|
||||
#include "xe2_common.h"
|
||||
#include "xe2_ops.h"
|
||||
|
||||
#include "rad_planes.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
|
||||
namespace xe2 {
|
||||
|
||||
namespace {
|
||||
|
||||
int64_t laststride(const RadTensor* t) { return t->rank ? t->stride[t->rank - 1] : 1; }
|
||||
|
||||
struct HPlane {
|
||||
const char* p = nullptr;
|
||||
uint32_t dt = 0;
|
||||
int64_t row_bytes = 0, br = 0, bc = 0;
|
||||
float at(int64_t i, int64_t j) const { return rad_load_f32(p + i * row_bytes, dt, j); }
|
||||
float cover(int64_t r, int64_t c) const { return at(br > 0 ? r / br : 0, bc > 0 ? c / bc : 0); }
|
||||
};
|
||||
|
||||
inline bool role_is(const char* r, const char* want) {
|
||||
for (int i = 0; i < RAD_ENC_STR; ++i) {
|
||||
if (r[i] != want[i]) return false;
|
||||
if (!want[i]) return true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
inline HPlane hplane(const char* base, const char* role) {
|
||||
HPlane v;
|
||||
const RadPlanesHeader* h = (const RadPlanesHeader*)base;
|
||||
if (h->magic != RAD_PLANES_MAGIC) return v;
|
||||
const RadPlanesEntry* e = (const RadPlanesEntry*)(base + sizeof(RadPlanesHeader));
|
||||
for (int i = 0; i < h->n_planes && i < RAD_ENC_MAX_PLANES; ++i)
|
||||
if (role_is(e[i].role, role)) {
|
||||
v.p = base + e[i].offset;
|
||||
v.dt = e[i].dtype;
|
||||
v.row_bytes = e[i].row_bytes;
|
||||
v.br = e[i].block[0];
|
||||
v.bc = e[i].block[1];
|
||||
return v;
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
int rerank(const RadArgs* a, RadStream st, bool joined) {
|
||||
if (!rad_args_have(a, 5)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *W = &a->t[1], *IN = &a->t[2], *IDX = &a->t[3], *VAL = &a->t[4];
|
||||
const RadTensor* PAIRS = (a->n_t > 5 && a->t[5].data) ? &a->t[5] : nullptr;
|
||||
const int64_t R = rad_args_geti_or(a, "R", 1), K = rad_args_geti_or(a, "n_embd", 0);
|
||||
const int64_t NV = rad_args_geti_or(a, "n_vocab", 0), voff = rad_args_geti_or(a, "vocab_off", 0);
|
||||
if (R <= 0 || K <= 0 || NV <= 0) return RAD_E_SHAPE;
|
||||
const int64_t M = rad_tensor_numel(X) / K;
|
||||
if (M <= 0 || rad_tensor_numel(IN) < M * R) return RAD_E_SHAPE;
|
||||
if (rad_tensor_numel(IDX) < M * R || rad_tensor_numel(VAL) < M * R) return RAD_E_SHAPE;
|
||||
if (!joined && rad_tensor_numel(W) < NV * K) return RAD_E_SHAPE;
|
||||
if (PAIRS && (PAIRS->dtype != RAD_F32 || rad_tensor_numel(PAIRS) < M * R * 2)) return RAD_E_SHAPE;
|
||||
Rows x, in, idx, val, w;
|
||||
if (int rc = rows_view(X, K, &x, "logit_rerank x"); rc < 0) return rc;
|
||||
if (int rc = rows_view(IN, R, &in, "logit_rerank in"); rc < 0) return rc;
|
||||
if (int rc = rows_view(IDX, R, &idx, "logit_rerank idx"); rc < 0) return rc;
|
||||
if (int rc = rows_view(VAL, R, &val, "logit_rerank val"); rc < 0) return rc;
|
||||
if (!joined)
|
||||
if (int rc = rows_view(W, K, &w, "logit_rerank head"); rc < 0) return rc;
|
||||
const char* wb = (const char*)W->data;
|
||||
float* pairs = PAIRS ? (float*)PAIRS->data : nullptr;
|
||||
sycl::queue* q = queue_of(st);
|
||||
if (!q) return RAD_E_DEVICE;
|
||||
float* ws = workspace(*q, (size_t)(M * R * 3));
|
||||
if (!ws) return RAD_E_DEVICE;
|
||||
const size_t wg = 16;
|
||||
const size_t groups = (size_t)((M + (int64_t)wg - 1) / (int64_t)wg);
|
||||
return submit([&] {
|
||||
syclex::nd_launch(*q, sycl::nd_range<1>{groups * wg, wg}, [=](sycl::nd_item<1> it) {
|
||||
const int64_t m = (int64_t)it.get_global_id(0);
|
||||
if (m >= M) return;
|
||||
int32_t* id = (int32_t*)(ws + m * R * 3);
|
||||
float* sc = ws + m * R * 3 + R;
|
||||
float* used = sc + R;
|
||||
HPlane cp, sp;
|
||||
if (joined) {
|
||||
cp = hplane(wb, "codes");
|
||||
sp = hplane(wb, "scale");
|
||||
if (!cp.p || !sp.p) return; /* the layout hook guarantees a joined head */
|
||||
}
|
||||
for (int64_t r = 0; r < R; ++r) {
|
||||
const int64_t g = ld_index(in.dtype, in.base, m * in.pitch + r);
|
||||
const int64_t local = g - voff;
|
||||
used[r] = 0.0f;
|
||||
if (g < 0 || local < 0 || local >= NV) {
|
||||
id[r] = -1;
|
||||
sc[r] = -INFINITY;
|
||||
continue;
|
||||
}
|
||||
double acc = 0.0;
|
||||
for (int64_t k = 0; k < K; ++k)
|
||||
acc += (double)rad_load_f32(x.base, x.dtype, m * x.pitch + k) *
|
||||
(double)(joined ? cp.at(local, k) * sp.cover(local, k)
|
||||
: rad_load_f32(w.base, w.dtype, local * w.pitch + k));
|
||||
id[r] = (int32_t)g;
|
||||
sc[r] = (float)acc;
|
||||
}
|
||||
for (int64_t o = 0; o < R; ++o) {
|
||||
int64_t best = -1;
|
||||
for (int64_t c = 0; c < R; ++c) {
|
||||
if (used[c] != 0.0f || id[c] < 0) continue;
|
||||
if (best < 0 || sc[c] > sc[best] || (sc[c] == sc[best] && id[c] < id[best])) best = c;
|
||||
}
|
||||
const int32_t oid = best >= 0 ? id[best] : -1;
|
||||
const float ov = best >= 0 ? sc[best] : -INFINITY;
|
||||
if (best >= 0) used[best] = 1.0f;
|
||||
st_index(idx.dtype, idx.base, m * idx.pitch + o, (int64_t)oid);
|
||||
rad_store_f32(val.base, val.dtype, m * val.pitch + o, ov);
|
||||
if (pairs) {
|
||||
float* p = pairs + (m * R + o) * 2;
|
||||
p[0] = sycl::bit_cast<float>(oid);
|
||||
p[1] = ov;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int dflash_conv(const RadArgs* a, RadStream st) {
|
||||
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *DL = &a->t[1], *BS = &a->t[2], *O = &a->t[3];
|
||||
const int64_t taps = rad_args_geti_or(a, "taps", 0), group = rad_args_geti_or(a, "group_size", 0);
|
||||
const int64_t NG = rad_args_geti_or(a, "NG", 0), bsz = rad_args_geti_or(a, "block_size", 0);
|
||||
if (taps <= 0 || group <= 0 || NG <= 0 || bsz <= 0) return RAD_E_INVAL;
|
||||
if (X->data == O->data) return RAD_E_INVAL;
|
||||
if (X->rank != 2 || O->rank != 2) return RAD_E_SHAPE;
|
||||
const int64_t T = X->shape[0], H = X->shape[1];
|
||||
if (T <= 0 || O->shape[0] != T || O->shape[1] != H || H != NG * group) return RAD_E_SHAPE;
|
||||
if (rad_tensor_numel(BS) < taps * H) return RAD_E_SHAPE;
|
||||
int64_t d_rs = 0, d_ts = 0, d_gs = 0;
|
||||
if (DL->rank == 3) {
|
||||
if (DL->shape[0] < T || DL->shape[1] < taps || DL->shape[2] < NG) return RAD_E_SHAPE;
|
||||
d_rs = DL->stride[0]; d_ts = DL->stride[1]; d_gs = DL->stride[2];
|
||||
} else if (DL->rank == 2) {
|
||||
if (DL->shape[0] < T || DL->shape[1] < taps * NG) return RAD_E_SHAPE;
|
||||
d_rs = DL->stride[0]; d_gs = DL->stride[1]; d_ts = NG * d_gs;
|
||||
} else {
|
||||
return RAD_E_SHAPE;
|
||||
}
|
||||
Rows bs;
|
||||
if (int rc = rows_view(BS, H, &bs, "dflash_conv bias"); rc < 0) return rc;
|
||||
const int64_t bcs = laststride(BS);
|
||||
const int64_t x_rs = X->stride[0], x_cs = X->stride[1], o_rs = O->stride[0], o_cs = O->stride[1];
|
||||
const char *xb = (const char*)X->data, *db = (const char*)DL->data;
|
||||
char* ob = (char*)O->data;
|
||||
const uint32_t xdt = X->dtype, ddt = DL->dtype, odt = O->dtype;
|
||||
sycl::queue* q = queue_of(st);
|
||||
if (!q) return RAD_E_DEVICE;
|
||||
const int64_t total = T * H;
|
||||
const size_t wg = 256;
|
||||
const size_t groups = (size_t)((total + (int64_t)wg - 1) / (int64_t)wg);
|
||||
return submit([&] {
|
||||
syclex::nd_launch(*q, sycl::nd_range<1>{groups * wg, wg}, [=](sycl::nd_item<1> it) {
|
||||
const int64_t gi = (int64_t)it.get_global_id(0);
|
||||
if (gi >= total) return;
|
||||
const int64_t t = gi / H, h = gi % H, g = h / group;
|
||||
float acc = 0.0f;
|
||||
for (int64_t j = 0; j < taps; ++j) {
|
||||
if (j > 0 && t % bsz < j) continue;
|
||||
const float c = rad_load_f32(bs.base, bs.dtype, j * bs.pitch + h * bcs) +
|
||||
rad_load_f32(db, ddt, t * d_rs + j * d_ts + g * d_gs);
|
||||
const float term = c * rad_load_f32(xb, xdt, (t - j) * x_rs + h * x_cs);
|
||||
acc = j == 0 ? term : acc + term;
|
||||
}
|
||||
rad_store_f32(ob, odt, t * o_rs + h * o_cs, acc);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
int logit_rerank(const RadArgs* a, RadStream s) { return rerank(a, s, false); }
|
||||
int logit_rerank_head(const RadArgs* a, RadStream s) { return rerank(a, s, true); }
|
||||
|
||||
} // namespace xe2
|
||||
+181
-4
@@ -2,17 +2,27 @@
|
||||
*
|
||||
* add: y = a + b, b broadcast along rows when it holds one row (a bias add), and with `div`,
|
||||
* y = rd(rd(a + b) / div), rd being y's dtype: libref's elementwise2 (ref_elementwise.cpp).
|
||||
* mul: the same with a * b and no `div`.
|
||||
* sigmoid: libref's act_sigmoid, 1 / (1 + exp(-x)) with the exp in double rounded once (ref_exp),
|
||||
* walked in logical order through offlin.
|
||||
* scatter_rows: row m of v to row idx[m] of x; a negative index is skipped, one past x's rows refused.
|
||||
* layernorm: libref's, the mean and the squared deviations summed serially in index order by one
|
||||
* work-item, then y = ((x - mean) * s) * w (+ b).
|
||||
* grid_embed: x += the side x side table bilinearly resampled at each row's (r, c) of an (h, w) grid
|
||||
* (the vision tower's position embedding), the four taps added in libref's order.
|
||||
*/
|
||||
#include "xe2_common.h"
|
||||
#include "xe2_ops.h"
|
||||
|
||||
namespace xe2 {
|
||||
|
||||
int add(const RadArgs* a, RadStream s) {
|
||||
if (!rad_args_have(a, 3)) return refuse("add: missing operand");
|
||||
namespace {
|
||||
|
||||
int elementwise2(const RadArgs* a, RadStream s, bool mul) {
|
||||
if (!rad_args_have(a, 3)) return refuse("%s: missing operand", mul ? "mul" : "add");
|
||||
const RadTensor *A = &a->t[0], *B = &a->t[1], *Y = &a->t[2];
|
||||
const int64_t n = rad_args_geti_or(a, "n", rad_tensor_numel(Y));
|
||||
const float div = (float)rad_args_getf_or(a, "div", 1.0);
|
||||
const float div = mul ? 1.0f : (float)rad_args_getf_or(a, "div", 1.0);
|
||||
if (!(div != 0.0f) || !sycl::isfinite(div)) return RAD_E_INVAL;
|
||||
if (n <= 0) return RAD_E_SHAPE;
|
||||
Rows ya, aa, ba;
|
||||
@@ -37,11 +47,178 @@ int add(const RadArgs* a, RadStream s) {
|
||||
const int64_t r = g / n, i = g % n;
|
||||
const float u = rad_load_f32(aa.base, aa.dtype, r * aa.pitch + i);
|
||||
const float v = rad_load_f32(ba.base, ba.dtype, r * ba.pitch + i);
|
||||
float x = u + v;
|
||||
float x = mul ? u * v : u + v;
|
||||
if (div != 1.0f) x = round_dt(ya.dtype, x) / div;
|
||||
rad_store_f32(ya.base, ya.dtype, r * ya.pitch + i, x);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int add(const RadArgs* a, RadStream s) { return elementwise2(a, s, false); }
|
||||
int mul(const RadArgs* a, RadStream s) { return elementwise2(a, s, true); }
|
||||
|
||||
int sigmoid(const RadArgs* a, RadStream s) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *Y = &a->t[1];
|
||||
const int64_t nel = rad_tensor_numel(Y);
|
||||
if (nel <= 0 || rad_tensor_numel(X) < nel) return RAD_E_SHAPE;
|
||||
const Lin x = Lin::of(X), y = Lin::of(Y);
|
||||
sycl::queue* q = queue_of(s);
|
||||
if (!q) return RAD_E_DEVICE;
|
||||
const size_t wg = 256;
|
||||
const size_t groups = (size_t)((nel + (int64_t)wg - 1) / (int64_t)wg);
|
||||
return submit([&] {
|
||||
syclex::nd_launch(*q, sycl::nd_range<1>{groups * wg, wg}, [=](sycl::nd_item<1> it) {
|
||||
const int64_t i = (int64_t)it.get_global_id(0);
|
||||
if (i >= nel) return;
|
||||
const float v = rad_load_f32(x.base, x.dtype, x.off(i));
|
||||
rad_store_f32(y.base, y.dtype, y.off(i), 1.0f / (1.0f + (float)sycl::exp((double)-v)));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
int scatter_rows(const RadArgs* a, RadStream s) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *V = &a->t[0], *I = &a->t[1], *X = &a->t[2];
|
||||
const int64_t n = rad_args_geti_or(a, "n", V->rank >= 1 ? V->shape[V->rank - 1] : 0);
|
||||
if (n <= 0) return RAD_E_SHAPE;
|
||||
Rows v, x;
|
||||
if (int rc = rows_view(V, n, &v, "scatter_rows v"); rc < 0) return rc;
|
||||
if (int rc = rows_view(X, n, &x, "scatter_rows x"); rc < 0) return rc;
|
||||
const int64_t M = v.rows, dst_rows = x.rows;
|
||||
if (M <= 0 || dst_rows <= 0 || rad_tensor_numel(I) < M) return RAD_E_SHAPE;
|
||||
const Lin idx = Lin::of(I);
|
||||
sycl::queue* q = queue_of(s);
|
||||
if (!q) return RAD_E_DEVICE;
|
||||
/* libref refuses an index past x's rows before writing anything; the indices live on the card,
|
||||
* so a device flag records one and the call reports it after the copy is skipped. */
|
||||
int* bad = sycl::malloc_shared<int>(1, *q);
|
||||
if (!bad) return refuse("scatter_rows: no flag memory");
|
||||
*bad = 0;
|
||||
int rc = submit([&] {
|
||||
syclex::nd_launch(*q, sycl::nd_range<1>{256, 256}, [=](sycl::nd_item<1> it) {
|
||||
for (int64_t m = (int64_t)it.get_local_id(0); m < M; m += 256)
|
||||
if (ld_index(idx.dtype, idx.base, idx.off(m)) >= dst_rows) *bad = 1;
|
||||
});
|
||||
q->wait();
|
||||
});
|
||||
if (rc >= 0 && *bad) rc = RAD_E_INVAL;
|
||||
sycl::free(bad, *q);
|
||||
if (rc < 0) return rc;
|
||||
const int64_t total = M * n;
|
||||
const size_t wg = 256;
|
||||
const size_t groups = (size_t)((total + (int64_t)wg - 1) / (int64_t)wg);
|
||||
return submit([&] {
|
||||
syclex::nd_launch(*q, sycl::nd_range<1>{groups * wg, wg}, [=](sycl::nd_item<1> it) {
|
||||
const int64_t g = (int64_t)it.get_global_id(0);
|
||||
if (g >= total) return;
|
||||
const int64_t m = g / n, i = g % n;
|
||||
const int64_t r = ld_index(idx.dtype, idx.base, idx.off(m));
|
||||
if (r < 0) return;
|
||||
rad_store_f32(x.base, x.dtype, r * x.pitch + i, rad_load_f32(v.base, v.dtype, m * v.pitch + i));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
int layernorm(const RadArgs* a, RadStream s) {
|
||||
if (!a || a->n_t < 4 || !a->t[0].data || !a->t[1].data || !a->t[3].data) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *W = &a->t[1], *Y = &a->t[3];
|
||||
const RadTensor* B = rad_arg_in(a, 2);
|
||||
const int64_t n = rad_args_geti_or(a, "n", W->rank ? W->shape[W->rank - 1] : 0);
|
||||
const float eps = (float)rad_args_getf_or(a, "eps", 1e-5);
|
||||
if (n <= 0) return RAD_E_SHAPE;
|
||||
Rows x, y;
|
||||
if (int rc = rows_view(X, n, &x, "layernorm x"); rc < 0) return rc;
|
||||
if (int rc = rows_view(Y, n, &y, "layernorm y"); rc < 0) return rc;
|
||||
const int64_t rows = x.rows;
|
||||
if (rows <= 0 || rad_tensor_numel(Y) < rows * n || rad_tensor_numel(W) < n) return RAD_E_SHAPE;
|
||||
if (B && rad_tensor_numel(B) < n) return RAD_E_SHAPE;
|
||||
const Lin w = Lin::of(W);
|
||||
const bool hb = B && B->data;
|
||||
const Lin b = hb ? Lin::of(B) : Lin{};
|
||||
sycl::queue* q = queue_of(s);
|
||||
if (!q) return RAD_E_DEVICE;
|
||||
constexpr size_t wg = 256;
|
||||
return submit([&] {
|
||||
syclex::nd_launch(*q, 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 mean = 0.0f, sc = 0.0f;
|
||||
if (t == 0) {
|
||||
float sum = 0.0f;
|
||||
for (int64_t i = 0; i < n; ++i) sum += rad_load_f32(x.base, x.dtype, r * x.pitch + i);
|
||||
mean = sum / (float)n;
|
||||
float ss = 0.0f;
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const float d = rad_load_f32(x.base, x.dtype, r * x.pitch + i) - mean;
|
||||
ss += d * d;
|
||||
}
|
||||
sc = 1.0f / sycl::sqrt(ss / (float)n + eps);
|
||||
}
|
||||
mean = sycl::group_broadcast(it.get_group(), mean, 0);
|
||||
sc = sycl::group_broadcast(it.get_group(), sc, 0);
|
||||
for (int64_t i = t; i < n; i += (int64_t)wg) {
|
||||
float v = (rad_load_f32(x.base, x.dtype, r * x.pitch + i) - mean) * sc *
|
||||
rad_load_f32(w.base, w.dtype, w.off(i));
|
||||
if (hb) v += rad_load_f32(b.base, b.dtype, b.off(i));
|
||||
rad_store_f32(y.base, y.dtype, r * y.pitch + i, v);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
int grid_embed(const RadArgs* a, RadStream s) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *TAB = &a->t[1], *CRD = &a->t[2];
|
||||
const int64_t n = rad_args_geti_or(a, "n", TAB->rank ? TAB->shape[TAB->rank - 1] : 0);
|
||||
const int64_t side = rad_args_geti_or(a, "side", 0);
|
||||
if (n <= 0 || side <= 0 || rad_tensor_numel(TAB) < side * side * n) return RAD_E_SHAPE;
|
||||
Rows x, tab;
|
||||
if (int rc = rows_view(X, n, &x, "grid_embed x"); rc < 0) return rc;
|
||||
if (int rc = rows_view(TAB, n, &tab, "grid_embed table"); rc < 0) return rc;
|
||||
const int64_t rows = x.rows;
|
||||
if (rows <= 0 || CRD->rank != 2 || CRD->shape[0] < 4 || CRD->shape[1] < rows) return RAD_E_SHAPE;
|
||||
const int64_t cs = CRD->stride[0], ms = CRD->stride[1];
|
||||
const char* cb = (const char*)CRD->data;
|
||||
const uint32_t cdt = CRD->dtype;
|
||||
sycl::queue* q = queue_of(s);
|
||||
if (!q) return RAD_E_DEVICE;
|
||||
const int64_t total = rows * n;
|
||||
const size_t wg = 256;
|
||||
const size_t groups = (size_t)((total + (int64_t)wg - 1) / (int64_t)wg);
|
||||
return submit([&] {
|
||||
syclex::nd_launch(*q, sycl::nd_range<1>{groups * wg, wg}, [=](sycl::nd_item<1> it) {
|
||||
const int64_t g = (int64_t)it.get_global_id(0);
|
||||
if (g >= total) return;
|
||||
const int64_t r = g / n, i = g % n;
|
||||
const int64_t gr = ld_index(cdt, cb, 0 * cs + r * ms), gc = ld_index(cdt, cb, 1 * cs + r * ms);
|
||||
const int64_t gh = ld_index(cdt, cb, 2 * cs + r * ms), gw = ld_index(cdt, cb, 3 * cs + r * ms);
|
||||
int64_t th[2], tw[2];
|
||||
float wh[2], ww[2];
|
||||
auto axis = [&](int64_t idx, int64_t size, int64_t* t, float* w) {
|
||||
const float src = (float)idx * (float)(side - 1) / (float)(size - 1 > 1 ? size - 1 : 1);
|
||||
const float fl = sycl::floor(src);
|
||||
for (int k = 0; k < 2; ++k) {
|
||||
const int64_t tap = (int64_t)fl + k;
|
||||
t[k] = tap < 0 ? 0 : (tap > side - 1 ? side - 1 : tap);
|
||||
const float d = sycl::fabs(src - fl - (float)k);
|
||||
w[k] = 1.0f - d > 0.0f ? 1.0f - d : 0.0f;
|
||||
}
|
||||
};
|
||||
axis(gr, gh, th, wh);
|
||||
axis(gc, gw, tw, ww);
|
||||
float acc = 0.0f;
|
||||
for (int ki = 0; ki < 2; ++ki)
|
||||
for (int kj = 0; kj < 2; ++kj)
|
||||
acc += rad_load_f32(tab.base, tab.dtype, (th[ki] * side + tw[kj]) * tab.pitch + i) *
|
||||
(wh[ki] * ww[kj]);
|
||||
const float pe = round_dt(x.dtype, acc);
|
||||
const int64_t xo = r * x.pitch + i;
|
||||
rad_store_f32(x.base, x.dtype, xo, rad_load_f32(x.base, x.dtype, xo) + pe);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
} // namespace xe2
|
||||
@@ -19,16 +19,6 @@ namespace {
|
||||
|
||||
bool is_int(uint32_t dt) { return dt == RAD_I32 || dt == RAD_I64 || dt == RAD_U32 || dt == RAD_I16; }
|
||||
|
||||
inline void st_index(uint32_t dt, void* p, int64_t i, int64_t v) {
|
||||
switch (dt) {
|
||||
case RAD_I32: ((int32_t*)p)[i] = (int32_t)v; break;
|
||||
case RAD_U32: ((uint32_t*)p)[i] = (uint32_t)v; break;
|
||||
case RAD_I64: ((int64_t*)p)[i] = v; break;
|
||||
case RAD_I16: ((int16_t*)p)[i] = (int16_t)v; break;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
|
||||
constexpr size_t kWg = 256;
|
||||
|
||||
} // namespace
|
||||
|
||||
@@ -0,0 +1,948 @@
|
||||
/* 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
|
||||
+140
-9
@@ -12,6 +12,11 @@
|
||||
#include "xe2_common.h"
|
||||
#include "xe2_ops.h"
|
||||
|
||||
#include "rad_planes.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
|
||||
namespace xe2 {
|
||||
|
||||
namespace {
|
||||
@@ -32,24 +37,96 @@ bool is_float(uint32_t dt) {
|
||||
return dt == RAD_F32 || dt == RAD_F16 || dt == RAD_BF16 || dt == RAD_F8E4M3 || dt == RAD_F8E5M2;
|
||||
}
|
||||
|
||||
int gemm_plain(const RadArgs* a, RadStream st, const char* nkey, const char* kkey, const char* op) {
|
||||
if (!a || a->n_t < 3 || !a->t[0].data || !a->t[1].data || !a->t[2].data) return RAD_E_INVAL;
|
||||
const RadTensor *A = &a->t[0], *B = &a->t[1], *Y = &a->t[2];
|
||||
/* A plane of a joined head, found on the card (the header lives in device memory). */
|
||||
struct HPlane {
|
||||
const char* p = nullptr;
|
||||
uint32_t dt = 0;
|
||||
int64_t row_bytes = 0, br = 0, bc = 0;
|
||||
float at(int64_t i, int64_t j) const { return rad_load_f32(p + i * row_bytes, dt, j); }
|
||||
float cover(int64_t r, int64_t c) const { return at(br > 0 ? r / br : 0, bc > 0 ? c / bc : 0); }
|
||||
};
|
||||
|
||||
inline bool role_is(const char* r, const char* want) {
|
||||
for (int i = 0; i < RAD_ENC_STR; ++i) {
|
||||
if (r[i] != want[i]) return false;
|
||||
if (!want[i]) return true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
inline HPlane hplane(const char* base, const char* role) {
|
||||
HPlane v;
|
||||
const RadPlanesHeader* h = (const RadPlanesHeader*)base;
|
||||
if (h->magic != RAD_PLANES_MAGIC) return v;
|
||||
const RadPlanesEntry* e = (const RadPlanesEntry*)(base + sizeof(RadPlanesHeader));
|
||||
for (int i = 0; i < h->n_planes && i < RAD_ENC_MAX_PLANES; ++i)
|
||||
if (role_is(e[i].role, role)) {
|
||||
v.p = base + e[i].offset;
|
||||
v.dt = e[i].dtype;
|
||||
v.row_bytes = e[i].row_bytes;
|
||||
v.br = e[i].block[0];
|
||||
v.bc = e[i].block[1];
|
||||
return v;
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
inline float gelu(float x) { return 0.5f * x * (1.0f + (float)sycl::erf((double)(x * 0.70710678118654752f))); }
|
||||
inline float gelu_tanh(float x) {
|
||||
const float k0 = 0.7978845608028654f, k1 = 0.044715f;
|
||||
return 0.5f * x * (1.0f + (float)sycl::tanh((double)(k0 * (x + k1 * x * x * x))));
|
||||
}
|
||||
|
||||
/* libref's gemm_nt_impl: acc += a * b over ascending k, then the bias, stored; then the activation
|
||||
* on the stored value and the residual added to it, each stored (gemm_epilogue). `joined`: B is a
|
||||
* head of E4M3 / int8 codes and a scale plane, each element decoded to code * scale in f32 first
|
||||
* (gemm_scaled_rows). */
|
||||
int gemm_plain(const RadArgs* a, RadStream st, const char* nkey, const char* kkey, const char* op,
|
||||
bool bias_form = false, bool joined = false) {
|
||||
const int nt = bias_form ? 5 : 3;
|
||||
if (!a || a->n_t < nt || !a->t[0].data || !a->t[1].data || !a->t[nt - 1].data) return RAD_E_INVAL;
|
||||
const RadTensor *A = &a->t[0], *B = &a->t[1], *Y = &a->t[nt - 1];
|
||||
const RadTensor* bias = bias_form ? rad_arg_in(a, 2) : nullptr;
|
||||
const RadTensor* res = bias_form ? rad_arg_in(a, 3) : nullptr;
|
||||
int act = 0;
|
||||
if (bias_form) {
|
||||
const char* as = rad_args_gets_or(a, "act", "none");
|
||||
if (!std::strcmp(as, "none")) act = 0;
|
||||
else if (!std::strcmp(as, "gelu")) act = 1;
|
||||
else if (!std::strcmp(as, "gelu_tanh")) act = 2;
|
||||
else return RAD_E_INVAL;
|
||||
}
|
||||
const int64_t K = rad_args_geti_or(a, kkey, B->rank >= 2 ? B->shape[B->rank - 1] : 0);
|
||||
const int64_t N = rad_args_geti_or(a, nkey, B->rank >= 2 ? B->shape[B->rank - 2] : 0);
|
||||
if (K <= 0 || N <= 0) return RAD_E_SHAPE;
|
||||
const int64_t M = rad_tensor_numel(Y) / N;
|
||||
if (M <= 0) return RAD_E_SHAPE;
|
||||
if (!is_float(B->dtype) || !is_float(A->dtype))
|
||||
if (!is_float(A->dtype) || (!joined && !is_float(B->dtype)))
|
||||
return refuse("%s: dtype pair %u x %u is not served (a quantised weight is gemm_nt_q's)", op,
|
||||
A->dtype, B->dtype);
|
||||
if (rad_tensor_numel(A) < M * K || rad_tensor_numel(B) < N * K) return RAD_E_SHAPE;
|
||||
if (rad_tensor_numel(A) < M * K || (!joined && rad_tensor_numel(B) < N * K)) return RAD_E_SHAPE;
|
||||
if (bias && rad_tensor_numel(bias) < N) return RAD_E_SHAPE;
|
||||
if (res && rad_tensor_numel(res) < M * N) return RAD_E_SHAPE;
|
||||
const int64_t ars = row_stride(A, K), acs = A->rank >= 2 ? A->stride[A->rank - 1] : 1;
|
||||
const int64_t brs = row_stride(B, K), bcs = B->rank >= 2 ? B->stride[B->rank - 1] : 1;
|
||||
const int64_t brs = joined ? 0 : row_stride(B, K), bcs = !joined && B->rank >= 2 ? B->stride[B->rank - 1] : 1;
|
||||
const int64_t yrs = row_stride(Y, N), ycs = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1;
|
||||
const int64_t rrs = res ? row_stride(res, N) : 0, rcs = res && res->rank >= 2 ? res->stride[res->rank - 1] : 1;
|
||||
const int64_t bis = bias && bias->rank ? bias->stride[bias->rank - 1] : 1;
|
||||
if (res && res->data != Y->data) {
|
||||
/* libref snapshots an overlapping residual; here an element reads its residual before its
|
||||
* store, which is the same only when the residual is Y itself or apart from it. */
|
||||
const char *rl = (const char*)res->data, *yl = (const char*)Y->data;
|
||||
const int64_t span = (M - 1) * std::max(yrs, rrs) + N * std::max(ycs, rcs);
|
||||
const int64_t eb = 4;
|
||||
if (rl < yl + span * eb && yl < rl + span * eb && (rrs != yrs || rcs != ycs || res->dtype != Y->dtype))
|
||||
return refuse("%s: a residual overlapping y in another layout", op);
|
||||
}
|
||||
const char *ab = (const char*)A->data, *bb = (const char*)B->data;
|
||||
const char* bsb = bias ? (const char*)bias->data : nullptr;
|
||||
const char* rb = res ? (const char*)res->data : nullptr;
|
||||
char* yb = (char*)Y->data;
|
||||
const uint32_t adt = A->dtype, bdt = B->dtype, ydt = Y->dtype;
|
||||
const uint32_t bidt = bias ? bias->dtype : 0, rdt = res ? res->dtype : 0;
|
||||
|
||||
sycl::queue* q = queue_of(st);
|
||||
if (!q) return RAD_E_DEVICE;
|
||||
@@ -61,9 +138,25 @@ int gemm_plain(const RadArgs* a, RadStream st, const char* nkey, const char* kke
|
||||
const int64_t m = (int64_t)it.get_global_id(0), n = (int64_t)it.get_global_id(1);
|
||||
if (n >= N) return;
|
||||
float acc = 0.0f;
|
||||
for (int64_t k = 0; k < K; ++k)
|
||||
acc += rad_load_f32(ab, adt, m * ars + k * acs) * rad_load_f32(bb, bdt, n * brs + k * bcs);
|
||||
rad_store_f32(yb, ydt, m * yrs + n * ycs, acc);
|
||||
if (joined) {
|
||||
const HPlane cp = hplane(bb, "codes"), sp = hplane(bb, "scale");
|
||||
if (!cp.p || !sp.p) return; /* the layout hook guarantees a joined head */
|
||||
for (int64_t k = 0; k < K; ++k)
|
||||
acc += rad_load_f32(ab, adt, m * ars + k * acs) * (cp.at(n, k) * sp.cover(n, k));
|
||||
} else {
|
||||
for (int64_t k = 0; k < K; ++k)
|
||||
acc += rad_load_f32(ab, adt, m * ars + k * acs) * rad_load_f32(bb, bdt, n * brs + k * bcs);
|
||||
}
|
||||
const int64_t o = m * yrs + n * ycs;
|
||||
const float rv = rb ? rad_load_f32(rb, rdt, m * rrs + n * rcs) : 0.0f;
|
||||
float v = acc;
|
||||
if (bsb) v += rad_load_f32(bsb, bidt, n * bis);
|
||||
rad_store_f32(yb, ydt, o, v);
|
||||
if (act || rb) {
|
||||
if (act == 1) rad_store_f32(yb, ydt, o, gelu(rad_load_f32(yb, ydt, o)));
|
||||
else if (act == 2) rad_store_f32(yb, ydt, o, gelu_tanh(rad_load_f32(yb, ydt, o)));
|
||||
if (rb) rad_store_f32(yb, ydt, o, rv + rad_load_f32(yb, ydt, o));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -71,8 +164,46 @@ int gemm_plain(const RadArgs* a, RadStream st, const char* nkey, const char* kke
|
||||
} // namespace
|
||||
|
||||
int gemm_nt(const RadArgs* a, RadStream s) { return gemm_plain(a, s, "N", "K", "gemm_nt"); }
|
||||
int gemm_nt_bias(const RadArgs* a, RadStream s) {
|
||||
return gemm_plain(a, s, "N", "K", "gemm_nt_bias", true);
|
||||
}
|
||||
int logits_gemm(const RadArgs* a, RadStream s) {
|
||||
return gemm_plain(a, s, "n_vocab", "n_embd", "logits_gemm");
|
||||
}
|
||||
int logits_gemm_head(const RadArgs* a, RadStream s) {
|
||||
return gemm_plain(a, s, "n_vocab", "n_embd", "logits_gemm", false, true);
|
||||
}
|
||||
|
||||
/* libref's ref_layout_head: operand 1 (the head) of codes and one scale, joined. */
|
||||
int head_layout(const RadParam*, int, int operand, const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* planes, int n, RadLayout* out) {
|
||||
if (n < 2 || operand != 1) return RAD_E_UNSUPPORTED;
|
||||
if (!rad_enc_is(enc, "affine") || enc->transform[0] || enc->n_planes != 2) return RAD_E_DTYPE;
|
||||
if (!sel || n != 2 || sel[0] < 0 || sel[0] >= enc->n_planes || sel[1] < 0 || sel[1] >= enc->n_planes)
|
||||
return RAD_E_DTYPE;
|
||||
const RadEncPlane& c = enc->plane[sel[0]];
|
||||
const RadEncPlane& sc = enc->plane[sel[1]];
|
||||
if (std::strncmp(c.role, "codes", RAD_ENC_STR) != 0 || std::strncmp(sc.role, "scale", RAD_ENC_STR) != 0)
|
||||
return RAD_E_DTYPE;
|
||||
const bool fs = sc.dtype == RAD_F32 || sc.dtype == RAD_F16 || sc.dtype == RAD_BF16;
|
||||
if (!(c.kind == RAD_PLANE_TILED && c.block[0] == 1 && c.block[1] == 1 &&
|
||||
(c.dtype == RAD_F8E4M3 || c.dtype == RAD_I8) && sc.kind == RAD_PLANE_TILED && fs))
|
||||
return RAD_E_DTYPE;
|
||||
return rad_planes_layout(enc, sel, planes, n, out);
|
||||
}
|
||||
int head_relayout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* planes, int n, void* dst, int64_t dst_bytes) {
|
||||
RadLayout lay{};
|
||||
const int st = head_layout(p, n_p, operand, enc, sel, planes, n, &lay);
|
||||
if (st != RAD_OK) return st;
|
||||
return rad_planes_relayout(enc, sel, planes, n, dst, dst_bytes);
|
||||
}
|
||||
int head_unrelayout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel,
|
||||
const void* src, int64_t src_bytes, const RadTensor* planes, int n) {
|
||||
RadLayout lay{};
|
||||
const int st = head_layout(p, n_p, operand, enc, sel, planes, n, &lay);
|
||||
if (st != RAD_OK) return st;
|
||||
return rad_planes_unrelayout(enc, sel, src, src_bytes, planes, n);
|
||||
}
|
||||
|
||||
} // namespace xe2
|
||||
@@ -0,0 +1,210 @@
|
||||
/* xe2_gemm_m2.cpp -- gemm_nt_q at dtype m2xfp4 (the M2XFP4 grid of Qwen3.8-27B-PARO-M2XFP4).
|
||||
* Correctness first: libref's gemm_m2 (ref_gemm.cpp) per output --
|
||||
*
|
||||
* w[k] = (e2m1(code[n][k]) * 2^(e[n][k/32] - 127)) * (1 + meta field / 4)
|
||||
* acc = acc + (a[m][k] * a_scale[m][k/128]) * w[k] for ascending k, f32
|
||||
*
|
||||
* -- the meta byte's two-bit field [2s, 2s+2) over subgroups s of eight columns. The activation is
|
||||
* givens_dense_quant's E4M3 with a scale per 128 columns; the weight's Givens rotation is the
|
||||
* activation's, so the planes are read as they are stored. Parts (`pb1`, `pb2`, a fused projection
|
||||
* rotated per piece): weight rows [0, e1), [e1, e2), [e2, N) read copies 0, 1, 2 of the activation
|
||||
* and its scale, side by side, as libref's gemm_m2 and libr4d's mx_parts do.
|
||||
*
|
||||
* `b` reaches the kernel as the weight's codes rows, then its meta rows ("m2.codes.meta"), `b_scale`
|
||||
* as the E8M0 plane [N, K/32]. The layout hooks are libref's m2 arm (ref_layout_gemm_q,
|
||||
* ref_planes.h) line for line, so both libraries ask for the same stored bytes.
|
||||
*/
|
||||
#include "xe2_common.h"
|
||||
#include "xe2_ops.h"
|
||||
|
||||
#include "rad_planes.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
|
||||
namespace xe2 {
|
||||
|
||||
namespace {
|
||||
|
||||
int64_t row_stride(const RadTensor* t, int64_t cols) {
|
||||
if (!t || t->rank < 2) return cols;
|
||||
int64_t span = 1;
|
||||
for (int i = (int)t->rank - 1; i >= 0; --i) {
|
||||
span *= t->shape[i];
|
||||
if (span == cols) return (i > 0) ? t->stride[i - 1] : cols;
|
||||
if (span > cols) break;
|
||||
}
|
||||
return t->stride[t->rank - 2];
|
||||
}
|
||||
|
||||
int64_t last_stride(const RadTensor* t) { return t->rank ? t->stride[t->rank - 1] : 1; }
|
||||
|
||||
bool sel_roles(const RadEncoding* enc, const int* sel, int n, const char* r0, const char* r1) {
|
||||
if (!enc || !sel || n != 2) return false;
|
||||
for (int i = 0; i < 2; ++i)
|
||||
if (sel[i] < 0 || sel[i] >= enc->n_planes) return false;
|
||||
return std::strncmp(enc->plane[sel[0]].role, r0, RAD_ENC_STR) == 0 &&
|
||||
std::strncmp(enc->plane[sel[1]].role, r1, RAD_ENC_STR) == 0;
|
||||
}
|
||||
|
||||
/* libref's m2_enc_planes: three tiled planes over 32-column groups, untransformed or under a
|
||||
* "givens" transform with its tables beside them. */
|
||||
bool m2_enc_planes(const RadEncoding* enc) {
|
||||
if (!rad_enc_is(enc, "m2xfp4")) return false;
|
||||
if (enc->transform[0] && std::strncmp(enc->transform, "givens", RAD_ENC_STR) != 0) return false;
|
||||
const RadEncPlane* sc = rad_enc_plane(enc, "scale");
|
||||
const RadEncPlane* mt = rad_enc_plane(enc, "meta");
|
||||
const bool planes = enc->plane[0].kind == RAD_PLANE_TILED &&
|
||||
enc->plane[0].dtype == RAD_FP4E2M1 && enc->plane[0].block[0] == 1 &&
|
||||
enc->plane[0].block[1] == 1 && sc && mt && sc->kind == RAD_PLANE_TILED &&
|
||||
sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == 32 &&
|
||||
mt->kind == RAD_PLANE_TILED && mt->dtype == RAD_U8 && mt->block[0] == 1 &&
|
||||
mt->block[1] == 32;
|
||||
if (!planes) return false;
|
||||
if (!enc->transform[0]) return enc->n_planes == 3;
|
||||
return enc->n_planes >= 6 && rad_enc_plane(enc, "t.pairs") &&
|
||||
rad_enc_plane(enc, "t.angle") && rad_enc_plane(enc, "t.scale");
|
||||
}
|
||||
|
||||
constexpr const char* kTag = "m2.codes.meta";
|
||||
|
||||
} // namespace
|
||||
|
||||
/* ------------------------------------------------------------------ the layout hooks */
|
||||
int gemm_m2_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* planes, int n, RadLayout* out) {
|
||||
const char* dt = rad_param_gets(p, n_p, "dtype", nullptr);
|
||||
if (!dt || std::strcmp(dt, "m2xfp4") != 0) return RAD_E_DTYPE;
|
||||
const long long group = rad_param_geti(p, n_p, "group", 0);
|
||||
const long long N = rad_param_geti(p, n_p, "N", 0), K = rad_param_geti(p, n_p, "K", 0);
|
||||
if (!m2_enc_planes(enc) || group != 32 || N <= 0 || K <= 0 || K % 32) return RAD_E_DTYPE;
|
||||
if (operand == 2) {
|
||||
if (!sel_roles(enc, sel, n, "codes", "meta")) return RAD_E_DTYPE;
|
||||
if (planes[0].shape[0] != N || planes[0].shape[1] != K || planes[1].shape[0] != N ||
|
||||
planes[1].shape[1] != K / 32)
|
||||
return RAD_E_SHAPE;
|
||||
out->tag = kTag;
|
||||
out->dtype = RAD_U8;
|
||||
out->rank = 1;
|
||||
out->shape[0] = N * (K / 2 + K / 32);
|
||||
out->align = 0;
|
||||
out->bytes = out->shape[0];
|
||||
return RAD_OK;
|
||||
}
|
||||
if (operand == 3 || operand == 6) {
|
||||
if (n != 1 || sel[0] < 0 || sel[0] >= enc->n_planes ||
|
||||
std::strncmp(enc->plane[sel[0]].role, "scale", RAD_ENC_STR) != 0)
|
||||
return RAD_E_DTYPE;
|
||||
return RAD_E_UNSUPPORTED; /* one plane, stored as it is */
|
||||
}
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
int gemm_m2_relayout(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
|
||||
const int* sel, const RadTensor* planes, int n, void* dst, int64_t dst_bytes) {
|
||||
RadLayout lay{};
|
||||
const int st = gemm_m2_layout(p, n_p, operand, enc, sel, planes, n, &lay);
|
||||
if (st != RAD_OK) return st;
|
||||
if (!lay.tag || std::strcmp(lay.tag, kTag) != 0)
|
||||
return rad_planes_relayout(enc, sel, planes, n, dst, dst_bytes);
|
||||
if (dst_bytes != lay.bytes) return RAD_E_SHAPE;
|
||||
uint8_t* d = (uint8_t*)dst;
|
||||
for (int i = 0; i < n; ++i) {
|
||||
const int64_t b = planes[i].shape[0] * rad_enc_row_bytes(planes[i].dtype, planes[i].shape[1]);
|
||||
std::memcpy(d, planes[i].data, (size_t)b);
|
||||
d += b;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int gemm_m2_unrelayout(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
|
||||
const int* sel, const void* src, int64_t src_bytes, const RadTensor* planes,
|
||||
int n) {
|
||||
RadLayout lay{};
|
||||
const int st = gemm_m2_layout(p, n_p, operand, enc, sel, planes, n, &lay);
|
||||
if (st != RAD_OK) return st;
|
||||
if (!lay.tag || std::strcmp(lay.tag, kTag) != 0)
|
||||
return rad_planes_unrelayout(enc, sel, src, src_bytes, planes, n);
|
||||
if (src_bytes != lay.bytes) return RAD_E_SHAPE;
|
||||
const uint8_t* s = (const uint8_t*)src;
|
||||
for (int i = 0; i < n; ++i) {
|
||||
const int64_t b = planes[i].shape[0] * rad_enc_row_bytes(planes[i].dtype, planes[i].shape[1]);
|
||||
std::memcpy(planes[i].data, s, (size_t)b);
|
||||
s += b;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the kernel */
|
||||
int gemm_nt_q_m2(const RadArgs* a, RadStream st) {
|
||||
if (!a || a->n_t < 5) return RAD_E_INVAL;
|
||||
const RadTensor *A = &a->t[0], *B = &a->t[2], *Y = &a->t[4];
|
||||
const RadTensor *AS = rad_arg_in(a, 1), *BS = rad_arg_in(a, 3);
|
||||
if (!A->data || !B->data || !Y->data) return RAD_E_INVAL;
|
||||
if (rad_arg_in(a, 5)) return RAD_E_UNSUPPORTED; /* a_sum belongs to the asym grids */
|
||||
if (A->dtype != RAD_F8E4M3 || B->dtype != RAD_U8 || !AS || !BS || !AS->data || !BS->data ||
|
||||
BS->dtype != RAD_E8M0 || BS->rank < 2)
|
||||
return RAD_E_DTYPE;
|
||||
const int64_t K = rad_args_geti_or(a, "K", 0), N = rad_args_geti_or(a, "N", 0);
|
||||
if (K <= 0 || K % 32 || N <= 0) return RAD_E_SHAPE;
|
||||
const int64_t M = rad_tensor_numel(Y) / N;
|
||||
if (M <= 0) return RAD_E_SHAPE;
|
||||
const int64_t kb = K / 32, akb = (K + 127) / 128;
|
||||
const int64_t pb1 = rad_args_geti_or(a, "pb1", 0), pb2 = rad_args_geti_or(a, "pb2", 0);
|
||||
const bool parted = pb1 > 0 || pb2 > 0;
|
||||
const int64_t e1 = pb1 > 0 ? std::min<int64_t>(pb1, N) : N;
|
||||
const int64_t e2 = pb2 > 0 ? std::max<int64_t>(e1, std::min<int64_t>(pb2, N)) : N;
|
||||
const int64_t parts = e2 < N ? 3 : (e1 < N ? 2 : 1);
|
||||
if (parted && ((e1 % 16) || (e2 % 16))) return RAD_E_SHAPE;
|
||||
if (parted && e1 == e2 && e2 < N) return RAD_E_SHAPE;
|
||||
const int64_t acols = parts * K, scols = parts * akb;
|
||||
/* `b` is the stored codes-then-meta blob: a rank-1 u8 of its bytes (the shape hook's
|
||||
* description), or the weight's logical [N, K] u8 view of the same bytes (the engine's). */
|
||||
const bool blob = (B->rank == 1 && rad_tensor_numel(B) == N * (K / 2 + kb)) ||
|
||||
(B->rank == 2 && B->shape[0] == N && B->shape[1] == K);
|
||||
if (!blob) return RAD_E_SHAPE;
|
||||
if (rad_tensor_numel(A) < M * acols ||
|
||||
rad_tensor_numel(BS) < N * kb || rad_tensor_numel(AS) < M * scols)
|
||||
return RAD_E_SHAPE;
|
||||
if (A->rank >= 2 && A->shape[A->rank - 1] != acols) return RAD_E_SHAPE;
|
||||
const int64_t ars = row_stride(A, acols), acs = last_stride(A);
|
||||
const int64_t srs = row_stride(AS, scols), scs = last_stride(AS);
|
||||
const int64_t brs = row_stride(BS, kb);
|
||||
const int64_t yrs = row_stride(Y, N), ycs = last_stride(Y);
|
||||
const char *ab = (const char*)A->data, *sb = (const char*)AS->data;
|
||||
const uint8_t* codes0 = (const uint8_t*)B->data;
|
||||
const uint8_t* meta0 = codes0 + N * (K / 2);
|
||||
const uint8_t* expe0 = (const uint8_t*)BS->data;
|
||||
char* yb = (char*)Y->data;
|
||||
const uint32_t adt = A->dtype, sdt = AS->dtype, ydt = Y->dtype;
|
||||
sycl::queue* q = queue_of(st);
|
||||
if (!q) return RAD_E_DEVICE;
|
||||
const int64_t total = M * N;
|
||||
constexpr size_t wg = 128;
|
||||
const size_t groups = (size_t)((total + (int64_t)wg - 1) / (int64_t)wg);
|
||||
return submit([&] {
|
||||
syclex::nd_launch(*q, sycl::nd_range<1>{groups * wg, wg}, [=](sycl::nd_item<1> it) {
|
||||
const int64_t g = (int64_t)it.get_global_id(0);
|
||||
if (g >= total) return;
|
||||
const int64_t n = g % N, m = g / N;
|
||||
const int64_t part = n < e1 ? 0 : (n < e2 ? 1 : 2);
|
||||
const int64_t a0 = m * ars + part * K * acs, s0 = m * srs + part * akb * scs;
|
||||
const uint8_t* codes = codes0 + n * (K / 2);
|
||||
const uint8_t* meta = meta0 + n * kb;
|
||||
const uint8_t* expe = expe0 + n * brs;
|
||||
constexpr float e2m1[8] = { 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f };
|
||||
float acc = 0.0f;
|
||||
for (int64_t k = 0; k < K; ++k) {
|
||||
const uint8_t c = (uint8_t)((codes[k >> 1] >> (4 * (k & 1))) & 0xF);
|
||||
const float cv = (c & 8) ? -e2m1[c & 7] : e2m1[c & 7];
|
||||
const float ev = sycl::ldexp(1.0f, (int)expe[k >> 5] - 127);
|
||||
const float km = 1.0f + 0.25f * (float)((meta[k >> 5] >> (2 * ((k & 31) >> 3))) & 3);
|
||||
const float w = cv * ev * km;
|
||||
acc += rad_load_f32(ab, adt, a0 + k * acs) * rad_load_f32(sb, sdt, s0 + (k >> 7) * scs) * w;
|
||||
}
|
||||
rad_store_f32(yb, ydt, m * yrs + n * ycs, acc);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
} // namespace xe2
|
||||
@@ -0,0 +1,93 @@
|
||||
/* xe2_givens.cpp -- givens_dense_quant: ParoQuant's activation side for the M2XFP4 linears.
|
||||
* Correctness first, libref's ref_givens_dense_quant (ref_quant.cpp) step for step:
|
||||
*
|
||||
* per (row, part p, 128-column group gi):
|
||||
* in[i] = x[gi*128 + i] / D[p*n + gi*128 + i] f32
|
||||
* y[j] = (float) sum over ascending i of (double)T[p][gi][j][i] * (double)in[i]
|
||||
* scale = amax(|y|) / qmax (1 for an all-zero group), code = clamp(y / scale, +-qmax)
|
||||
*
|
||||
* qmax 448 for an E4M3 `q`, 127 (rounded to nearest even) for an i8 one; `s` holds a scale per
|
||||
* (row, part, group). One work-group a (row, part, group): the inputs in local memory, a work-item
|
||||
* an output j, its dot in double in libref's order, so the codes and scales are libref's.
|
||||
*/
|
||||
#include "xe2_common.h"
|
||||
#include "xe2_ops.h"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
namespace xe2 {
|
||||
|
||||
namespace {
|
||||
|
||||
int64_t row_stride(const RadTensor* t, int64_t cols) {
|
||||
if (!t || t->rank < 2) return cols;
|
||||
int64_t span = 1;
|
||||
for (int i = (int)t->rank - 1; i >= 0; --i) {
|
||||
span *= t->shape[i];
|
||||
if (span == cols) return (i > 0) ? t->stride[i - 1] : cols;
|
||||
if (span > cols) break;
|
||||
}
|
||||
return t->stride[t->rank - 2];
|
||||
}
|
||||
|
||||
int64_t last_stride(const RadTensor* t) { return t->rank ? t->stride[t->rank - 1] : 1; }
|
||||
|
||||
constexpr int kG = 128;
|
||||
|
||||
} // namespace
|
||||
|
||||
int givens_dense_quant(const RadArgs* a, RadStream st) {
|
||||
if (!rad_args_have(a, 5)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *T = &a->t[1], *D = &a->t[2], *Q = &a->t[3], *S = &a->t[4];
|
||||
const int64_t n = rad_args_geti_or(a, "n", 0), P = rad_args_geti_or(a, "parts", 1);
|
||||
const int64_t g = rad_args_geti_or(a, "group", 0);
|
||||
if (n <= 0 || P <= 0 || g != kG || n % g != 0) return RAD_E_SHAPE;
|
||||
const bool i8 = Q->dtype == RAD_I8;
|
||||
if (!i8 && Q->dtype != RAD_F8E4M3) return RAD_E_DTYPE;
|
||||
if (std::strcmp(rad_args_gets_or(a, "out", ""), i8 ? "i8" : "fp8") != 0) return RAD_E_DTYPE;
|
||||
const int64_t rows = rad_tensor_numel(X) / n, ngrp = n / g;
|
||||
if (rows <= 0 || rad_tensor_numel(T) < P * n * g || rad_tensor_numel(D) < P * n ||
|
||||
rad_tensor_numel(Q) < rows * P * n || rad_tensor_numel(S) < rows * P * ngrp)
|
||||
return RAD_E_SHAPE;
|
||||
if (!rad_tensor_is_contiguous(T) || !rad_tensor_is_contiguous(D)) return refuse("givens_dense_quant: tables not contiguous");
|
||||
const float qmax = i8 ? 127.0f : 448.0f;
|
||||
const int64_t xrs = row_stride(X, n), xcs = last_stride(X);
|
||||
const int64_t qrs = row_stride(Q, P * n), qcs = last_stride(Q);
|
||||
const int64_t srs = row_stride(S, P * ngrp), scs = last_stride(S);
|
||||
const char *xb = (const char*)X->data, *tb = (const char*)T->data, *db = (const char*)D->data;
|
||||
char *qb = (char*)Q->data, *sb = (char*)S->data;
|
||||
const uint32_t xdt = X->dtype, tdt = T->dtype, ddt = D->dtype, qdt = Q->dtype, sdt = S->dtype;
|
||||
sycl::queue* q = queue_of(st);
|
||||
if (!q) return RAD_E_DEVICE;
|
||||
const size_t groups = (size_t)(rows * P * ngrp);
|
||||
return submit([&] {
|
||||
q->submit([&](sycl::handler& h) {
|
||||
sycl::local_accessor<float, 1> in(sycl::range<1>(kG), h);
|
||||
h.parallel_for(sycl::nd_range<1>{groups * kG, kG}, [=](sycl::nd_item<1> it) {
|
||||
const int64_t gid = (int64_t)it.get_group(0);
|
||||
const int64_t gi = gid % ngrp, p = (gid / ngrp) % P, r = gid / (ngrp * P);
|
||||
const int j = (int)it.get_local_id(0);
|
||||
const int64_t c = gi * kG + j;
|
||||
in[j] = rad_load_f32(xb, xdt, r * xrs + c * xcs) / rad_load_f32(db, ddt, p * n + c);
|
||||
sycl::group_barrier(it.get_group());
|
||||
const int64_t t0 = ((p * ngrp + gi) * kG + j) * kG;
|
||||
double acc = 0.0;
|
||||
for (int i = 0; i < kG; ++i)
|
||||
acc += (double)rad_load_f32(tb, tdt, t0 + i) * (double)in[i];
|
||||
const float y = (float)acc;
|
||||
const float amax = sycl::reduce_over_group(it.get_group(), sycl::fabs(y),
|
||||
sycl::maximum<float>());
|
||||
const float scl = amax > 0.0f ? amax * (1.0f / qmax) : 1.0f;
|
||||
const float inv = 1.0f / scl;
|
||||
float v = y * inv;
|
||||
if (v > qmax) v = qmax;
|
||||
if (v < -qmax) v = -qmax;
|
||||
if (i8) v = sycl::rint(v);
|
||||
rad_store_f32(qb, qdt, r * qrs + (p * n + c) * qcs, v);
|
||||
if (j == 0) rad_store_f32(sb, sdt, r * srs + (p * ngrp + gi) * scs, scl);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
} // namespace xe2
|
||||
@@ -5,6 +5,11 @@
|
||||
namespace xe2 {
|
||||
|
||||
int add(const RadArgs* a, RadStream s);
|
||||
int mul(const RadArgs* a, RadStream s);
|
||||
int sigmoid(const RadArgs* a, RadStream s);
|
||||
int scatter_rows(const RadArgs* a, RadStream s);
|
||||
int layernorm(const RadArgs* a, RadStream s);
|
||||
int grid_embed(const RadArgs* a, RadStream s);
|
||||
|
||||
int rmsnorm(const RadArgs* a, RadStream s);
|
||||
int rmsnorm_quant_fp8(const RadArgs* a, RadStream s);
|
||||
@@ -12,6 +17,7 @@ int quant_act_fp8(const RadArgs* a, RadStream s);
|
||||
int gated_quant_fp8(const RadArgs* a, RadStream s);
|
||||
|
||||
int rope(const RadArgs* a, RadStream s);
|
||||
int rope_table(const RadArgs* a, RadStream s);
|
||||
int embed_lookup(const RadArgs* a, RadStream s);
|
||||
int gather_rows(const RadArgs* a, RadStream s);
|
||||
int cast(const RadArgs* a, RadStream s);
|
||||
@@ -61,5 +67,33 @@ int gemm_zp_relayout(const RadParam* p, int n_p, int operand, const RadEncoding*
|
||||
int gemm_zp_unrelayout(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
|
||||
const int* sel, const void* src, int64_t src_bytes, const RadTensor* planes,
|
||||
int n);
|
||||
int gemm_nt_q_m2(const RadArgs* a, RadStream s);
|
||||
int givens_dense_quant(const RadArgs* a, RadStream s);
|
||||
int gemm_nt_bias(const RadArgs* a, RadStream s);
|
||||
int dflash_conv(const RadArgs* a, RadStream s);
|
||||
int attn_dense(const RadArgs* a, RadStream s);
|
||||
int logit_rerank(const RadArgs* a, RadStream s);
|
||||
int logit_rerank_head(const RadArgs* a, RadStream s);
|
||||
int logits_gemm_head(const RadArgs* a, RadStream s);
|
||||
int head_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* planes, int n, RadLayout* out);
|
||||
int head_relayout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* planes, int n, void* dst, int64_t dst_bytes);
|
||||
int head_unrelayout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel,
|
||||
const void* src, int64_t src_bytes, const RadTensor* planes, int n);
|
||||
int gdn_conv_prep(const RadArgs* a, RadStream s);
|
||||
int gdn_conv_update(const RadArgs* a, RadStream s);
|
||||
int gdn_kkt_solve(const RadArgs* a, RadStream s);
|
||||
int gdn_chunk_scan(const RadArgs* a, RadStream s);
|
||||
int gdn_recurrent_update(const RadArgs* a, RadStream s);
|
||||
int gdn_gated_rmsnorm(const RadArgs* a, RadStream s);
|
||||
int gdn_conv_recurrent_update(const RadArgs* a, RadStream s);
|
||||
int gemm_m2_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* planes, int n, RadLayout* out);
|
||||
int gemm_m2_relayout(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
|
||||
const int* sel, const RadTensor* planes, int n, void* dst, int64_t dst_bytes);
|
||||
int gemm_m2_unrelayout(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
|
||||
const int* sel, const void* src, int64_t src_bytes, const RadTensor* planes,
|
||||
int n);
|
||||
|
||||
} // namespace xe2
|
||||
+153
-36
@@ -6,9 +6,10 @@
|
||||
* angle pos * inv in f32 and its cosine and sine in double, rounded to f32, as libref's
|
||||
* ref_cos/ref_sin are: positions reach 131072, where f32 range reduction is at its weakest.
|
||||
*
|
||||
* Modes: neox (i with i + rot/2) and gptj (2i with 2i+1), one position component per token. The
|
||||
* multi-component modes (mrope, imrope, axial) are refused at launch with their name; their rows
|
||||
* are not declared either (the `mode` constraint in xe2_rows.cpp).
|
||||
* Modes: neox (i with i + rot/2) and gptj (2i with 2i+1); the multi-component modes pair like neox
|
||||
* and choose each frequency's position component from `sections` (mrope contiguous, imrope
|
||||
* interleaved as Qwen3-VL and Qwen3.5, axial contiguous on per-section ladders), positions [C, M]
|
||||
* component-major -- libref's rope_freqs. rope_table writes cos/sin rows per position.
|
||||
*/
|
||||
#include "xe2_common.h"
|
||||
#include "xe2_ops.h"
|
||||
@@ -16,6 +17,7 @@
|
||||
#include "rad_yarn.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
namespace xe2 {
|
||||
@@ -24,10 +26,6 @@ namespace {
|
||||
|
||||
constexpr int kMaxHalf = 128; /* head_dim up to 256 */
|
||||
|
||||
struct Freqs {
|
||||
float inv[kMaxHalf];
|
||||
};
|
||||
|
||||
/* libref's row_stride: fold trailing axes until they span `cols`; the next axis out carries the
|
||||
* row. */
|
||||
int64_t row_stride(const RadTensor* t, int64_t cols) {
|
||||
@@ -43,6 +41,75 @@ int64_t row_stride(const RadTensor* t, int64_t cols) {
|
||||
|
||||
} // namespace
|
||||
|
||||
namespace {
|
||||
|
||||
enum { kNeox = 0, kGptj = 1, kMrope = 2, kImrope = 3, kAxial = 4 };
|
||||
|
||||
struct Freqs {
|
||||
float inv[kMaxHalf];
|
||||
int comp[kMaxHalf];
|
||||
};
|
||||
|
||||
/* "11 11 10" -> {11, 11, 10}; absent is none, -1 a non-positive entry (libref's rope_sections). */
|
||||
int sections(const RadArgs* a, int64_t* sec) {
|
||||
const char* v = rad_args_gets_or(a, "sections", nullptr);
|
||||
int n = 0;
|
||||
while (v && *v && n < 8) {
|
||||
char* end = nullptr;
|
||||
const long long x = std::strtoll(v, &end, 10);
|
||||
if (end == v) break;
|
||||
if (x <= 0) return -1;
|
||||
sec[n++] = x;
|
||||
v = end;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/* libref's rope_freqs: each frequency's position component and inverse. */
|
||||
int freqs(int mode, int64_t rot, int64_t den, float theta, const int64_t* sec, int n_sec, Freqs* f) {
|
||||
const int64_t half = rot / 2;
|
||||
if (half > kMaxHalf) return refuse("rope: rotary_dim %lld over %d", (long long)rot, 2 * kMaxHalf);
|
||||
int64_t start[8] = {}, total = 0;
|
||||
for (int c = 0; c < n_sec; ++c) { start[c] = total; total += sec[c]; }
|
||||
if ((mode == kMrope || mode == kAxial) && n_sec > 0 && total != half) return RAD_E_SHAPE;
|
||||
for (int64_t i = 0; i < half; ++i) {
|
||||
int c = 0;
|
||||
float inv = 1.0f / (float)std::pow((double)theta, (double)((float)(2 * i) / (float)den));
|
||||
if (n_sec > 0 && (mode == kMrope || mode == kAxial)) {
|
||||
while (c + 1 < n_sec && i >= start[c + 1]) ++c;
|
||||
if (mode == kAxial) {
|
||||
const int64_t j = i - start[c];
|
||||
inv = 1.0f / (float)std::pow((double)theta, (double)((float)(2 * j) / (float)(2 * sec[c])));
|
||||
}
|
||||
} else if (n_sec >= 3 && mode == kImrope) {
|
||||
if (i % 3 == 1 && i < 3 * sec[1]) c = 1;
|
||||
else if (i % 3 == 2 && i < 3 * sec[2]) c = 2;
|
||||
}
|
||||
f->comp[i] = c;
|
||||
f->inv[i] = inv;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int ladder(const RadArgs* a, int64_t rot, int64_t head_dim, int64_t* den) {
|
||||
const char* lad = rad_args_gets_or(a, "ladder", nullptr);
|
||||
if (!lad || !std::strcmp(lad, "rotary")) { *den = rot; return RAD_OK; }
|
||||
if (!std::strcmp(lad, "head")) {
|
||||
if (head_dim <= 0) return RAD_E_SHAPE;
|
||||
*den = head_dim;
|
||||
return RAD_OK;
|
||||
}
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* A position as the rotation reads it, divided by the scale in f32 (libref's rope_pos). */
|
||||
inline float pos_at(const char* pb, uint32_t pdt, int64_t off, float div) {
|
||||
const bool flt = pdt == RAD_F32 || pdt == RAD_BF16 || pdt == RAD_F16;
|
||||
return (flt ? rad_load_f32(pb, pdt, off) : (float)ld_index(pdt, pb, off)) / div;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int rope(const RadArgs* a, RadStream st) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *QKV = &a->t[0], *POS = &a->t[1];
|
||||
@@ -51,40 +118,45 @@ int rope(const RadArgs* a, RadStream st) {
|
||||
const int64_t n_head_kv = rad_args_geti_or(a, "n_head_kv", 0);
|
||||
const float theta = (float)rad_args_getf_or(a, "theta", 10000.0);
|
||||
const float rscale = (float)rad_args_getf_or(a, "scale", 1.0);
|
||||
static const char* kModes[] = { "neox", "gptj", "mrope", "imrope", "axial" };
|
||||
const char* mode_s = rad_args_gets_or(a, "mode", "");
|
||||
int mode = -1;
|
||||
if (!std::strcmp(mode_s, "neox")) mode = 0;
|
||||
else if (!std::strcmp(mode_s, "gptj")) mode = 1;
|
||||
else return refuse("rope: mode '%s' is not served (neox and gptj are)", mode_s);
|
||||
for (int i = 0; i < 5; ++i)
|
||||
if (!std::strcmp(mode_s, kModes[i])) mode = i;
|
||||
if (mode < 0) return RAD_E_UNSUPPORTED;
|
||||
int64_t rot = rad_args_geti_or(a, "rotary_dim", head_dim);
|
||||
if (head_dim <= 0 || n_head <= 0 || rot <= 0 || rot > head_dim || (rot & 1)) return RAD_E_SHAPE;
|
||||
int64_t den = rot;
|
||||
if (const char* lad = rad_args_gets_or(a, "ladder", nullptr)) {
|
||||
if (!std::strcmp(lad, "head")) den = head_dim;
|
||||
else if (std::strcmp(lad, "rotary")) return RAD_E_UNSUPPORTED;
|
||||
int64_t den;
|
||||
if (int rc = ladder(a, rot, head_dim, &den); rc < 0) return rc;
|
||||
int64_t sec[8] = {};
|
||||
const int n_sec = sections(a, sec);
|
||||
if (n_sec < 0) return RAD_E_SHAPE;
|
||||
/* Positions: [M] one component a token; [C, M] C components, component-major. */
|
||||
const bool multi = POS->rank >= 2;
|
||||
const int64_t n_comp = multi ? POS->shape[0] : 1;
|
||||
const int64_t M = multi ? POS->shape[1] : rad_tensor_numel(POS);
|
||||
if (multi) {
|
||||
if (mode == kNeox || mode == kGptj || n_sec <= 0) return RAD_E_SHAPE;
|
||||
const int64_t need = mode == kImrope ? 3 : n_sec;
|
||||
if (n_comp < need || n_comp > 8) return RAD_E_SHAPE;
|
||||
}
|
||||
if (rad_args_gets_or(a, "sections", nullptr) || POS->rank >= 2)
|
||||
return refuse("rope: multi-component positions are not served");
|
||||
const int64_t M = rad_tensor_numel(POS);
|
||||
const int64_t nfreq = rot / 2;
|
||||
if (den == head_dim && rot < head_dim && mode == 0) rot = head_dim;
|
||||
const int64_t half = rot / 2;
|
||||
if (half > kMaxHalf) return refuse("rope: rotary_dim %lld over %d", (long long)rot, 2 * kMaxHalf);
|
||||
|
||||
/* The ladder, as libref builds it. */
|
||||
if (den == head_dim && rot < head_dim && !multi && mode == kNeox) rot = head_dim;
|
||||
Freqs f{};
|
||||
for (int64_t i = 0; i < half; ++i)
|
||||
f.inv[i] = 1.0f / (float)std::pow((double)theta, (double)((float)(2 * i) / (float)den));
|
||||
if (int rc = freqs(mode, rot, den, theta, sec, multi ? n_sec : 0, &f); rc < 0) return rc;
|
||||
const int64_t half = rot / 2;
|
||||
const RadYarn yarn = rad_yarn_args(a);
|
||||
if (!rad_yarn_valid(yarn)) return RAD_E_INVAL;
|
||||
if (yarn.factor != 0.0f) {
|
||||
if (rscale != 1.0f) return RAD_E_UNSUPPORTED;
|
||||
if (mode == kAxial || rscale != 1.0f) return RAD_E_UNSUPPORTED;
|
||||
for (int64_t i = 0; i < half; ++i) f.inv[i] = yarn.frequency(f.inv[i], (int)i);
|
||||
}
|
||||
const RadLlama3 l3 = rad_llama3_args(a);
|
||||
if (!rad_llama3_valid(l3) || (l3.factor != 0.0f && yarn.factor != 0.0f)) return RAD_E_INVAL;
|
||||
if (l3.factor != 0.0f)
|
||||
if (l3.factor != 0.0f) {
|
||||
if (mode == kAxial || multi) return RAD_E_UNSUPPORTED;
|
||||
for (int64_t i = 0; i < half; ++i) f.inv[i] = l3.frequency(f.inv[i]);
|
||||
}
|
||||
for (int64_t i = nfreq; i < half; ++i) f.inv[i] = 0.0f;
|
||||
const float magnitude = yarn.magnitude;
|
||||
|
||||
@@ -92,14 +164,14 @@ int rope(const RadArgs* a, RadStream st) {
|
||||
if (M <= 0 || rad_tensor_numel(QKV) < M * stride_row) return RAD_E_SHAPE;
|
||||
const int64_t rs = row_stride(QKV, stride_row);
|
||||
const int64_t ds = QKV->rank ? QKV->stride[QKV->rank - 1] : 1;
|
||||
const int64_t pcs = multi ? POS->stride[0] : 0, pms = multi ? POS->stride[1] : 0;
|
||||
const Lin pl = Lin::of(POS);
|
||||
char* base = (char*)QKV->data;
|
||||
const uint32_t dt = QKV->dtype;
|
||||
const char* pbase = (const char*)POS->data;
|
||||
const uint32_t pdt = POS->dtype;
|
||||
const bool pflt = pdt == RAD_F32 || pdt == RAD_BF16 || pdt == RAD_F16;
|
||||
const bool pcontig = rad_tensor_is_contiguous(POS);
|
||||
if (!pcontig) return refuse("rope: positions are not contiguous");
|
||||
const float div = rscale != 0.0f ? rscale : 1.0f;
|
||||
const int pairs = mode == kGptj ? kGptj : kNeox; /* the multi modes pair like neox */
|
||||
const int64_t heads = n_head + n_head_kv;
|
||||
const int64_t total = M * heads * half;
|
||||
|
||||
@@ -112,17 +184,62 @@ int rope(const RadArgs* a, RadStream st) {
|
||||
const int64_t g = (int64_t)it.get_global_id(0);
|
||||
if (g >= total) return;
|
||||
const int64_t i = g % half, h = (g / half) % heads, m = g / (half * heads);
|
||||
const float p = (pflt ? rad_load_f32(pbase, pdt, m) : (float)ld_index(pdt, pbase, m)) / div;
|
||||
const int c = f.comp[i];
|
||||
const float p = multi ? pos_at(pbase, pdt, c * pcs + m * pms, div)
|
||||
: pos_at(pbase, pdt, pl.off(m), div);
|
||||
const float ang = p * f.inv[i];
|
||||
const float c = (float)sycl::cos((double)ang) * magnitude;
|
||||
const float s = (float)sycl::sin((double)ang) * magnitude;
|
||||
const int64_t i0 = mode == 1 ? 2 * i : i;
|
||||
const int64_t i1 = mode == 1 ? 2 * i + 1 : i + half;
|
||||
const float cs = (float)sycl::cos((double)ang) * magnitude;
|
||||
const float sn = (float)sycl::sin((double)ang) * magnitude;
|
||||
const int64_t i0 = pairs == kGptj ? 2 * i : i;
|
||||
const int64_t i1 = pairs == kGptj ? 2 * i + 1 : i + half;
|
||||
const int64_t hb = m * rs + h * head_dim * ds;
|
||||
const float x0 = rad_load_f32(base, dt, hb + i0 * ds);
|
||||
const float x1 = rad_load_f32(base, dt, hb + i1 * ds);
|
||||
rad_store_f32(base, dt, hb + i0 * ds, x0 * c - x1 * s);
|
||||
rad_store_f32(base, dt, hb + i1 * ds, x0 * s + x1 * c);
|
||||
rad_store_f32(base, dt, hb + i0 * ds, x0 * cs - x1 * sn);
|
||||
rad_store_f32(base, dt, hb + i1 * ds, x0 * sn + x1 * cs);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/* rope_table: cos and sin rows for each position, cs[pos * rot + i] and cs[pos * rot + half + i],
|
||||
* as libref's ref_rope_table (a position outside the table is skipped). */
|
||||
int rope_table(const RadArgs* a, RadStream st) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *POS = &a->t[0], *CS = &a->t[1];
|
||||
const int64_t rot = rad_args_geti_or(a, "rot", 0);
|
||||
const int64_t head_dim = rad_args_geti_or(a, "head_dim", 0);
|
||||
const float theta = (float)rad_args_getf_or(a, "theta", 10000.0);
|
||||
const float rscale = (float)rad_args_getf_or(a, "scale", 1.0);
|
||||
if (rot < 2 || (rot & 1)) return RAD_E_SHAPE;
|
||||
int64_t den;
|
||||
if (int rc = ladder(a, rot, head_dim, &den); rc < 0) return rc;
|
||||
const int64_t M = rad_tensor_numel(POS);
|
||||
if (M <= 0 || rad_tensor_numel(CS) % rot) return RAD_E_SHAPE;
|
||||
const int64_t rows = rad_tensor_numel(CS) / rot, half = rot / 2;
|
||||
if (half > kMaxHalf) return refuse("rope_table: rot %lld over %d", (long long)rot, 2 * kMaxHalf);
|
||||
const RadYarn yarn = rad_yarn_args(a);
|
||||
if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && rscale != 1.0f)) return RAD_E_INVAL;
|
||||
Freqs f{};
|
||||
for (int64_t i = 0; i < half; ++i)
|
||||
f.inv[i] = yarn.frequency(1.0f / (float)std::pow((double)theta, (double)((float)(2 * i) / (float)den)), (int)i);
|
||||
const float magnitude = yarn.magnitude;
|
||||
const float div = rscale != 0.0f ? rscale : 1.0f;
|
||||
const Lin pl = Lin::of(POS), cl = Lin::of(CS);
|
||||
sycl::queue* q = queue_of(st);
|
||||
if (!q) return RAD_E_DEVICE;
|
||||
const int64_t total = M * half;
|
||||
const size_t wg = 128;
|
||||
const size_t groups = (size_t)((total + (int64_t)wg - 1) / (int64_t)wg);
|
||||
return submit([&] {
|
||||
syclex::nd_launch(*q, sycl::nd_range<1>{groups * wg, wg}, [=](sycl::nd_item<1> it) {
|
||||
const int64_t g = (int64_t)it.get_global_id(0);
|
||||
if (g >= total) return;
|
||||
const int64_t i = g % half, m = g / half;
|
||||
const int64_t pp = ld_index(pl.dtype, pl.base, pl.off(m));
|
||||
if (pp < 0 || pp >= rows) return;
|
||||
const float ang = ((float)pp / div) * f.inv[i];
|
||||
rad_store_f32(cl.base, cl.dtype, cl.off(pp * rot + i), (float)sycl::cos((double)ang) * magnitude);
|
||||
rad_store_f32(cl.base, cl.dtype, cl.off(pp * rot + half + i), (float)sycl::sin((double)ang) * magnitude);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
+109
-2
@@ -11,7 +11,7 @@
|
||||
|
||||
namespace {
|
||||
|
||||
const RadConstraint cRopeModes[] = { RAD_CIN("mode", "neox gptj") };
|
||||
const RadConstraint cRopeModes[] = { RAD_CIN("mode", "neox gptj mrope imrope axial") };
|
||||
/* The GEMMs here read float weights only; a quantised dtype key is gemm_nt_q's. */
|
||||
const RadConstraint cFloatDtype[] = { RAD_CIN("dtype", "bf16 f16 fp16 f32 fp32") };
|
||||
/* The decode band of the skinny bf16 GEMV (xe2_gemv.cpp). */
|
||||
@@ -24,6 +24,8 @@ const RadConstraint cFp8Dtype[] = { RAD_CIN("dtype", "fp8a8 fp8a8f32 fp8a16") };
|
||||
const RadConstraint cFp8Gated[] = { RAD_CIN("dtype", "fp8a8 fp8a8f32 fp8a16"), RAD_CLE("N", 57344) };
|
||||
/* The zero-point grids over quant_act_i8's activation (xe2_gemm_zp.cpp). */
|
||||
const RadConstraint cZpI8Dtype[] = { RAD_CIN("dtype", "w2a8 w4a8_asym") };
|
||||
/* The M2XFP4 grid over givens_dense_quant's fp8 activation (xe2_gemm_m2.cpp). */
|
||||
const RadConstraint cM2Dtype[] = { RAD_CIN("dtype", "m2xfp4") };
|
||||
|
||||
/* Rows by field name (C++20 designated initialisers must follow declaration order, so the compiler
|
||||
* checks it), unlike a positional table where a shifted field can still compile. */
|
||||
@@ -34,6 +36,29 @@ const RadKernelInfo kKernels[] = {
|
||||
.dtypes = "any float dtype in and out (bf16, f16, f32, fp8), f32 arithmetic, rounded as libref",
|
||||
.domain = RAD_DOMAIN_DEVICE, .priority = 0,
|
||||
.launch = xe2::add },
|
||||
{ .name = "xe2_mul", .op = "mul", .family = "elem",
|
||||
.computes = "elementwise product, b broadcast along rows when it is one row",
|
||||
.shape = "any n and row count; rows may be padded, the last axis dense",
|
||||
.dtypes = "any float dtype in and out, f32 arithmetic, rounded as libref",
|
||||
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::mul },
|
||||
{ .name = "xe2_sigmoid", .op = "sigmoid", .family = "elem",
|
||||
.computes = "1 / (1 + exp(-x)), the exp in double rounded once as libref's",
|
||||
.shape = "any element count; any strides", .dtypes = "any float dtype in and out",
|
||||
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::sigmoid },
|
||||
{ .name = "xe2_scatter_rows", .op = "scatter_rows", .family = "gather",
|
||||
.computes = "row m of v to row idx[m] of x; a negative index skipped, one past x refused",
|
||||
.shape = "any n and row counts; rows may be padded, the last axis dense",
|
||||
.dtypes = "any float dtype; integer indices",
|
||||
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::scatter_rows },
|
||||
{ .name = "xe2_layernorm", .op = "layernorm", .family = "norm",
|
||||
.computes = "layer norm with a gain and an optional bias, libref's serial sums",
|
||||
.shape = "any n and row count; rows may be padded, the last axis dense",
|
||||
.dtypes = "any float dtype in and out",
|
||||
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::layernorm },
|
||||
{ .name = "xe2_grid_embed", .op = "grid_embed", .family = "elem",
|
||||
.computes = "x += a square position table bilinearly resampled at each row's grid cell",
|
||||
.shape = "any n, rows and side", .dtypes = "any float dtype; integer coordinates",
|
||||
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::grid_embed },
|
||||
|
||||
{ .name = "xe2_rmsnorm", .op = "rmsnorm", .family = "norm",
|
||||
.computes = "RMS norm, one work-group a row, f32 work-group reduction",
|
||||
@@ -61,10 +86,14 @@ const RadKernelInfo kKernels[] = {
|
||||
{ .name = "xe2_rope", .op = "rope", .family = "rope",
|
||||
.computes = "rotary embedding in place over q and k heads; frequency ladder (YaRN, llama3) "
|
||||
"on the host as libref builds it, cos/sin in double",
|
||||
.shape = "neox or gptj, one position component a token, rotary_dim <= 256",
|
||||
.shape = "neox, gptj, mrope, imrope, axial; [M] or [C, M] positions, rotary_dim <= 256",
|
||||
.dtypes = "bf16 qkv (any float), integer or float positions",
|
||||
.domain = RAD_DOMAIN_DEVICE, .constraints = cRopeModes, .n_constraints = 1,
|
||||
.launch = xe2::rope },
|
||||
{ .name = "xe2_rope_table", .op = "rope_table", .family = "rope",
|
||||
.computes = "cos and sin rows per position on libref's ladder (YaRN), in double",
|
||||
.shape = "rot <= 256", .dtypes = "integer positions, float table",
|
||||
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::rope_table },
|
||||
{ .name = "xe2_embed_lookup", .op = "embed_lookup", .family = "vocab",
|
||||
.computes = "embedding gather times mult; an id outside the table writes a zero row",
|
||||
.shape = "any n_embd and n_vocab, vocab_offset",
|
||||
@@ -234,6 +263,84 @@ const RadKernelInfo kKernels[] = {
|
||||
.domain = RAD_DOMAIN_DEVICE, .constraints = cZpI8Dtype, .n_constraints = 1,
|
||||
.launch = xe2::gemm_nt_q_zp, .layout = xe2::gemm_zp_layout,
|
||||
.relayout = xe2::gemm_zp_relayout, .unrelayout = xe2::gemm_zp_unrelayout },
|
||||
{ .name = "xe2_gemm_nt_q_m2_ref", .op = "gemm_nt_q", .family = "gemm",
|
||||
.computes = "Y = A B^T over the M2XFP4 grid against givens_dense_quant's fp8 activation, "
|
||||
"libref's gemm_m2 per output; the correctness-first form",
|
||||
.shape = "any M, N; K a multiple of 32, group 32",
|
||||
.dtypes = "m2xfp4: e2m1 codes and u8 meta concatenated, e8m0 scale per (row, 32); E4M3 "
|
||||
"activation with a scale per 128 columns",
|
||||
.domain = RAD_DOMAIN_DEVICE, .constraints = cM2Dtype, .n_constraints = 1,
|
||||
.launch = xe2::gemm_nt_q_m2, .layout = xe2::gemm_m2_layout,
|
||||
.relayout = xe2::gemm_m2_relayout, .unrelayout = xe2::gemm_m2_unrelayout },
|
||||
{ .name = "xe2_givens_dense_quant", .op = "givens_dense_quant", .family = "quant",
|
||||
.computes = "ParoQuant's activation quantiser: x / D through a dense 128x128 rotation per "
|
||||
"(part, group) in double, then the fp8 or i8 group quantiser; libref's form",
|
||||
.shape = "any rows; n a multiple of 128, group 128, any parts",
|
||||
.dtypes = "float x, f16 rotation, float channel scales; E4M3 or i8 codes, f32 scales",
|
||||
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::givens_dense_quant },
|
||||
{ .name = "xe2_attn_dense", .op = "attn_dense", .family = "attn",
|
||||
.computes = "unpaged dense attention over cu_seqlens segments (causal, window, blocks); "
|
||||
"libref's two passes, exp in double",
|
||||
.shape = "head_dim <= 256, any heads, gqa, segments", .dtypes = "any float q, k, v, o",
|
||||
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::attn_dense },
|
||||
{ .name = "xe2_dflash_conv", .op = "dflash_conv", .family = "draft",
|
||||
.computes = "DFlash2's per-block causal tap conv with per-row tap deltas; libref's order",
|
||||
.shape = "any T, taps, groups, block size", .dtypes = "any float dtype",
|
||||
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::dflash_conv },
|
||||
{ .name = "xe2_logit_rerank", .op = "logit_rerank", .family = "draft",
|
||||
.computes = "R candidates a row rescored against a float head in double, row_topk's order",
|
||||
.shape = "any rows and R", .dtypes = "float x and head; integer ids",
|
||||
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::logit_rerank },
|
||||
{ .name = "xe2_logit_rerank_head", .op = "logit_rerank", .family = "draft",
|
||||
.computes = "R candidates a row rescored against a head of codes and a scale plane, joined",
|
||||
.shape = "any rows and R", .dtypes = "float x; E4M3 or i8 codes with a float scale",
|
||||
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::logit_rerank_head, .layout = xe2::head_layout,
|
||||
.relayout = xe2::head_relayout, .unrelayout = xe2::head_unrelayout },
|
||||
{ .name = "xe2_gemm_nt_bias_ref", .op = "gemm_nt_bias", .family = "gemm",
|
||||
.computes = "Y = A B^T + bias, then gelu / gelu_tanh and a residual; libref's order",
|
||||
.shape = "any M, N, K", .dtypes = "float A and B",
|
||||
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::gemm_nt_bias },
|
||||
{ .name = "xe2_logits_gemm_head_ref", .op = "logits_gemm", .family = "vocab",
|
||||
.computes = "the lm_head over a head of E4M3 / int8 codes with a scale plane, joined; each "
|
||||
"weight decoded to code * scale, then libref's plain product",
|
||||
.shape = "any M, n_vocab, n_embd", .dtypes = "float A; E4M3 or i8 codes, float block scale",
|
||||
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::logits_gemm_head, .layout = xe2::head_layout,
|
||||
.relayout = xe2::head_relayout, .unrelayout = xe2::head_unrelayout },
|
||||
{ .name = "xe2_gdn_conv_prep", .op = "gdn_conv_prep", .family = "gdn",
|
||||
.computes = "the causal conv with silu and its state, the q/k l2 norm, the chunked gate cumsum and beta; libref's arithmetic",
|
||||
.shape = "q, k, v as [T, heads, width]; conv width <= 17",
|
||||
.dtypes = "any float dtype; integer cu, slots and counts",
|
||||
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::gdn_conv_prep },
|
||||
{ .name = "xe2_gdn_conv_update", .op = "gdn_conv_update", .family = "gdn",
|
||||
.computes = "the decode step's causal conv against the rolling window, shifted by one; libref's arithmetic",
|
||||
.shape = "q, k, v as [T, heads, width]; conv width <= 17",
|
||||
.dtypes = "any float dtype; integer cu, slots and counts",
|
||||
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::gdn_conv_update },
|
||||
{ .name = "xe2_gdn_kkt_solve", .op = "gdn_kkt_solve", .family = "gdn",
|
||||
.computes = "(I + strict_lower(beta K K^T e^{g_i-g_j}))^-1 per chunk and v head, forward substitution; libref's arithmetic",
|
||||
.shape = "q, k, v as [T, heads, width]; conv width <= 17",
|
||||
.dtypes = "any float dtype; integer cu, slots and counts",
|
||||
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::gdn_kkt_solve },
|
||||
{ .name = "xe2_gdn_chunk_scan", .op = "gdn_chunk_scan", .family = "gdn",
|
||||
.computes = "the chunked delta-rule scan over a prefill chunk, state in and out; libref's arithmetic",
|
||||
.shape = "q, k, v as [T, heads, width]; conv width <= 17",
|
||||
.dtypes = "any float dtype; integer cu, slots and counts",
|
||||
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::gdn_chunk_scan },
|
||||
{ .name = "xe2_gdn_recurrent_update", .op = "gdn_recurrent_update", .family = "gdn",
|
||||
.computes = "the decode delta-rule step against the paged state, gated RMS norm folded in; libref's arithmetic",
|
||||
.shape = "q, k, v as [T, heads, width]; conv width <= 17",
|
||||
.dtypes = "any float dtype; integer cu, slots and counts",
|
||||
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::gdn_recurrent_update },
|
||||
{ .name = "xe2_gdn_gated_rmsnorm", .op = "gdn_gated_rmsnorm", .family = "gdn",
|
||||
.computes = "x rsqrt(mean(x^2) + eps) w act(z) per (token, head); libref's arithmetic",
|
||||
.shape = "q, k, v as [T, heads, width]; conv width <= 17",
|
||||
.dtypes = "any float dtype; integer cu, slots and counts",
|
||||
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::gdn_gated_rmsnorm },
|
||||
{ .name = "xe2_gdn_conv_recurrent_update", .op = "gdn_conv_recurrent_update", .family = "gdn",
|
||||
.computes = "gdn_conv_update then gdn_recurrent_update, libref's definition of the pair; libref's arithmetic",
|
||||
.shape = "q, k, v as [T, heads, width]; conv width <= 17",
|
||||
.dtypes = "any float dtype; integer cu, slots and counts",
|
||||
.domain = RAD_DOMAIN_DEVICE, .launch = xe2::gdn_conv_recurrent_update },
|
||||
};
|
||||
|
||||
const RadPluginInfo kInfo = {
|
||||
|
||||
Reference in new issue
Block a user