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_elementwise.cpp
T
Deadcode dc339b4cd2 radiance 1.4.0
- Qwen3.8-Flash-Next on one card: the heat engine moves 64 experts a step (was 8), its copies and
  the prefill's expert staging run on the card's DMA engines instead of as copy kernels, and at
  decode the next layer's likeliest experts are copied onto the card ahead of its GEMMs. Against
  1.3.0 at --tp 1: prefill +17-20% from 8K tokens up, throughput under load +16-20%
- deploy/compose/flashnext-tp1.yaml: Qwen3.8-Flash-Next on one card and 64 GB of host RAM
  (4096-token prefill steps, 4 sequences, a 301K-token cache)
- #61: --busy-prefill-chunk (default auto): a long prefill leaves the rest of the step to the
  requests decoding beside it and to new arrivals, instead of taking all of it (baKon)
- LiquidAI's LFM2 and LFM2-VL, and d1's /v1/systemone (after zivius's PR #50)
- a startup report: every option with its value and where it came from, the hardware, and what
  on it costs speed with the fix; /diagnostics serves it (behind the API key; without one, only
  to the same machine)
- #69: a GPU memory fault names the buffer and kernel argument behind it and ends the server at
  once (exit status 70), instead of hanging or writing a core of tens of gigabytes
- #64: a card without Resizable BAR is refused at startup, naming what to turn on, instead of
  crashing at the first launch
- the image is built with ROCm 10.1 (the host's amdgpu driver must support it), with ROCm's
  libLLVM rebuilt so the same source compiles to the same kernels every time; a source build
  takes ROCm 10.1 or 7.2
- #71: the image ships curl, jq and a CA bundle, so --model <HF repo id> works in the container,
  and hfget.sh runs under its busybox (baKon)
- --profile-ops shows how long each op's lane sat idle before it; cardclock.py skips an
  integrated GPU instead of stopping
2026-10-12 11:46:14 +02:00

837 lines
41 KiB
C++

/* ref_elementwise.cpp -- the norms and the elementwise ops.
*
* Nothing here is interesting except where the fused forms round, and those places are the whole
* reason the ops exist: `rmsnorm_add` is one pass in every real implementation, so the reference
* has to say exactly which of its two intermediates is rounded and which is not, or a fused kernel
* checked against it fails on a tolerance nobody can explain.
*/
#include "ref_common.h"
#include "ref_ops.h"
#include <algorithm>
#include <vector>
using namespace ref;
/* Rows of a tensor read as [rows, n]. `n` is a declared parameter and the row count is whatever
* the operand actually carries, which is the rule this plugin follows everywhere (ref_ops.h). */
static inline int64_t rows_of(const RadTensor* t, int64_t n) {
return n > 0 ? numel(t) / n : 0;
}
/* ------------------------------------------------------------------ rmsnorm */
/* y = x * rsqrt(mean(x^2) + eps) * (w + w_add)
*
* The mean is over the LAST n elements of a row and is accumulated in f32 in ascending index
* order. `w_add` is GemmaRMSNorm's `1 +`: Qwen3.5, Qwen3-Next and Gemma store a zero-centred gain
* and use 1 + w, and forming that in the weight's dtype first loses 0.3% per channel (libr4d's
* r4d_rmsnorm_had_quant_i8 says the same). It defaults to 0, so a plain RMS norm is the plain
* call. */
int ref_rmsnorm(const RadArgs* a, RadStream) {
if (!a || a->n_t < 3 || !a->t[0].data || !a->t[2].data) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *y = &a->t[2];
/* An absent gain is one, and `wadd` belongs to a gain, so it is refused without one. */
const RadTensor* w = a->t[1].data ? &a->t[1] : nullptr;
const int64_t n = p_int(a, "n", w && w->rank ? w->shape[w->rank - 1] : 0);
const float eps = p_f32(a, "eps", 1e-6f);
const float wadd = p_f32(a, "wadd", 0.0f);
/* `mult` scales the normed row before its one rounding: a residual branch weighted by a
* constant (Gemma 4's audio feed-forward, a half) without a second pass over the row. */
const float mult = p_f32(a, "mult", 1.0f);
if (n <= 0) return RAD_E_SHAPE;
if (!w && wadd != 0.0f) return RAD_E_INVAL;
const int64_t rows = rows_of(x, n);
if (rows <= 0 || numel(y) < rows * n || (w && numel(w) < n)) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(x, r, n), yb = rowoff(y, r, n);
const int64_t xs = laststride(x), ys = laststride(y), ws = w ? laststride(w) : 0;
float ss = 0.0f;
for (int64_t i = 0; i < n; ++i) { float v = ldt(x, xb + i * xs); ss += v * v; }
const float s = 1.0f / std::sqrt(ss / (float)n + eps);
for (int64_t i = 0; i < n; ++i)
stt(y, yb + i * ys,
ldt(x, xb + i * xs) * s * (w ? ldt(w, i * ws) + wadd : 1.0f) * mult);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ rmsnorm_add */
/* residual_out = x + residual; y = rmsnorm(residual_out) * (w + w_add)
*
* THE ROUNDING IS THE CONTRACT. The sum is formed in f32 and the variance is taken from the
* UNROUNDED sum, but the multiply that produces y reads the sum back from residual_out AFTER it
* has been narrowed to that operand's dtype. That is what vLLM's fused_add_rms_norm does and what
* every fused kernel in this project will do, because the residual has to be stored anyway and
* re-reading it is free. A reference that kept f32 all the way through would be half a ULP better
* and would disagree with every kernel it certifies.
*/
int ref_rmsnorm_add(const RadArgs* a, RadStream) {
if (!have(a, 5)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *res = &a->t[1], *w = &a->t[2], *y = &a->t[3], *ro = &a->t[4];
const int64_t n = p_int(a, "n", w->rank ? w->shape[w->rank - 1] : 0);
const float eps = p_f32(a, "eps", 1e-6f);
const float wadd = p_f32(a, "wadd", 0.0f);
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(x, n);
if (rows <= 0 || numel(y) < rows * n || numel(ro) < rows * n ||
numel(res) < rows * n || numel(w) < n) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(x, r, n), rb = rowoff(res, r, n);
const int64_t yb = rowoff(y, r, n), ob = rowoff(ro, r, n);
const int64_t xs = laststride(x), rs = laststride(res);
const int64_t ys = laststride(y), os = laststride(ro), ws = laststride(w);
float ss = 0.0f;
for (int64_t i = 0; i < n; ++i) {
float v = ldt(x, xb + i * xs) + ldt(res, rb + i * rs);
ss += v * v;
stt(ro, ob + i * os, v);
}
const float s = 1.0f / std::sqrt(ss / (float)n + eps);
for (int64_t i = 0; i < n; ++i)
stt(y, yb + i * ys, ldt(ro, ob + i * os) * s * (ldt(w, i * ws) + wadd));
}
return RAD_OK;
}
/* ------------------------------------------------------------------ layernorm */
/* y = (x - mean) * rsqrt(var + eps) * w + b, with the BIASED variance (divide by n, not n-1),
* which is what every transformer implementation means by layer norm. `b` is optional: a ViT that
* dropped its bias passes a null operand rather than a zero tensor. */
int ref_layernorm(const RadArgs* a, RadStream) {
if (a->n_t < 4 || !a->t[0].data || !a->t[1].data || !a->t[3].data) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *w = &a->t[1], *y = &a->t[3];
const RadTensor* b = t_in(a, 2);
const int64_t n = p_int(a, "n", w->rank ? w->shape[w->rank - 1] : 0);
const float eps = p_f32(a, "eps", 1e-5f);
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(x, n);
if (rows <= 0 || numel(y) < rows * n || numel(w) < n) return RAD_E_SHAPE;
if (b && numel(b) < n) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(x, r, n), yb = rowoff(y, r, n);
const int64_t xs = laststride(x), ys = laststride(y), ws = laststride(w);
float sum = 0.0f;
for (int64_t i = 0; i < n; ++i) sum += ldt(x, xb + i * xs);
const float mean = sum / (float)n;
float ss = 0.0f;
for (int64_t i = 0; i < n; ++i) { float d = ldt(x, xb + i * xs) - mean; ss += d * d; }
const float s = 1.0f / std::sqrt(ss / (float)n + eps);
for (int64_t i = 0; i < n; ++i) {
float v = (ldt(x, xb + i * xs) - mean) * s * ldt(w, i * ws);
if (b) v += ldt(b, i * laststride(b));
stt(y, yb + i * ys, v);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ grid_embed */
/* A learned side x side table of position rows, resampled to a grid of its own size per row of x
* and added in: the vision tower's position embedding, which is trained at one grid and applied to
* images of any shape.
*
* THE SAMPLING IS BILINEAR WITH THE CORNERS ALIGNED: grid row r of a grid of height g sits at table
* coordinate r * (side - 1) / max(g - 1, 1), in f32, and its two taps are the floor and the floor
* plus one, clamped to the table, weighted by distance. The four products are summed in f32 in the
* order (top-left, top-right, bottom-left, bottom-right) and rounded to x's dtype -- the position
* embedding as a tensor of its own -- and only then added to x, which is rounded again. */
static float round_to(uint32_t dt, float v) {
return dt == RAD_BF16 ? rad_bf16_to_f32(rad_f32_to_bf16(v)) : v;
}
int ref_grid_embed(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *tab = &a->t[1], *crd = &a->t[2];
const int64_t n = p_int(a, "n", tab->rank ? tab->shape[tab->rank - 1] : 0);
const int64_t side = p_int(a, "side", 0);
if (n <= 0 || side <= 0 || numel(tab) < side * side * n) return RAD_E_SHAPE;
const int64_t rows = rows_of(x, n);
if (rows <= 0 || crd->rank != 2 || crd->shape[0] < 4 || crd->shape[1] < rows)
return RAD_E_SHAPE;
const int64_t cs = crd->stride[0], ms = crd->stride[1];
const int64_t ts = laststride(tab);
#pragma omp parallel for schedule(static)
for (int64_t r = 0; r < rows; ++r) {
const int64_t gr = ld_int(crd->dtype, crd->data, 0 * cs + r * ms);
const int64_t gc = ld_int(crd->dtype, crd->data, 1 * cs + r * ms);
const int64_t gh = ld_int(crd->dtype, crd->data, 2 * cs + r * ms);
const int64_t gw = ld_int(crd->dtype, crd->data, 3 * cs + r * ms);
int64_t th[2], tw[2];
float wh[2], ww[2];
auto axis = [&](int64_t idx, int64_t size, int64_t* t, float* w) {
const float src = (float)idx * (float)(side - 1) / (float)(size - 1 > 1 ? size - 1 : 1);
const float fl = std::floor(src);
for (int k = 0; k < 2; ++k) {
int64_t tap = (int64_t)fl + k;
t[k] = tap < 0 ? 0 : (tap > side - 1 ? side - 1 : tap);
const float d = std::fabs(src - fl - (float)k);
w[k] = 1.0f - d > 0.0f ? 1.0f - d : 0.0f;
}
};
axis(gr, gh, th, wh);
axis(gc, gw, tw, ww);
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
for (int64_t i = 0; i < n; ++i) {
float acc = 0.0f;
for (int ki = 0; ki < 2; ++ki)
for (int kj = 0; kj < 2; ++kj)
acc += ldt(tab, rowoff(tab, th[ki] * side + tw[kj], n) + i * ts) *
(wh[ki] * ww[kj]);
const float pe = round_to(x->dtype, acc);
stt(x, xb + i * xs, ldt(x, xb + i * xs) + pe);
}
}
return RAD_OK;
}
/* grid_embed_aa: the table resampled as torch's F.interpolate(mode="bilinear", align_corners=False,
* antialias=True) does it -- SigLIP2's position embedding. Per axis a triangle filter on half-pixel
* centres, widened by the scale when shrinking, its taps inside the table normalised to sum to one.
* Separable, f32 throughout, rounded once before the add. A coordinate outside its grid is clamped
* into it, so every input is defined. */
static void aa_taps(int64_t at, int64_t size, int64_t side, float* w, int64_t* lo, int64_t* cnt) {
if (size < 1) size = 1;
at = at < 0 ? 0 : (at >= size ? size - 1 : at);
const float scale = (float)side / (float)size;
const float support = scale > 1.0f ? scale : 1.0f, inv = 1.0f / support;
const float center = scale * ((float)at + 0.5f);
int64_t a = (int64_t)(center - support + 0.5f), b = (int64_t)(center + support + 0.5f);
if (a < 0) a = 0;
if (b > side) b = side;
float total = 0.0f;
for (int64_t j = a; j < b; ++j) {
const float d = std::fabs(((float)j - center + 0.5f) * inv);
w[j - a] = d < 1.0f ? 1.0f - d : 0.0f;
total += w[j - a];
}
for (int64_t j = a; j < b; ++j) w[j - a] = total != 0.0f ? w[j - a] / total : 0.0f;
*lo = a;
*cnt = b > a ? b - a : 0;
}
int ref_grid_embed_aa(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *tab = &a->t[1], *crd = &a->t[2];
const int64_t n = p_int(a, "n", tab->rank ? tab->shape[tab->rank - 1] : 0);
const int64_t side = p_int(a, "side", 0);
if (n <= 0 || side <= 0 || numel(tab) < side * side * n) return RAD_E_SHAPE;
const int64_t rows = rows_of(x, n);
if (rows <= 0 || crd->rank != 2 || crd->shape[0] < 4 || crd->shape[1] < rows)
return RAD_E_SHAPE;
const int64_t cs = crd->stride[0], ms = crd->stride[1];
const int64_t ts = laststride(tab);
#pragma omp parallel for schedule(static)
for (int64_t r = 0; r < rows; ++r) {
int64_t g[4];
for (int c = 0; c < 4; ++c) g[c] = ld_int(crd->dtype, crd->data, c * cs + r * ms);
std::vector<float> wh((size_t)side), ww((size_t)side);
int64_t h0 = 0, nh = 0, w0 = 0, nw = 0;
aa_taps(g[0], g[2], side, wh.data(), &h0, &nh);
aa_taps(g[1], g[3], side, ww.data(), &w0, &nw);
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
for (int64_t i = 0; i < n; ++i) {
float acc = 0.0f;
for (int64_t y = 0; y < nh; ++y) {
float row = 0.0f;
for (int64_t c = 0; c < nw; ++c)
row += ldt(tab, rowoff(tab, (h0 + y) * side + w0 + c, n) + i * ts) *
ww[(size_t)c];
acc += row * wh[(size_t)y];
}
const float pe = round_to(x->dtype, acc);
stt(x, xb + i * xs, ldt(x, xb + i * xs) + pe);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ add / mul */
/* Elementwise over the output's extent. `b` may carry one row instead of all of them, so a bias
* add is this op rather than a second one: an operand with exactly `n` elements against an output
* of rows*n broadcasts along rows, and nothing else broadcasts at all. Silent broadcasting of an
* arbitrary shape is how a shape bug becomes a plausible number. */
static int elementwise2(const RadArgs* a, bool mul) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *A = &a->t[0], *B = &a->t[1], *Y = &a->t[2];
const int64_t n = p_int(a, "n", numel(Y));
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(Y, n);
if (rows <= 0 || numel(A) < rows * n) return RAD_E_SHAPE;
const bool bcast = numel(B) == n && rows > 1;
if (!bcast && numel(B) < rows * n) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
for (int64_t r = 0; r < rows; ++r) {
const int64_t ab = rowoff(A, r, n), yb = rowoff(Y, r, n);
const int64_t bb = bcast ? 0 : rowoff(B, r, n);
const int64_t as = laststride(A), bs = laststride(B), ys = laststride(Y);
for (int64_t i = 0; i < n; ++i) {
float u = ldt(A, ab + i * as), v = ldt(B, bb + i * bs);
stt(Y, yb + i * ys, mul ? u * v : u + v);
}
}
return RAD_OK;
}
int ref_add(const RadArgs* a, RadStream) { return elementwise2(a, false); }
int ref_mul(const RadArgs* a, RadStream) { return elementwise2(a, true); }
/* ------------------------------------------------------------------ mul_weight */
/* y = x * w, `w` a WEIGHT of one element or of one row: a learned gain on an activation -- a
* per-layer scalar on the residual stream (Gemma 4's layer_scalar), or a per-channel one (a
* vision tower's layer scale). Its own op and not a form of `mul` because an op's operand is a
* weight or an activation by its schema, and `mul`'s `b` is an activation. The product is f32,
* rounded once to y's dtype. */
int ref_mul_weight(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *W = &a->t[1], *Y = &a->t[2];
const int64_t n = p_int(a, "n", numel(Y));
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(Y, n);
if (rows <= 0 || numel(X) < rows * n) return RAD_E_SHAPE;
const bool scalar = numel(W) == 1;
if (!scalar && numel(W) != n) return RAD_E_SHAPE;
const int64_t ws = scalar ? 0 : laststride(W);
#pragma omp parallel for schedule(static)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(X, r, n), yb = rowoff(Y, r, n);
const int64_t xs = laststride(X), ys = laststride(Y);
for (int64_t i = 0; i < n; ++i)
stt(Y, yb + i * ys, ldt(X, xb + i * xs) * ldt(W, i * ws));
}
return RAD_OK;
}
/* ------------------------------------------------------------------ scale_rows */
/* y[m, i] = x[m, i] * act(s[m]) -- one scalar per ROW, broadcast across the row.
*
* IT IS NOT `mul`, AND THE DIFFERENCE IS WHICH AXIS BROADCASTS. `mul` lets `b` carry one ROW and
* broadcasts it down the rows, which is a bias's shape; this carries one COLUMN and broadcasts it
* across them, which is a per-token gate's. Giving `mul` both rules would make them ambiguous
* exactly when rows == n, and a silent choice between two broadcasts is how a shape bug becomes a
* plausible number -- which is the rule the comment above elementwise2 already states.
*
* The activation is applied to the SCALAR and not to the product, which is what a gate means:
* Qwen3.5-MoE's shared expert is scaled by `sigmoid(shared_expert_gate(x))`. */
/* `add` PRESENT IS THE FUSED GATE-AND-ADD FORM: y = narrow(x * act(s)) + add, and the NARROW is
* the whole of why this is expressible as one op rather than an approximation of two. The pair it
* stands in for writes the product into a bf16 buffer and then adds that buffer to `add`, so the
* product is rounded BEFORE the sum sees it; an f32 product carried into the add would differ in
* the last bit of every channel. Written here as the two stores it replaces, through `y` itself,
* because the oracle's job is to be obviously the same rather than to be quick.
*
* `add` is read before `y` is written so the two may alias without the sum reading its own output. */
int ref_scale_rows(const RadArgs* a, RadStream) {
if (!have(a, 4)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *sc = &a->t[1], *y = &a->t[3];
const RadTensor *ad = t_in(a, 2);
const int64_t n = p_int(a, "n", numel(y));
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(y, n);
if (rows <= 0 || numel(x) < rows * n || numel(sc) < rows) return RAD_E_SHAPE;
if (ad && numel(ad) < rows * n) return RAD_E_SHAPE;
const char* act = p_str(a, "act", "none");
const bool sig = act && !std::strcmp(act, "sigmoid");
if (act && std::strcmp(act, "sigmoid") && std::strcmp(act, "none")) return RAD_E_INVAL;
const int64_t ss = laststride(sc);
#pragma omp parallel for schedule(static)
for (int64_t r = 0; r < rows; ++r) {
const float v0 = ldt(sc, r * ss);
const float v = sig ? act_sigmoid(v0) : v0;
const int64_t xb = rowoff(x, r, n), yb = rowoff(y, r, n);
const int64_t xs = laststride(x), ys = laststride(y);
const int64_t ab = ad ? rowoff(ad, r, n) : 0;
const int64_t as = ad ? laststride(ad) : 1;
for (int64_t i = 0; i < n; ++i) {
const float av = ad ? ldt(ad, ab + i * as) : 0.0f;
stt(y, yb + i * ys, ldt(x, xb + i * xs) * v);
if (ad) stt(y, yb + i * ys, ldt(y, yb + i * ys) + av);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ silu_mul */
/* y[.., i] = silu(gate_up[.., i]) * gate_up[.., n + i]. The gate is the FIRST half, which is the
* order rad-convert fuses gate and up into one weight in, so the two conventions cannot drift. */
int ref_silu_mul(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *gu = &a->t[0], *y = &a->t[1];
const int64_t n = p_int(a, "n", numel(y));
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(y, n);
if (rows <= 0 || numel(gu) < rows * 2 * n) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
for (int64_t r = 0; r < rows; ++r) {
const int64_t gb = rowoff(gu, r, 2 * n), yb = rowoff(y, r, n);
const int64_t gs = laststride(gu), ys = laststride(y);
for (int64_t i = 0; i < n; ++i)
stt(y, yb + i * ys, act_silu(ldt(gu, gb + i * gs)) * ldt(gu, gb + (n + i) * gs));
}
return RAD_OK;
}
/* ------------------------------------------------------------------ act_mul */
/* y = act(a) * b, the gated product with its two halves in two operands. `silu_mul` reads one
* fused gate_up row; this reads the gate and the multiplier from wherever they are, which covers
* a fused gate_up as two column slices of it AND a gate whose multiplier is some other tensor --
* Gemma's per-layer-input block multiplies gelu(gate(x)) by a per-layer embedding.
*
* THE ACTIVATION IS ROUNDED TO y's DTYPE BEFORE THE PRODUCT, which is what the unfused pair does:
* `act(gate)` is a tensor, and the product reads it back. */
static float gelu_tanh_f(float x) {
const float k0 = 0.7978845608028654f, k1 = 0.044715f;
return 0.5f * x * (1.0f + std::tanh(k0 * (x + k1 * x * x * x)));
}
int ref_act_mul(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *A = &a->t[0], *B = &a->t[1], *Y = &a->t[2];
const int64_t n = p_int(a, "n", numel(Y));
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(Y, n);
if (rows <= 0 || numel(A) < rows * n || numel(B) < rows * n) return RAD_E_SHAPE;
static const char* kActs[] = { "silu", "gelu", "gelu_tanh", "sigmoid" };
const int act = p_enum(a, "act", kActs, 4, -1);
if (act < 0) return RAD_E_INVAL;
#pragma omp parallel for schedule(static)
for (int64_t r = 0; r < rows; ++r) {
const int64_t ab = rowoff(A, r, n), bb = rowoff(B, r, n), yb = rowoff(Y, r, n);
const int64_t as = laststride(A), bs = laststride(B), ys = laststride(Y);
for (int64_t i = 0; i < n; ++i) {
const float g = ldt(A, ab + i * as);
const float v = act == 0 ? act_silu(g) : act == 1 ? act_gelu(g)
: act == 2 ? gelu_tanh_f(g) : act_sigmoid(g);
stt(Y, yb + i * ys, round_to(Y->dtype, v) * ldt(B, bb + i * bs));
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ seg_mean */
/* y[s, :] = the mean of x's rows [cu[s], cu[s+1]): one row a segment, which is a sentence
* embedding's mean pooling over a ragged batch. The sum is taken in DOUBLE and divided once, so the
* pooled row does not depend on how many rows a segment has beyond the one rounding to y's dtype.
* An empty segment writes zeros. */
int ref_seg_mean(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *cu = &a->t[1], *Y = &a->t[2];
const int64_t n = p_int(a, "n", 0);
const int64_t S = numel(cu) - 1;
if (n <= 0 || S <= 0 || numel(Y) < S * n) return RAD_E_SHAPE;
const int64_t total = ld_int(cu->dtype, cu->data, offlin(cu, S));
if (total < 0 || numel(X) < total * n) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
for (int64_t s = 0; s < S; ++s) {
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));
const int64_t yb = rowoff(Y, s, n), ys = laststride(Y), xs = laststride(X);
for (int64_t i = 0; i < n; ++i) {
double acc = 0.0;
for (int64_t r = b0; r < b1; ++r) acc += ldt(X, rowoff(X, r, n) + i * xs);
stt(Y, yb + i * ys, b1 > b0 ? (float)(acc / (double)(b1 - b0)) : 0.0f);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ pool_rows */
/* Row r of y is the mean of x's rows [r*k, r*k + k), summed in f32 and rounded to y's dtype, then
* multiplied by `mult` and rounded again -- the unfused pair, which stores the mean. A vision
* pooler whose processor lays each k-patch window out consecutively pools with this. */
int ref_pool_rows(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *Y = &a->t[1];
const int64_t n = p_int(a, "n", 0), k = p_int(a, "k", 0);
const float mult = p_f32(a, "mult", 1.0f);
if (n <= 0 || k <= 0) return RAD_E_SHAPE;
const int64_t rows_in = rows_of(X, n);
if (rows_in <= 0 || rows_in % k) return RAD_E_SHAPE;
const int64_t rows = rows_in / k;
if (numel(Y) < rows * n) return RAD_E_SHAPE;
const float inv = 1.0f / (float)k;
#pragma omp parallel for schedule(static)
for (int64_t r = 0; r < rows; ++r) {
const int64_t yb = rowoff(Y, r, n), ys = laststride(Y), xs = laststride(X);
for (int64_t i = 0; i < n; ++i) {
float acc = 0.0f;
for (int64_t j = 0; j < k; ++j) acc += ldt(X, rowoff(X, r * k + j, n) + i * xs);
stt(Y, yb + i * ys, acc * inv);
stt(Y, yb + i * ys, ldt(Y, yb + i * ys) * mult);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ relu */
/* y = max(x, 0) over [M, n], each operand at its own row pitch. */
int ref_relu(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *Y = &a->t[1];
const int64_t n = p_int(a, "n", numel(Y));
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(Y, n);
if (rows <= 0 || numel(X) < rows * n) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(X, r, n), yb = rowoff(Y, r, n);
const int64_t xs = laststride(X), ys = laststride(Y);
for (int64_t i = 0; i < n; ++i) {
const float v = ldt(X, xb + i * xs);
stt(Y, yb + i * ys, v > 0.0f ? v : 0.0f);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ clamp */
/* y = min(max(x, lo), hi), the bounds WEIGHTS of one element each: a clipped linear's input or
* output range (Gemma 4's audio tower), which the checkpoint states per projection. */
int ref_clamp(const RadArgs* a, RadStream) {
if (!have(a, 4)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *L = &a->t[1], *H = &a->t[2], *Y = &a->t[3];
const int64_t n = p_int(a, "n", numel(Y));
if (n <= 0 || numel(L) < 1 || numel(H) < 1) return RAD_E_SHAPE;
const int64_t rows = rows_of(Y, n);
if (rows <= 0 || numel(X) < rows * n) return RAD_E_SHAPE;
const float lo = ldt(L, 0), hi = ldt(H, 0);
#pragma omp parallel for schedule(static)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(X, r, n), yb = rowoff(Y, r, n);
const int64_t xs = laststride(X), ys = laststride(Y);
for (int64_t i = 0; i < n; ++i) {
float v = ldt(X, xb + i * xs);
v = v < lo ? lo : v;
v = v > hi ? hi : v;
stt(Y, yb + i * ys, v);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ conv2d */
/* A 2-D convolution over (time, width) with channels innermost, segment by segment.
*
* x is [M, W * cin]: row t is time t, element (t, w, c) at column w * cin + c. Each cu_seqlens
* segment [cu[s] / cu_div, cu[s+1] / cu_div) is convolved ON ITS OWN, zero-padded by `pad` at its
* edges on both axes -- two clips in one pass must not see each other -- and its output rows start
* at cu[s] / (cu_div * stride). `w` is PyTorch's [cout, cin, kh, kw]. With the optional `valid`
* operand, input row t (pass-global) is read as zeros unless valid[t * valid_stride] != 0: the
* frame mask Gemma 4's subsampler multiplies in before each convolution. f32 accumulation, one
* rounding. */
int ref_conv2d(const RadArgs* a, RadStream) {
if (!a || a->n_t < 5 || !a->t[0].data || !a->t[1].data || !a->t[2].data || !a->t[4].data)
return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *Wt = &a->t[1], *cu = &a->t[2], *Y = &a->t[4];
const RadTensor* V = a->t[3].data ? &a->t[3] : nullptr;
const int64_t W = p_int(a, "width", 0), cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0);
const int64_t kh = p_int(a, "kh", 0), kw = p_int(a, "kw", 0);
const int64_t st = p_int(a, "stride", 1), pad = p_int(a, "pad", 0);
const int64_t cdiv = p_int(a, "cu_div", 1), vst = p_int(a, "valid_stride", 1);
if (W <= 0 || cin <= 0 || cout <= 0 || kh <= 0 || kw <= 0 || st <= 0 || pad < 0 || cdiv <= 0 ||
vst <= 0)
return RAD_E_SHAPE;
const int64_t Wo = (W + 2 * pad - kw) / st + 1;
if (Wo <= 0 || numel(Wt) < cout * cin * kh * kw) return RAD_E_SHAPE;
const int64_t S = numel(cu) - 1;
if (S <= 0) return RAD_E_SHAPE;
const int64_t rin = W * cin, rout = Wo * cout;
const int64_t Min = rows_of(X, rin), Mout = rows_of(Y, rout);
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 || (c0 / cdiv) % st || c1 < c0) return RAD_E_SHAPE;
const int64_t t0 = c0 / cdiv, T = c1 / cdiv - t0;
if (T <= 0) continue;
const int64_t To = (T + 2 * pad - kh) / st + 1, o0 = t0 / st;
if (To <= 0) continue;
if (t0 + T > Min || o0 + To > Mout) return RAD_E_SHAPE;
if (V && numel(V) < (t0 + T - 1) * vst + 1) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
for (int64_t to = 0; to < To; ++to) {
const int64_t yb = rowoff(Y, o0 + to, rout), ys = laststride(Y), xs = laststride(X);
for (int64_t wo = 0; wo < Wo; ++wo)
for (int64_t co = 0; co < cout; ++co) {
float acc = 0.0f;
for (int64_t i = 0; i < kh; ++i) {
const int64_t ti = to * st - pad + i;
if (ti < 0 || ti >= T) continue;
const int64_t tg = t0 + ti;
if (V && ld_int(V->dtype, V->data, offlin(V, tg * vst)) == 0) continue;
const int64_t xb = rowoff(X, tg, rin);
for (int64_t j = 0; j < kw; ++j) {
const int64_t wi = wo * st - pad + j;
if (wi < 0 || wi >= W) continue;
for (int64_t ci = 0; ci < cin; ++ci)
acc += ldt(X, xb + (wi * cin + ci) * xs) *
ldt(Wt, ((co * cin + ci) * kh + i) * kw + j);
}
}
stt(Y, yb + (wo * cout + co) * ys, acc);
}
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ conv1d_dw */
/* A causal depthwise convolution over time: y[t, c] = sum_j w[c, j] * x[t - (k-1) + j, c], the
* rows before the segment's start (cu[s] / cu_div) read as zeros. `w` is PyTorch's depthwise
* [C, 1, k]. f32 accumulation, one rounding. */
int ref_conv1d_dw(const RadArgs* a, RadStream) {
if (!have(a, 4)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *Wt = &a->t[1], *cu = &a->t[2], *Y = &a->t[3];
const int64_t C = p_int(a, "n", 0), K = p_int(a, "k", 0), cdiv = p_int(a, "cu_div", 1);
if (C <= 0 || K <= 0 || cdiv <= 0 || numel(Wt) < C * K) return RAD_E_SHAPE;
const int64_t S = numel(cu) - 1;
if (S <= 0) return RAD_E_SHAPE;
const int64_t Mx = rows_of(X, C), My = rows_of(Y, C);
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 > Mx || t1 > My) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
for (int64_t t = t0; t < t1; ++t) {
const int64_t yb = rowoff(Y, t, C), ys = laststride(Y), xs = laststride(X);
for (int64_t c = 0; c < C; ++c) {
float acc = 0.0f;
for (int64_t j = 0; j < K; ++j) {
const int64_t tt = t - (K - 1) + j;
if (tt < t0) continue;
acc += ldt(X, rowoff(X, tt, C) + c * xs) * ldt(Wt, c * K + j);
}
stt(Y, yb + c * ys, acc);
}
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ rel_sinusoid */
/* The sinusoidal relative-position table, row d for distance d: sin(d * inv[i]) in the first
* half, cos(d * inv[i]) in the second, inv[i] = exp(i * -log(max_timescale) / max(n/2 - 1, 1)).
* Computed in f32 step by step the way the reference's torch expressions are, then rounded. */
int ref_rel_sinusoid(const RadArgs* a, RadStream) {
if (!have(a, 1)) return RAD_E_INVAL;
const RadTensor* Y = &a->t[0];
const int64_t n = p_int(a, "n", 0);
if (n <= 0 || n % 2) return RAD_E_SHAPE;
const int64_t rows = rows_of(Y, n);
if (rows <= 0) return RAD_E_SHAPE;
const int64_t h = n / 2;
const double mt = (double)p_f32(a, "max_timescale", 10000.0f);
const float inc = (float)(std::log(mt / 1.0) / (double)(h - 1 > 1 ? h - 1 : 1));
#pragma omp parallel for schedule(static)
for (int64_t d = 0; d < rows; ++d) {
const int64_t yb = rowoff(Y, d, n), ys = laststride(Y);
for (int64_t i = 0; i < h; ++i) {
const float inv = std::exp((float)i * -inc);
const float ang = (float)d * inv;
stt(Y, yb + i * ys, std::sin(ang));
stt(Y, yb + (h + i) * ys, std::cos(ang));
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ gelu / silu */
static int unary(const RadArgs* a, int which) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *y = &a->t[1];
const int64_t nel = numel(y);
if (nel <= 0 || numel(x) < nel) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
for (int64_t i = 0; i < nel; ++i) {
float v = ldt(x, offlin(x, i));
stt(y, offlin(y, i), which == 0 ? act_gelu(v) : which == 1 ? act_silu(v) : act_sigmoid(v));
}
return RAD_OK;
}
int ref_gelu(const RadArgs* a, RadStream) { return unary(a, 0); }
int ref_silu(const RadArgs* a, RadStream) { return unary(a, 1); }
/* ------------------------------------------------------------------ sigmoid */
/* Its own op rather than a `which` on gelu/silu, because a gated shared expert issues it against
* the router's output and the selector has to be able to name it (docs/OPS.md, "New ops"). Without
* it that expert runs ungated, which is a different model and not a slower one. */
int ref_sigmoid(const RadArgs* a, RadStream) { return unary(a, 2); }
/* ------------------------------------------------------------------ fill */
/* y = value over [M, n], at y's own row pitch. The value is rounded once, by the store. */
int ref_fill(const RadArgs* a, RadStream) {
if (!have(a, 1)) return RAD_E_INVAL;
const RadTensor* y = &a->t[0];
const int64_t n = p_int(a, "n", numel(y));
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(y, n);
if (rows <= 0) return RAD_E_SHAPE;
const float v = p_f32(a, "value", 0.0f);
#pragma omp parallel for schedule(static)
for (int64_t r = 0; r < rows; ++r) {
const int64_t yb = rowoff(y, r, n), ys = laststride(y);
for (int64_t i = 0; i < n; ++i) stt(y, yb + i * ys, v);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ gather_rows */
/* y[i, :] = x[idx[i], :]. The op that turns "correct" into "affordable": without it a plugin runs
* the lm_head GEMM over every token of a prefill chunk when the sampler wants one row per
* sequence -- n_tok/n_seq times the work, and at max_tok 8192 against a 248K vocab the logits
* buffer alone is 8 GiB (docs/OPS.md).
*
* `M` is a RANGE parameter, so the number of rows actually gathered is the extent of `y` and not
* the declared worst case; `idx` is read for exactly that many entries. A negative index writes a
* zero row, matching embed_lookup's padding rule -- it is what a step with fewer sampled rows
* than the buffer's extent leaves behind, and zeros are the only answer that cannot be mistaken
* for a real logit row. An index at or past x's row count is RAD_E_INVAL: that is a caller bug,
* and reading it would be reading another sequence's hidden state. */
int ref_gather_rows(const RadArgs* a, RadStream) {
if (!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 = p_int(a, "n", y->rank >= 1 ? y->shape[y->rank - 1] : 0);
if (n <= 0) return RAD_E_SHAPE;
const int64_t M = rows_of(y, n);
const int64_t src_rows = rows_of(x, n);
if (M <= 0 || src_rows <= 0 || numel(idx) < M) return RAD_E_SHAPE;
/* Validated before the loop, because an OpenMP body cannot return. */
for (int64_t m = 0; m < M; ++m) {
const int64_t r = ld_int(idx->dtype, idx->data, offlin(idx, m));
if (r >= src_rows) return RAD_E_INVAL;
}
#pragma omp parallel for schedule(static)
for (int64_t m = 0; m < M; ++m) {
const int64_t r = ld_int(idx->dtype, idx->data, offlin(idx, m));
const int64_t yb = rowoff(y, m, n), ys = laststride(y);
if (r < 0) { for (int64_t i = 0; i < n; ++i) stt(y, yb + i * ys, 0.0f); continue; }
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
for (int64_t i = 0; i < n; ++i) stt(y, yb + i * ys, ldt(x, xb + i * xs));
}
return RAD_OK;
}
/* ------------------------------------------------------------------ scatter_rows */
/* The mirror of gather_rows, and it exists for the same reason that one does: without it the only
* way to write M rows to M arbitrary destinations is M transfers, and at a few hundred bytes a row
* that is dispatch cost with the data as a rounding error.
*
* `x` IS INOUT AND THE WRITE IS PARTIAL. Rows no index names keep whatever they held -- which is
* the whole point when the destination is a pool other sequences are also using. An op that
* returned a fresh `x` would have to copy everything it was not asked to change.
*
* DUPLICATE INDICES ARE NOT LEGAL, and the schema says so with RAD_OPD_F_IDX_UNIQUE rather than
* leaving it to prose. Two rows landing on one destination has no defined winner on a parallel
* machine, so an op that permitted it would be one whose reference implementation and whose real
* kernel are allowed to disagree -- which is exactly what the oracle exists to rule out. */
int ref_scatter_rows(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *v = &a->t[0], *idx = &a->t[1], *x = &a->t[2];
const int64_t n = p_int(a, "n", v->rank >= 1 ? v->shape[v->rank - 1] : 0);
if (n <= 0) return RAD_E_SHAPE;
const int64_t M = rows_of(v, n);
const int64_t dst_rows = rows_of(x, n);
if (M <= 0 || dst_rows <= 0 || numel(idx) < M) return RAD_E_SHAPE;
/* Validated before the loop, because an OpenMP body cannot return. A negative index is a
* skip, mirroring the zero row gather_rows writes for one: both mean "this slot has no
* counterpart", and on this side the honest response is to leave the destination alone. */
for (int64_t m = 0; m < M; ++m) {
const int64_t r = ld_int(idx->dtype, idx->data, offlin(idx, m));
if (r >= dst_rows) return RAD_E_INVAL;
}
#pragma omp parallel for schedule(static)
for (int64_t m = 0; m < M; ++m) {
const int64_t r = ld_int(idx->dtype, idx->data, offlin(idx, m));
if (r < 0) continue;
const int64_t vb = rowoff(v, m, n), vs = laststride(v);
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
for (int64_t i = 0; i < n; ++i) stt(x, xb + i * xs, ldt(v, vb + i * vs));
}
return RAD_OK;
}
/* ------------------------------------------------------------------ cast */
/* `from` and `to` are in the schema because the SELECTOR needs them -- a kernel that converts bf16
* to int8 is a different kernel from one that converts f32 to f16, and the constraint has to be
* expressible. Ref does not read them: the tensors carry their own dtypes and those are what the
* bytes actually are. A disagreement between the parameter and the tensor is a caller bug that
* ref cannot diagnose better than the caller can. */
int ref_cast(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *y = &a->t[1];
const int64_t nel = numel(y);
if (nel <= 0 || numel(x) < nel) return RAD_E_SHAPE;
/* Integer targets and sources go through the integer path, so a token id or a block index
* survives a cast that f32 would round. */
const bool int_pair = (x->dtype == RAD_I32 || x->dtype == RAD_I64 || x->dtype == RAD_U32 ||
x->dtype == RAD_I16) &&
(y->dtype == RAD_I32 || y->dtype == RAD_I64 || y->dtype == RAD_U32 ||
y->dtype == RAD_I16);
#pragma omp parallel for schedule(static)
for (int64_t i = 0; i < nel; ++i) {
if (int_pair) st_int(y->dtype, y->data, offlin(y, i), ld_int(x->dtype, x->data, offlin(x, i)));
else stt(y, offlin(y, i), ldt(x, offlin(x, i)));
}
return RAD_OK;
}
/* ------------------------------------------------------------------ softmax */
/* Max-subtracted, f32, over the last n elements of a row. The max subtraction is not an
* optimisation: without it a 60-nat logit range overflows, and every kernel this is an oracle for
* does it, so the reference must too or the two differ by more than rounding. */
int ref_softmax(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *y = &a->t[1];
const int64_t n = p_int(a, "n", numel(y));
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(y, n);
if (rows <= 0 || numel(x) < rows * n) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(x, r, n), yb = rowoff(y, r, n);
const int64_t xs = laststride(x), ys = laststride(y);
float mx = -INFINITY;
for (int64_t i = 0; i < n; ++i) { float v = ldt(x, xb + i * xs); if (v > mx) mx = v; }
float sum = 0.0f;
for (int64_t i = 0; i < n; ++i) {
float e = ref_exp(ldt(x, xb + i * xs) - mx);
sum += e;
stt(y, yb + i * ys, e);
}
const float inv = 1.0f / sum;
for (int64_t i = 0; i < n; ++i) stt(y, yb + i * ys, ldt(y, yb + i * ys) * inv);
}
return RAD_OK;
}