From fca4cbe3b5a8d186cf192e2f8bb155dbf722b26b Mon Sep 17 00:00:00 2001 From: pascallinxweiler Date: Fri, 23 Oct 2026 16:05:59 +0200 Subject: [PATCH] libxe2: rope, embed_lookup, gather_rows, cast rope builds its frequency ladder on the host per launch exactly as libref's rope_freqs does (a double pow, then YaRN or llama3 from rad_yarn.h) and takes cos and sin of the f32 angle in double on the card, as libref does; positions reach 131072 at MiniCPM5's context. neox and gptj with one position component; the row says so with a mode constraint and the launch refuses anything else by name. The gathers write a zero row for an index outside the table, libr4d's rule: libref instead checks every index on the host before running, which a launch cannot do without waiting on its stream. rad-kbench against libref: fixture 127/127 and MiniCPM5-2B 94/94, rel_l2 0. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1 --- libxe2/xe2_common.h | 13 +++++ libxe2/xe2_gather.cpp | 124 ++++++++++++++++++++++++++++++++++++++++ libxe2/xe2_ops.h | 5 ++ libxe2/xe2_rope.cpp | 130 ++++++++++++++++++++++++++++++++++++++++++ libxe2/xe2_rows.cpp | 25 ++++++++ 5 files changed, 297 insertions(+) create mode 100644 libxe2/xe2_gather.cpp create mode 100644 libxe2/xe2_rope.cpp diff --git a/libxe2/xe2_common.h b/libxe2/xe2_common.h index 67e4bd38..da37efb7 100644 --- a/libxe2/xe2_common.h +++ b/libxe2/xe2_common.h @@ -57,6 +57,19 @@ int submit(F&& f) { return RAD_OK; } +/* An index or position element as libref's ld_int reads it. */ +inline int64_t ld_index(uint32_t dt, const void* p, int64_t i) { + switch (dt) { + case RAD_I32: return (int64_t)((const int32_t*)p)[i]; + case RAD_U32: return (int64_t)((const uint32_t*)p)[i]; + case RAD_I64: return ((const int64_t*)p)[i]; + case RAD_I16: return (int64_t)((const int16_t*)p)[i]; + case RAD_I8: return (int64_t)((const int8_t*)p)[i]; + case RAD_U8: return (int64_t)((const uint8_t*)p)[i]; + default: return 0; + } +} + /* 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; diff --git a/libxe2/xe2_gather.cpp b/libxe2/xe2_gather.cpp new file mode 100644 index 00000000..9c3e5a1a --- /dev/null +++ b/libxe2/xe2_gather.cpp @@ -0,0 +1,124 @@ +/* xe2_gather.cpp -- row gathers and the dtype cast. + * + * embed_lookup x[m, :] = wte[tok[m] - vocab_offset, :] * mult + * gather_rows y[i, :] = x[idx[i], :] + * cast y = x in y's dtype; integer to integer bypasses f32, as libref's does + * + * Index checks differ from libref's in one way, by necessity: libref reads every index on the host + * before running and returns RAD_E_INVAL for one past the table, but a launch cannot read device + * memory without waiting for the stream, which a launch must not do. Here such a row is written as + * zeros, the rule libr4d's embed_lookup_bf16 states ("a negative or out-of-range id writes a zero + * row"). A negative index is a zero row in both. + */ +#include "xe2_common.h" +#include "xe2_ops.h" + +namespace xe2 { + +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 + +/* ------------------------------------------------------------------ embed_lookup */ +int embed_lookup(const RadArgs* a, RadStream st) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const RadTensor *TOK = &a->t[0], *WTE = &a->t[1], *X = &a->t[2]; + const int64_t n_embd = rad_args_geti_or(a, "n_embd", WTE->rank >= 2 ? WTE->shape[WTE->rank - 1] : 0); + const int64_t n_vocab = rad_args_geti_or(a, "n_vocab", WTE->rank >= 2 ? WTE->shape[WTE->rank - 2] : 0); + const int64_t voff = rad_args_geti_or(a, "vocab_offset", 0); + const float mult = (float)rad_args_getf_or(a, "mult", 1.0); + if (n_embd <= 0 || n_vocab <= 0 || voff < 0) return RAD_E_SHAPE; + Rows x; + if (int rc = rows_view(X, n_embd, &x, "embed_lookup x"); rc < 0) return rc; + const int64_t M = x.rows; + if (M <= 0 || rad_tensor_numel(TOK) < M || rad_tensor_numel(WTE) < n_vocab * n_embd) + return RAD_E_SHAPE; + if (!rad_tensor_is_contiguous(TOK)) return refuse("embed_lookup: token ids not contiguous"); + const int64_t ws = WTE->rank >= 2 ? WTE->stride[WTE->rank - 2] : n_embd; + const int64_t wc = WTE->rank >= 2 ? WTE->stride[WTE->rank - 1] : 1; + const char* wb = (const char*)WTE->data; + const uint32_t wdt = WTE->dtype; + const char* tb = (const char*)TOK->data; + const uint32_t tdt = TOK->dtype; + sycl::queue* q = queue_of(st); + if (!q) return RAD_E_DEVICE; + return submit([&] { + syclex::nd_launch(*q, sycl::nd_range<1>{(size_t)M * kWg, kWg}, [=](sycl::nd_item<1> it) { + const int64_t m = (int64_t)it.get_group(0); + const int64_t id = ld_index(tdt, tb, m) - voff; + const bool have = id >= 0 && id < n_vocab; + for (int64_t i = (int64_t)it.get_local_id(0); i < n_embd; i += kWg) + rad_store_f32(x.base, x.dtype, m * x.pitch + i, + have ? rad_load_f32(wb, wdt, id * ws + i * wc) * mult : 0.0f); + }); + }); +} + +/* ------------------------------------------------------------------ gather_rows */ +int gather_rows(const RadArgs* a, RadStream st) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *IDX = &a->t[1], *Y = &a->t[2]; + const int64_t n = rad_args_geti_or(a, "n", Y->rank >= 1 ? Y->shape[Y->rank - 1] : 0); + if (n <= 0) return RAD_E_SHAPE; + Rows x, y; + if (int rc = rows_view(Y, n, &y, "gather_rows y"); rc < 0) return rc; + if (int rc = rows_view(X, n, &x, "gather_rows x"); rc < 0) return rc; + const int64_t M = y.rows, src_rows = x.rows; + if (M <= 0 || src_rows <= 0 || rad_tensor_numel(IDX) < M) return RAD_E_SHAPE; + if (!rad_tensor_is_contiguous(IDX)) return refuse("gather_rows: idx not contiguous"); + const char* ib = (const char*)IDX->data; + const uint32_t idt = IDX->dtype; + sycl::queue* q = queue_of(st); + if (!q) return RAD_E_DEVICE; + return submit([&] { + syclex::nd_launch(*q, sycl::nd_range<1>{(size_t)M * kWg, kWg}, [=](sycl::nd_item<1> it) { + const int64_t m = (int64_t)it.get_group(0); + const int64_t r = ld_index(idt, ib, m); + const bool have = r >= 0 && r < src_rows; + for (int64_t i = (int64_t)it.get_local_id(0); i < n; i += kWg) + rad_store_f32(y.base, y.dtype, m * y.pitch + i, + have ? rad_load_f32(x.base, x.dtype, r * x.pitch + i) : 0.0f); + }); + }); +} + +/* ------------------------------------------------------------------ cast */ +int cast(const RadArgs* a, RadStream st) { + 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; + if (!rad_tensor_is_contiguous(X) || !rad_tensor_is_contiguous(Y)) + return refuse("cast: strided operands are not served"); + const bool int_pair = is_int(X->dtype) && is_int(Y->dtype); + const char* xb = (const char*)X->data; + char* yb = (char*)Y->data; + const uint32_t xdt = X->dtype, ydt = Y->dtype; + sycl::queue* q = queue_of(st); + if (!q) return RAD_E_DEVICE; + const size_t groups = (size_t)((nel + (int64_t)kWg - 1) / (int64_t)kWg); + return submit([&] { + syclex::nd_launch(*q, sycl::nd_range<1>{groups * kWg, kWg}, [=](sycl::nd_item<1> it) { + const int64_t i = (int64_t)it.get_global_id(0); + if (i >= nel) return; + if (int_pair) st_index(ydt, yb, i, ld_index(xdt, xb, i)); + else rad_store_f32(yb, ydt, i, rad_load_f32(xb, xdt, i)); + }); + }); +} + +} // namespace xe2 diff --git a/libxe2/xe2_ops.h b/libxe2/xe2_ops.h index 12a2f3a7..19571284 100644 --- a/libxe2/xe2_ops.h +++ b/libxe2/xe2_ops.h @@ -11,4 +11,9 @@ int rmsnorm_quant_fp8(const RadArgs* a, RadStream s); 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 embed_lookup(const RadArgs* a, RadStream s); +int gather_rows(const RadArgs* a, RadStream s); +int cast(const RadArgs* a, RadStream s); + } // namespace xe2 diff --git a/libxe2/xe2_rope.cpp b/libxe2/xe2_rope.cpp new file mode 100644 index 00000000..95117e2c --- /dev/null +++ b/libxe2/xe2_rope.cpp @@ -0,0 +1,130 @@ +/* xe2_rope.cpp -- rotary position embedding over a packed qkv row, in place. + * + * The frequency ladder is computed on the host per launch, exactly as libref's rope_freqs does + * (theta^(2i/den) through a double pow, then YaRN or llama3 scaling from rad_yarn.h), and handed to + * the kernel as a table: at most 64 floats for MiniCPM5's head_dim 128. The card computes the + * 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). + */ +#include "xe2_common.h" +#include "xe2_ops.h" + +#include "rad_yarn.h" + +#include +#include + +namespace xe2 { + +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) { + 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]; +} + +} // 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]; + const int64_t head_dim = rad_args_geti_or(a, "head_dim", 0); + const int64_t n_head = rad_args_geti_or(a, "n_head", 0); + 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); + 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); + 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; + } + 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. */ + 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)); + 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; + 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) + 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; + + const int64_t stride_row = (n_head + 2 * n_head_kv) * head_dim; + 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; + 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 int64_t heads = n_head + n_head_kv; + const int64_t total = M * heads * half; + + sycl::queue* q = queue_of(st); + if (!q) return RAD_E_DEVICE; + 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, 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 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 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); + }); + }); +} + +} // namespace xe2 diff --git a/libxe2/xe2_rows.cpp b/libxe2/xe2_rows.cpp index 6fd8f9cd..25fb45fd 100644 --- a/libxe2/xe2_rows.cpp +++ b/libxe2/xe2_rows.cpp @@ -11,6 +11,8 @@ namespace { +const RadConstraint cRopeModes[] = { RAD_CIN("mode", "neox gptj") }; + /* Rows by field name (C++20 designated initialisers must follow declaration order, so the compiler * checks it), unlike a positional table where a shifted field can still compile. */ const RadKernelInfo kKernels[] = { @@ -43,6 +45,29 @@ const RadKernelInfo kKernels[] = { .shape = "any n and group", .dtypes = "bf16 gate_up, E4M3 (or i8) codes, f32 scales, optional bf16 out", .domain = RAD_DOMAIN_DEVICE, .launch = xe2::gated_quant_fp8 }, + + { .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", + .dtypes = "bf16 qkv (any float), integer or float positions", + .domain = RAD_DOMAIN_DEVICE, .constraints = cRopeModes, .n_constraints = 1, + .launch = xe2::rope }, + { .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", + .dtypes = "integer ids, float table and output", + .domain = RAD_DOMAIN_DEVICE, .launch = xe2::embed_lookup }, + { .name = "xe2_gather_rows", .op = "gather_rows", .family = "elem", + .computes = "row gather; a negative or out-of-range index writes a zero row", + .shape = "any n", + .dtypes = "integer indices, float rows", + .domain = RAD_DOMAIN_DEVICE, .launch = xe2::gather_rows }, + { .name = "xe2_cast", .op = "cast", .family = "elem", + .computes = "dtype conversion; integer to integer exact", + .shape = "contiguous operands", + .dtypes = "any float or integer pair", + .domain = RAD_DOMAIN_DEVICE, .launch = xe2::cast }, }; const RadPluginInfo kInfo = {