radiance 1.2.4

- EmbeddingGemma 2 (google/embeddinggemma-2): text, image, video and audio embeddings on the
  card (libr4d) and on the CPU (libavx); prompt_name, Matryoshka dimensions, image budgets,
  mixed content parts and the messages form on /v1/embeddings
- #43: on serves that lend the activation arena to the experts (Qwen3.8-Flash-Next with
  expert_tiered), every image after the first read its rows from the wrong place -- garbage
  replies, or an earlier request's image. Fixed
- the Qwen vision towers' attention resolves on the card again (broken on main after 1.2.3,
  never released)
- #42: a warning at startup when amdgpu cwsr_enable is 0, and a stalled queue is reported as
  slow or stuck; the guide covers the GPU-hang-and-reset chain
This commit is contained in:
Deadcode committed 2026-10-07 22:42:45 +02:00
1 parent 05af4db458
commit 7d840861af
76 files changed
+8324 -467

No files matched your search

+184 -13
View File
@@ -34,6 +34,8 @@
#include "ref_gemm.h"
#include "ref_ops.h"
#include <algorithm>
using namespace ref;
namespace {
@@ -222,7 +224,10 @@ int ref_attn_dense(const RadArgs* a, RadStream) {
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);
if (head_dim <= 0 || gqa <= 0) return RAD_E_SHAPE;
/* `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
@@ -260,9 +265,13 @@ int ref_attn_dense(const RadArgs* a, RadStream) {
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;
const int64_t jend = causal ? (i + 1) : b1;
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 = b0; j < jend; ++j) {
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)
@@ -277,7 +286,7 @@ int ref_attn_dense(const RadArgs* a, RadStream) {
continue;
}
float sum = 0.0f;
for (int64_t j = b0; j < jend; ++j) {
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)
@@ -507,7 +516,9 @@ int ref_rope(const RadArgs* a, RadStream) {
/* ------------------------------------------------------------------ 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.
* 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
@@ -525,26 +536,65 @@ int ref_qk_norm_rope(const RadArgs* a, RadStream) {
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);
static const char* kModes[] = { "neox", "gptj" };
const int mode = p_enum(a, "mode", kModes, 2, ROPE_NEOX);
const int v_norm = (int)p_int(a, "v_norm", 0);
static const char* kModes[] = { "neox", "gptj", "blocks" };
const int mode = p_enum(a, "mode", kModes, 3, 0);
if (mode < 0) return RAD_E_UNSUPPORTED;
const bool blocks = mode == 2;
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 (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) return RAD_E_SHAPE;
for (int c = 0; 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;
const int64_t M = numel(pos);
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;
RAD_REF_TRY(rope_freqs(mode, rot, theta, nullptr, 0, &f));
if (!blocks) RAD_REF_TRY(rope_freqs(mode, rot, theta, nullptr, 0, &f));
#pragma omp parallel for schedule(static)
for (int64_t m = 0; m < M; ++m) {
float p[8];
const float one = (float)ld_int(pos->dtype, pos->data, offlin(pos, m)) /
(rscale != 0.0f ? rscale : 1.0f);
for (int c = 0; c < 8; ++c) p[c] = one;
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;
@@ -557,7 +607,128 @@ int ref_qk_norm_rope(const RadArgs* a, RadStream) {
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));
rope_head(qkv, base, ds, rot, mode, f, p);
if (!blocks) {
rope_head(qkv, base, ds, rot, 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 = start + j, i1 = 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;
+315 -6
View File
@@ -25,24 +25,31 @@ static inline int64_t rows_of(const RadTensor* t, int64_t n) {
* 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 (!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", w->rank ? w->shape[w->rank - 1] : 0);
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 || numel(w) < n) return RAD_E_SHAPE;
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 = laststride(w);
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 * (ldt(w, i * ws) + wadd));
stt(y, yb + i * ys,
ldt(x, xb + i * xs) * s * (w ? ldt(w, i * ws) + wadd : 1.0f) * mult);
}
return RAD_OK;
}
@@ -212,6 +219,33 @@ static int elementwise2(const RadArgs* a, bool mul) {
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.
*
@@ -283,6 +317,281 @@ int ref_silu_mul(const RadArgs* a, RadStream) {
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;
+2 -1
View File
@@ -310,6 +310,7 @@ int ref_embed_lookup(const RadArgs* a, RadStream) {
const int64_t n_embd = p_int(a, "n_embd", wte->rank >= 2 ? wte->shape[wte->rank - 1] : 0);
const int64_t n_vocab = p_int(a, "n_vocab", wte->rank >= 2 ? wte->shape[wte->rank - 2] : 0);
const int64_t voff = p_int(a, "vocab_offset", 0);
const float mult = p_f32(a, "mult", 1.0f);
if (n_embd <= 0 || n_vocab <= 0 || voff < 0) return RAD_E_SHAPE;
const int64_t M = numel(x) / n_embd;
if (M <= 0 || numel(tok) < M || numel(wte) < n_vocab * n_embd) return RAD_E_SHAPE;
@@ -338,7 +339,7 @@ int ref_embed_lookup(const RadArgs* a, RadStream) {
const int64_t xb = rowoff(x, m, n_embd), xs = laststride(x);
const bool have_row = id >= 0 && id < n_vocab;
for (int64_t i = 0; i < n_embd; ++i)
stt(x, xb + i * xs, have_row ? ldt(wte, id * ws + i * wc) : 0.0f);
stt(x, xb + i * xs, have_row ? ldt(wte, id * ws + i * wc) * mult : 0.0f);
}
return RAD_OK;
}
+20
View File
@@ -73,6 +73,16 @@ int ref_grid_embed (const RadArgs*, RadStream);
int ref_add (const RadArgs*, RadStream);
int ref_mul (const RadArgs*, RadStream);
int ref_silu_mul (const RadArgs*, RadStream);
int ref_act_mul (const RadArgs*, RadStream);
int ref_mul_weight (const RadArgs*, RadStream);
int ref_seg_mean (const RadArgs*, RadStream);
int ref_pool_rows (const RadArgs*, RadStream);
int ref_relu (const RadArgs*, RadStream);
int ref_clamp (const RadArgs*, RadStream);
int ref_conv2d (const RadArgs*, RadStream);
int ref_conv1d_dw (const RadArgs*, RadStream);
int ref_rel_sinusoid (const RadArgs*, RadStream);
int ref_attn_local_rel (const RadArgs*, RadStream);
int ref_gelu (const RadArgs*, RadStream);
int ref_silu (const RadArgs*, RadStream);
int ref_sigmoid (const RadArgs*, RadStream);
@@ -191,6 +201,16 @@ REF_SHAPE_FN(ref_grid_embed);
REF_SHAPE_FN(ref_add);
REF_SHAPE_FN(ref_mul);
REF_SHAPE_FN(ref_silu_mul);
REF_SHAPE_FN(ref_act_mul);
REF_SHAPE_FN(ref_mul_weight);
REF_SHAPE_FN(ref_seg_mean);
REF_SHAPE_FN(ref_pool_rows);
REF_SHAPE_FN(ref_relu);
REF_SHAPE_FN(ref_clamp);
REF_SHAPE_FN(ref_conv2d);
REF_SHAPE_FN(ref_conv1d_dw);
REF_SHAPE_FN(ref_rel_sinusoid);
REF_SHAPE_FN(ref_attn_local_rel);
REF_SHAPE_FN(ref_gelu);
REF_SHAPE_FN(ref_silu);
REF_SHAPE_FN(ref_sigmoid);
+1 -1
View File
@@ -469,7 +469,7 @@ int ref_gram_accum(const RadArgs* a, RadStream) {
*
* THREE OPS THAT EXIST SO THAT A HOST RUN IS POSSIBLE AT ALL. libr4d fuses the fp8 activation
* quantiser into whichever kernel already has the row in registers, and declares the fused form as
* its own op. Without a host kernel for those names, `RADIANCE_HOST_DOMAIN` -- the only thing that
* its own op. Without a host kernel for those names, a host-backend run -- the only thing that
* can answer "is the GRAPH right", because the per-op oracle reads the same graph both sides --
* cannot start on an fp8 model ("site 'host' is unavailable for this band").
*
+112 -12
View File
@@ -73,9 +73,15 @@
#define ARR(a) (a), (int)(sizeof(a) / sizeof((a)[0]))
/* ---- elementwise and norms ---------------------------------------------------------------- */
static const RadParamSpec pRmsnorm[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype"),
/* `mult` scales the normed row before its one rounding (default 1). */
/* rmsnorm_add has no `mult`: it is the fused pair, and nothing fuses a scaled branch. */
static const RadParamSpec pRmsnormAdd[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype"),
P_F64O("wadd") };
static const RadOperandSpec oRmsnorm[] = { OPD("x"), WGT("w"), OUT("y") };
static const RadParamSpec pRmsnorm[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype"),
P_F64O("wadd"), P_F64O("mult") };
/* `w` is optional: absent, the gain is one (a norm with no scale, such as Gemma 4's value norm and
* its multimodal embedder's pre-projection norm). */
static const RadOperandSpec oRmsnorm[] = { OPD("x"), WGT_O("w"), OUT("y") };
/* The GATED RESIDUAL pair. `inject` and `group` are the two switches the operand list is banded
* on: `inject` 0 is the final mixer (no per-branch gate weight, no gate output) and `group` 0 is a
@@ -141,9 +147,41 @@ static const RadParamSpec pGridEmbed[] = { P_INT("M"), P_INT("n"), P_INT("side")
static const RadOperandSpec oGridEmbed[] = { INOUT("x"), WGT("table"), OPD("coord") };
static const RadParamSpec pMnD[] = { P_INT("M"), P_INT("n"), P_STR("dtype") };
/* `scalar` 1 says `w` is one element rather than one row: a kernel reads that off the operand, and
* the parameter is what lets a shape description say which of the two geometries it is. */
static const RadParamSpec pMulWeight[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_INTO("scalar") };
static const RadOperandSpec oBinary[] = { OPD("a"), OPD("b"), OUT("y") };
static const RadOperandSpec oGateUp[] = { OPD("gate_up"), OUT("y") };
static const RadOperandSpec oMulWeight[] = { OPD("x"), WGT("w"), OUT("y") };
static const RadParamSpec pActMul[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_STR("dtype") };
/* `M` is the step's token count and bands the op; the segment count is cu_seqlens' length. */
static const RadParamSpec pSegMean[] = { P_INT("M"), P_INT("n"), P_STR("dtype") };
static const RadOperandSpec oSegMean[] = { OPD("x"), OPD("cu_seqlens"), OUT("y") };
/* `M` is the INPUT row count, a multiple of `k`; y has M / k rows. */
static const RadParamSpec pPoolRows[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_F64O("mult"),
P_STR("dtype") };
static const RadOperandSpec oUnary[] = { OPD("x"), OUT("y") };
/* The audio (USM conformer) tower's operators. */
static const RadOperandSpec oClamp[] = { OPD("x"), WGT("lo"), WGT("hi"), OUT("y") };
/* `M` is the INPUT time rows. */
static const RadParamSpec pConv2d[] = { P_INT("M"), P_INT("width"), P_INT("cin"), P_INT("cout"),
P_INT("kh"), P_INT("kw"), P_INT("stride"), P_INT("pad"),
P_INTO("cu_div"), P_INTO("valid_stride"),
P_STR("dtype") };
static const RadOperandSpec oConv2d[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OPD_O("valid"),
OUT("y") };
static const RadParamSpec pConv1dDw[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_INTO("cu_div"),
P_STR("dtype") };
static const RadOperandSpec oConv1dDw[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OUT("y") };
/* `M` is the table's rows: one a distance. */
static const RadParamSpec pRelSin[] = { P_INT("M"), P_INT("n"), P_F64O("max_timescale"),
P_STR("dtype") };
static const RadOperandSpec oRelSin[] = { OUT("y") };
static const RadParamSpec pAttnLocalRel[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
P_INT("left"), P_INT("right"), P_F64("softcap"),
P_INTO("cu_div"), P_STR("dtype") };
static const RadOperandSpec oAttnLocalRel[] = { OPD("q"), OPD("k"), OPD("v"), OPD("relk"),
WGT("pds"), OPD("cu_seqlens"), OUT("out") };
/* `fill` has no input: `value` is the whole of what it writes. */
static const RadParamSpec pFill[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_F64O("value") };
static const RadOperandSpec oFill[] = { OUT("y") };
@@ -262,7 +300,7 @@ static const RadConstraint cPagedBlock[] = { RAD_CGE("block_size", 1) };
static const RadParamSpec pAttnDense[] = { P_INT("M"), P_INT("head_dim"), P_INT("gqa"),
P_INT("causal"), P_STR("dtype"), P_F64O("scale"),
P_INTO("max_seqlen") };
P_INTO("max_seqlen"), P_INTO("window") };
static const RadOperandSpec oAttnDense[] = { OPD("q"), OPD("k"), OPD("v"), OPD("cu_seqlens"),
OUT("out") };
@@ -304,10 +342,13 @@ static const RadParamSpec pQsaBlockKey[] = { P_INT("M"), P_INT("n"), P_INT("rati
static const RadOperandSpec oQsaBlockKey[] = { OPD("k"), WGT("w"), OPD_O("page"), OPD_O("pos"),
OUT("out") };
/* `mode` "blocks" rotates each of `sections` (pair counts) as its own neox block of channels,
* reading the position component `comps` names for it; positions are then [C, M]. */
static const RadParamSpec pQkNormRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
P_INT("n_head_kv"), P_F64("theta"), P_F64("eps"),
P_F64O("scale"), P_STRO("mode"), P_INTO("rotary_dim"),
P_F64O("wadd") };
P_F64O("wadd"), P_INTO("v_norm"), P_STRO("sections"),
P_STRO("comps") };
static const RadOperandSpec oQkNormRope[] = { INOUT("qkv"), OPD("positions"), WGT("q_w"),
WGT("k_w") };
@@ -506,6 +547,11 @@ static const RadParamSpec pEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_voc
* A parameter because a global scale needs the whole table
* and the transform sees one block. */
P_F64O("wscale") };
/* embed_lookup's own list: pEmbed and `mult`, the factor every gathered row is multiplied by --
* Gemma's sqrt(hidden). embed_lookup_q has its table scale and does not take it. */
static const RadParamSpec pEmbedM[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_vocab"),
P_STR("dtype"), P_INTO("vocab_offset"),
P_F64O("wscale"), P_F64O("mult") };
static const RadOperandSpec oEmbed[] = { OPD("tokens"), WGT("wte"), OUT("x") };
/* The quantised table: one scale for all of it. A SEPARATE OP and not a dtype on the above --
* the operand list differs and operands are positional, the same argument gemm_nt_q makes. */
@@ -566,11 +612,12 @@ static const RadOperandSpec oMerge[] = { OPD("gathered"), OPD("params"),
/* ================================================================== the schema table */
static const RadOpSchema kSchemas[] = {
{ "rmsnorm", ARR(pRmsnorm), ARR(oRmsnorm),
"y = x * rsqrt(mean(x^2) + eps) * (w + wadd). `wadd` is not in docs/OPS.md's elementwise table: "
"y = x * rsqrt(mean(x^2) + eps) * (w + wadd) * mult. `wadd` is not in docs/OPS.md's elementwise table: "
"it is GemmaRMSNorm's `1 +`, which Qwen3.5, Qwen3-Next and Gemma all need, and it defaults to 0. "
"Spelled `wadd` and not `w_add` because that is what libr4d's fused norms call it and one "
"vocabulary cannot have two spellings of one parameter." },
{ "rmsnorm_add", ARR(pRmsnorm), ARR(oRmsnormAdd),
"vocabulary cannot have two spellings of one parameter. `mult` (default 1) scales the row "
"before its one rounding." },
{ "rmsnorm_add", ARR(pRmsnormAdd), ARR(oRmsnormAdd),
"residual_out = x + residual, then y = rmsnorm(residual_out) * w. The variance is taken from "
"the unrounded f32 sum; the multiply reads residual_out back AFTER it has been narrowed, which "
"is what every fused implementation does." },
@@ -606,6 +653,38 @@ static const RadOpSchema kSchemas[] = {
"y = a + b. An operand carrying exactly n elements against a taller output broadcasts along "
"rows; nothing else broadcasts." },
{ "mul", ARR(pMnD), ARR(oBinary), "y = a * b, with the same one broadcast rule as `add`." },
{ "mul_weight", ARR(pMulWeight), ARR(oMulWeight),
"y = x * w, `w` a WEIGHT of one element (a scalar for the whole output) or of one row "
"(broadcast down the rows): a learned gain on an activation. f32 product, rounded once." },
{ "act_mul", ARR(pActMul), ARR(oBinary),
"y = act(a) * b, `act` \"silu\", \"gelu\" (exact erf), \"gelu_tanh\" or \"sigmoid\". The activation is "
"rounded to y's dtype before the product, which is the unfused pair. `a` and `b` may be column "
"slices of one fused row." },
{ "seg_mean", ARR(pSegMean), ARR(oSegMean),
"y[s] = mean of x's rows [cu[s], cu[s+1]): one row a segment, summed in double and rounded "
"once to y's dtype. An empty segment is a zero row." },
{ "pool_rows", ARR(pPoolRows), ARR(oUnary),
"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 "
"times `mult` (default 1) and rounded again. M, the input rows, is a multiple of k." },
{ "relu", ARR(pMnD), ARR(oUnary), "y = max(x, 0), each operand at its own row pitch." },
{ "clamp", ARR(pMnD), ARR(oClamp),
"y = min(max(x, lo), hi), `lo` and `hi` WEIGHTS of one element each: a clipped linear's range." },
{ "conv2d", ARR(pConv2d), ARR(oConv2d),
"A 2-D convolution over (time, width), channels innermost: x[t, w*cin + c] -> y[t, w*cout + c], "
"w [cout, cin, kh, kw]. Each cu_seqlens segment (rows cu/cu_div) is convolved on its own with "
"zero padding `pad` at its edges; its output rows start at cu/(cu_div*stride). With `valid`, "
"input row t reads as zeros unless valid[t * valid_stride] != 0. f32 sum, one rounding." },
{ "conv1d_dw", ARR(pConv1dDw), ARR(oConv1dDw),
"Causal depthwise convolution over time: y[t, c] = sum_j w[c, 0, j] * x[t - (k-1) + j, c], rows "
"before the segment's start (cu/cu_div) read as zeros. f32 sum, one rounding." },
{ "rel_sinusoid", ARR(pRelSin), ARR(oRelSin),
"Row d: sin(d * inv[i]) then cos(d * inv[i]) over n/2 timescales, inv[i] = exp(i * "
"-log(max_timescale) / max(n/2 - 1, 1)), each step in f32, rounded once." },
{ "attn_local_rel", ARR(pAttnLocalRel), ARR(oAttnLocalRel),
"Local attention with a relative-position term (Gemma 4's audio): query i of a segment sees "
"keys j with 0 <= i - j <= left (`right` 0). qf = q * head_dim^-0.5/ln2 * softplus(pds); logit "
"= qf.k * ln(1+e)/ln2 + qf.relk[i-j]; softcap * tanh(logit / softcap); softmax; .v. f32, one "
"rounding." },
{ "silu_mul", ARR(pMnD), ARR(oGateUp),
"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." },
@@ -755,7 +834,8 @@ static const RadOpSchema kSchemas[] = {
"including this step's query rows. k_descale / v_descale are optional and apply to an fp8 "
"cache. `scale` is not in docs/OPS.md and defaults to 1/sqrt(head_dim)." },
{ "attn_dense", ARR(pAttnDense), ARR(oAttnDense),
"Dense varlen attention over cu_seqlens segments -- the vision tower's. Nothing paged." },
"Dense varlen attention over cu_seqlens segments. Nothing paged. `window` is attn_paged's rule "
"over a segment's positions: causal, i - j < window; non-causal, |i - j| < window; 0 none." },
{ "kv_store", ARR(pKvStore), ARR(oKvStore),
"Writes k and v into the paged cache at slot_mapping; a negative slot is skipped. The cache is "
"INOUT rather than the OUT docs/OPS.md draws, because the op touches only the mapped slots." },
@@ -778,7 +858,8 @@ static const RadOpSchema kSchemas[] = {
"`scale` divides the position; `rotary_dim` is optional and defaults to head_dim." },
{ "qk_norm_rope", ARR(pQkNormRope), ARR(oQkNormRope),
"Per-head RMS norm of q and k against their own gains, then rope. THE NORM OUTPUT IS ROUNDED "
"TO THE TENSOR'S DTYPE BEFORE THE ROTATION, which is what the unfused pair does." },
"TO THE TENSOR'S DTYPE BEFORE THE ROTATION, which is what the unfused pair does. `v_norm` 1 "
"also RMS-norms each v head with a unit gain, unrotated." },
{ "scale_rows", ARR(pScaleRows), ARR(oScaleRows),
"y[m, i] = x[m, i] * act(s[m]): one scalar per ROW, broadcast ACROSS the row. `mul` broadcasts "
@@ -895,9 +976,10 @@ static const RadOpSchema kSchemas[] = {
"[rows][row] and y is [rows][world_size][row], so one row of y carries every rank's words for "
"that row. The vocab-parallel candidate merge reads exactly that." },
{ "embed_lookup", ARR(pEmbed), ARR(oEmbed),
{ "embed_lookup", ARR(pEmbedM), ARR(oEmbed),
"A gather from wte[n_vocab, n_embd]. A negative token id writes a zero row (padding); an id at "
"or above n_vocab fails the launch." },
"or above n_vocab fails the launch. `mult`, when given, multiplies every gathered row and the "
"product is rounded once to x's dtype (Gemma's sqrt(hidden)); absent it is a plain copy." },
{ "embed_lookup_q", ARR(pEmbed), ARR(oEmbedQ),
"The same gather from a table quantised with ONE scale for all of it: x[m] = wte[id] * scale[0]. "
"Qwen3.8-Flash-Next-FP8's 320-million-row n-gram embedding is stored that way -- E4M3 codes and a "
@@ -1007,6 +1089,24 @@ SIMPLE("ref_add", "add", "elem", "elementwise sum", DT_FLOAT, ref_add),
SIMPLE("ref_mul", "mul", "elem", "elementwise product", DT_FLOAT, ref_mul),
SIMPLE("ref_silu_mul", "silu_mul", "elem", "silu-gated product over a fused gate_up", DT_FLOAT,
ref_silu_mul),
SIMPLE("ref_act_mul", "act_mul", "elem", "act(a) * b over two operands", DT_FLOAT, ref_act_mul),
SIMPLE("ref_mul_weight", "mul_weight", "elem", "x * a scalar or one-row weight", DT_FLOAT,
ref_mul_weight),
SIMPLE("ref_seg_mean", "seg_mean", "elem", "mean of each cu_seqlens segment's rows", DT_FLOAT,
ref_seg_mean),
SIMPLE("ref_pool_rows", "pool_rows", "elem", "mean of every k consecutive rows, then a multiplier",
DT_FLOAT, ref_pool_rows),
SIMPLE("ref_relu", "relu", "elem", "max(x, 0)", DT_FLOAT, ref_relu),
SIMPLE("ref_clamp", "clamp", "elem", "x clamped to two weight scalars", DT_FLOAT, ref_clamp),
SIMPLE("ref_conv2d", "conv2d", "elem", "segment-wise 2-D convolution, channels innermost",
DT_FLOAT, ref_conv2d),
SIMPLE("ref_conv1d_dw", "conv1d_dw", "elem", "segment-wise causal depthwise convolution",
DT_FLOAT, ref_conv1d_dw),
SIMPLE("ref_rel_sinusoid", "rel_sinusoid", "elem", "sinusoidal relative-position table", DT_FLOAT,
ref_rel_sinusoid),
SIMPLE("ref_attn_local_rel", "attn_local_rel", "attn",
"local attention with a relative-position term and a softcap", DT_FLOAT,
ref_attn_local_rel),
SIMPLE("ref_gelu", "gelu", "elem", "exact erf gelu", DT_FLOAT, ref_gelu),
SIMPLE("ref_silu", "silu", "elem", "silu", DT_FLOAT, ref_silu),
SIMPLE("ref_sigmoid", "sigmoid", "elem", "logistic sigmoid", DT_FLOAT, ref_sigmoid),
@@ -1028,7 +1128,7 @@ SIMPLE("ref_quant_act_fp8", "quant_act_fp8", "quant", "symmetric block-scaled E4
"float in, fp8_e4m3 out, f32 scale", ref_quant_act_fp8),
/* THE FUSED FORMS, AND THEY EXIST SO A HOST RUN IS POSSIBLE AT ALL. libr4d fuses the fp8
* activation quantiser into whichever kernel already has the row in registers and declares the
* fused op as its own; without host kernels for those names, RADIANCE_HOST_DOMAIN -- the only
* fused op as its own; without host kernels for those names, a host-backend run -- the only
* thing that can answer "is the GRAPH right", because the per-op oracle reads the same graph on
* both sides -- cannot start on an fp8 model. */
SIMPLE("ref_rmsnorm_quant_fp8", "rmsnorm_quant_fp8", "quant",
+153 -1
View File
@@ -468,6 +468,131 @@ int ref_mul_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
return binary_shape(p, n_p, operand, "mul", out);
}
int ref_mul_weight_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
Opd o;
o.t(D, { M, n }); /* x */
if (gi(p, n_p, "scalar", 0)) o.t(D, { 1 }); /* w -- the scalar form */
else o.t(D, { n }); /* w -- one row */
o.t(D, { M, n }); /* y */
return o.finish("mul_weight", operand, out);
}
int ref_act_mul_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
return binary_shape(p, n_p, operand, "act_mul", out);
}
int ref_seg_mean_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
if (M <= 0 || n <= 0) return RAD_E_UNSUPPORTED;
const int64_t S = n_seq_of(p, n_p);
Opd o;
o.t(D, { M, n }); /* x */
o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */
o.t(D, { S, n }); /* y */
return o.finish("seg_mean", operand, out);
}
int ref_pool_rows_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t n = gi(p, n_p, "n", 0), k = gi(p, n_p, "k", 0);
/* A band's bound need not be whole windows; the rows a pass issues always are, so the
* description takes the whole windows under it. */
int64_t M = gi(p, n_p, "M", 0);
if (k > 0) M -= M % k;
if (M <= 0 || n <= 0 || k <= 0) return RAD_E_UNSUPPORTED;
Opd o;
o.t(D, { M, n }); /* x */
o.t(D, { M / k, n }); /* y */
return o.finish("pool_rows", operand, out);
}
int ref_relu_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
Opd o;
o.t(D, { M, n }); /* x */
o.t(D, { M, n }); /* y */
return o.finish("relu", operand, out);
}
int ref_clamp_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
Opd o;
o.t(D, { M, n }); /* x */
o.t(D, { 1 }); /* lo */
o.t(D, { 1 }); /* hi */
o.t(D, { M, n }); /* y */
return o.finish("clamp", operand, out);
}
/* THE AUDIO TOWER'S SEGMENTED OPS ARE DESCRIBED AS ONE SEGMENT. `cu_seqlens` counts in units
* `cu_div` times finer than the operand's rows (a subsampled layer reads the pass's frame
* boundaries), so the description's rows are M / cu_div and a band that does not divide -- or,
* for a strided convolution, does not divide into whole output rows -- is declined rather than
* described into a refusal. */
int ref_conv2d_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), W = gi(p, n_p, "width", 0);
const int64_t cin = gi(p, n_p, "cin", 0), cout = gi(p, n_p, "cout", 0);
const int64_t kh = gi(p, n_p, "kh", 0), kw = gi(p, n_p, "kw", 0);
const int64_t st = gi(p, n_p, "stride", 1), pad = gi(p, n_p, "pad", 0);
const int64_t cdiv = gi(p, n_p, "cu_div", 1), vst = gi(p, n_p, "valid_stride", 1);
if (M <= 0 || W <= 0 || st <= 0 || cdiv <= 0 || vst <= 0 || M % (cdiv * st))
return RAD_E_UNSUPPORTED;
const int64_t T = M / cdiv;
const int64_t To = (T + 2 * pad - kh) / st + 1, Wo = (W + 2 * pad - kw) / st + 1;
Opd o;
o.t(D, { T, W * cin }); /* x */
o.t(D, { cout, cin, kh, kw }); /* w */
o.t_idx({ 2 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */
o.t_idx({ T * vst }, 2, -1, 0); /* valid: 0 or 1 a row */
o.t(D, { To, Wo * cout }); /* y */
return o.finish("conv2d", operand, out);
}
int ref_conv1d_dw_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), C = gi(p, n_p, "n", 0), K = gi(p, n_p, "k", 0);
const int64_t cdiv = gi(p, n_p, "cu_div", 1);
if (M <= 0 || cdiv <= 0 || M % cdiv) return RAD_E_UNSUPPORTED;
Opd o;
o.t(D, { M / cdiv, C }); /* x */
o.t(D, { C, 1, K }); /* w */
o.t_idx({ 2 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */
o.t(D, { M / cdiv, C }); /* y */
return o.finish("conv1d_dw", operand, out);
}
int ref_rel_sinusoid_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
Opd o;
o.t(D, { M, n }); /* y */
return o.finish("rel_sinusoid", operand, out);
}
int ref_attn_local_rel_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), hd = gi(p, n_p, "head_dim", 0);
const int64_t H = gi(p, n_p, "n_head", 0), L = gi(p, n_p, "left", 0);
const int64_t cdiv = gi(p, n_p, "cu_div", 1);
if (M <= 0 || cdiv <= 0 || M % cdiv || L < 0) return RAD_E_UNSUPPORTED;
const int64_t T = M / cdiv;
Opd o;
o.t(D, { T, H * hd }); /* q */
o.t(D, { T, H * hd }); /* k */
o.t(D, { T, H * hd }); /* v */
o.t(D, { L + 1, H * hd }); /* relk */
o.t(D, { hd }); /* pds */
o.t_idx({ 2 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */
o.t(D, { T, H * hd }); /* out */
return o.finish("attn_local_rel", operand, out);
}
int ref_silu_mul_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
@@ -1017,7 +1142,34 @@ int ref_qk_norm_rope_shape(const RadParam* p, int n_p, int operand, RadOpdDesc*
* the parameters could know it. The vocabulary's `qk_norm_rope` takes the same contiguous fused
* [q|k|v] row `rope` does, so it is describable and is described. */
o.t(D, { M, (nh + 2 * nkv) * hd }); /* qkv, INOUT */
o.t_idx({ M }, 0, -1, 0); /* positions */
/* `blocks` takes a position per component, [C, M] component-major, C being one past the
* largest component `comps` names (the section count when it names none). */
const char* mode = gs(p, n_p, "mode");
if (mode && !std::strcmp(mode, "blocks")) {
int64_t nc = 0;
for (const char* q = gs(p, n_p, "sections"); q && *q; ) {
char* e = nullptr;
(void)std::strtoll(q, &e, 10);
if (e == q) break;
++nc;
q = e;
}
if (const char* cs = gs(p, n_p, "comps")) {
int64_t mx = -1;
for (const char* q = cs; *q; ) {
char* e = nullptr;
const long long x = std::strtoll(q, &e, 10);
if (e == q) break;
mx = x > mx ? x : mx;
q = e;
}
nc = mx + 1;
}
if (nc <= 0) return RAD_E_UNSUPPORTED;
o.t_idx({ nc, M }, M, -1, 0); /* positions */
} else {
o.t_idx({ M }, 0, -1, 0); /* positions */
}
o.t(D, { hd }); /* q_w -- one gain per head channel */
o.t(D, { hd }); /* k_w */
return o.finish("qk_norm_rope", operand, out);