ops: rmsnorm_p, gelu_mul, logit_softcap, scale in lockstep across libref/libavx/libr4d + OPS.md rows

Elementwise ops with numeric selftest cases against the f64 oracle (both legs
of logit_softcap: bf16 and the f32 band the sampling chain carries). libr4d
gains env-gated verification probes alongside them (R4D_VERIFY_OFF
recompute-on-host checks; default off — instruments, not features).
This commit is contained in:
sfjes committed 2026-10-10 00:36:07 -07:00
1 parent 73620ef00e
commit c37ce73d72
20 files changed
+2260 -51

No files matched your search

+11
View File
@@ -418,6 +418,17 @@ static inline float act_gelu(float x) {
return 0.5f * x * (1.0f + std::erf(x * 0.70710678118654752f));
}
/* The tanh approximation (PyTorch's gelu_tanh / gemma's gelu_pytorch_tanh) -- the form gated
* feed-forwards are trained with. The constants are the standard fit and are the same two the
* gemm_nt_bias "gelu_tanh" epilogue uses (ref_gemm.cpp), which is a GEMM-local copy of this same
* formula; both compute the identical function, so a GELU-gated FFN and a tanh-gelu epilogue agree
* to the last bit. Kept here rather than `#include`d into ref_gemm.cpp so the elementwise header
* stays self-contained. */
static inline float act_gelu_tanh(float x) {
const float k0 = 0.7978845608028654f, k1 = 0.044715f;
return 0.5f * x * (1.0f + std::tanh(k0 * (x + k1 * x * x * x)));
}
/* softplus in the two-sided form, with the large-x cutoff FLA and libr4d both use: above the
* threshold log1p(e^x) IS x to every bit f32 holds, and evaluating it costs an overflow. */
static inline float act_softplus(float x, float thr) {
+103
View File
@@ -54,6 +54,37 @@ int ref_rmsnorm(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------------------ rmsnorm_p */
/* y = x * rsqrt(mean(x^2) + eps) -- the SAME normalisation as rmsnorm with NO gain at all. It is
* its own op rather than a zeroed gain on rmsnorm because the gain is a real, weightless thing:
* Gemma's attention normalises the VALUE with a bare RMS (llama.cpp's ggml_rms_norm(V, eps), no
* tensor) while normalising the KEY with the k_norm gain, and there is no checkpoint plane to feed
* a `wadd`/`w` through for the value -- so an rmsnorm call would need a phantom all-zero weight to
* express it, which is a name map to a tensor that does not exist. The mean is accumulated in f32
* in ascending index order, exactly as rmsnorm does, so the two agree bit-for-bit where rmsnorm's
* gain happens to be one. */
int ref_rmsnorm_p(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);
const float eps = p_f32(a, "eps", 1e-6f);
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(x, n);
if (rows <= 0 || numel(y) < 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 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);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ rmsnorm_add */
/* residual_out = x + residual; y = rmsnorm(residual_out) * (w + w_add)
*
@@ -592,6 +623,32 @@ int ref_rel_sinusoid(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------------------ gelu_mul */
/* y[.., i] = gelu_tanh(gate_up[.., i]) * gate_up[.., n + i] -- the tanh GELU, and the gate is the
* FIRST half, for the same order-locking reason as silu_mul. This is Gemma's gated FFN
* (down(gelu_tanh(gate(x)) * up(x)), activation gelu_pytorch_tanh in the checkpoint). It is not
* `gemm_nt`'s "gelu_tanh" EPLOGUE, which applies the activation to a whole GEMM's output and has no
* gate to multiply; gating needs the product of two halves of one fused plane, which is silu_mul's
* shape. The exact-erf form is the unary `gelu` op; a GELU-gated feed-forward in this family is
* trained with the tanh approximation, so this op is the tanh one on purpose and says so. */
int ref_gelu_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_gelu_tanh(ldt(gu, gb + i * gs)) * ldt(gu, gb + (n + i) * gs));
}
return RAD_OK;
}
/* ------------------------------------------------------------------ gelu / silu */
static int unary(const RadArgs* a, int which) {
if (!have(a, 2)) return RAD_E_INVAL;
@@ -635,6 +692,52 @@ int ref_fill(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------------------ logit_softcap */
/* y = cap * tanh(x / cap), Gemma's final-logit softcap: the logits_gemm's output is a nearly
* unbounded row and the sampler wants it bounded, so this is issued against the LOGITS, not the
* hidden stream. Its own op for the same reason sigmoid is -- the selector has to be able to name
* it -- and `cap` is a parameter of the call, which the which-switch above cannot carry. */
int ref_logit_softcap(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;
const float cap = p_f32(a, "cap", 30.0f);
if (!(cap > 0.0f)) return RAD_E_INVAL;
#pragma omp parallel for schedule(static)
for (int64_t i = 0; i < nel; ++i) {
const float v = ldt(x, offlin(x, i));
stt(y, offlin(y, i), cap * std::tanhf(v / cap));
}
return RAD_OK;
}
/* ------------------------------------------------------------------ scale */
/* y = x * s, where s is a [1] weight broadcast over every element of x.
*
* Gemma 4's per-layer scalar: the residual stream is scaled by a learned [1] value at the end of
* every layer (llama.cpp `out_scale`, `cur = cur * out_scale`). It is NOT `mul`, which broadcasts
* a single ROW down the rows (a bias's shape) -- this broadcasts a single SCALAR over the whole
* [M, n] tensor. `scale_rows` is the per-ROW version (one scalar a row); this is the per-TENSOR
* version (one scalar for all rows). Giving `mul` both rules would make them ambiguous exactly
* when rows == 1, so a silent choice between two broadcasts is how a shape bug becomes a
* plausible number -- the same reason `scale_rows` is its own op.
*
* `s` is a weight (a [1] tensor in the checkpoint), not a parameter: it varies per layer, so it
* is a declared weight the name map points at, not a call constant. Read once, outside the loop:
* a per-element reload of a [1] tensor is the same value every time and costs a load per element. */
int ref_scale(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *s = &a->t[1], *y = &a->t[2];
const int64_t nel = numel(y);
if (nel <= 0 || numel(x) < nel || numel(s) < 1) return RAD_E_SHAPE;
const float sv = ldt(s, 0);
#pragma omp parallel for schedule(static)
for (int64_t i = 0; i < nel; ++i)
stt(y, offlin(y, i), ldt(x, offlin(x, i)) * sv);
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
+8
View File
@@ -63,6 +63,7 @@ extern "C" {
/* ---- elementwise and norms */
int ref_rmsnorm (const RadArgs*, RadStream);
int ref_rmsnorm_p (const RadArgs*, RadStream);
int ref_rmsnorm_add (const RadArgs*, RadStream);
int ref_hc_enter (const RadArgs*, RadStream);
int ref_hc_read (const RadArgs*, RadStream);
@@ -73,6 +74,7 @@ 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_gelu_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);
@@ -86,6 +88,8 @@ 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);
int ref_logit_softcap (const RadArgs*, RadStream);
int ref_scale (const RadArgs*, RadStream);
int ref_fill (const RadArgs*, RadStream);
int ref_gather_rows (const RadArgs*, RadStream);
int ref_scatter_rows (const RadArgs*, RadStream);
@@ -192,6 +196,7 @@ int ref_sample_logprobs (const RadArgs*, RadStream);
int fn##_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
REF_SHAPE_FN(ref_rmsnorm);
REF_SHAPE_FN(ref_rmsnorm_p);
REF_SHAPE_FN(ref_rmsnorm_add);
REF_SHAPE_FN(ref_hc_enter);
REF_SHAPE_FN(ref_hc_read);
@@ -202,6 +207,7 @@ 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_gelu_mul);
REF_SHAPE_FN(ref_act_mul);
REF_SHAPE_FN(ref_mul_weight);
REF_SHAPE_FN(ref_seg_mean);
@@ -215,6 +221,8 @@ REF_SHAPE_FN(ref_attn_local_rel);
REF_SHAPE_FN(ref_gelu);
REF_SHAPE_FN(ref_silu);
REF_SHAPE_FN(ref_sigmoid);
REF_SHAPE_FN(ref_logit_softcap);
REF_SHAPE_FN(ref_scale);
REF_SHAPE_FN(ref_fill);
REF_SHAPE_FN(ref_gather_rows);
REF_SHAPE_FN(ref_scatter_rows);
+31 -3
View File
@@ -150,6 +150,9 @@ 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") };
/* `cap` required and not optional: a softcap without a cap is a different op, and the one model in
* scope whose graph issues it (Gemma 4) has a value for it. */
static const RadParamSpec pMnCap[] = { P_INT("M"), P_INT("n"), P_F64("cap"), P_STR("dtype") };
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") };
@@ -185,6 +188,7 @@ static const RadOperandSpec oAttnLocalRel[] = { OPD("q"), OPD("k"), OPD("v"), OP
/* `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") };
static const RadOperandSpec oScale[] = { OPD("x"), WGT("s"), OUT("y") };
static const RadOperandSpec oGather[] = { OPD("x"), OPD("idx"), OUT("y") };
static const RadOperandSpec oScatterRows[] = { OPD("v"), OPD("idx"), INOUT("x") };
@@ -318,7 +322,8 @@ static const RadParamSpec pRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_he
P_INT("n_head_kv"), P_F64("theta"), P_F64("scale"),
P_STR("mode"), P_INTO("rotary_dim"), P_STRO("sections"),
P_F64O("yarn_factor"), P_F64O("yarn_low"),
P_F64O("yarn_high"), P_F64O("yarn_magnitude") };
P_F64O("yarn_high"), P_F64O("yarn_magnitude"),
P_STRO("ladder") };
static const RadOperandSpec oRope[] = { INOUT("qkv"), OPD("positions") };
/* The cos/sin plane a fused prologue reads instead of theta: written at each position's OWN row
@@ -327,7 +332,8 @@ static const RadOperandSpec oRope[] = { INOUT("qkv"), OPD("positions") };
static const RadParamSpec pRopeTable[] = { P_INT("M"), P_INT("rot"), P_F64("theta"),
P_F64("scale"), P_STR("dtype"),
P_F64O("yarn_factor"), P_F64O("yarn_low"),
P_F64O("yarn_high"), P_F64O("yarn_magnitude") };
P_F64O("yarn_high"), P_F64O("yarn_magnitude"),
P_INTO("head_dim"), P_STRO("ladder") };
static const RadOperandSpec oRopeTable[] = { OPD("positions"), OUT("cos_sin") };
/* QSA's compressed key, libr4d's schema exactly (libr4d/r4d_rows.cpp): `block_size` is `ratio`
@@ -623,6 +629,11 @@ static const RadOpSchema kSchemas[] = {
"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. `mult` (default 1) scales the row "
"before its one rounding." },
{ "rmsnorm_p", ARR(pLayernorm), ARR(oUnary),
"y = x * rsqrt(mean(x^2) + eps); an rmsnorm with NO gain tensor at all. wadd is 1 so the result "
"is a plain normalisation. Gemma's attention normalises the value with a bare RMS (a weightless "
"ggml_rms_norm) and the key with the k_norm gain in the same layer, which one op with a required "
"gain cannot express." },
{ "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 "
@@ -694,6 +705,10 @@ static const RadOpSchema kSchemas[] = {
{ "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." },
{ "gelu_mul", ARR(pMnD), ARR(oGateUp),
"y[i] = gelu_tanh(gate_up[i]) * gate_up[n + i], the tanh approximation (gemma's "
"gelu_pytorch_tanh), and the GATE IS THE FIRST HALF as in silu_mul. Its own op, not gelu, because "
"gated feed-forwards are trained with the tanh form and the unary gelu is the exact erf one." },
{ "gelu", ARR(pMnD), ARR(oUnary),
"y = 0.5x(1 + erf(x/sqrt(2))). The exact erf form, not the tanh approximation." },
{ "silu", ARR(pMnD), ARR(oUnary), "y = x * sigmoid(x)." },
@@ -702,6 +717,10 @@ static const RadOpSchema kSchemas[] = {
"y = value, every element of an [M, n] extent (default 0), rounded once to y's dtype. The op a "
"rank issues where it computes nothing and a reader downstream -- an all-reduce, a residual -- "
"still expects a defined buffer." },
{ "logit_softcap", ARR(pMnCap), ARR(oUnary), "y = cap * tanh(x / cap); the final-logit softcap." },
{ "scale", ARR(pMnD), ARR(oScale),
"y = x * s, s a [1] weight broadcast over every element; the per-tensor scalar (per-layer scalar, "
"`mul` broadcasts a row, `scale_rows` a column-per-row)." },
{ "ple_gate", ARR(pPleGate), ARR(oPleGate),
"Per-Layer Embedding's gate. K = grouped_rmsnorm(k) * (w_key + wadd) and Q likewise over `q`, "
"one rsqrt per `n`-wide stream and one gain across all hc*n; s[c] = sum_d K[c][d]*Q[c][d] / "
@@ -1079,6 +1098,8 @@ static const RadOpSchema kSchemas[] = {
static const RadKernelInfo kKernels[] = {
SIMPLE("ref_rmsnorm", "rmsnorm", "norm", "root-mean-square norm with a gain", DT_FLOAT,
ref_rmsnorm),
SIMPLE("ref_rmsnorm_p", "rmsnorm_p", "norm", "weightless RMS norm (no gain, plain x/rms)", DT_FLOAT,
ref_rmsnorm_p),
SIMPLE("ref_rmsnorm_add", "rmsnorm_add", "norm", "residual add then RMS norm", DT_FLOAT,
ref_rmsnorm_add),
SIMPLE("ref_hc_enter", "hc_enter", "norm", "gated residual entry: hc copies of x", DT_FLOAT,
@@ -1097,7 +1118,7 @@ SIMPLE("ref_grid_embed", "grid_embed", "elem",
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),
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),
@@ -1120,6 +1141,13 @@ 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),
SIMPLE("ref_fill", "fill", "elem", "constant fill", DT_FLOAT, ref_fill),
SIMPLE("ref_gelu_mul", "gelu_mul", "elem",
"tanh-gelu-gated product over a fused gate_up (gemma's gelu_pytorch_tanh)", DT_FLOAT,
ref_gelu_mul),
SIMPLE("ref_logit_softcap", "logit_softcap", "elem", "final-logit softcap: cap * tanh(x / cap)",
DT_FLOAT, ref_logit_softcap),
SIMPLE("ref_scale", "scale", "elem", "per-tensor scalar scale: y = x * s (s a [1] weight)",
DT_FLOAT, ref_scale),
SIMPLE("ref_ngram_ids", "ngram_ids", "vocab", "hashed n-gram row ids for PLE", DT_ANY,
ref_ngram_ids),
SIMPLE("ref_ple_gate", "ple_gate", "norm", "PLE gate: three grouped norms, a dot, a signed sqrt",
+32
View File
@@ -331,6 +331,15 @@ int ref_rmsnorm_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
return o.finish("rmsnorm", operand, out);
}
int ref_rmsnorm_p_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("rmsnorm_p", operand, out);
}
int ref_rmsnorm_add_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);
@@ -602,6 +611,15 @@ int ref_silu_mul_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
return o.finish("silu_mul", operand, out);
}
int ref_gelu_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);
Opd o;
o.t(D, { M, 2 * n }); /* gate_up -- the gate is the FIRST half */
o.t(D, { M, n }); /* y */
return o.finish("gelu_mul", operand, out);
}
static int unary_shape(const RadParam* p, int n_p, int operand, const char* op, 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);
@@ -628,6 +646,20 @@ int ref_fill_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
o.t(D, { M, n }); /* y */
return o.finish("fill", operand, out);
}
int ref_logit_softcap_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
return unary_shape(p, n_p, operand, "logit_softcap", out);
}
int ref_scale_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
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 uint32_t D = act_dt(p, n_p);
Opd o;
o.t(D, { M, n }); /* x */
o.t(D, { 1 }); /* s -- one scalar, broadcast over everything */
o.t(D, { M, n }); /* y */
return o.finish("scale", operand, out);
}
int ref_softmax_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
return unary_shape(p, n_p, operand, "softmax", out);
}