/* 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); 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" #include "rad_yarn.h" #include #include #include namespace xe2 { namespace { constexpr int kMaxHalf = 256; /* head_dim up to 512 (Gemma 4's global heads, proportional rope) */ /* 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 namespace { enum { kNeox = 0, kGptj = 1, kMrope = 2, kImrope = 3, kAxial = 4 }; struct Freqs { float inv[kMaxHalf]; int8_t comp[kMaxHalf]; /* a component index, < 8: int8 keeps the by-value table at 1.25 KB */ }; /* "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]; 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); static const char* kModes[] = { "neox", "gptj", "mrope", "imrope", "axial" }; const char* mode_s = rad_args_gets_or(a, "mode", ""); int mode = -1; 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; 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; } const int64_t nfreq = rot / 2; if (den == head_dim && rot < head_dim && !multi && mode == kNeox) rot = head_dim; Freqs f{}; 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 (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 (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; 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; 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 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; 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 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 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 * cs - x1 * sn); rad_store_f32(base, dt, hb + i1 * ds, x0 * sn + x1 * cs); }); }); } /* qk_norm_rope: libref's ref_qk_norm_rope. A work-item a (row, head): the head's RMS norm with * libref's ordered sum and its gain (+ wadd; absent: unit), rounded to the tensor's dtype, then the * rotation: neox / gptj / imrope / axial from rope's frequency table (measured by rot), blocks and * gptj_blocks section by section with inv = 1 / pow(theta, j / sec) in double rounded once. With * v_norm the v heads are normed at unit gain and not turned. For the vision towers (once a picture), * so the plain form. */ int qk_norm_rope(const RadArgs* a, RadStream st) { if (!a || a->n_t < 4 || !a->t[0].data) return RAD_E_INVAL; const RadTensor *QKV = &a->t[0], *POS = rad_arg_in(a, 1), *QW = rad_arg_in(a, 2), *KW = rad_arg_in(a, 3); 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 eps = (float)rad_args_getf_or(a, "eps", 1e-6); const float rscale = (float)rad_args_getf_or(a, "scale", 1.0); const float wadd = (float)rad_args_getf_or(a, "wadd", 0.0); const int v_norm = (int)rad_args_geti_or(a, "v_norm", 0); static const char* kM[] = { "neox", "gptj", "blocks", "gptj_blocks", "imrope", "axial" }; const char* ms = rad_args_gets_or(a, "mode", "neox"); int mode = -1; for (int i = 0; i < 6; ++i) if (!std::strcmp(ms, kM[i])) mode = i; if (mode < 0) return RAD_E_UNSUPPORTED; const bool blocks = mode == 2 || mode == 3, adjacent = mode == 3, im = mode == 4, axial = mode == 5; 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; if ((QW && rad_tensor_numel(QW) < head_dim) || (KW && rad_tensor_numel(KW) < head_dim)) return RAD_E_SHAPE; const bool turn = rot > 0; if (turn && !POS) return RAD_E_INVAL; int64_t sec[8] = {}, comp[8] = {}; int n_sec = 0; if (turn && (im || axial || blocks)) { n_sec = sections(a, sec); if (n_sec < (im ? 3 : 1)) return RAD_E_SHAPE; } if (turn && blocks) { int64_t total = 0; for (int c = 0; c < n_sec; ++c) { total += sec[c]; comp[c] = c; } if (2 * total != rot) return RAD_E_SHAPE; if (const char* cs = rad_args_gets_or(a, "comps", nullptr)) { int k = 0; for (const char* v = cs; *v && k < 8;) { char* end = nullptr; const long long x = std::strtoll(v, &end, 10); if (end == v) break; comp[k++] = x; v = end; } if (k != n_sec) return RAD_E_SHAPE; } } const int64_t stride_row = (n_head + 2 * n_head_kv) * head_dim; const bool multi = POS && POS->rank >= 2; const int64_t n_comp = multi ? POS->shape[0] : 1; const int64_t M = !POS ? rad_tensor_numel(QKV) / stride_row : multi ? POS->shape[1] : rad_tensor_numel(POS); if (turn) { if (multi && !blocks && !im && !axial) return RAD_E_SHAPE; if (multi && im && n_comp < 3) return RAD_E_SHAPE; if (multi && axial && n_comp < n_sec) return RAD_E_SHAPE; if (n_comp > 8) return RAD_E_SHAPE; for (int c = 0; blocks && c < n_sec; ++c) if (comp[c] < 0 || comp[c] >= n_comp) return RAD_E_SHAPE; } 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; Freqs f{}; if (turn && !blocks) { const int fm = im ? kImrope : axial ? kAxial : mode; /* neox 0, gptj 1 */ if (int rc = freqs(fm, rot, rot, theta, sec, (im && !multi) ? 0 : (im || axial ? n_sec : 0), &f); rc < 0) return rc; } const bool gptj_pairs = mode == 1; const int64_t pcs = multi ? POS->stride[0] : 0, pms = multi ? POS->stride[1] : 0; const Lin pl = POS ? Lin::of(POS) : Lin{}; char* base = (char*)QKV->data; const uint32_t dt = QKV->dtype; const char* pbase = POS ? (const char*)POS->data : nullptr; const uint32_t pdt = POS ? POS->dtype : 0; const char* qwb = QW ? (const char*)QW->data : nullptr; const char* kwb = KW ? (const char*)KW->data : nullptr; const uint32_t qwdt = QW ? QW->dtype : 0, kwdt = KW ? KW->dtype : 0; const int64_t qws = QW && QW->rank ? QW->stride[QW->rank - 1] : 1, kws = KW && KW->rank ? KW->stride[KW->rank - 1] : 1; const float div = rscale != 0.0f ? rscale : 1.0f; const int64_t heads = n_head + n_head_kv + (v_norm ? n_head_kv : 0); const int64_t total = M * heads; struct Sec { int64_t sec[8], comp[8]; } sc{}; for (int c = 0; c < 8; ++c) { sc.sec[c] = sec[c]; sc.comp[c] = comp[c]; } sycl::queue* q = queue_of(st); if (!q) return RAD_E_DEVICE; 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 m = g / heads, h = g % heads; const bool vh = h >= n_head + n_head_kv; /* a v head under v_norm */ const int64_t hb = m * rs + (vh ? n_head + n_head_kv + (h - n_head - n_head_kv) : h) * head_dim * ds; const char* wb = vh ? nullptr : (h < n_head ? qwb : kwb); const uint32_t wdt = h < n_head ? qwdt : kwdt; const int64_t wst = h < n_head ? qws : kws; float ss = 0.0f; for (int64_t d = 0; d < head_dim; ++d) { const float x = rad_load_f32(base, dt, hb + d * ds); ss += x * x; } const float s = 1.0f / sycl::sqrt(ss / (float)head_dim + eps); for (int64_t d = 0; d < head_dim; ++d) { const float x = rad_load_f32(base, dt, hb + d * ds) * s; rad_store_f32(base, dt, hb + d * ds, wb ? x * (rad_load_f32(wb, wdt, d * wst) + wadd) : x); } if (!turn || vh) return; auto P = [&](int64_t c) { return multi ? pos_at(pbase, pdt, c * pcs + m * pms, div) : pos_at(pbase, pdt, pl.off(m), div); }; if (!blocks) { const int64_t half = rot / 2; for (int64_t i = 0; i < half; ++i) { const float ang = P(f.comp[i]) * f.inv[i]; const float cs = (float)sycl::cos((double)ang), sn = (float)sycl::sin((double)ang); const int64_t i0 = gptj_pairs ? 2 * i : i, i1 = gptj_pairs ? 2 * i + 1 : i + half; const float x0 = rad_load_f32(base, dt, hb + i0 * ds), x1 = rad_load_f32(base, dt, hb + i1 * ds); rad_store_f32(base, dt, hb + i0 * ds, x0 * cs - x1 * sn); rad_store_f32(base, dt, hb + i1 * ds, x0 * sn + x1 * cs); } return; } int64_t start = 0; for (int c = 0; c < n_sec; ++c) { const float pc = P(sc.comp[c]); for (int64_t j = 0; j < sc.sec[c]; ++j) { const float inv = 1.0f / (float)sycl::pow((double)theta, (double)((float)j / (float)sc.sec[c])); const float ang = pc * inv; const float cs = (float)sycl::cos((double)ang), sn = (float)sycl::sin((double)ang); const int64_t i0 = adjacent ? start + 2 * j : start + j; const int64_t i1 = adjacent ? start + 2 * j + 1 : start + sc.sec[c] + j; const float x0 = rad_load_f32(base, dt, hb + i0 * ds), x1 = rad_load_f32(base, dt, hb + i1 * ds); rad_store_f32(base, dt, hb + i0 * ds, x0 * cs - x1 * sn); rad_store_f32(base, dt, hb + i1 * ds, x0 * sn + x1 * cs); } start += 2 * sc.sec[c]; } }); }); } /* qkv_norm_rope / qkv_norm_rope_kv_store: the attention prologue over separate q, k and v (Gemma * 3 and 4, a DFlash2 drafter, Hunyuan v3) in one launch: the value norm (rmsnorm_p), the q and k * norms (rmsnorm a head), the two rotaries and, with _kv_store, kv_store of the finished k and v. * docs/OPS.md requires it byte-identical to those ops, so each step is libxe2's own: a head's norm * is xe2_rmsnorm's bf16 head-row form (a lane n/16 contiguous elements, its squares in order, the * lanes by reduce_over_group; under XE2_EXACT=1 libref's ascending sum, as xe2_rmsnorm then takes), * rounded to bf16 as the norm stores it; the rotary is xe2_rope's arithmetic on its frequency table; * the store converts as xe2_kv_store does. A sub-group a (token, head); the head is staged in local * memory so a rotary pair may sit on any two lanes. Five or six launches a layer become one: on * Gemma 4 E2B's 35 layers that is ~175 fewer a decode step. */ namespace { constexpr int kQnrSg = 4; /* sub-groups (tasks) a work-group */ struct QnrHead { char* base = nullptr; /* bf16 rows */ int64_t pitch = 0; /* elements */ }; int qkv_norm_rope_impl(const RadArgs* a, RadStream st, bool store) { if (!a || a->n_t < (store ? 8 : 6)) return RAD_E_INVAL; const RadTensor *Q = rad_arg_in(a, 0), *K = rad_arg_in(a, 1), *V = rad_arg_in(a, 2); const RadTensor *POS = rad_arg_in(a, 3), *QW = rad_arg_in(a, 4), *KW = rad_arg_in(a, 5); if (!Q || !K || !V || !POS || !QW || !KW) return RAD_E_INVAL; if (Q->dtype != RAD_BF16 || K->dtype != RAD_BF16 || V->dtype != RAD_BF16) return refuse("qkv_norm_rope: q, k and v must be bf16"); if (QW->dtype != KW->dtype || (QW->dtype != RAD_BF16 && QW->dtype != RAD_F32)) return refuse("qkv_norm_rope: gains must both be bf16 or f32"); const int64_t hd = rad_args_geti_or(a, "head_dim", 0); const int64_t nq = rad_args_geti_or(a, "n_head", 0); const int64_t nkv = rad_args_geti_or(a, "n_head_kv", 0); int64_t rot = rad_args_geti_or(a, "rotary_dim", hd); const int vk = (int)rad_args_geti_or(a, "v_from_k", 0); const int vn = (int)rad_args_geti_or(a, "v_norm", 1); if (hd != 128 && hd != 256 && hd != 512) return refuse("qkv_norm_rope: head_dim %lld", (long long)hd); if (vk && !vn) return RAD_E_INVAL; if (nq < 0 || nkv <= 0 || rot <= 0 || rot > hd || (rot & 1)) return RAD_E_SHAPE; if (rad_tensor_numel(QW) < hd || rad_tensor_numel(KW) < hd) return RAD_E_SHAPE; if (QW->rank && QW->stride[QW->rank - 1] != 1) return RAD_E_STRIDE; if (KW->rank && KW->stride[KW->rank - 1] != 1) return RAD_E_STRIDE; const char* mode = rad_args_gets_or(a, "mode", "neox"); if (std::strcmp(mode, "neox")) return RAD_E_UNSUPPORTED; if (rad_args_getf_or(a, "yarn_factor", 0.0) != 0.0) return RAD_E_UNSUPPORTED; if (POS->rank > 1) return RAD_E_SHAPE; int64_t den; if (int rc = ladder(a, rot, hd, &den); rc < 0) return rc; const int64_t nfreq = rot / 2; if (den == hd && rot < hd) rot = hd; /* xe2_rope's widening; frequencies past nfreq are 0 */ Freqs f{}; if (int rc = freqs(kNeox, rot, den, (float)rad_args_getf_or(a, "theta", 10000.0), nullptr, 0, &f); rc < 0) return rc; for (int64_t i = nfreq; i < rot / 2; ++i) f.inv[i] = 0.0f; const float eps = (float)rad_args_getf_or(a, "eps", 1e-6); const float wadd = (float)rad_args_getf_or(a, "wadd", 0.0); const float rsc = (float)rad_args_getf_or(a, "scale", 1.0); const float div = rsc != 0.0f ? rsc : 1.0f; Rows q{}, k{}, v{}; if (nq) { if (int rc = rows_view(Q, nq * hd, &q, "qkv_norm_rope q"); rc < 0) return rc; } if (int rc = rows_view(K, nkv * hd, &k, "qkv_norm_rope k"); rc < 0) return rc; if (int rc = rows_view(V, nkv * hd, &v, "qkv_norm_rope v"); rc < 0) return rc; const int64_t M = nq ? q.rows : k.rows; const int64_t npos = rad_tensor_numel(POS); if (npos <= 0 || M < npos || k.rows != M || v.rows != M) return RAD_E_SHAPE; auto vec_ok = [](const Rows& r) { return r.pitch % 8 == 0 && rad_ptr_aligned(r.base, 16); }; if ((nq && !vec_ok(q)) || !vec_ok(k) || !vec_ok(v)) return refuse("qkv_norm_rope: rows not 16-byte aligned"); /* the cache, as xe2_kv_store reads it */ const char* sm = nullptr; uint32_t smdt = 0; int64_t nslot = 0, bs = 0, nblk = 0, csb = 0, csh = 0, cso = 0, csd = 1; char* cb = nullptr; uint32_t cdt = 0; float kinv = 1.0f, vinv = 1.0f; if (store) { const RadTensor *SM = rad_arg_in(a, 6), *KV = rad_arg_in(a, 7); if (!SM || !KV) return RAD_E_INVAL; if (!rad_tensor_is_contiguous(SM)) return refuse("qkv_norm_rope_kv_store: slot_mapping not contiguous"); bs = rad_args_geti_or(a, "block_size", 0); if (bs <= 0) return RAD_E_SHAPE; nslot = rad_tensor_numel(SM); if (nslot <= 0 || nslot > M) return RAD_E_SHAPE; if (KV->rank == 4) { if (KV->shape[1] != nkv || KV->shape[2] != bs || KV->shape[3] < 2 * hd) return RAD_E_SHAPE; nblk = KV->shape[0]; csb = KV->stride[0]; csh = KV->stride[1]; cso = KV->stride[2]; csd = KV->stride[3]; } else { cso = 2 * hd; csh = bs * cso; csb = nkv * csh; } const bool fp8 = KV->dtype == RAD_F8E4M3 || KV->dtype == RAD_F8E5M2; kinv = fp8 ? 1.0f / (float)rad_args_getf_or(a, "k_scale", 1.0) : 1.0f; vinv = fp8 ? 1.0f / (float)rad_args_getf_or(a, "v_scale", 1.0) : 1.0f; sm = (const char*)SM->data; smdt = SM->dtype; cb = (char*)KV->data; cdt = KV->dtype; } /* v's own heads: normed (and stored), stored only, or with neither nothing to do */ const int64_t heads = nq + nkv + ((vk || (!vn && !store)) ? 0 : nkv); const int64_t total = M * heads; const bool exact = exact_only(); const int nv = (int)(hd / 128); /* 16-byte vectors a lane */ const char* qwb = (const char*)QW->data; const char* kwb = (const char*)KW->data; const bool wf32 = QW->dtype == RAD_F32; const char* pb = (const char*)POS->data; const uint32_t pdt = POS->dtype; const Lin pl = Lin::of(POS); sycl::queue* qu = queue_of(st); if (!qu) return RAD_E_DEVICE; using V8 = sycl::vec; const size_t wg = (size_t)kQnrSg * kSub; const size_t groups = (size_t)((total + kQnrSg - 1) / kQnrSg); return submit([&] { syclex::nd_launch(*qu, sycl::nd_range<1>{groups * wg, wg}, [=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] { const sycl::sub_group sg = it.get_sub_group(); const int sgi = (int)sg.get_group_linear_id(); float* lbuf = *sycl::ext::oneapi::group_local_memory_for_overwrite(it.get_group()); float* buf = lbuf + sgi * 512; const int64_t task = (int64_t)it.get_group(0) * kQnrSg + sgi; if (task >= total) return; /* uniform over the sub-group */ const int64_t m = task / heads, hh = task % heads; const int l = (int)sg.get_local_linear_id(); const int per = nv * 8; /* contiguous elements a lane */ /* the head's raw values, a lane's run of `per` */ auto load = [&](const char* base, int64_t off, float* x) { for (int u = 0; u < 4; ++u) { if (u >= nv) break; const V8 w = *(const V8*)((const uint16_t*)base + off + (l * nv + u) * 8); for (int j = 0; j < 8; ++j) x[u * 8 + j] = sycl::bit_cast((uint32_t)w[j] << 16); } }; /* xe2_rmsnorm on one head row: y = bf16(x * s * gw * mult), mult 1 */ auto norm = [&](const float* x, const char* gb, float* y) { float ss = 0.0f; if (!exact) { for (int e = 0; e < 32; ++e) { if (e >= per) break; ss += x[e] * x[e]; } ss = sycl::reduce_over_group(sg, ss, sycl::plus()); } else { for (int L = 0; L < kSub; ++L) for (int e = 0; e < 32; ++e) { if (e >= per) break; const float xv = sycl::select_from_group(sg, x[e], L); ss += xv * xv; } } const float s = 1.0f / sycl::sqrt(ss / (float)hd + eps); const float mult = 1.0f; for (int e = 0; e < 32; ++e) { if (e >= per) break; const int64_t i = (int64_t)l * per + e; const float gw = !gb ? 1.0f : (wf32 ? ((const float*)gb)[i] : sycl::bit_cast((uint32_t)((const uint16_t*)gb)[i] << 16)) + wadd; y[e] = rad_bf16_to_f32(rad_f32_to_bf16(x[e] * s * gw * mult)); } }; auto put = [&](char* base, int64_t off, const float* y) { for (int u = 0; u < 4; ++u) { if (u >= nv) break; V8 o; for (int j = 0; j < 8; ++j) o[j] = rad_f32_to_bf16(y[u * 8 + j]); *(V8*)((uint16_t*)base + off + (l * nv + u) * 8) = o; } }; /* the cache slot of row m, or -1 */ int64_t cbase = -1; if (store && m < nslot) { const int64_t slot = ld_index(smdt, sm, m); if (slot >= 0) { const int64_t blk = slot / bs, off = slot % bs; if (nblk <= 0 || blk < nblk) cbase = blk * csb + off * cso; } } auto cache = [&](int64_t h, int64_t col0, const float* y, float inv) { if (cbase < 0) return; for (int e = 0; e < 32; ++e) { if (e >= per) break; const int64_t d = (int64_t)l * per + e; rad_store_f32(cb, cdt, cbase + h * csh + (col0 + d) * csd, y[e] * inv); } }; float x[32], y[32]; if (hh >= nq + nkv) { /* a value head: rmsnorm_p in place, or only stored */ const int64_t h = hh - nq - nkv; const int64_t off = m * v.pitch + h * hd; load(v.base, off, x); if (vn) { norm(x, nullptr, y); put(v.base, off, y); cache(h, hd, y, vinv); } else { cache(h, hd, x, vinv); } return; } const bool isq = hh < nq; const int64_t h = isq ? hh : hh - nq; const Rows& r = isq ? q : k; const int64_t off = m * r.pitch + h * hd; load(r.base, off, x); if (vk && !isq) { /* v = rmsnorm_p(raw k), before the k norm */ norm(x, nullptr, y); put(v.base, m * v.pitch + h * hd, y); cache(h, hd, y, vinv); } norm(x, isq ? qwb : kwb, y); if (m < npos) { for (int e = 0; e < 32; ++e) { if (e >= per) break; buf[l * per + e] = y[e]; } sycl::group_barrier(sg); const float p = pos_at(pb, pdt, pl.off(m), div); const int64_t half = rot / 2; for (int64_t i = l; i < half; i += kSub) { const float ang = p * f.inv[i]; const float cs = (float)sycl::cos((double)ang) * 1.0f; const float sn = (float)sycl::sin((double)ang) * 1.0f; const float x0 = buf[i], x1 = buf[i + half]; buf[i] = rad_bf16_to_f32(rad_f32_to_bf16(x0 * cs - x1 * sn)); buf[i + half] = rad_bf16_to_f32(rad_f32_to_bf16(x0 * sn + x1 * cs)); } sycl::group_barrier(sg); for (int e = 0; e < 32; ++e) { if (e >= per) break; y[e] = buf[l * per + e]; } } put(r.base, off, y); if (!isq) cache(h, 0, y, kinv); }); }); } } // namespace int qkv_norm_rope(const RadArgs* a, RadStream st) { return qkv_norm_rope_impl(a, st, false); } int qkv_norm_rope_kv_store(const RadArgs* a, RadStream st) { return qkv_norm_rope_impl(a, st, true); } /* qk_norm_rope_gate / qk_norm_rope_gate_kv_store: the gated-attention prologue (the qwen35 family, * Qwen4-Exp, FishOmni, the MTP heads) in one launch. It splits the interleaved [q|gate] projection * per head, applies the q and k norms and partial NeoX rotaries from a precomputed cos/sin table * (`rope_table`), optionally copies the gate, and with _kv_store also stores k and v. docs/OPS.md * requires it byte-identical to the unfused chain, and each step is libxe2's own: * - the norm is xe2_rmsnorm's bf16 head-row form, as qkv_norm_rope above takes it; * - the rotation reads cos and sin as xe2_rope_table wrote them, which is xe2_rope's arithmetic; * - the store converts as xe2_kv_store does. * Four or five launches per attention layer become one. A position outside the table is clamped * into it, as libr4d's row does. */ namespace { int qk_norm_rope_gate_impl(const RadArgs* a, RadStream st, bool store) { enum { QG = 0, KI, CS, POSI, WQ, WK, QO, KO, GO, VI, SMI, KVI }; if (!a || a->n_t < (store ? 12 : 8)) return RAD_E_INVAL; const RadTensor *QGT = rad_arg_in(a, QG), *K = rad_arg_in(a, KI), *CST = rad_arg_in(a, CS); const RadTensor *POS = rad_arg_in(a, POSI), *QW = rad_arg_in(a, WQ), *KW = rad_arg_in(a, WK); const RadTensor *QOT = rad_arg_in(a, QO), *KOT = rad_arg_in(a, KO), *GOT = rad_arg_in(a, GO); const int64_t hd = rad_args_geti_or(a, "head_dim", 0); const int64_t nq = rad_args_geti_or(a, "n_head", 0); const int64_t nkv = rad_args_geti_or(a, "n_head_kv", 0); const int64_t rot = rad_args_geti_or(a, "rot", 0); if (!K || !CST || !POS || !KW || !KOT) return RAD_E_INVAL; if (nq < 0 || nkv <= 0) return RAD_E_SHAPE; if (nq > 0 && (!QGT || !QW || !QOT)) return RAD_E_INVAL; if (hd != 128 && hd != 256 && hd != 512) return refuse("qk_norm_rope_gate: head_dim %lld", (long long)hd); if (rot < 2 || (rot & 1) || rot > hd) return RAD_E_SHAPE; if ((nq && (QGT->dtype != RAD_BF16 || QOT->dtype != RAD_BF16)) || K->dtype != RAD_BF16 || KOT->dtype != RAD_BF16 || (GOT && GOT->dtype != RAD_BF16)) return refuse("qk_norm_rope_gate: q, gate and k must be bf16"); if ((QW && QW->dtype != KW->dtype) || (KW->dtype != RAD_BF16 && KW->dtype != RAD_F32)) return refuse("qk_norm_rope_gate: gains must both be bf16 or f32"); if (rad_tensor_numel(KW) < hd || (QW && rad_tensor_numel(QW) < hd)) return RAD_E_SHAPE; if (KW->rank && KW->stride[KW->rank - 1] != 1) return RAD_E_STRIDE; if (QW && QW->rank && QW->stride[QW->rank - 1] != 1) return RAD_E_STRIDE; if (CST->dtype != RAD_F32 && CST->dtype != RAD_BF16) return RAD_E_DTYPE; if (!rad_tensor_is_contiguous(CST) || !rad_tensor_is_contiguous(POS)) return RAD_E_STRIDE; const int64_t cs_rows = rad_tensor_numel(CST) / rot; if (cs_rows < 1 || rad_tensor_numel(CST) % rot) return RAD_E_SHAPE; const float eps = (float)rad_args_getf_or(a, "eps", 1e-6); const float wadd = (float)rad_args_getf_or(a, "wadd", 0.0); Rows qg{}, qo{}, go{}, k{}, ko{}, v{}; if (nq) { if (int rc = rows_view(QGT, 2 * nq * hd, &qg, "qk_norm_rope_gate q_gate"); rc < 0) return rc; if (int rc = rows_view(QOT, nq * hd, &qo, "qk_norm_rope_gate q_out"); rc < 0) return rc; if (GOT) { if (int rc = rows_view(GOT, nq * hd, &go, "qk_norm_rope_gate gate_out"); rc < 0) return rc; } } if (int rc = rows_view(K, nkv * hd, &k, "qk_norm_rope_gate k"); rc < 0) return rc; if (int rc = rows_view(KOT, nkv * hd, &ko, "qk_norm_rope_gate k_out"); rc < 0) return rc; const int64_t M = nq ? qg.rows : k.rows; if (M <= 0 || k.rows < M || ko.rows < M || (nq && (qo.rows < M || (GOT && go.rows < M)))) return RAD_E_SHAPE; const int64_t npos = rad_tensor_numel(POS); if (npos < M) return RAD_E_SHAPE; auto vec_ok = [](const Rows& r) { return r.pitch % 8 == 0 && rad_ptr_aligned(r.base, 16); }; if ((nq && (!vec_ok(qg) || !vec_ok(qo) || (GOT && !vec_ok(go)))) || !vec_ok(k) || !vec_ok(ko)) return refuse("qk_norm_rope_gate: rows not 16-byte aligned"); /* the cache, as xe2_kv_store reads it (qkv_norm_rope_impl's checks) */ const char* sm = nullptr; uint32_t smdt = 0; int64_t nslot = 0, bs = 0, nblk = 0, csb = 0, csh = 0, cso = 0, csd = 1; char* cb = nullptr; uint32_t cdt = 0; float kinv = 1.0f, vinv = 1.0f; if (store) { const RadTensor *V = rad_arg_in(a, VI), *SM = rad_arg_in(a, SMI), *KV = rad_arg_in(a, KVI); if (!V || !SM || !KV) return RAD_E_INVAL; if (V->dtype != RAD_BF16) return refuse("qk_norm_rope_gate_kv_store: v must be bf16"); if (int rc = rows_view(V, nkv * hd, &v, "qk_norm_rope_gate_kv_store v"); rc < 0) return rc; if (v.rows < M) return RAD_E_SHAPE; if (!vec_ok(v)) return refuse("qk_norm_rope_gate_kv_store: v rows not 16-byte aligned"); if (!rad_tensor_is_contiguous(SM)) return refuse("qk_norm_rope_gate_kv_store: slot_mapping not contiguous"); bs = rad_args_geti_or(a, "block_size", 0); if (bs <= 0) return RAD_E_SHAPE; nslot = rad_tensor_numel(SM); if (nslot <= 0 || nslot > M) return RAD_E_SHAPE; if (KV->rank == 4) { if (KV->shape[1] != nkv || KV->shape[2] != bs || KV->shape[3] < 2 * hd) return RAD_E_SHAPE; nblk = KV->shape[0]; csb = KV->stride[0]; csh = KV->stride[1]; cso = KV->stride[2]; csd = KV->stride[3]; } else { cso = 2 * hd; csh = bs * cso; csb = nkv * csh; } const bool fp8 = KV->dtype == RAD_F8E4M3 || KV->dtype == RAD_F8E5M2; kinv = fp8 ? 1.0f / (float)rad_args_getf_or(a, "k_scale", 1.0) : 1.0f; vinv = fp8 ? 1.0f / (float)rad_args_getf_or(a, "v_scale", 1.0) : 1.0f; sm = (const char*)SM->data; smdt = SM->dtype; cb = (char*)KV->data; cdt = KV->dtype; } /* tasks: q heads, k heads, and with the store the v heads (copied to the cache only) */ const int64_t heads = nq + nkv + (store ? nkv : 0); const int64_t total = M * heads; const bool exact = exact_only(); const int nv = (int)(hd / 128); /* 16-byte vectors a lane */ const char* qwb = QW ? (const char*)QW->data : nullptr; const char* kwb = (const char*)KW->data; const bool wf32 = KW->dtype == RAD_F32; const char* csp = (const char*)CST->data; const bool cs32 = CST->dtype == RAD_F32; const char* pb = (const char*)POS->data; const uint32_t pdt = POS->dtype; const bool gate = GOT != nullptr; sycl::queue* qu = queue_of(st); if (!qu) return RAD_E_DEVICE; using V8 = sycl::vec; const size_t wg = (size_t)kQnrSg * kSub; const size_t groups = (size_t)((total + kQnrSg - 1) / kQnrSg); return submit([&] { syclex::nd_launch(*qu, sycl::nd_range<1>{groups * wg, wg}, [=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] { const sycl::sub_group sg = it.get_sub_group(); const int sgi = (int)sg.get_group_linear_id(); float* lbuf = *sycl::ext::oneapi::group_local_memory_for_overwrite(it.get_group()); float* buf = lbuf + sgi * 512; const int64_t task = (int64_t)it.get_group(0) * kQnrSg + sgi; if (task >= total) return; /* uniform over the sub-group */ const int64_t m = task / heads, hh = task % heads; const int l = (int)sg.get_local_linear_id(); const int per = nv * 8; /* contiguous elements a lane */ auto load = [&](const char* base, int64_t off, float* x) { for (int u = 0; u < 4; ++u) { if (u >= nv) break; const V8 w = *(const V8*)((const uint16_t*)base + off + (l * nv + u) * 8); for (int j = 0; j < 8; ++j) x[u * 8 + j] = sycl::bit_cast((uint32_t)w[j] << 16); } }; /* xe2_rmsnorm on one head row: y = bf16(x * s * gw * mult), mult 1 */ auto norm = [&](const float* x, const char* gb, float* y) { float ss = 0.0f; if (!exact) { for (int e = 0; e < 32; ++e) { if (e >= per) break; ss += x[e] * x[e]; } ss = sycl::reduce_over_group(sg, ss, sycl::plus()); } else { for (int L = 0; L < kSub; ++L) for (int e = 0; e < 32; ++e) { if (e >= per) break; const float xv = sycl::select_from_group(sg, x[e], L); ss += xv * xv; } } const float s = 1.0f / sycl::sqrt(ss / (float)hd + eps); const float mult = 1.0f; for (int e = 0; e < 32; ++e) { if (e >= per) break; const int64_t i = (int64_t)l * per + e; const float gw = (wf32 ? ((const float*)gb)[i] : sycl::bit_cast((uint32_t)((const uint16_t*)gb)[i] << 16)) + wadd; y[e] = rad_bf16_to_f32(rad_f32_to_bf16(x[e] * s * gw * mult)); } }; auto put = [&](char* base, int64_t off, const float* y) { for (int u = 0; u < 4; ++u) { if (u >= nv) break; V8 o; for (int j = 0; j < 8; ++j) o[j] = rad_f32_to_bf16(y[u * 8 + j]); *(V8*)((uint16_t*)base + off + (l * nv + u) * 8) = o; } }; int64_t cbase = -1; if (store && m < nslot) { const int64_t slot = ld_index(smdt, sm, m); if (slot >= 0) { const int64_t blk = slot / bs, off = slot % bs; if (nblk <= 0 || blk < nblk) cbase = blk * csb + off * cso; } } auto cache = [&](int64_t h, int64_t col0, const float* y, float inv) { if (cbase < 0) return; for (int e = 0; e < 32; ++e) { if (e >= per) break; const int64_t d = (int64_t)l * per + e; rad_store_f32(cb, cdt, cbase + h * csh + (col0 + d) * csd, y[e] * inv); } }; float x[32], y[32]; if (hh >= nq + nkv) { /* a value head: kv_store's v half, as it is */ const int64_t h = hh - nq - nkv; load(v.base, m * v.pitch + h * hd, x); cache(h, hd, x, vinv); return; } const bool isq = hh < nq; const int64_t h = isq ? hh : hh - nq; if (isq) { const int64_t src = m * qg.pitch + h * 2 * hd; if (gate) { /* the gate half, bit for bit */ for (int u = 0; u < 4; ++u) { if (u >= nv) break; *(V8*)((uint16_t*)go.base + m * go.pitch + h * hd + (l * nv + u) * 8) = *(const V8*)((const uint16_t*)qg.base + src + hd + (l * nv + u) * 8); } } load(qg.base, src, x); } else { load(k.base, m * k.pitch + h * hd, x); } norm(x, isq ? qwb : kwb, y); for (int e = 0; e < 32; ++e) { if (e >= per) break; buf[l * per + e] = y[e]; } sycl::group_barrier(sg); int64_t pp = ld_index(pdt, pb, m); pp = pp < 0 ? 0 : (pp < cs_rows ? pp : cs_rows - 1); const int64_t half = rot / 2, co = pp * rot; for (int64_t i = l; i < half; i += kSub) { const float cs = cs32 ? ((const float*)csp)[co + i] : sycl::bit_cast((uint32_t)((const uint16_t*)csp)[co + i] << 16); const float sn = cs32 ? ((const float*)csp)[co + half + i] : sycl::bit_cast((uint32_t)((const uint16_t*)csp)[co + half + i] << 16); const float x0 = buf[i], x1 = buf[i + half]; buf[i] = rad_bf16_to_f32(rad_f32_to_bf16(x0 * cs - x1 * sn)); buf[i + half] = rad_bf16_to_f32(rad_f32_to_bf16(x0 * sn + x1 * cs)); } sycl::group_barrier(sg); for (int e = 0; e < 32; ++e) { if (e >= per) break; y[e] = buf[l * per + e]; } if (isq) { put(qo.base, m * qo.pitch + h * hd, y); } else { put(ko.base, m * ko.pitch + h * hd, y); cache(h, 0, y, kinv); } }); }); } } // namespace int qk_norm_rope_gate(const RadArgs* a, RadStream st) { return qk_norm_rope_gate_impl(a, st, false); } int qk_norm_rope_gate_kv_store(const RadArgs* a, RadStream st) { return qk_norm_rope_gate_impl(a, st, true); } /* 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); }); }); } } // namespace xe2