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

+19 -2
View File
@@ -43,7 +43,11 @@ std::vector<Case> build_cases() {
add("rmsnorm", { HI("M", 7), HI("n", 640), HF("eps", 1e-6), HS("dtype", dt),
HF("wadd", 0) }, EB(7, 640, w, 2));
add("rmsnorm", { HI("M", 3), HI("n", 645), HF("eps", 1e-5), HS("dtype", dt),
HF("wadd", 1) }, EB(3, 645, w, 2));
HF("wadd", 1) }, EB(3, 645, w, 2));
add("rmsnorm_p", { HI("M", 7), HI("n", 640), HF("eps", 1e-6), HS("dtype", dt) },
EB(7, 640, w, 2));
add("rmsnorm_p", { HI("M", 3), HI("n", 645), HF("eps", 1e-5), HS("dtype", dt) },
EB(3, 645, w, 2));
add("rmsnorm_add", { HI("M", 5), HI("n", 640), HF("eps", 1e-6), HS("dtype", dt),
HF("wadd", 0) }, EB(5, 640, w, 4));
add("layernorm", { HI("M", 5), HI("n", 645), HF("eps", 1e-5), HS("dtype", dt) },
@@ -51,11 +55,15 @@ std::vector<Case> build_cases() {
add("add", { HI("M", 9), HI("n", 645), HS("dtype", dt) }, EB(9, 645, w, 3));
add("mul", { HI("M", 9), HI("n", 640), HS("dtype", dt) }, EB(9, 640, w, 3));
add("silu_mul", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 3));
add("gelu_mul", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 3));
add("gelu", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2));
add("silu", { HI("M", 6), HI("n", 640), HS("dtype", dt) }, EB(6, 640, w, 2));
add("sigmoid", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2));
add("fill", { HI("M", 6), HI("n", 645), HS("dtype", dt), HF("value", 1.3) },
EB(6, 645, w, 1));
add("logit_softcap", { HI("M", 6), HI("n", 645), HF("cap", 30.0), HS("dtype", dt) },
EB(6, 645, w, 2));
add("scale", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2));
add("softmax", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2));
add("gather_rows", { HI("M", 6), HI("n", 640), HS("dtype", dt) }, EB(6, 640, w, 2));
for (const char* act : { "silu", "gelu", "gelu_tanh", "sigmoid" })
@@ -297,8 +305,17 @@ std::vector<Case> build_cases() {
add("qsa_block_key", { HI("M", 12), HI("n", 128), HI("ratio", 4), HI("rotary_dim", 64),
HF("eps", 1e-6), HF("theta", 1e7), HF("scale", 1), HF("wadd", 0),
HS("dtype", dt), HF("yarn_factor", 2), HF("yarn_low", 14),
HF("yarn_high", 22), HF("yarn_magnitude", 1.069314718) });
HF("yarn_high", 22), HF("yarn_magnitude", 1.069314718) });
}
/* The proportional ladder: a partial rotary (rotary_dim < head_dim) with `ladder` head, so the
* denominator is head_dim and libavx's answer must agree with libref's on it. */
for (const char* mode : { "neox", "gptj" }) {
add("rope", { HI("M", 12), HI("head_dim", 64), HI("n_head", 4), HI("n_head_kv", 2),
HF("theta", 10000.0), HF("scale", 1.0), HS("mode", mode),
HI("rotary_dim", 32), HS("ladder", "head") });
}
add("rope_table", { HI("M", 12), HI("rot", 32), HF("theta", 10000.0), HF("scale", 1.0),
HS("dtype", "f32"), HI("head_dim", 64), HS("ladder", "head") });
/* The multi-component forms: Qwen3-VL's interleaved M-RoPE over a partial rotary, and a vision
* tower's 2-D axial rotary over a whole 72-wide head. */
for (const char* dt : { "f32", "bf16" }) {
+122
View File
@@ -551,6 +551,39 @@ AVX_KERNEL(silu_mul) {
return RAD_OK;
}
/* ------------------------------------------------------------------ gelu_mul
*
* y[i] = gelu_tanh(gate_up[i]) * gate_up[n + i], the gate the FIRST half exactly as in silu_mul.
* The activation keeps libref's ONE definition of gelu_tanh (act_gelu_tanh, std::tanh): the tree's
* rule for a non-polynomial activation is a single source of truth, so this runs libref's scalar
* formula into the f32 scratch rather than a second vectorised tanh whose agreement with the first
* would be a property of its coefficients -- the same decision the unary gelu above makes. */
AVX_KERNEL(gelu_mul) {
if (!rad_args_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;
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
/* One in_row over the whole 2n row, as silu_mul does: the halves are adjacent and one
* conversion of 2n beats two of n. */
float* s = scratch_f32((size_t)(2 * n));
float* sy = scratch_f32_b((size_t)n);
const float* g = in_row(gu, rowoff(gu, r, 2 * n), 2 * n, s);
const float* u = g + n;
for (int64_t i = 0; i < n; ++i) {
const float x = g[i];
const float t = std::tanh(0.7978845608028654f * (x + 0.044715f * x * x * x));
sy[i] = 0.5f * x * (1.0f + t) * u[i];
}
out_row(y, rowoff(y, r, n), n, sy);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ gelu / silu / sigmoid
*
* These run over the whole tensor rather than row by row -- libref's `unary` does the same -- so
@@ -640,6 +673,95 @@ AVX_KERNEL(fill) {
return RAD_OK;
}
/* ------------------------------------------------------------------ logit_softcap */
/* y = cap * tanh(x / cap). Its own list entry rather than another unary<WHICH>, because WHICH is
* a compile-time choice and `cap` is a runtime parameter -- the template has nowhere to put it.
* The vector path keeps the tree's one definition of the non-polynomial part: tanh(z) is
* 2*sigmoid(2z) - 1, so the work is vf_sigmoid's existing minimax exp plus two multiplies. The
* scalar fallback is libm's tanhf, which is what libref's oracle computes. */
AVX_KERNEL(logit_softcap) {
if (!rad_args_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;
if (!dense_row(x) || !dense_row(y) || !rad_tensor_is_contiguous(x) ||
!rad_tensor_is_contiguous(y)) {
AVX_PARALLEL_FOR_IF(nel >= AVX_PAR_MIN)
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;
}
const int64_t TILE = 4096;
const int64_t ntile = (nel + TILE - 1) / TILE;
AVX_PARALLEL_FOR_IF(nel >= AVX_PAR_MIN)
for (int64_t t = 0; t < ntile; ++t) {
const int64_t off = t * TILE;
const int64_t m = (nel - off) < TILE ? (nel - off) : TILE;
float* s = scratch_f32((size_t)TILE);
float* so = scratch_f32_b((size_t)TILE);
const float* v = in_row(x, off, m, s);
const vf z = vf_set1(2.0f / cap); /* x / cap, doubled: the argument of the sigmoid */
const vf c2 = vf_set1(2.0f * cap); /* 2*cap * sigmoid(...) */
const vf c1 = vf_set1(-cap); /* ... - cap */
int64_t i = 0;
for (; i + VF_N <= m; i += VF_N)
vf_storeu(so + i, vf_fma(c2, vf_sigmoid(vf_mul(vf_loadu(v + i), z)), c1));
for (; i < m; ++i)
so[i] = cap * std::tanhf(v[i] / cap);
out_row(y, off, m, so);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ scale */
/* y = x * s, s a [1] weight broadcast over every element. A plain multiply by a scalar: the
* vector path is vf_mul against a broadcast, and the scalar fallback is a plain multiply. There is
* no non-polynomial part, so nothing is reused from the sigmoid path; it is its own list entry
* (rather than a `mul` with a [1] operand) for the same reason `mul` refuses a scalar broadcast --
* a silent choice between a row-broadcast and a scalar-broadcast is how a shape bug becomes a
* plausible number. The scalar is 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. */
AVX_KERNEL(scale) {
if (!rad_args_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);
if (!dense_row(x) || !dense_row(y) || !rad_tensor_is_contiguous(x) ||
!rad_tensor_is_contiguous(y)) {
AVX_PARALLEL_FOR_IF(nel >= AVX_PAR_MIN)
for (int64_t i = 0; i < nel; ++i)
stt(y, offlin(y, i), ldt(x, offlin(x, i)) * sv);
return RAD_OK;
}
const int64_t TILE = 4096;
const int64_t ntile = (nel + TILE - 1) / TILE;
AVX_PARALLEL_FOR_IF(nel >= AVX_PAR_MIN)
for (int64_t t = 0; t < ntile; ++t) {
const int64_t off = t * TILE;
const int64_t m = (nel - off) < TILE ? (nel - off) : TILE;
float* sbuf = scratch_f32((size_t)TILE);
float* so = scratch_f32_b((size_t)TILE);
const float* v = in_row(x, off, m, sbuf);
const vf sc = vf_set1(sv);
int64_t i = 0;
for (; i + VF_N <= m; i += VF_N)
vf_storeu(so + i, vf_mul(vf_loadu(v + i), sc));
for (; i < m; ++i)
so[i] = v[i] * sv;
out_row(y, off, m, so);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ gather_rows */
/* y[i, :] = x[idx[i], :]. A negative index writes a ZERO ROW -- the padding rule embed_lookup
* follows, and what a step with fewer sampled rows than the buffer's extent leaves behind. An
+9 -8
View File
@@ -84,15 +84,16 @@ int avx_isa_force(int level);
* suffix of every implementation symbol: avx_<name>_sc / _v1 / _v2 / _v3. */
#define AVX_OP_LIST(X) \
/* ---- elementwise and norms */ \
X(rmsnorm) X(rmsnorm_add) X(hc_enter) X(hc_read) \
X(hc_write) X(mtp_enter) X(layernorm) X(add) \
X(grid_embed) \
X(mul) X(silu_mul) X(gelu) X(silu) \
X(sigmoid) X(gather_rows) X(scatter_rows) X(ngram_ids) \
X(rmsnorm) X(rmsnorm_p) X(rmsnorm_add) X(hc_enter) \
X(hc_read) X(hc_write) X(mtp_enter) X(layernorm) \
X(add) X(grid_embed) \
X(mul) X(silu_mul) X(gelu_mul) X(gelu) \
X(silu) X(sigmoid) X(logit_softcap) X(gather_rows) \
X(scatter_rows) X(ngram_ids) \
X(ple_gate) X(ple_conv) X(cast) X(softmax) \
X(scale_rows) X(fill) X(act_mul) X(seg_mean) \
X(mul_weight) X(pool_rows) X(relu) X(clamp) \
X(conv2d) X(conv1d_dw) X(rel_sinusoid) \
X(scale_rows) X(scale) X(fill) X(act_mul) \
X(seg_mean) X(mul_weight) X(pool_rows) X(relu) \
X(clamp) X(conv2d) X(conv1d_dw) X(rel_sinusoid) \
/* ---- quantisation and rotation */ \
X(quant_act_i8) X(had_quant_act_i8) X(quant_act_fp8) X(had_quant_act_fp8) \
X(gram_accum) X(rmsnorm_had_quant_i8) X(gated_had_quant_i8) X(dequant) \
+30
View File
@@ -98,6 +98,36 @@ AVX_KERNEL(rmsnorm) {
return RAD_OK;
}
/* ------------------------------------------------------------------ rmsnorm_p */
/* y = x * rsqrt(mean(x^2) + eps) -- the rmsnorm with no gain. Same one-conversion, two-pass shape
* and same four-accumulator sum of squares as rmsnorm; the only difference is there is no weight
* to widen and no gain to multiply in, because the op has no `w` at all. */
AVX_KERNEL(rmsnorm_p) {
if (!rad_args_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;
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
float* sx = scratch_f32((size_t)n);
float* sy = scratch_f32_b((size_t)n);
const float* v = in_row(x, rowoff(x, r, n), n, sx);
const float ss = row_sumsq(v, n);
const float s = 1.0f / std::sqrt(ss / (float)n + eps);
const vf vs = vf_set1(s);
int64_t i = 0;
for (; i + VF_N <= n; i += VF_N)
vf_storeu(sy + i, vf_mul(vf_loadu(v + i), vs));
for (; i < n; ++i) sy[i] = v[i] * s;
out_row(y, rowoff(y, r, n), n, sy);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ rmsnorm_add */
/* residual_out = x + residual; y = rmsnorm(residual_out) * (w + wadd), with the variance from the
* unrounded sum and the multiply from the narrowed one. */
+22 -2
View File
@@ -131,6 +131,8 @@ static const RadOperandSpec oGridEmbed[] = { INOUT("x"), WGT("table"), OPD("coor
static const RadParamSpec pMnD[] = { P_INT("M"), P_INT("n"), P_STR("dtype") };
static const RadParamSpec pMulWeight[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_INTO("scalar") };
/* `cap` required, for the reason libref's pMnCap states: a softcap without a cap is a different op. */
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 oMulWeight[] = { OPD("x"), WGT("w"), OUT("y") };
static const RadParamSpec pActMul[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_STR("dtype") };
@@ -162,6 +164,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") };
@@ -250,13 +253,15 @@ static const RadParamSpec pRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_
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") };
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`
@@ -476,6 +481,9 @@ static const RadOpSchema kSchemas[] = {
{ "rmsnorm", ARR(pRmsnorm), ARR(oRmsnorm),
"y = x * rsqrt(mean(x^2) + eps) * (w + wadd). The sum of squares is a four-accumulator vector "
"reduction, so it does not sum in libref's order and does not claim to." },
{ "rmsnorm_p", ARR(pLayernorm), ARR(oUnary),
"y = x * rsqrt(mean(x^2) + eps), the rmsnorm with no gain at all. Same four-accumulator sum of "
"squares as rmsnorm; the only difference is there is no weight to widen, so the op has no `w`." },
{ "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 and the multiply reads residual_out back AFTER narrowing -- both are libref's "
@@ -517,10 +525,15 @@ static const RadOpSchema kSchemas[] = {
"y[r] = the mean of x's rows [r*k, r*k + k), rounded to y's dtype, times mult, rounded again." },
{ "silu_mul", ARR(pMnD), ARR(oGateUp),
"silu-gated product over a fused [M, 2n] gate_up: y = silu(gate) * up." },
{ "gelu_mul", ARR(pMnD), ARR(oGateUp),
"gelu_mul over a fused [M, 2n] gate_up: y = gelu_tanh(gate) * up, gate the FIRST half, the tanh "
"form (libref's act_gelu_tanh, std::tanh) rather than the exact-erf gelu." },
{ "gelu", ARR(pMnD), ARR(oUnary), "exact erf gelu." },
{ "silu", ARR(pMnD), ARR(oUnary), "silu." },
{ "sigmoid", ARR(pMnD), ARR(oUnary), "logistic sigmoid." },
{ "fill", ARR(pFill), ARR(oFill), "y = value over [M, n], rounded once to y's dtype (default 0)." },
{ "logit_softcap", ARR(pMnCap), ARR(oUnary), "cap * tanh(x / cap), the final-logit softcap." },
{ "scale", ARR(pMnD), ARR(oScale), "y = x * s, s a [1] weight broadcast over every element." },
{ "ple_gate", ARR(pPleGate), ARR(oPleGate),
"PLE gate: three grouped norms, a dot, a signed sqrt." },
{ "ple_conv", ARR(pPleConv), ARR(oPleConv),
@@ -683,6 +696,8 @@ AVX_OP_LIST(AVX_THUNK_DECL)
static const RadKernelInfo kKernels[] = {
SIMPLE("avx_rmsnorm", "rmsnorm", "norm", "root-mean-square norm with a gain", DT_FLOAT, L(rmsnorm)),
SIMPLE("avx_rmsnorm_p", "rmsnorm_p", "norm", "weightless RMS norm (no gain)", DT_FLOAT,
L(rmsnorm_p)),
SIMPLE("avx_rmsnorm_add", "rmsnorm_add", "norm", "residual add then RMS norm", DT_FLOAT,
L(rmsnorm_add)),
SIMPLE("avx_hc_enter", "hc_enter", "norm", "gated residual entry: hc copies of x", DT_FLOAT,
@@ -719,10 +734,15 @@ SIMPLE("avx_attn_local_rel", "attn_local_rel", "attn",
L(attn_local_rel)),
SIMPLE("avx_silu_mul", "silu_mul", "elem", "silu-gated product over a fused gate_up", DT_FLOAT,
L(silu_mul)),
SIMPLE("avx_gelu_mul", "gelu_mul", "elem", "gelu_tanh-gated product over a fused gate_up", DT_FLOAT,
L(gelu_mul)),
SIMPLE("avx_gelu", "gelu", "elem", "exact erf gelu", DT_FLOAT, L(gelu)),
SIMPLE("avx_silu", "silu", "elem", "silu", DT_FLOAT, L(silu)),
SIMPLE("avx_sigmoid", "sigmoid", "elem", "logistic sigmoid", DT_FLOAT, L(sigmoid)),
SIMPLE("avx_fill", "fill", "elem", "constant fill", DT_FLOAT, L(fill)),
SIMPLE("avx_logit_softcap", "logit_softcap", "elem", "final-logit softcap: cap * tanh(x / cap)",
DT_FLOAT, L(logit_softcap)),
SIMPLE("avx_scale", "scale", "elem", "a [1] weight broadcast over every element", DT_FLOAT, L(scale)),
SIMPLE("avx_gather_rows", "gather_rows", "elem", "y[i,:] = x[idx[i],:]", DT_ANY, L(gather_rows)),
SIMPLE("avx_scatter_rows", "scatter_rows", "elem", "x[idx[i],:] = v[i,:]", DT_ANY,
L(scatter_rows)),