This repository has been archived on 2026-11-24. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
radiance-sycl/libxe2/xe2_rope.cpp
T
pascallinxweilerandClaude Opus 5.5 fca4cbe3b5 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
2026-10-23 16:05:59 +02:00

131 lines
5.8 KiB
C++

/* 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 <cmath>
#include <cstring>
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