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/libref/ref_attn.cpp
T
Deadcode b068190326 radiance 1.6.0
- Qwen-Image 2.1 and 2.1 Turbo: text to image and image edits over OpenAI's images API,
  /v1/images/generations and /v1/images/edits. An edit takes up to ten pictures and an optional
  mask, outside which the picture comes back exactly as it was; `background: transparent`, png,
  jpeg and webp output, `n` pictures from one prompt, streamed previews (`partial_images`), and
  vLLM-Omni's seed, negative_prompt with true_cfg_scale, num_inference_steps, width and height.
  arch/qwenimage21 serves the diffusers pipeline directory, converted with
  data/recipes/qwen-image-2.1-fp8.recipe (block fp8) or qwen-image-2.1-bf16.recipe.
  deploy/compose/qwen-image-2.1.yaml and qwen-image-2.1-turbo.yaml serve the fp8 containers on
  two cards. Two R9700s make a 2048x2048 picture in 61 s at the base model's 40 steps and in
  13 s with Turbo (56 and 12 s with --tp-wire wht6), a 1024x1024 one in 6.0 and 2.6 s. The
  models are under Qwen's research license, which is non-commercial
- an image generator is a program kind of its own (core/gen): an architecture declares its
  conditioning, denoising and decoding passes, and the driver runs the schedule, the pictures of
  a batch and the conditioning cache. An image model's /v1/models entry is its generator's name
  (qwen-image-2.1, qwen-image-2.1-turbo), and its capabilities and startup banner list only the
  images endpoints
- the tiled prefill GEMMs run their tiles in groups of activation bands, 16 for fp8 and 8 for
  bf16, so an operand larger than the 64 MB cache is read once a group instead of once a band. A
  bf16 GEMM with more than 64 MB of weight runs up to twice as fast
- fixed: a second lane opened in the middle of a step started beside work lane 0 had not
  finished. Gemma 4 26B-A4B opens its lane that way, so its first step after startup could read
  rows not yet written
- startup no longer warns about --checkpoint-slots when it was not passed, nor about an expert
  floor on a model with no experts
- the image's FFmpeg writes png, jpeg and webp (libwebp)
- for out-of-tree plugins: RAD_ABI_VERSION is 16. The op vocabulary gains the image generator's
  ops (conv2d_nhwc, ln_mod, ln_mod_quant_fp8, flow_euler, attn_prefix_self and others; docs/OPS.md,
  "Image generation"), and all_reduce takes an optional `overlap`. Plugins built against 1.5.0
  must be rebuilt
2026-10-14 14:03:59 +02:00

905 lines
46 KiB
C++

/* ref_attn.cpp -- paged attention, dense attention, the KV write, and the two rotary forms.
*
* These are the ops most likely to be subtly wrong in any implementation, so they are written for
* legibility over everything else: the mask is an explicit predicate per key, the softmax is two
* plain passes with the max subtracted, and nothing is fused.
*
* ============================== THE PAGED LAYOUT ==============================
*
* kv_cache[num_blocks, kv_heads, block_size, 2 * head_dim] K then V inside a slot
*
* This is the layout every kernel in the project has to match (libr4d's `R4DArgs::kv` names the
* same one), so it is stated in ref_ops.h and obeyed here. A flat slot index
* s decomposes as block = s / block_size, offset = s % block_size; `block_table[seq, i]` holds the
* block id of the sequence's i-th block and `slot_mapping[token]` holds the flat slot a token's KV
* goes to.
*
* ============================== THE MASK ==============================
*
* `seqused[s]` is the sequence's TOTAL key count INCLUDING this step's query tokens, so query row
* i of a q_len-row step sits at absolute position seqused[s] - q_len + i. That is what makes one
* kernel serve a decode (q_len 1), a speculative verify (q_len <= 64) and a prefill chunk
* (q_len in the thousands) without the caller passing a second length.
*
* causal = 1 key j is visible when j <= pos
* causal = 0 key j is visible when j < seqused[s]
* window > 0 causal: additionally pos - j < window; non-causal: |pos - j| < window, which is
* the two-sided reading libr4d's h128 kernel documents.
*/
#include "ref_common.h"
#include "rad_yarn.h"
/* `row_stride`: which axis carries a row of `cols` elements, at whatever rank the operand arrived
* in. Every q/k/v/out below goes through it rather than through `rank >= 3 ? stride[rank-3] : cols`
* -- the comment above kv_store shows where that shortcut is wrong. */
#include "ref_gemm.h"
#include "ref_ops.h"
#include <algorithm>
using namespace ref;
namespace {
/* The largest head this reference accumulates in one stack frame. The widest in circulation is an
* image VAE's single-head mid-block attention at 1152 (Qwen-Image 2.1), so 2048 is headroom; above
* it the op says RAD_E_UNSUPPORTED by name instead of overflowing a frame. */
enum { REF_HD_MAX = 2048 };
struct KVView {
const RadTensor* t;
int64_t sb, sh, so, sd; /* strides: block, kv head, slot offset, element */
int64_t head_dim;
};
static inline KVView kv_view(const RadTensor* c, int64_t head_dim, int64_t block_size,
int64_t kv_heads) {
KVView v{};
v.t = c;
v.head_dim = head_dim;
if (c->rank == 4) {
v.sb = c->stride[0]; v.sh = c->stride[1]; v.so = c->stride[2]; v.sd = c->stride[3];
} else {
v.sd = 1;
v.so = 2 * head_dim;
v.sh = block_size * v.so;
v.sb = kv_heads * v.sh;
}
return v;
}
} /* namespace */
/* ------------------------------------------------------------------ attn_paged */
int ref_attn_paged(const RadArgs* a, RadStream) {
if (a->n_t < 8) return RAD_E_INVAL;
const RadTensor *q = &a->t[0], *kv = &a->t[1], *bt = &a->t[2], *su = &a->t[3], *o = &a->t[7];
const RadTensor* kdes = t_in(a, 4);
const RadTensor* vdes = t_in(a, 5);
const RadTensor* cus = t_in(a, 6);
if (!q->data || !kv->data || !bt->data || !su->data || !o->data) return RAD_E_INVAL;
const int64_t head_dim = p_int(a, "head_dim", q->rank >= 3 ? q->shape[q->rank - 1] : 0);
const int64_t gqa = p_int(a, "gqa", 1);
/* `block_size` is RAD_DERIVED on this op (docs/OPS.md), so a caller who did not pin it and
* resolved to a kernel that declares no RAD_C_EQ for it -- ref's own row -- arrives here
* without the key. The cache tensor says what the block size is; ref reads it off the operand,
* which is this plugin's rule anyway, and cross-checks it below where the caller did name one. */
const int64_t block_size = p_int(a, "block_size", kv->rank == 4 ? kv->shape[2] : 0);
const int causal = (int)p_int(a, "causal", 1);
const int64_t window = p_int(a, "window", 0);
if (head_dim <= 0 || gqa <= 0 || block_size <= 0) return RAD_E_SHAPE;
if (head_dim > REF_HD_MAX) return RAD_E_UNSUPPORTED;
const int64_t kv_heads = kv->rank == 4 ? kv->shape[1] : 0;
if (kv_heads <= 0) return RAD_E_SHAPE;
const int64_t q_heads = gqa * kv_heads;
/* gqa and the cache's head count decide the query head count, so a rank-3 query that disagrees
* is a caller bug that would otherwise stride through the wrong rows and return plausible
* numbers. */
if (q->rank >= 3 && q->shape[q->rank - 2] != q_heads) return RAD_E_SHAPE;
const int64_t n_seq = numel(su);
const int64_t rows = numel(q) / (q_heads * head_dim);
if (n_seq <= 0 || rows <= 0) return RAD_E_SHAPE;
/* RAGGED BATCHES. cu_seqlens is optional and absent means every sequence presents the same
* query length, the uniform case. Present, it
* is [n_seq + 1] with cu[0] == 0 and cu[n_seq] == rows, and sequence s owns query rows
* [cu[s], cu[s+1]). A serving scheduler mixes one sequence prefill chunk with other single
* decode rows in the same step, so the ragged case is the ordinary one. */
if (!cus && rows % n_seq != 0) return RAD_E_SHAPE;
if (cus && numel(cus) != n_seq + 1) return RAD_E_SHAPE;
const int64_t q_len = cus ? 0 : rows / n_seq;
if (numel(o) < rows * q_heads * head_dim) return RAD_E_SHAPE;
if (kv->rank == 4 && kv->shape[2] != block_size) return RAD_E_SHAPE;
if (kv->rank == 4 && kv->shape[3] < 2 * head_dim) return RAD_E_SHAPE;
const int64_t max_blocks = bt->rank >= 2 ? bt->shape[bt->rank - 1] : numel(bt) / n_seq;
const int64_t bt_rs = bt->rank >= 2 ? bt->stride[bt->rank - 2] : max_blocks;
const int64_t bt_cs = bt->rank >= 2 ? bt->stride[bt->rank - 1] : 1;
const KVView kvv = kv_view(kv, head_dim, block_size, kv_heads);
/* Row strides of q and out read as [rows, q_heads, head_dim], at whatever rank they arrived. */
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 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 = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim));
const int64_t total = rows * q_heads;
#pragma omp parallel for schedule(static)
for (int64_t idx = 0; idx < total; ++idx) {
const int64_t h = idx % q_heads;
const int64_t tok = idx / q_heads; /* the dense query row */
/* Which sequence owns it, and where inside that sequence's query it sits. Linear rather than a
* binary search: n_seq is a handful and this is the reference. */
int64_t s = 0, qlen = q_len, i = 0;
if (cus) {
while (s + 1 < n_seq && ld_int(cus->dtype, cus->data, offlin(cus, s + 1)) <= tok) ++s;
const int64_t beg = ld_int(cus->dtype, cus->data, offlin(cus, s));
qlen = ld_int(cus->dtype, cus->data, offlin(cus, s + 1)) - beg;
i = tok - beg;
} else {
s = tok / q_len;
i = tok - s * q_len;
}
if (qlen <= 0) continue;
const int64_t kh = h / gqa;
const int64_t ctx = ld_int(su->dtype, su->data, offlin(su, s));
const int64_t pos = ctx - qlen + i;
const int64_t qb = tok * q_rs + h * q_hs;
const int64_t ob = tok * o_rs + h * o_hs;
const float kds = kdes ? ldt(kdes, s * kv_heads + kh) : 1.0f;
const float vds = vdes ? ldt(vdes, s * kv_heads + kh) : 1.0f;
/* Pass one: the maximum score, so the exponent below cannot overflow. */
float mx = -INFINITY;
for (int64_t j = 0; j < ctx; ++j) {
if (causal ? (j > pos) : (j >= ctx)) continue;
if (window > 0) {
const int64_t d = pos - j;
if (causal ? (d >= window) : (d >= window || d <= -window)) continue;
}
if (j / block_size >= max_blocks) break; /* bounds first: the table is only this wide */
const int64_t blk = ld_int(bt->dtype, bt->data, s * bt_rs + (j / block_size) * bt_cs);
if (blk < 0) continue;
const int64_t kb = blk * kvv.sb + kh * kvv.sh + (j % block_size) * kvv.so;
float dot = 0.0f;
for (int64_t d = 0; d < head_dim; ++d)
dot += ldt(q, qb + d * q_ds) * (ldt(kv, kb + d * kvv.sd) * kds);
dot *= scale;
if (dot > mx) mx = dot;
}
float acc[REF_HD_MAX];
for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f;
/* No visible key at all -- an empty sliding window on the first token of a sequence -- is a
* zero row, not a NaN. A softmax over nothing has no defined answer and zero is the one
* every kernel in this project produces. */
if (mx == -INFINITY) {
for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, 0.0f);
continue;
}
/* Pass two: the scores again, exponentiated and accumulated in ascending key order. The
* dot product is recomputed rather than kept, because keeping it would need a buffer the
* size of the context and the reference has time it does not have memory. */
float sum = 0.0f;
for (int64_t j = 0; j < ctx; ++j) {
if (causal ? (j > pos) : (j >= ctx)) continue;
if (window > 0) {
const int64_t d = pos - j;
if (causal ? (d >= window) : (d >= window || d <= -window)) continue;
}
if (j / block_size >= max_blocks) break; /* bounds first: the table is only this wide */
const int64_t blk = ld_int(bt->dtype, bt->data, s * bt_rs + (j / block_size) * bt_cs);
if (blk < 0) continue;
const int64_t kb = blk * kvv.sb + kh * kvv.sh + (j % block_size) * kvv.so;
float dot = 0.0f;
for (int64_t d = 0; d < head_dim; ++d)
dot += ldt(q, qb + d * q_ds) * (ldt(kv, kb + d * kvv.sd) * kds);
const float w = ref_exp(dot * scale - mx);
sum += w;
for (int64_t d = 0; d < head_dim; ++d)
acc[d] += w * (ldt(kv, kb + (head_dim + d) * kvv.sd) * vds);
}
const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, acc[d] * inv);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ attn_dense */
/* The vision tower's: nothing paged, nothing quantised, `cu_seqlens` bounding one image (or one
* attention window) per entry so a whole batch is ONE launch rather than a per-segment loop and a
* concatenate. Causal is a parameter because a dense decoder-only prefill wants the same kernel. */
int ref_attn_dense(const RadArgs* a, RadStream) {
if (!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 = p_int(a, "head_dim", q->rank >= 3 ? q->shape[q->rank - 1] : 0);
const int64_t gqa = p_int(a, "gqa", 1);
const int causal = (int)p_int(a, "causal", 0);
/* `window` is attn_paged's rule over a segment's own positions: causal, key j is visible to
* query i when i - j < window; non-causal, when |i - j| < window. 0 is no window. */
const int64_t window = p_int(a, "window", 0);
if (head_dim <= 0 || gqa <= 0 || window < 0) return RAD_E_SHAPE;
if (head_dim > REF_HD_MAX) return RAD_E_UNSUPPORTED;
/* [tokens, heads, head_dim], or [tokens, heads * head_dim] -- a column slice of a fused
* projection, whose row pitch is the projection's. */
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 = numel(cu) - 1;
if (n_seq <= 0) return RAD_E_SHAPE;
const int64_t total_q = numel(q) / (q_heads * head_dim);
if (numel(o) < total_q * q_heads * head_dim) return RAD_E_SHAPE;
if (numel(k) < total_q * kv_heads * head_dim) return RAD_E_SHAPE;
if (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 = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim));
#pragma omp parallel for schedule(static)
for (int64_t sh = 0; sh < n_seq * q_heads; ++sh) {
const int64_t s = sh / q_heads, h = sh % q_heads, kh = h / gqa;
const int64_t b0 = ld_int(cu->dtype, cu->data, offlin(cu, s));
const int64_t b1 = ld_int(cu->dtype, cu->data, offlin(cu, s + 1));
for (int64_t i = b0; i < b1; ++i) {
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 = std::max<int64_t>(b0, i - window + 1);
if (!causal) jend = std::min<int64_t>(b1, i + window);
}
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 += ldt(q, qb + d * q_ds) * ldt(k, kb + d * k_ds);
dot *= scale;
if (dot > mx) mx = dot;
}
float acc[REF_HD_MAX];
for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f;
if (mx == -INFINITY) {
for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, 0.0f);
continue;
}
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 += ldt(q, qb + d * q_ds) * ldt(k, kb + d * k_ds);
const float w = ref_exp(dot * scale - mx);
sum += w;
for (int64_t d = 0; d < head_dim; ++d) acc[d] += w * ldt(v, vb + d * v_ds);
}
const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, acc[d] * inv);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ kv_store */
/* Writes this step's keys and values into the paged cache at `slot_mapping`. The cache operand is
* INOUT and not OUT: this op touches only the mapped slots and every other slot in the pool must
* survive it, which is a liveness fact the buffer planner has to know (docs/OPS.md draws it as an
* output; that is the one role this plugin states differently, and deliberately).
*
* A NEGATIVE slot is skipped. That is how a padded batch row says "this token has no cache slot",
* and it has to be a documented value rather than an accident: libr4d treats slot <= 0 as null
* because vLLM reserves block 0, but a generic reference must not steal a valid slot, so ref skips
* only the strictly negative.
*
* `k` AND `v` ARRIVE RANK 2 FROM THE ENGINE AND THEIR ROWS ARE NOT DENSE. An architecture that
* de-interleaves the projection hands [tokens, kv_heads, head_dim]; one that does not hands a
* COLUMN SLICE of the fused QKV plane -- [tokens, kv_heads * head_dim] whose row stride is the
* whole projection's width, 2560 against 256 on a 16-head model with 2 kv heads. Deriving the row
* stride from the shape instead of from the tensor puts token 0 in the right slot and every token
* after it inside the previous token's QUERY rows, which is a cache that looks written and holds
* the wrong keys from the second token on. `row_stride` asks the operand instead. */
int ref_kv_store(const RadArgs* a, RadStream) {
if (!have(a, 4)) return RAD_E_INVAL;
const RadTensor *k = &a->t[0], *v = &a->t[1], *sm = &a->t[2], *kv = &a->t[3];
const int64_t head_dim = p_int(a, "head_dim", k->rank >= 3 ? k->shape[k->rank - 1] : 0);
const int64_t block_size = p_int(a, "block_size", 0);
int64_t kv_heads = p_int(a, "n_head_kv", kv->rank == 4 ? kv->shape[1] : 0);
if (head_dim <= 0 || block_size <= 0 || kv_heads <= 0) return RAD_E_SHAPE;
if (kv->rank == 4 && (kv->shape[1] != kv_heads || kv->shape[2] != block_size ||
kv->shape[3] < 2 * head_dim)) return RAD_E_SHAPE;
const int64_t M = numel(sm);
if (M <= 0 || numel(k) < M * kv_heads * head_dim) return RAD_E_SHAPE;
const int64_t n_blocks = kv->rank == 4 ? kv->shape[0] : 0;
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 KVView kvv = kv_view(kv, head_dim, block_size, kv_heads);
/* AN FP8 CACHE STORES k / k_scale: the scales are the descales the reader multiplies back by,
* 1.0 unless the call names them. A wider cache stores the value itself. */
const bool fp8 = kv->dtype == RAD_F8E4M3 || kv->dtype == RAD_F8E5M2;
const float ks = fp8 ? 1.0f / p_f32(a, "k_scale", 1.0f) : 1.0f;
const float vs = fp8 ? 1.0f / p_f32(a, "v_scale", 1.0f) : 1.0f;
for (int64_t t = 0; t < M; ++t) {
const int64_t slot = ld_int(sm->dtype, sm->data, offlin(sm, t));
if (slot >= 0 && n_blocks > 0 && slot / block_size >= n_blocks) return RAD_E_SHAPE;
}
#pragma omp parallel for schedule(static)
for (int64_t t = 0; t < M; ++t) {
const int64_t slot = ld_int(sm->dtype, sm->data, offlin(sm, t));
if (slot < 0) continue;
const int64_t blk = slot / block_size, off = slot % block_size;
for (int64_t h = 0; h < kv_heads; ++h) {
const int64_t cb = blk * kvv.sb + h * kvv.sh + off * kvv.so;
for (int64_t d = 0; d < head_dim; ++d) {
stt(kv, cb + d * kvv.sd, ldt(k, t * k_rs + h * k_hs + d * k_ds) * ks);
stt(kv, cb + (head_dim + d) * kvv.sd, ldt(v, t * v_rs + h * v_hs + d * v_ds) * vs);
}
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ rope */
namespace {
/* NeoX pairs element i with i + rotary_dim/2; GPT-J (the "interleaved" style) pairs 2i with 2i+1.
* Which one a checkpoint wants is a property of the checkpoint, so it is a parameter and not a
* guess -- and getting it wrong produces fluent text with a broken sense of position, which is the
* hardest kind of wrong to notice (spec §12 makes the same point about token boundaries).
*
* THE MULTI-COMPONENT MODES pair like NeoX and differ in which position component drives each
* frequency (i indexes the rot/2 frequencies):
* mrope contiguous sections: frequencies [0, s0) take component 0, the next s1 component 1...
* (Qwen2-VL), all on one ladder theta^(-2i/rot).
* imrope interleaved (Qwen3-VL): component 1 where i % 3 == 1 and i < 3*s1, component 2 where
* i % 3 == 2 and i < 3*s2, component 0 everywhere else; one ladder.
* axial contiguous sections, EACH ON ITS OWN LADDER theta^(-2j/(2*s_c)) for its j-th
* frequency -- a 2-D rotary embedding over (row, column), the vision tower's.
* With one position component a token -- a rank-1 `positions` -- every component is that one and
* mrope and imrope ARE neox. */
enum { ROPE_NEOX = 0, ROPE_GPTJ = 1, ROPE_MROPE = 2, ROPE_IMROPE = 3, ROPE_AXIAL = 4 };
struct RopeFreq {
int comp[REF_HD_MAX / 2];
float inv[REF_HD_MAX / 2];
};
/* Which component and inverse frequency each of the rot/2 frequencies uses. */
/* `den` is the width the BASE ladder is measured in: `rot` for a `rotary` ladder (a partial rotary
* is a complete rotation of its own width) and `head_dim` for `head`, the proportional variant. The
* loop count and the NeoX/GPT-J pairing still come from `rot`; `axial` overrides `inv` below. */
static int rope_freqs(int mode, int64_t rot, int64_t den, float theta, const int64_t* sec,
int n_sec, RopeFreq* f) {
const int64_t half = rot / 2;
if (half > REF_HD_MAX / 2) return RAD_E_UNSUPPORTED;
int64_t start[8] = {}, total = 0;
for (int c = 0; c < n_sec; ++c) { start[c] = total; total += sec[c]; }
if ((mode == ROPE_MROPE || mode == ROPE_AXIAL) && n_sec > 0 && total != half) return RAD_E_SHAPE;
for (int64_t i = 0; i < half; ++i) {
int c = 0;
float inv = 1.0f / std::pow(theta, (float)(2 * i) / (float)den);
if (n_sec > 0 && (mode == ROPE_MROPE || mode == ROPE_AXIAL)) {
while (c + 1 < n_sec && i >= start[c + 1]) ++c;
if (mode == ROPE_AXIAL) {
const int64_t j = i - start[c];
inv = 1.0f / std::pow(theta, (float)(2 * j) / (float)(2 * sec[c]));
}
} else if (n_sec >= 3 && mode == ROPE_IMROPE) {
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;
}
static void rope_head(const RadTensor* t, int64_t base, int64_t ds, int64_t rot, int mode,
const RopeFreq& f, const float* pos, float magnitude = 1.0f) {
const int64_t half = rot / 2;
for (int64_t i = 0; i < half; ++i) {
const float ang = pos[f.comp[i]] * f.inv[i];
const float c = std::cos(ang) * magnitude, s = std::sin(ang) * magnitude;
const int64_t i0 = (mode == ROPE_GPTJ) ? 2 * i : i;
const int64_t i1 = (mode == ROPE_GPTJ) ? 2 * i + 1 : i + half;
const float x0 = ldt(t, base + i0 * ds), x1 = ldt(t, base + i1 * ds);
stt(t, base + i0 * ds, x0 * c - x1 * s);
stt(t, base + i1 * ds, x0 * s + x1 * c);
}
}
/* "11 11 10" -> {11, 11, 10}. Absent is no sections. */
static int rope_sections(const RadArgs* a, int64_t* sec) {
const char* v = p_str(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;
}
/* `ladder` names the width the base frequency ladder is measured in -- see rope_freqs. Absent and
* `rotary` divide by `rot` (every existing model); `head` divides by `head_dim`, which it needs. An
* unknown value is a schema error, not a silent default: a mistyped ladder is a silent wrong angle. */
static int rope_ladder(const RadArgs* a, int64_t rot, int64_t head_dim, int64_t* den) {
const char* lad = p_str(a, "ladder", nullptr);
if (!lad) { *den = rot; return RAD_OK; }
if (!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;
}
} /* namespace */
int ref_rope(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *qkv = &a->t[0], *pos = &a->t[1];
const int64_t head_dim = p_int(a, "head_dim", 0);
const int64_t n_head = p_int(a, "n_head", 0);
const int64_t n_head_kv = p_int(a, "n_head_kv", 0);
const float theta = p_f32(a, "theta", 10000.0f);
const float rscale = p_f32(a, "scale", 1.0f);
static const char* kModes[] = { "neox", "gptj", "mrope", "imrope", "axial" };
const int mode = p_enum(a, "mode", kModes, 5, -1);
if (mode < 0) return RAD_E_UNSUPPORTED;
int64_t rot = p_int(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;
RAD_REF_TRY(rope_ladder(a, rot, head_dim, &den));
int64_t sec[8] = {};
const int n_sec = rope_sections(a, sec);
if (n_sec < 0) return RAD_E_SHAPE;
/* POSITIONS: [M] is one component a token; [C, M] is 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] : numel(pos);
if (multi) {
if (mode == ROPE_NEOX || mode == ROPE_GPTJ || n_sec <= 0) return RAD_E_SHAPE;
const int64_t need = mode == ROPE_IMROPE ? 3 : n_sec;
if (n_comp < need || n_comp > 8) return RAD_E_SHAPE;
}
/* THE PROPORTIONAL LADDER (`head`) is HF's: the rotation spans the whole head -- pair i is
* (i, i + head_dim/2) -- and every frequency past rotary_dim/2 is zero, so those pairs turn by
* nothing. A rotary of rotary_dim's own width, pairing (i, i + rot/2), turns other channels. */
const int64_t nfreq = rot / 2;
if (den == head_dim && rot < head_dim && !multi && mode == ROPE_NEOX) rot = head_dim;
RopeFreq f;
RAD_REF_TRY(rope_freqs(mode, rot, den, theta, sec, multi ? n_sec : 0, &f));
const RadYarn yarn = rad_yarn_args(a);
if (!rad_yarn_valid(yarn)) return RAD_E_INVAL;
if (yarn.factor != 0.0f) {
if (mode == ROPE_AXIAL || rscale != 1.0f) return RAD_E_UNSUPPORTED;
for (int64_t i = 0; i < rot / 2; ++i) f.inv[i] = yarn.frequency(f.inv[i], (int)i);
}
for (int64_t i = nfreq; i < rot / 2; ++i) f.inv[i] = 0.0f;
const int64_t stride_row = (n_head + 2 * n_head_kv) * head_dim;
if (M <= 0 || numel(qkv) < M * stride_row) return RAD_E_SHAPE;
const int64_t rs = qkv->rank >= 2 ? qkv->stride[qkv->rank - 2] : stride_row;
const int64_t ds = laststride(qkv);
const int64_t pcs = multi ? pos->stride[0] : 0, pms = multi ? pos->stride[1] : 0;
#pragma omp parallel for schedule(static)
for (int64_t m = 0; m < M; ++m) {
float p[8];
const float div = rscale != 0.0f ? rscale : 1.0f;
if (multi) {
for (int64_t c = 0; c < n_comp; ++c)
p[c] = (float)ld_int(pos->dtype, pos->data, c * pcs + m * pms) / div;
} else {
const float one = (float)ld_int(pos->dtype, pos->data, offlin(pos, m)) / div;
for (int c = 0; c < 8; ++c) p[c] = one;
}
const int64_t row = m * rs;
/* Q heads then K heads. The V heads that follow are left alone, which is the whole reason
* this op takes the fused qkv rather than two tensors. */
for (int64_t h = 0; h < n_head + n_head_kv; ++h)
rope_head(qkv, row + h * head_dim * ds, ds, rot, mode, f, p, yarn.magnitude);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ qk_norm_rope */
/* The QK-norm preamble and the rotation in one op: an RMS norm over each 128-wide (or whatever
* head_dim is) q and k head against its own gain vector, then RoPE. `v_norm` 1 also RMS-norms
* each v head with a UNIT gain and no rotation -- Gemma 4's value norm, which has no weight. The
* v heads are otherwise left alone.
*
* THE NORM OUTPUT IS ROUNDED TO THE TENSOR'S DTYPE BEFORE THE ROTATION. That is not an accident of
* writing it back in place -- it is what the unfused pair does, because the norm stores a tensor
* and the rotation reads it, and libr4d's r4d_qk_norm_rope_gate matches the unfused reference for
* exactly this reason. A fused kernel that kept f32 across the seam would be half a ULP better and
* would fail a comparison against this. */
int ref_qk_norm_rope(const RadArgs* a, RadStream) {
if (!have(a, 4)) return RAD_E_INVAL;
const RadTensor *qkv = &a->t[0], *pos = &a->t[1], *qw = &a->t[2], *kw = &a->t[3];
const int64_t head_dim = p_int(a, "head_dim", 0);
const int64_t n_head = p_int(a, "n_head", 0);
const int64_t n_head_kv = p_int(a, "n_head_kv", 0);
const float theta = p_f32(a, "theta", 10000.0f);
const float eps = p_f32(a, "eps", 1e-6f);
const float rscale = p_f32(a, "scale", 1.0f);
const float wadd = p_f32(a, "wadd", 0.0f);
const int v_norm = (int)p_int(a, "v_norm", 0);
/* `gptj_blocks` is `blocks` with each section's pairs ADJACENT -- (start + 2j, start + 2j + 1),
* the complex-number form a 3-axis image rotary takes (Qwen-Image's). `imrope` is `rope`'s
* interleaved M-RoPE over NeoX pairs, after the norm (Qwen3-VL's text attention). */
static const char* kModes[] = { "neox", "gptj", "blocks", "gptj_blocks", "imrope" };
const int mode = p_enum(a, "mode", kModes, 5, 0);
if (mode < 0) return RAD_E_UNSUPPORTED;
const bool blocks = mode == 2 || mode == 3;
const bool adjacent = mode == 3;
const bool im = mode == 4;
int64_t rot = p_int(a, "rotary_dim", head_dim);
if (head_dim <= 0 || n_head <= 0 || rot <= 0 || rot > head_dim || (rot & 1)) return RAD_E_SHAPE;
if (numel(qw) < head_dim || numel(kw) < head_dim) return RAD_E_SHAPE;
/* BLOCKS: section c is `sec[c]` rotary pairs over its own run of 2 * sec[c] channels, paired
* (start + j, start + sec[c] + j) and turned by position component comps[c] at
* theta^(-j / sec[c]) -- each section a complete neox rotary of its own width. The sections
* fill the rotated prefix exactly. Positions are [C, M], component-major. */
int64_t sec[8] = {}, comp[8] = {};
int n_sec = 0;
if (im) {
n_sec = rope_sections(a, sec);
if (n_sec < 3) return RAD_E_SHAPE;
}
if (blocks) {
n_sec = rope_sections(a, sec);
if (n_sec <= 0) return RAD_E_SHAPE;
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 = p_str(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 bool multi = pos->rank >= 2;
const int64_t n_comp = multi ? pos->shape[0] : 1;
const int64_t M = multi ? pos->shape[1] : numel(pos);
if (multi && !blocks && !im) return RAD_E_SHAPE;
if (multi && im && n_comp < 3) 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;
const int64_t pcs = multi ? pos->stride[0] : 0, pms = multi ? pos->stride[1] : 0;
const int64_t stride_row = (n_head + 2 * n_head_kv) * head_dim;
if (M <= 0 || numel(qkv) < M * stride_row) return RAD_E_SHAPE;
const int64_t rs = qkv->rank >= 2 ? qkv->stride[qkv->rank - 2] : stride_row;
const int64_t ds = laststride(qkv);
RopeFreq f;
/* No `ladder` on this row yet: the fused norm+rope measures by `rot`, as it always has. */
if (im) RAD_REF_TRY(rope_freqs(ROPE_IMROPE, rot, rot, theta, sec, multi ? n_sec : 0, &f));
else RAD_REF_TRY(rope_freqs(blocks ? 0 : mode, rot, rot, theta, nullptr, 0, &f));
#pragma omp parallel for schedule(static)
for (int64_t m = 0; m < M; ++m) {
float p[8];
const float div = rscale != 0.0f ? rscale : 1.0f;
if (multi) {
for (int64_t c = 0; c < n_comp && c < 8; ++c)
p[c] = (float)ld_int(pos->dtype, pos->data, c * pcs + m * pms) / div;
} else {
const float one = (float)ld_int(pos->dtype, pos->data, offlin(pos, m)) / div;
for (int c = 0; c < 8; ++c) p[c] = one;
}
const int64_t row = m * rs;
for (int64_t h = 0; h < n_head + n_head_kv; ++h) {
const RadTensor* w = h < n_head ? qw : kw;
const int64_t base = row + h * head_dim * ds, ws = laststride(w);
float ss = 0.0f;
for (int64_t d = 0; d < head_dim; ++d) {
float x = ldt(qkv, base + d * ds);
ss += x * x;
}
const float sc = 1.0f / std::sqrt(ss / (float)head_dim + eps);
for (int64_t d = 0; d < head_dim; ++d)
stt(qkv, base + d * ds, ldt(qkv, base + d * ds) * sc * (ldt(w, d * ws) + wadd));
if (!blocks) {
rope_head(qkv, base, ds, rot, im ? ROPE_IMROPE : mode, f, p);
continue;
}
int64_t start = 0;
for (int c = 0; c < n_sec; ++c) {
for (int64_t j = 0; j < sec[c]; ++j) {
const float inv = 1.0f / std::pow(theta, (float)j / (float)sec[c]);
const float ang = p[comp[c]] * inv;
const float cs = std::cos(ang), sn = std::sin(ang);
const int64_t i0 = adjacent ? start + 2 * j : start + j;
const int64_t i1 = adjacent ? start + 2 * j + 1 : start + sec[c] + j;
const float x0 = ldt(qkv, base + i0 * ds), x1 = ldt(qkv, base + i1 * ds);
stt(qkv, base + i0 * ds, x0 * cs - x1 * sn);
stt(qkv, base + i1 * ds, x0 * sn + x1 * cs);
}
start += 2 * sec[c];
}
}
for (int64_t h = 0; v_norm && h < n_head_kv; ++h) {
const int64_t base = row + (n_head + n_head_kv + h) * head_dim * ds;
float ss = 0.0f;
for (int64_t d = 0; d < head_dim; ++d) {
float x = ldt(qkv, base + d * ds);
ss += x * x;
}
const float sc = 1.0f / std::sqrt(ss / (float)head_dim + eps);
for (int64_t d = 0; d < head_dim; ++d)
stt(qkv, base + d * ds, ldt(qkv, base + d * ds) * sc);
}
}
return RAD_OK;
}
/* A value as a tensor of `dt` holds it: rounded through the dtype's own store and load. */
static inline float round_dt(uint32_t dt, float v) {
uint64_t buf = 0;
st_dt(dt, &buf, 0, v);
return ld_dt(dt, &buf, 0);
}
static inline int64_t rows_n(const RadTensor* t, int64_t n) { return n > 0 ? numel(t) / n : 0; }
/* ------------------------------------------------------------------ attn_local_rel */
/* Local attention with a relative-position term: Gemma 4's audio (USM conformer) attention.
*
* Query row i of a cu_seqlens segment sees the key rows j of the same segment with
* 0 <= i - j <= left (`right` must be 0). Per head:
*
* qf[d] = q[i,d] * (head_dim^-0.5 / ln 2) * softplus(pds[d])
* logit = sum_d qf[d] * k[j,d] * (ln(1 + e) / ln 2) + sum_d qf[d] * relk[i - j, d]
* logit = softcap * tanh(logit / softcap)
*
* then a softmax over those keys and the weighted sum of v, all in f32 and rounded once. `relk`
* is [left + 1, n_head * head_dim]: row d is the projected relative position for distance d.
*
* The reference computes this in 12-query blocks over 24-key context windows and shifts the
* relative term into place (Transformer-XL's rel_shift); every key outside 0 <= i - j <= left
* carries a -1e9 logit there and a zero weight after the softmax, so the sliding form below is
* the same function. softplus(pds) is rounded to the weight's dtype before use, as the reference
* evaluates it on the bf16 parameter. */
int ref_attn_local_rel(const RadArgs* a, RadStream) {
if (!have(a, 7)) return RAD_E_INVAL;
const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *rk = &a->t[3];
const RadTensor *pds = &a->t[4], *cu = &a->t[5], *o = &a->t[6];
const int64_t D = p_int(a, "head_dim", 0), H = p_int(a, "n_head", 0);
const int64_t L = p_int(a, "left", 0), R = p_int(a, "right", 0);
const int64_t cdiv = p_int(a, "cu_div", 1);
const float cap = p_f32(a, "softcap", 0.0f);
if (D <= 0 || H <= 0 || L < 0 || cdiv <= 0 || !(cap > 0.0f)) return RAD_E_SHAPE;
if (R != 0) return RAD_E_UNSUPPORTED;
if (D > REF_HD_MAX || L + 1 > REF_HD_MAX) return RAD_E_UNSUPPORTED;
const int64_t W = H * D;
if (numel(pds) < D || numel(rk) < (L + 1) * W) return RAD_E_SHAPE;
const int64_t S = numel(cu) - 1;
if (S <= 0) return RAD_E_SHAPE;
const int64_t Mq = rows_n(q, W), Mk = rows_n(k, W), Mv = rows_n(v, W), Mo = rows_n(o, W);
const float qs = (float)(1.0 / std::sqrt((double)D) / std::log(2.0));
const float ks = (float)(std::log(1.0 + std::exp(1.0)) / std::log(2.0));
float spd[REF_HD_MAX];
for (int64_t d = 0; d < D; ++d)
spd[d] = round_dt(pds->dtype, act_softplus(ldt(pds, d * laststride(pds)), 20.0f));
for (int64_t s = 0; s < S; ++s) {
const int64_t c0 = ld_int(cu->dtype, cu->data, offlin(cu, s));
const int64_t c1 = ld_int(cu->dtype, cu->data, offlin(cu, s + 1));
if (c0 % cdiv || c1 % cdiv || c1 < c0) return RAD_E_SHAPE;
const int64_t t0 = c0 / cdiv, t1 = c1 / cdiv;
if (t1 > Mq || t1 > Mk || t1 > Mv || t1 > Mo) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
for (int64_t ih = 0; ih < (t1 - t0) * H; ++ih) {
const int64_t i = t0 + ih / H, h = ih % H;
float qf[REF_HD_MAX], lg[REF_HD_MAX], acc[REF_HD_MAX];
const int64_t qb = rowoff(q, i, W) + h * D * laststride(q);
for (int64_t d = 0; d < D; ++d) qf[d] = ldt(q, qb + d * laststride(q)) * qs * spd[d];
const int64_t j0 = i - L > t0 ? i - L : t0;
float mx = -INFINITY;
for (int64_t j = j0; j <= i; ++j) {
const int64_t kb = rowoff(k, j, W) + h * D * laststride(k);
const int64_t rb = rowoff(rk, i - j, W) + h * D * laststride(rk);
float ac = 0.0f, bd = 0.0f;
for (int64_t d = 0; d < D; ++d) {
ac += qf[d] * (ldt(k, kb + d * laststride(k)) * ks);
bd += qf[d] * ldt(rk, rb + d * laststride(rk));
}
const float x = cap * std::tanh((ac + bd) / cap);
lg[j - j0] = x;
mx = x > mx ? x : mx;
}
float sum = 0.0f;
for (int64_t j = j0; j <= i; ++j) {
lg[j - j0] = std::exp(lg[j - j0] - mx);
sum += lg[j - j0];
}
for (int64_t d = 0; d < D; ++d) acc[d] = 0.0f;
for (int64_t j = j0; j <= i; ++j) {
const float p = lg[j - j0] / sum;
const int64_t vb = rowoff(v, j, W) + h * D * laststride(v);
for (int64_t d = 0; d < D; ++d) acc[d] += p * ldt(v, vb + d * laststride(v));
}
const int64_t ob = rowoff(o, i, W) + h * D * laststride(o);
for (int64_t d = 0; d < D; ++d) stt(o, ob + d * laststride(o), acc[d]);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ rope_table */
/* The cos/sin plane a fused prologue reads instead of theta, written at each position's OWN row of
* a [max_ctx, rot] table: `rot` values a row, cos for the first rot/2 and sin for the second.
*
* THE ANGLES ARE `rope`'s, TO THE LAST OPERATION, and that is the whole contract: a fused rotation
* that read a table built any other way would be a different model, and the difference would be a
* fraction of a ULP per element -- fluent text, subtly wrong positions, exactly the failure class
* this file's rope_head comment is about. Only the rows `positions` names are written; a negative
* position is a padded row and writes nothing. */
int ref_rope_table(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *pos = &a->t[0], *cs = &a->t[1];
const int64_t rot = p_int(a, "rot", 0);
const int64_t head_dim = p_int(a, "head_dim", 0);
const float theta = p_f32(a, "theta", 10000.0f);
const float rscale = p_f32(a, "scale", 1.0f);
if (rot < 2 || (rot & 1)) return RAD_E_SHAPE;
int64_t den;
RAD_REF_TRY(rope_ladder(a, rot, head_dim, &den));
const int64_t M = numel(pos);
if (M <= 0 || numel(cs) % rot) return RAD_E_SHAPE;
const int64_t rows = numel(cs) / rot;
const int64_t half = rot / 2;
const RadYarn yarn = rad_yarn_args(a);
if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && rscale != 1.0f)) return RAD_E_INVAL;
#pragma omp parallel for schedule(static)
for (int64_t m = 0; m < M; ++m) {
const int64_t pp = ld_int(pos->dtype, pos->data, offlin(pos, m));
if (pp < 0 || pp >= rows) continue;
const float p = (float)pp / (rscale != 0.0f ? rscale : 1.0f);
for (int64_t i = 0; i < half; ++i) {
const float inv = yarn.frequency(1.0f / std::pow(theta, (float)(2 * i) / (float)den), (int)i);
const float ang = p * inv;
stt(cs, offlin(cs, pp * rot + i), std::cos(ang) * yarn.magnitude);
stt(cs, offlin(cs, pp * rot + half + i), std::sin(ang) * yarn.magnitude);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ qsa_block_key */
/* The QSA indexer's compressed key (docs/OPS.md, docs/QSA.md): for each of M blocks,
*
* pooled = mean of the block's `ratio` rows of k, accumulated in f32 and ROUNDED TO k's dtype
* normed = pooled * rsqrt(mean(pooled^2) + eps) * (wadd + w)
* out = NeoX rotary of normed's first `rotary_dim` lanes at the block's position, the rest
* passed through, rounded once at the store
*
* The rounding after the mean is the reference model's (`.float().mean(dim=1).to(dtype)`) and is
* part of the answer. The block's position is `pos[b]` (a [>= M, 1 or 3] list carries a block's
* components side by side, read under `mode` mrope/imrope and `sections`), or `pos0 + b*ratio`
* without one. `page[b]`, when given, is the output row, and a negative entry writes nothing. The
* rotary is `rope`'s ladder with YaRN's blend and magnitude when the coefficients are given. */
int ref_qsa_block_key(const RadArgs* a, RadStream) {
const RadTensor* k = t_in(a, 0);
const RadTensor* w = t_in(a, 1);
const RadTensor* page = t_in(a, 2);
const RadTensor* pos = t_in(a, 3);
const RadTensor* out = t_in(a, 4);
if (!k || !w || !out) return RAD_E_INVAL;
const int64_t n = p_int(a, "n", 0), ratio = p_int(a, "ratio", 0);
const int64_t rot = p_int(a, "rotary_dim", 0), pos0 = p_int(a, "pos0", -1);
if (n <= 0 || n > REF_HD_MAX || ratio <= 0 || (pos0 < 0 && !pos)) return RAD_E_INVAL;
if (rot < 0 || rot > n || (rot & 1)) return RAD_E_SHAPE;
if (p_int(a, "block_size", ratio) != ratio) return RAD_E_SHAPE;
if (k->rank != 2 || out->rank < 2 || out->shape[0] < 1) return RAD_E_SHAPE;
const int64_t M = page ? numel(page) : out->shape[0];
if (M < 1 || numel(out) / out->shape[0] != n) return RAD_E_SHAPE;
if (k->shape[0] != M * ratio || k->shape[1] != n || numel(w) < n) return RAD_E_SHAPE;
const bool pos2 = pos && pos->rank == 2;
if (pos && (pos2 ? pos->shape[0] < M : numel(pos) < M)) return RAD_E_SHAPE;
const float eps = p_f32(a, "eps", 1e-6f), wadd = p_f32(a, "wadd", 1.0f);
const float theta = p_f32(a, "theta", 10000.0f), rscale = p_f32(a, "scale", 1.0f);
static const char* kModes[] = { "neox", "mrope", "imrope" };
const int mi = p_enum(a, "mode", kModes, 3, 0);
if (mi < 0) return RAD_E_UNSUPPORTED;
const int mode = mi == 1 ? ROPE_MROPE : mi == 2 ? ROPE_IMROPE : ROPE_NEOX;
int64_t sec[8] = {};
const int n_sec = rope_sections(a, sec);
if (n_sec < 0 || n_sec > 3) return RAD_E_SHAPE;
/* Several components only with a mode, its sections and three columns of `pos`; otherwise
* every frequency reads the block's one position, which every mode reads as NeoX. */
const bool mc = mode != ROPE_NEOX && n_sec > 0 && pos2 && pos->shape[1] >= 3;
const RadYarn yarn = rad_yarn_args(a);
if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && (rot <= 0 || rscale != 1.0f)))
return RAD_E_INVAL;
RopeFreq f;
RAD_REF_TRY(rope_freqs(mc ? mode : ROPE_NEOX, rot, rot, theta, sec, mc ? n_sec : 0, &f));
for (int64_t i = 0; i < rot / 2; ++i) f.inv[i] = yarn.frequency(f.inv[i], (int)i);
#pragma omp parallel for schedule(static)
for (int64_t b = 0; b < M; ++b) {
const int64_t orow = page ? ld_int(page->dtype, page->data, offlin(page, b)) : b;
if (orow < 0) continue;
float x[REF_HD_MAX], y[REF_HD_MAX];
double ss = 0.0;
for (int64_t t = 0; t < n; ++t) {
float acc = 0.0f;
for (int64_t j = 0; j < ratio; ++j) acc += ldt(k, offlin(k, (b * ratio + j) * n + t));
uint64_t tmp = 0;
st_dt(k->dtype, &tmp, 0, acc / (float)ratio);
x[t] = ld_dt(k->dtype, &tmp, 0);
ss += (double)x[t] * x[t];
}
const float inv = 1.0f / std::sqrt((float)(ss / (double)n) + eps);
for (int64_t t = 0; t < n; ++t) y[t] = x[t] * inv * (wadd + ldt(w, offlin(w, t)));
float p[3] = {};
for (int c = 0; c < (mc ? 3 : 1); ++c) {
const int64_t bp = !pos ? pos0 + b * ratio
: ld_int(pos->dtype, pos->data,
offlin(pos, pos2 ? b * pos->shape[1] + c : b));
p[c] = (float)bp / (rscale != 0.0f ? rscale : 1.0f);
}
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 c = std::cos(ang) * yarn.magnitude, s = std::sin(ang) * yarn.magnitude;
const float x0 = y[i], x1 = y[half + i];
y[i] = x0 * c - x1 * s;
y[half + i] = x0 * s + x1 * c;
}
for (int64_t t = 0; t < n; ++t) stt(out, offlin(out, orow * n + t), y[t]);
}
return RAD_OK;
}