Archived
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:
1 parent
73620ef00e
commit
c37ce73d72
20 files changed
+2260
-51
No files matched your search
@@ -5,3 +5,4 @@ compile_commands.json
|
||||
*.rad
|
||||
/sync-jarvis.sh
|
||||
__pycache__/
|
||||
.cache/
|
||||
@@ -1858,6 +1858,9 @@ idle scrubs, routing and issue dumps), `RADIANCE_OP_ORACLE*` (named ops checked
|
||||
the operands the model issued; `scripts/oracle.sh` drives it) and `RADIANCE_OP_REPEAT` (named ops
|
||||
run a second time on the same inputs, to ask whether a kernel is a function of them). They are
|
||||
instruments, not features; grep `getenv` if you need one, and read the comment beside it first.
|
||||
`libr4d` keeps the same culture under `R4D_DIAG` (master switch for selection/store/hidden-state
|
||||
traces), `R4D_VERIFY_ATTN` and `R4D_VERIFY_OFF` (device kernels recomputed on the host and diffed),
|
||||
and `RADIANCE_TRACE_RESID` (an arch-side residual ring); all default off.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+43
-2
@@ -159,6 +159,7 @@ adding a kernel plugin; "refused at load" names one op and leaves you to find th
|
||||
| op | params | operands |
|
||||
|---|---|---|
|
||||
| `rmsnorm` | `M`(range) `n` `eps`:f64 `dtype` `wadd`:f64/opt `mult`:f64/opt | `x`, `w`w? → `y` (no gain operand: a gain of one) |
|
||||
| `rmsnorm_p` | `M`(range) `n` `eps`:f64 `dtype` | `x` → `y` |
|
||||
| `rmsnorm_add` | `M`(range) `n` `eps`:f64 `dtype` `wadd`:f64/opt | `x`, `residual`, `w`w → `y`, `residual_out` |
|
||||
| `hc_enter` | `M`(range) `n` `hc` `dtype` | `x` → `h` |
|
||||
| `hc_read` | `M`(range) `n` `hc` `lowrank` `eps`:f64 `dtype` `wadd`:f64/opt `inject`/opt `group`/opt `rotate`/opt `mix`/opt | `h`, `w`w, `mix_down`w, `mix_up`w, `inject_w`w? → `x`, `inj`?, `q`?, `scale`?, `rq`?, `rscale`? |
|
||||
@@ -177,10 +178,13 @@ adding a kernel plugin; "refused at load" names one op and leaves you to find th
|
||||
| `conv2d` | `M`(range) `width` `cin` `cout` `kh` `kw` `stride` `pad` `cu_div`/opt `valid_stride`/opt `dtype` | `x`, `w`w, `cu_seqlens`, `valid`? → `y` |
|
||||
| `conv1d_dw` | `M`(range) `n` `k` `cu_div`/opt `dtype` | `x`, `w`w, `cu_seqlens` → `y` |
|
||||
| `rel_sinusoid` | `M`(range) `n` `max_timescale`:f64/opt `dtype` | → `y` |
|
||||
| `gelu_mul` | `M`(range) `n` `dtype` | `gate_up` → `y` (splits `[M,2n]` into gelu·up, tanh approx) |
|
||||
| `gelu` / `silu` | `M`(range) `n` `dtype` | `x` → `y` |
|
||||
| `cast` | `M`(range) `n` `from` `to` | `x` → `y` |
|
||||
| `softmax` | `M`(range) `n` `dtype` | `x` → `y` |
|
||||
| `sigmoid` | `M`(range) `n` `dtype` | `x` → `y` |
|
||||
| `logit_softcap` | `M`(range) `n` `cap`:f64 `dtype` | `x` → `y` |
|
||||
| `scale` | `M`(range) `n` `dtype` | `x`, `s`w → `y` |
|
||||
| `silu` | `M` `n` `dtype` | `x` → `y` |
|
||||
| `fill` | `M`(range) `n` `dtype` `value`:f64/opt | → `y` |
|
||||
|
||||
@@ -190,6 +194,15 @@ names one op.
|
||||
`rmsnorm_add` exists because the residual add and the next norm are one pass in every real
|
||||
implementation. A plugin asks for it first and falls back to `add` + `rmsnorm` (`spec.md` §2.3).
|
||||
|
||||
`rmsnorm_p` is `rmsnorm` with the gain removed: `x * rsqrt(mean(x^2) + eps)` and no `w` at all.
|
||||
Gemma's attention normalises the value with a bare RMS (a weightless norm) while normalising the
|
||||
key with the `k_norm` gain in the same layer, and there is no checkpoint plane to feed the value
|
||||
through a gain -- `rmsnorm` would need a phantom all-zero weight to say the same thing.
|
||||
|
||||
`gelu_mul` is `silu_mul` with the tanh GELU instead of silu -- Gemma's gated FFN is trained with
|
||||
`gelu_pytorch_tanh`, and gated feed-forwards ask for the tanh form rather than the unary `gelu`'s
|
||||
exact erf one. Both split the fused `gate_up` with the gate in the FIRST half.
|
||||
|
||||
`hc_read` / `hc_write` are the GATED RESIDUAL pair, which is what a hyper-connection model has
|
||||
instead of a pre-norm and a residual add. The stream is `hc` times the model width and every block
|
||||
reads a mix of the `hc` sub-streams and writes back into all of them, both gated by data:
|
||||
@@ -429,8 +442,8 @@ that folds dequantisation into its epilogue still receives them.
|
||||
| `attn_dense` | `M`(range) `head_dim` `gqa` `causal` `dtype` `scale`:f64/opt `max_seqlen`/opt `window`/opt | `q`, `k`, `v`, `cu_seqlens` → `out` |
|
||||
| `attn_local_rel` | `M`(range) `head_dim` `n_head` `left` `right` `softcap`:f64 `cu_div`/opt `dtype` | `q`, `k`, `v`, `relk`, `pds`w, `cu_seqlens` → `out` |
|
||||
| `kv_store` | `M`(range) `head_dim` `n_head_kv` `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `k`, `v`, `slot_mapping`, `kv_cache`:inout |
|
||||
| `rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `scale`:f64 `mode` `rotary_dim`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt | `qkv`:inout, `positions` |
|
||||
| `rope_table` | `M`(range) `rot` `theta`:f64 `scale`:f64 `dtype` `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt | `positions` → `cos_sin` |
|
||||
| `rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `scale`:f64 `mode` `rotary_dim`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `ladder`/opt | `qkv`:inout, `positions` |
|
||||
| `rope_table` | `M`(range) `rot` `theta`:f64 `scale`:f64 `dtype` `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `head_dim`/opt `ladder`/opt | `positions` → `cos_sin` |
|
||||
| `qk_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `wadd`:f64/opt `v_norm`/opt `sections`/opt `comps`/opt | `qkv`:inout, `positions`, `q_w`w, `k_w`w |
|
||||
|
||||
**`attn_local_rel`** is Gemma 4's audio attention: local, with a relative-position term and a
|
||||
@@ -484,6 +497,16 @@ restarts the frequency ladder in each, `theta^(-2j / (2 s_c))` for the run's `j`
|
||||
vision tower's 2-D rotary over row and column). With `[M]` positions every component is that one
|
||||
position, so `mrope` and `imrope` over a text batch are `neox` exactly.
|
||||
|
||||
**`ladder` names the width the base frequency ladder is measured in.** Absent, or `rotary`, the
|
||||
exponent divides by `rotary_dim`: a partial rotary is a complete rotation of its own width, and
|
||||
every existing model is bit-for-bit unchanged. `head` divides by `head_dim` instead -- the
|
||||
**proportional** variant, where the `rotary_dim / 2` frequencies are a prefix of the full-width
|
||||
table rather than a table rescaled to the rotated width: at `head_dim 512, rotary_dim 128`,
|
||||
frequency `i = 1` wants `theta^(-1 / 256)`, not `theta^(-1 / 64)`. Only the base ladder moves
|
||||
(`axial` keeps its per-section ladders), and the tail of the head past `rotary_dim` is untouched
|
||||
either way. `rope_table` carries a `head_dim` param for the same reason: its angles must stay
|
||||
`rope`'s to the last operation.
|
||||
|
||||
**`gemm_nt_bias`'s epilogue** is a linear layer's: the biased product rounded to `y`'s dtype, then
|
||||
`act` of it (`none`, `gelu` exact, `gelu_tanh`) rounded, then `res` added and rounded -- each step
|
||||
what a separate tensor would hold, so the fused form is the unfused chain to the bit.
|
||||
@@ -992,6 +1015,24 @@ holds only where the rank holds the WHOLE vocabulary -- `world_size` 1, not mere
|
||||
on most steps, so a check keyed on the offset alone refuses correct calls. Bounding ids is the
|
||||
caller's, and the tokeniser and the sampler both already are.
|
||||
|
||||
### `embed_lookup`'s runtime `mult`
|
||||
|
||||
`mult` (optional f64, default 1) multiplies the rows that are FOUND: `x[m] = wte[id] * mult`.
|
||||
A missed row — negative padding or another rank's token — writes zero, not zero times the scale.
|
||||
Absent it is the plain gather the op has always been, which is what keeps every other caller in
|
||||
the tree bit-identical.
|
||||
|
||||
**Not `wscale`.** `wscale` is the scale `embed_lookup_q`'s LAYOUT quantises with — a property of
|
||||
the stored table, read back as the dequant. `mult` is applied AFTER the gather, to the rows that
|
||||
come out of it; `embed_lookup_q` takes no `mult` at all, because its rows arrive already scaled by
|
||||
the table's own dequant.
|
||||
|
||||
**Why it exists**: Gemma 4 scales its embedding by `sqrt(n_embd)` at the lookup — the reference's
|
||||
`build_inp_embd` and HF's `Gemma4TextScaledWordEmbedding` both do it there, and the checkpoint's
|
||||
table is plain. Baking it into the table instead would untie it from the head, which the model
|
||||
ties and which the checkpoint stores twice; scaling the lookup leaves the table and the head the
|
||||
same tensor the weights loader already maps.
|
||||
|
||||
### `embed_lookup_q`, the n-gram gather
|
||||
|
||||
**A gather from a table quantised with ONE scale for all of it**: `x[m] = wte[id] * scale[0]`.
|
||||
|
||||
+19
-2
@@ -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" }) {
|
||||
|
||||
@@ -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
@@ -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) \
|
||||
|
||||
@@ -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
@@ -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)),
|
||||
|
||||
+35
-3
@@ -108,6 +108,24 @@ int r4d_attn_h128_gqa4_have_prefill(void);
|
||||
// Bytes of split-KV partial buffer one decode launch of this shape needs. Independent of the cache
|
||||
// dtype: the partials are f16 either way.
|
||||
long r4d_attn_decode_h256_gqa6_scratch_bytes(const R4DArgs* a);
|
||||
// The Gemma 4 dense sliding-window geometry: head_dim 256, 2 queries per KV head, sliding window.
|
||||
// Both bands: the decode band (q_len*gqa <= 64, i.e. q_len <= 32) and the windowed prefill band
|
||||
// (a prefill-length query, WIN on). The prefill leg is the same r4d_attn_prefill_kernel the
|
||||
// h256/gqa6 and h512/gqa8 dispatches instantiate, with the window bit turned on.
|
||||
int r4d_attn_prefill_h256_gqa2_fp8kv (const R4DArgs* a, hipStream_t stream);
|
||||
int r4d_attn_prefill_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t stream);
|
||||
int r4d_attn_decode_h256_gqa2_fp8kv (const R4DArgs* a, hipStream_t stream);
|
||||
int r4d_attn_decode_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t stream);
|
||||
long r4d_attn_decode_h256_gqa2_scratch_bytes(const R4DArgs* a);
|
||||
// The Gemma 4 dense global geometry: head_dim 512, 8 queries per KV head, full attention (window 0).
|
||||
// The one head_dim the library had not compiled -- a stand-alone instantiation, not the gqa8
|
||||
// parameterised body (whose prefill tile of 48 does not fit 512-channel tiles in LDS). Both legs
|
||||
// spill ~384 VGPRs at this head; a 3b tuning question, not a 3a one.
|
||||
int r4d_attn_prefill_h512_gqa8_fp8kv (const R4DArgs* a, hipStream_t stream);
|
||||
int r4d_attn_prefill_h512_gqa8_bf16kv(const R4DArgs* a, hipStream_t stream);
|
||||
int r4d_attn_decode_h512_gqa8_fp8kv (const R4DArgs* a, hipStream_t stream);
|
||||
int r4d_attn_decode_h512_gqa8_bf16kv (const R4DArgs* a, hipStream_t stream);
|
||||
long r4d_attn_decode_h512_gqa8_scratch_bytes(const R4DArgs* a);
|
||||
// The geometry the attention kernels above are compiled for, so a caller can test a model against
|
||||
// it instead of discovering the mismatch at the first launch.
|
||||
void r4d_attn_dims(int* head_dim, int* gqa, int* block_size, int* max_decode_rows);
|
||||
@@ -892,6 +910,11 @@ void r4d_dequant_w4_bf16(long wq, long ws, long out, int N, int K, int group, in
|
||||
// whole table, an unsliced lookup.
|
||||
int r4d_embed_lookup_bf16(long tok, long wte, long x, int M, int n_embd, int n_vocab,
|
||||
int vocab_off, int x_ld, long stream);
|
||||
// The same lookup with a RUNTIME gather scale on the rows that are found (x = table[id] *
|
||||
// scale); 1.0 is the plain copy, and a missed row still writes zero rather than zero * scale.
|
||||
// Gemma 4's embedding is scaled by sqrt(n_embd) at the lookup, not baked into the table.
|
||||
int r4d_embed_lookup_bf16_scaled(long tok, long wte, long x, int M, int n_embd, int n_vocab,
|
||||
int vocab_off, int x_ld, float scale, long stream);
|
||||
int r4d_gather_rows_bf16(long x, long idx, long y, int M, int n, int src_rows,
|
||||
int x_ld, int y_ld, long stream);
|
||||
// y = x * rsqrt(mean(x^2) + eps) * (w + wadd). `wadd` is GemmaRMSNorm's `1 +`, added in f32 after
|
||||
@@ -900,6 +923,9 @@ int r4d_gather_rows_bf16(long x, long idx, long y, int M, int n, int src_rows,
|
||||
// is -- or bf16. The activation either side is bf16 in both cases.
|
||||
int r4d_rmsnorm_bf16(long x, long w, long y, int M, int n, float eps, float wadd, int w_f32,
|
||||
int x_ld, int y_ld, long stream);
|
||||
// y = x * rsqrt(mean(x^2) + eps). The weightless RMS: the same two-pass sum of squares as rmsnorm
|
||||
// with the gain multiply dropped, gemma's bare value normalisation.
|
||||
int r4d_rmsnorm_p_bf16(long x, long y, int M, int n, float eps, int x_ld, int y_ld, long stream);
|
||||
// `op` 0 sums, 1 multiplies. A `b_ld` of 0 is the ONE broadcast form: every row reads the same n
|
||||
// elements, which is what makes a bias add this op rather than a second one.
|
||||
int r4d_binary_bf16(long a, long b, long y, int M, int n, int op,
|
||||
@@ -909,6 +935,9 @@ int r4d_fill_bf16(long y, int M, int n, int y_ld, float value, long stream);
|
||||
// y[.., i] = silu(gu[.., i]) * gu[.., n + i]. The GATE IS THE FIRST HALF -- the order rad-convert
|
||||
// fuses gate_proj and up_proj in.
|
||||
int r4d_silu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y_ld, long stream);
|
||||
// y[.., i] = gelu_tanh(gu[.., i]) * gu[.., n + i]. The GATE IS THE FIRST HALF, the tanh
|
||||
// approximation (gemma's gelu_pytorch_tanh), not the erf one.
|
||||
int r4d_gelu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y_ld, long stream);
|
||||
// In place over `n_rope_heads` consecutive heads of a row; anything after them (the V heads of a
|
||||
// fused projection) is untouched. `gptj` 0 pairs i with i + rot/2 (NeoX, and mrope, which is the
|
||||
// same arithmetic when every position component is equal); 1 pairs 2i with 2i+1. `rot` may be less
|
||||
@@ -918,9 +947,12 @@ int r4d_rope_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads, int
|
||||
float theta, float rscale, int row_pitch, long stream);
|
||||
// The multi-component rotary (docs/OPS.md, `rope`): `mode` 2 mrope, 3 imrope, 4 axial over
|
||||
// `sec[0..n_sec)`, component c of token m at pos[c * plane + m]. plane 0 is the call above.
|
||||
int r4d_rope_mc_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads, int rot, int gptj,
|
||||
float theta, float rscale, int row_pitch, int mode, const int* sec, int n_sec,
|
||||
int plane, long stream);
|
||||
// `den` is the width the base ladder's exponent divides by: `rot` (the `rotary` ladder, the
|
||||
// default) or `head_dim` (the `head` ladder, the proportional variant). The `rope` row resolves it
|
||||
// from its `ladder` param; the plain form above passes `rot`.
|
||||
int r4d_rope_mc_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads, int rot, int den,
|
||||
int gptj, float theta, float rscale, int row_pitch, int mode, const int* sec,
|
||||
int n_sec, int plane, long stream);
|
||||
// C[M,N] f32 = A[M,K] bf16 @ W[N,K]^T bf16, f32 accumulate. THE OUTPUT IS f32 and that is why this
|
||||
// is not r4d_gemm_bf16_nt_m16 under another name: the engine declares its logits buffer f32,
|
||||
// because a bf16 logit has eight bits of mantissa and a nucleus cut compares neighbouring
|
||||
|
||||
+787
-19
@@ -49,9 +49,360 @@
|
||||
#include "r4d_fp8_wmma.h"
|
||||
|
||||
#include <cstdlib>
|
||||
#include <vector>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
|
||||
// ================================================================== attn_paged verify
|
||||
// Copy n bytes from a (possibly host-page-table-unmapped) device VA into a regular allocation, via
|
||||
// the DEVICE page table (mapped) -- a host DtoH copy on such a VA faults. Global scope so the
|
||||
// verify (which reads the KV cache) can use it. Utility for the env-gated verify path only.
|
||||
__global__ void r4d_copy8_kernel(const uint8_t* __restrict__ src, uint8_t* __restrict__ dst, size_t n) {
|
||||
for (size_t i = blockIdx.x * (size_t)256 + threadIdx.x; i < n;
|
||||
i += (size_t)gridDim.x * 256)
|
||||
dst[i] = src[i];
|
||||
}
|
||||
// DEBUG (env-gated, R4D_VERIFY_OFF): run the paged-attention kernel, then recompute the SAME
|
||||
// attention on the host (the libref two-pass-softmax formula, f32) from the bf16/fp8 q and the
|
||||
// paged k/v the kernel read, and report the max deviation. A deviation well above the bf16
|
||||
// rounding (~1e-3) means the device kernel is wrong for the real (paged, ragged) inputs. GLOBAL
|
||||
// scope (not the anonymous namespace below) so the attention wrappers -- a different translation
|
||||
// unit -- can call it. Only the first few of each band (decode / prefill) are checked.
|
||||
static float attn_verify_bf16(uint16_t b) {
|
||||
uint32_t u = (uint32_t)b << 16;
|
||||
float f;
|
||||
std::memcpy(&f, &u, 4);
|
||||
return f;
|
||||
}
|
||||
static float attn_verify_e4m3(uint8_t b) {
|
||||
const float sign = (b & 0x80u) ? -1.0f : 1.0f;
|
||||
const uint32_t ex = (uint32_t)(b >> 3) & 0x0Fu, mn = (uint32_t)b & 0x07u;
|
||||
if (ex == 0) return sign * (float)mn * (1.0f / 512.0f);
|
||||
return sign * (1.0f + (float)mn / 8.0f) * std::ldexp(1.0f, (int)ex - 7);
|
||||
}
|
||||
int g_attn_decode_verify_n = 0;
|
||||
int g_attn_prefill_verify_n = 0;
|
||||
|
||||
/* Diagnostics master switch (degenerate-output investigation, 2026-10-08): OFF by default. Set
|
||||
* R4D_DIAG=1 to arm the env-gated probes; the probe families each keep their own env:
|
||||
* R4D_VERIFY_ATTN=1 -> verify_attn_paged (KV store + attention recompute, maxd);
|
||||
* the [KVCHK]/[HIDD]/[LOGITS] store/GEMM probes and [SAMPIN] (sampler input) run their capped
|
||||
* dumps under R4D_DIAG alone. Cleared 2026-10: KV store byte-exact, attention maxd ~0.04,
|
||||
* hidden state rich, logits sharp, softcap applied, sampler argmax correct. */
|
||||
int r4d_diag_on() {
|
||||
static const int v = std::getenv("R4D_DIAG") ? 1 : 0;
|
||||
return v;
|
||||
}
|
||||
|
||||
void verify_attn_paged(const R4DArgs* r, long stream, int kv_is_fp8, int is_decode) {
|
||||
static int on = -1;
|
||||
if (on < 0) { const char* e = std::getenv("R4D_VERIFY_ATTN"); on = (e && *e) ? 1 : 0; }
|
||||
if (!on) return;
|
||||
int* cnt = is_decode ? &g_attn_decode_verify_n : &g_attn_prefill_verify_n;
|
||||
const int cap = is_decode ? 10 : 4; /* decode 10 covers the first global (h512) layer too */
|
||||
if (*cnt >= cap) return;
|
||||
(*cnt)++;
|
||||
/* SYNC BEFORE ANY DtoH COPY (see verify_rmsnorm_p): the q / kv / out buffers are the products
|
||||
* of earlier ops on `stream`, and a subsequent op reuses the workspace. The DtoH copies below
|
||||
* run on the DEFAULT stream (concurrent with `stream`), so without this sync they can read a
|
||||
* buffer while a later op overwrites it. Syncing `stream` first guarantees the producers + this
|
||||
* kernel have completed and the consumer has not yet been launched. */
|
||||
hipStreamSynchronize((hipStream_t)stream);
|
||||
|
||||
const int ew = kv_is_fp8 ? 1 : 2;
|
||||
const int num_seqs = r->num_seqs, q_len = r->q_len, q_heads = r->q_heads,
|
||||
kv_heads = r->kv_heads, hd = r->head_dim, bs = r->block_size,
|
||||
max_blocks = r->max_blocks;
|
||||
const bool ragged = (r->cu_q != nullptr);
|
||||
const int total_q = ragged ? r->total_q : num_seqs * q_len;
|
||||
const int gqa = kv_heads > 0 ? q_heads / kv_heads : 1;
|
||||
fprintf(stderr, "[VERIFY attn_%s] START seqs=%d q_len=%d tot_q=%d qh=%d kvh=%d hd=%d bs=%d mb=%d kvs=%ld kvh_s=%ld\n",
|
||||
is_decode ? "decode" : "prefill", num_seqs, q_len, total_q,
|
||||
q_heads, kv_heads, hd, bs, max_blocks,
|
||||
(long)r->kv_block_stride, (long)r->kv_head_stride);
|
||||
|
||||
std::vector<int> bt_h((size_t)num_seqs * (size_t)max_blocks);
|
||||
hipMemcpy(bt_h.data(), r->block_table, bt_h.size() * 4, hipMemcpyDeviceToHost);
|
||||
std::vector<int> su_h(num_seqs);
|
||||
hipMemcpy(su_h.data(), r->seqused_k, su_h.size() * 4, hipMemcpyDeviceToHost);
|
||||
std::vector<int> cu_h(num_seqs + 1);
|
||||
if (ragged) hipMemcpy(cu_h.data(), r->cu_q, cu_h.size() * 4, hipMemcpyDeviceToHost);
|
||||
else for (int s = 0; s <= num_seqs; ++s) cu_h[s] = s * q_len;
|
||||
std::vector<float> kds_h(num_seqs * kv_heads), vds_h(num_seqs * kv_heads);
|
||||
if (r->k_descale) hipMemcpy(kds_h.data(), r->k_descale, kds_h.size() * 4, hipMemcpyDeviceToHost);
|
||||
if (r->v_descale) hipMemcpy(vds_h.data(), r->v_descale, vds_h.size() * 4, hipMemcpyDeviceToHost);
|
||||
fprintf(stderr, "[VERIFY attn_%s] P1 small-copies done su0=%d\n", is_decode ? "decode" : "prefill", su_h[0]);
|
||||
|
||||
/* Only the blocks the block tables actually reference are read, so copy just those (a full
|
||||
* cache can be gigabytes; a decode step touches one). */
|
||||
std::vector<int> used;
|
||||
for (int s = 0; s < num_seqs; ++s) {
|
||||
int nb = (su_h[s] + bs - 1) / bs;
|
||||
if (nb > max_blocks) nb = max_blocks;
|
||||
for (int b = 0; b < nb; ++b) {
|
||||
int blk = bt_h[(size_t)s * max_blocks + b];
|
||||
if (blk < 0) continue;
|
||||
bool seen = false;
|
||||
for (int u : used) if (u == blk) { seen = true; break; }
|
||||
if (!seen) used.push_back(blk);
|
||||
}
|
||||
}
|
||||
fprintf(stderr, "[VERIFY attn_%s] P2 used_n=%zu used0=%d\n", is_decode ? "decode" : "prefill", used.size(), used.empty() ? -1 : used[0]);
|
||||
/* The cache DtoH copy faults (host page table unmapped). Read the used blocks via a DEVICE copy
|
||||
* kernel (the device page table IS mapped -- the store kernel wrote the cache fine) into a
|
||||
* regular allocation, then DtoH that. TEMP (degenerate-output investigation). */
|
||||
const size_t per_bytes = (size_t)r->kv_block_stride * (size_t)ew;
|
||||
std::vector<uint8_t> kv_h(used.size() * per_bytes);
|
||||
{
|
||||
uint8_t* reg = nullptr;
|
||||
if (hipMalloc(®, kv_h.size()) == hipSuccess && reg) {
|
||||
for (size_t i = 0; i < used.size(); ++i)
|
||||
r4d_copy8_kernel<<<(unsigned)((per_bytes + 255) / 256), 256>>>(
|
||||
(const uint8_t*)r->kv + (size_t)used[i] * per_bytes, reg + i * per_bytes, per_bytes);
|
||||
hipDeviceSynchronize();
|
||||
hipMemcpy(kv_h.data(), reg, kv_h.size(), hipMemcpyDeviceToHost);
|
||||
hipFree(reg);
|
||||
}
|
||||
}
|
||||
fprintf(stderr, "[VERIFY attn_%s] P3 kv_h done bytes=%zu\n", is_decode ? "decode" : "prefill", kv_h.size());
|
||||
auto blkidx = [&](int blk) -> int {
|
||||
for (size_t i = 0; i < used.size(); ++i) if (used[i] == blk) return (int)i;
|
||||
return -1;
|
||||
};
|
||||
|
||||
std::vector<uint16_t> qh((size_t)total_q * (size_t)q_heads * (size_t)hd);
|
||||
hipMemcpy(qh.data(), r->q, qh.size() * 2, hipMemcpyDeviceToHost);
|
||||
fprintf(stderr, "[VERIFY attn_%s] P4 qh done bytes=%zu\n", is_decode ? "decode" : "prefill", qh.size() * 2);
|
||||
std::vector<uint16_t> oh((size_t)total_q * (size_t)q_heads * (size_t)hd);
|
||||
hipMemcpy(oh.data(), r->out, oh.size() * 2, hipMemcpyDeviceToHost);
|
||||
fprintf(stderr, "[VERIFY attn_%s] P5 oh done bytes=%zu\n", is_decode ? "decode" : "prefill", oh.size() * 2);
|
||||
|
||||
float maxq = 0.0f;
|
||||
for (size_t i = 0; i < qh.size(); ++i) { float a = fabsf(attn_verify_bf16(qh[i])); if (a > maxq) maxq = a; }
|
||||
|
||||
/* Cap the host recompute so a large prefill (total_q * ctx big) cannot stall the server; the
|
||||
* decode band (total_q 1) is always well under it. */
|
||||
int ctx_max = 0;
|
||||
for (int s = 0; s < num_seqs; ++s) if (su_h[s] > ctx_max) ctx_max = su_h[s];
|
||||
const long long work = (long long)total_q * (long long)q_heads * (long long)ctx_max * (long long)hd;
|
||||
if (work > 200000000LL) {
|
||||
fprintf(stderr, "[VERIFY attn_%s] SKIPPED (work=%lld>cap) seqs=%d q_len=%d tot_q=%d qh=%d kvh=%d hd=%d win=%d scale=%.3g maxq=%.6g\n",
|
||||
is_decode ? "decode" : "prefill", work, num_seqs, q_len, total_q, q_heads, kv_heads,
|
||||
hd, r->window, r->scale, maxq);
|
||||
return;
|
||||
}
|
||||
|
||||
float maxd = 0.0f; int bad = 0, ntot = 0;
|
||||
for (int t = 0; t < total_q; ++t) {
|
||||
int seq = 0, i = 0, ctx = 0, qlen_seq = 0;
|
||||
if (ragged) {
|
||||
for (int s = 0; s < num_seqs; ++s)
|
||||
if (t >= cu_h[s] && t < cu_h[s + 1]) { seq = s; break; }
|
||||
i = t - cu_h[seq];
|
||||
ctx = su_h[seq];
|
||||
qlen_seq = cu_h[seq + 1] - cu_h[seq];
|
||||
} else {
|
||||
seq = t / q_len;
|
||||
i = t % q_len;
|
||||
ctx = su_h[seq];
|
||||
qlen_seq = q_len;
|
||||
}
|
||||
const int pos = ctx - qlen_seq + i;
|
||||
for (int h = 0; h < q_heads; ++h) {
|
||||
const int kh = h / gqa;
|
||||
const float kds = r->k_descale ? kds_h[seq * kv_heads + kh] : 1.0f;
|
||||
const float vds = r->v_descale ? vds_h[seq * kv_heads + kh] : 1.0f;
|
||||
auto visible = [&](int j) -> bool {
|
||||
if (r->causal) {
|
||||
if (j > pos) return false;
|
||||
if (r->window > 0 && (pos - j) >= r->window) return false;
|
||||
} else {
|
||||
if (j >= ctx) return false;
|
||||
if (r->window > 0) { int d = pos - j; if (d >= r->window || d <= -r->window) return false; }
|
||||
}
|
||||
return true;
|
||||
};
|
||||
auto kdot = [&](int j, int idx) -> float {
|
||||
float dot = 0.0f;
|
||||
for (int d = 0; d < hd; ++d) {
|
||||
const long off = (long)idx * r->kv_block_stride + (long)kh * r->kv_head_stride
|
||||
+ (long)(j % bs) * 2 * hd + d;
|
||||
const uint8_t* p = kv_h.data() + off * ew;
|
||||
float k = kv_is_fp8 ? attn_verify_e4m3(p[0]) : attn_verify_bf16(*(const uint16_t*)p);
|
||||
dot += attn_verify_bf16(qh[(size_t)t * q_heads * hd + (size_t)h * hd + d]) * (k * kds);
|
||||
}
|
||||
return dot * r->scale;
|
||||
};
|
||||
float mx = -INFINITY;
|
||||
for (int j = 0; j < ctx; ++j) {
|
||||
if (!visible(j)) continue;
|
||||
if (j / bs >= max_blocks) break;
|
||||
int blk = bt_h[(size_t)seq * max_blocks + (j / bs)];
|
||||
if (blk < 0) continue;
|
||||
int idx = blkidx(blk);
|
||||
if (idx < 0) continue;
|
||||
float dot = kdot(j, idx);
|
||||
if (dot > mx) mx = dot;
|
||||
}
|
||||
std::vector<float> ref(hd, 0.0f);
|
||||
if (mx != -INFINITY) {
|
||||
float sum = 0.0f;
|
||||
for (int j = 0; j < ctx; ++j) {
|
||||
if (!visible(j)) continue;
|
||||
if (j / bs >= max_blocks) break;
|
||||
int blk = bt_h[(size_t)seq * max_blocks + (j / bs)];
|
||||
if (blk < 0) continue;
|
||||
int idx = blkidx(blk);
|
||||
if (idx < 0) continue;
|
||||
float dot = kdot(j, idx);
|
||||
const float w = std::exp(dot - mx);
|
||||
sum += w;
|
||||
for (int d = 0; d < hd; ++d) {
|
||||
const long off = (long)idx * r->kv_block_stride + (long)kh * r->kv_head_stride
|
||||
+ (long)(j % bs) * 2 * hd + hd + d;
|
||||
const uint8_t* p = kv_h.data() + off * ew;
|
||||
float v = kv_is_fp8 ? attn_verify_e4m3(p[0]) : attn_verify_bf16(*(const uint16_t*)p);
|
||||
ref[d] += w * (v * vds);
|
||||
}
|
||||
}
|
||||
const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
|
||||
for (int d = 0; d < hd; ++d) ref[d] *= inv;
|
||||
}
|
||||
for (int d = 0; d < hd; ++d) {
|
||||
float dv = fabsf(attn_verify_bf16(oh[(size_t)t * q_heads * hd + (size_t)h * hd + d]) - ref[d]);
|
||||
if (dv > maxd) maxd = dv;
|
||||
if (dv > 1e-2f) bad++;
|
||||
ntot++;
|
||||
}
|
||||
}
|
||||
}
|
||||
fprintf(stderr, "[VERIFY attn_%s] seqs=%d q_len=%d tot_q=%d qh=%d kvh=%d hd=%d bs=%d mb=%d win=%d caus=%d scale=%.3g maxd=%.6g bad=%d/%d maxq=%.6g\n",
|
||||
is_decode ? "decode" : "prefill", num_seqs, q_len, total_q, q_heads, kv_heads, hd, bs,
|
||||
max_blocks, r->window, r->causal, r->scale, maxd, bad, ntot, maxq);
|
||||
if (*cnt == 1) {
|
||||
fprintf(stderr, " q :"); for (int d = 0; d < 8 && d < hd; ++d) fprintf(stderr, " %g", attn_verify_bf16(qh[d]));
|
||||
fprintf(stderr, " out:"); for (int d = 0; d < 8 && d < hd; ++d) fprintf(stderr, " %g", attn_verify_bf16(oh[d]));
|
||||
fprintf(stderr, "\n");
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// DEBUG (env-gated, R4D_VERIFY_OFF=1): run the device kernel, then recompute the same op on the
|
||||
// host (the libref formula, f32) from the bf16 input the kernel read, and report the max deviation.
|
||||
// A deviation well above the bf16 rounding (~1e-3) means the device kernel is wrong for the real
|
||||
// shape; a deviation at the bf16 rounding means it is correct. Only the first few calls are
|
||||
// checked. OFF by default: the DtoH syncs inside perturb stream timing, which the KV-isolation
|
||||
// investigation cannot afford.
|
||||
int r4d_verify_on() {
|
||||
static int on = -1;
|
||||
if (on < 0) { const char* e = std::getenv("R4D_VERIFY_OFF"); on = (e && *e) ? 1 : 0; }
|
||||
return on;
|
||||
}
|
||||
int g_rmsnorm_p_verify_n = 0;
|
||||
int g_gelu_mul_verify_n = 0;
|
||||
|
||||
// The CORRECT bf16 -> f32 decode: the 16-bit pattern is the high half of the f32 bits. (Casting a
|
||||
// uint16_t to float gives the integer value of the pattern, 0..65535, which is NOT the value.)
|
||||
static float bf16_to_f32(uint16_t b) {
|
||||
uint32_t u = (uint32_t)b << 16;
|
||||
float f;
|
||||
std::memcpy(&f, &u, 4);
|
||||
return f;
|
||||
}
|
||||
|
||||
void verify_rmsnorm_p(const uint16_t* x, const uint16_t* y, int M, int n, int x_ld, int y_ld,
|
||||
float eps, long stream) {
|
||||
if (!r4d_verify_on() || g_rmsnorm_p_verify_n >= 4) return;
|
||||
g_rmsnorm_p_verify_n++;
|
||||
/* SYNC BEFORE ANY DtoH COPY: the input `x` is the output of an earlier GEMM on `stream`, and a
|
||||
* subsequent GEMM (launched after this verify returns) reuses the workspace and overwrites it.
|
||||
* The DtoH copy below runs on the DEFAULT stream (concurrent with `stream`), so without this
|
||||
* sync it can read `x` while the next GEMM is overwriting it -- a race that produced false
|
||||
* O(1e37) "garbage" readings. Syncing `stream` first guarantees the producer GEMM + this kernel
|
||||
* have completed and the consumer GEMM has not yet been launched. */
|
||||
hipStreamSynchronize((hipStream_t)stream);
|
||||
std::vector<uint16_t> xh((size_t)M * (size_t)x_ld);
|
||||
hipMemcpy(xh.data(), x, (size_t)M * (size_t)x_ld * 2, hipMemcpyDeviceToHost);
|
||||
std::vector<float> xf((size_t)M * (size_t)x_ld);
|
||||
for (size_t i = 0; i < xf.size(); ++i) xf[i] = bf16_to_f32(xh[i]);
|
||||
std::vector<float> ref((size_t)M * (size_t)y_ld);
|
||||
for (int m = 0; m < M; ++m) {
|
||||
float ss = 0.0f;
|
||||
for (int i = 0; i < n; ++i) { float v = xf[(size_t)m * (size_t)x_ld + i]; ss += v * v; }
|
||||
float s = 1.0f / sqrtf(ss / (float)n + eps);
|
||||
for (int i = 0; i < n; ++i)
|
||||
ref[(size_t)m * (size_t)y_ld + i] = xf[(size_t)m * (size_t)x_ld + i] * s;
|
||||
}
|
||||
std::vector<uint16_t> yh((size_t)M * (size_t)y_ld);
|
||||
hipMemcpy(yh.data(), y, (size_t)M * (size_t)y_ld * 2, hipMemcpyDeviceToHost);
|
||||
float maxd = 0.0f; int bad = 0;
|
||||
float maxin = 0.0f;
|
||||
for (size_t i = 0; i < xf.size(); ++i) { float a = fabsf(xf[i]); if (a > maxin) maxin = a; }
|
||||
for (int m = 0; m < M; ++m) for (int i = 0; i < n; ++i) {
|
||||
float d = fabsf(bf16_to_f32(yh[(size_t)m * (size_t)y_ld + i]) - ref[(size_t)m * (size_t)y_ld + i]);
|
||||
if (d > maxd) maxd = d;
|
||||
if (d > 1e-2f) bad++;
|
||||
}
|
||||
// sample: first 8 input, first 8 device-out, first 8 ref (all as f32); maxin = max-abs of the input (realistic ~O(1) vs GARBAGE ~O(1e37))
|
||||
fprintf(stderr, "[VERIFY rmsnorm_p] M=%d n=%d x_ld=%d y_ld=%d eps=%.3g maxd=%.6g bad=%d/%d maxin=%.6g\n",
|
||||
M, n, x_ld, y_ld, eps, maxd, bad, M * n, maxin);
|
||||
if (g_rmsnorm_p_verify_n == 1) {
|
||||
fprintf(stderr, " in :"); for (int i = 0; i < 8 && i < n; ++i) fprintf(stderr, " %g", xf[i]);
|
||||
fprintf(stderr, " out:"); for (int i = 0; i < 8 && i < n; ++i) fprintf(stderr, " %g", bf16_to_f32(yh[i]));
|
||||
fprintf(stderr, " ref:"); for (int i = 0; i < 8 && i < n; ++i) fprintf(stderr, " %g", ref[i]);
|
||||
fprintf(stderr, "\n");
|
||||
}
|
||||
}
|
||||
|
||||
void verify_gelu_mul(const uint16_t* gu, const uint16_t* y, int M, int n, int gu_ld, int y_ld,
|
||||
long stream) {
|
||||
if (!r4d_verify_on() || g_gelu_mul_verify_n >= 4) return;
|
||||
g_gelu_mul_verify_n++;
|
||||
/* SYNC BEFORE ANY DtoH COPY (see verify_rmsnorm_p): the input `gu` is the output of the
|
||||
* gate_up GEMM on `stream`, and a subsequent GEMM reuses the workspace and overwrites it.
|
||||
* The DtoH copy below runs on the DEFAULT stream (concurrent with `stream`), so without this
|
||||
* sync it can read `gu` while the next GEMM is overwriting it -- a race that produced false
|
||||
* O(1e37) "garbage" readings. Syncing `stream` first guarantees the gate_up GEMM + this kernel
|
||||
* have completed and the consumer GEMM has not yet been launched. */
|
||||
hipStreamSynchronize((hipStream_t)stream);
|
||||
std::vector<uint16_t> guh((size_t)M * (size_t)gu_ld);
|
||||
hipMemcpy(guh.data(), gu, (size_t)M * (size_t)gu_ld * 2, hipMemcpyDeviceToHost);
|
||||
std::vector<float> ref((size_t)M * (size_t)y_ld);
|
||||
const double k0 = 0.7978845608028654, k1 = 0.044715;
|
||||
for (int m = 0; m < M; ++m)
|
||||
for (int i = 0; i < n; ++i) {
|
||||
double g = (double)bf16_to_f32(guh[(size_t)m * (size_t)gu_ld + i]);
|
||||
double u = (double)bf16_to_f32(guh[(size_t)m * (size_t)gu_ld + n + i]);
|
||||
ref[(size_t)m * (size_t)y_ld + i] = (float)(0.5 * g * (1.0 + std::tanh(k0 * (g + k1 * g * g * g))) * u);
|
||||
}
|
||||
std::vector<uint16_t> yh((size_t)M * (size_t)y_ld);
|
||||
hipMemcpy(yh.data(), y, (size_t)M * (size_t)y_ld * 2, hipMemcpyDeviceToHost);
|
||||
float maxd = 0.0f; int bad = 0;
|
||||
float maxg = 0.0f;
|
||||
for (int m = 0; m < M; ++m) for (int i = 0; i < n; ++i) {
|
||||
float a = fabsf((float)bf16_to_f32(guh[(size_t)m * (size_t)gu_ld + i]));
|
||||
if (a > maxg) maxg = a;
|
||||
}
|
||||
for (int m = 0; m < M; ++m) for (int i = 0; i < n; ++i) {
|
||||
float d = fabsf(bf16_to_f32(yh[(size_t)m * (size_t)y_ld + i]) - ref[(size_t)m * (size_t)y_ld + i]);
|
||||
if (d > maxd) maxd = d;
|
||||
if (d > 1e-2f) bad++;
|
||||
}
|
||||
/* maxg = max-abs of the gate (first half of gu): realistic ~O(1) vs GARBAGE ~O(1e37). If maxg is
|
||||
* now realistic after the sync-before-copy fix, the O(1e37) readings were a verify artifact
|
||||
* (a race with a subsequent GEMM overwriting the workspace). If maxg is still ~O(1e37), the
|
||||
* gate_up GEMM is genuinely producing garbage. */
|
||||
fprintf(stderr, "[VERIFY gelu_mul] M=%d n=%d gu_ld=%d y_ld=%d maxd=%.6g bad=%d/%d maxg=%.6g\n",
|
||||
M, n, gu_ld, y_ld, maxd, bad, M * n, maxg);
|
||||
if (g_gelu_mul_verify_n == 1) {
|
||||
fprintf(stderr, " g :"); for (int i = 0; i < 8 && i < n; ++i) fprintf(stderr, " %g", bf16_to_f32(guh[i]));
|
||||
fprintf(stderr, " out:"); for (int i = 0; i < 8 && i < n; ++i) fprintf(stderr, " %g", bf16_to_f32(yh[i]));
|
||||
fprintf(stderr, " ref:"); for (int i = 0; i < 8 && i < n; ++i) fprintf(stderr, " %g", ref[i]);
|
||||
fprintf(stderr, "\n");
|
||||
}
|
||||
}
|
||||
|
||||
constexpr uint32_t kWave = 32;
|
||||
constexpr uint32_t kThreads = 256;
|
||||
constexpr uint32_t kWaves = kThreads / kWave;
|
||||
@@ -152,7 +503,7 @@ __global__ __launch_bounds__(kThreads) void embed_lookup_q_kernel(
|
||||
else dst[0] = 0;
|
||||
return;
|
||||
}
|
||||
const float s = !sc ? 1.0f : sc_f32 ? *(const float*)sc : bf16_to_f32(*(const uint16_t*)sc);
|
||||
const float s = !sc ? 1.0f : sc_f32 ? *(const float*)sc : bf2f(*(const uint16_t*)sc);
|
||||
const size_t at = (size_t)id * n_embd + j;
|
||||
float v[V];
|
||||
if constexpr (Q && V == 4) {
|
||||
@@ -163,10 +514,10 @@ __global__ __launch_bounds__(kThreads) void embed_lookup_q_kernel(
|
||||
v[0] = r4d_fp8::e4m3(((const uint8_t*)wte)[at]);
|
||||
} else if constexpr (V == 4) {
|
||||
const uint2 b = *(const uint2*)((const uint16_t*)wte + at);
|
||||
v[0] = bf16_to_f32((uint16_t)b.x); v[1] = bf16_to_f32((uint16_t)(b.x >> 16));
|
||||
v[2] = bf16_to_f32((uint16_t)b.y); v[3] = bf16_to_f32((uint16_t)(b.y >> 16));
|
||||
v[0] = bf2f((uint16_t)b.x); v[1] = bf2f((uint16_t)(b.x >> 16));
|
||||
v[2] = bf2f((uint16_t)b.y); v[3] = bf2f((uint16_t)(b.y >> 16));
|
||||
} else {
|
||||
v[0] = bf16_to_f32(((const uint16_t*)wte)[at]);
|
||||
v[0] = bf2f(((const uint16_t*)wte)[at]);
|
||||
}
|
||||
if constexpr (V == 4) {
|
||||
*(uint2*)dst = make_uint2(
|
||||
@@ -273,6 +624,29 @@ __global__ __launch_bounds__(THR) void rmsnorm_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- rmsnorm_p
|
||||
// ref_rmsnorm_p: y = x * rsqrt(mean(x^2) + eps) -- the SAME normalisation as rmsnorm with NO gain.
|
||||
// It is the weightless value normalisation Gemma's attention uses on V (llama.cpp's
|
||||
// ggml_rms_norm(V, eps), no tensor); there is no checkpoint plane to feed a gain through, so an
|
||||
// rmsnorm call would need a phantom all-zero weight. Two passes over the row, the sum of squares
|
||||
// in f32; the second pass drops the gain multiply rmsnorm has. The mean accumulates 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.
|
||||
__global__ __launch_bounds__(kThreads) void rmsnorm_p_kernel(
|
||||
const uint16_t* __restrict__ x, uint16_t* __restrict__ y,
|
||||
uint32_t n, float eps, uint32_t x_ld, uint32_t y_ld) {
|
||||
__shared__ float lds[kThreads / kWave];
|
||||
const uint32_t m = blockIdx.x;
|
||||
const uint16_t* __restrict__ xr = x + (size_t)m * x_ld;
|
||||
uint16_t* __restrict__ yr = y + (size_t)m * y_ld;
|
||||
float ss = 0.0f;
|
||||
for (uint32_t i = threadIdx.x; i < n; i += kThreads) { const float v = bf2f(xr[i]); ss += v * v; }
|
||||
ss = block_sum<kThreads / kWave>(ss, lds);
|
||||
const float s = rsqrtf(ss / (float)n + eps);
|
||||
for (uint32_t i = threadIdx.x; i < n; i += kThreads)
|
||||
yr[i] = f32_to_bf16(bf2f(xr[i]) * s);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- add / mul
|
||||
// ref_add / ref_mul, including THE ONE BROADCAST RULE: an operand carrying exactly n elements
|
||||
// against an output of rows*n broadcasts along rows, and nothing else broadcasts at all. That is
|
||||
@@ -310,6 +684,53 @@ __global__ __launch_bounds__(kThreads) void sigmoid_kernel(
|
||||
yr[i] = f32_to_bf16(1.0f / (1.0f + expf(-bf2f(xr[i]))));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- logit_softcap
|
||||
// ref_logit_softcap: y = cap * tanh(x / cap), the final-logit softcap. THE ROW-WISE-WITH-A-PITCH
|
||||
// SHAPE IS COPIED FROM sigmoid on purpose: Gemma's arch issues it against the logits_gemm's output,
|
||||
// and the pitch form costs nothing on a contiguous buffer -- it is x_ld == n.
|
||||
__global__ __launch_bounds__(kThreads) void logit_softcap_kernel(
|
||||
const uint16_t* __restrict__ x, uint16_t* __restrict__ y,
|
||||
uint32_t n, float cap, uint32_t x_ld, uint32_t y_ld) {
|
||||
const uint32_t m = blockIdx.x;
|
||||
const uint16_t* __restrict__ xr = x + (size_t)m * x_ld;
|
||||
uint16_t* __restrict__ yr = y + (size_t)m * y_ld;
|
||||
for (uint32_t i = threadIdx.x; i < n; i += kThreads)
|
||||
yr[i] = f32_to_bf16(cap * tanhf(bf2f(xr[i]) / cap));
|
||||
}
|
||||
|
||||
/* The f32 leg: the 1.3.0 sampling chain carries the logits in f32 from the gemm, so the softcap
|
||||
* is issued against f32 rows. The same row-with-pitch shape as the bf16 leg, and the math is the
|
||||
* op's definition verbatim -- no rounding pass, the buffer already holds the arithmetic dtype. */
|
||||
__global__ __launch_bounds__(kThreads) void logit_softcap_kernel_f32(
|
||||
const float* __restrict__ x, float* __restrict__ y,
|
||||
uint32_t n, float cap, uint32_t x_ld, uint32_t y_ld) {
|
||||
const uint32_t m = blockIdx.x;
|
||||
const float* __restrict__ xr = x + (size_t)m * x_ld;
|
||||
float* __restrict__ yr = y + (size_t)m * y_ld;
|
||||
for (uint32_t i = threadIdx.x; i < n; i += kThreads)
|
||||
yr[i] = cap * tanhf(xr[i] / cap);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- scale
|
||||
// ref_scale: y = x * s, s a [1] weight broadcast over every element. THE ROW-WISE-WITH-A-PITCH
|
||||
// SHAPE IS COPIED FROM sigmoid on purpose: Gemma's arch issues it against the residual stream at
|
||||
// the end of every layer (the per-layer scalar), and the pitch form costs nothing on a contiguous
|
||||
// buffer -- it is x_ld == n. The scalar is read once per block (a single load, cached), not per
|
||||
// element: a per-element reload of a [1] tensor is the same value every time and costs a load per
|
||||
// element. `s` is f32 or bf16 (the layer_scalar weight is bf16 in the checkpoint); the branch is
|
||||
// on its dtype, so the op is dtype-generic in the scalar and the bf16 kernel is the residual
|
||||
// stream's, which is what a served Gemma 4 issues it against.
|
||||
__global__ __launch_bounds__(kThreads) void scale_kernel(
|
||||
const uint16_t* __restrict__ x, const void* __restrict__ s, uint32_t s_dt,
|
||||
uint16_t* __restrict__ y, uint32_t n, uint32_t x_ld, uint32_t y_ld) {
|
||||
const uint32_t m = blockIdx.x;
|
||||
const float sv = (s_dt == RAD_F32) ? ((const float*)s)[0] : bf2f(((const uint16_t*)s)[0]);
|
||||
const uint16_t* __restrict__ xr = x + (size_t)m * x_ld;
|
||||
uint16_t* __restrict__ yr = y + (size_t)m * y_ld;
|
||||
for (uint32_t i = threadIdx.x; i < n; i += kThreads)
|
||||
yr[i] = f32_to_bf16(bf2f(xr[i]) * sv);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- silu_mul
|
||||
// ref_silu_mul: y[.., i] = silu(gu[.., i]) * gu[.., n + i]. THE GATE IS THE FIRST HALF, which is
|
||||
// the order rad-convert fuses gate_proj and up_proj into one weight in; the two conventions cannot
|
||||
@@ -326,6 +747,26 @@ __global__ __launch_bounds__(kThreads) void silu_mul_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- gelu_mul
|
||||
// ref_gelu_mul: y[.., i] = gelu_tanh(gu[.., i]) * gu[.., n + i]. THE GATE IS THE FIRST HALF, the
|
||||
// same order-lock as silu_mul. The tanh-approx GELU (gemma's gelu_pytorch_tanh), NOT the erf one:
|
||||
// gated feed-forwards are trained with the tanh form, and the constants are the standard fit the
|
||||
// gemm_nt_bias "gelu_tanh" epilogue uses (the identical function, so a GELU-gated FFN and a
|
||||
// tanh-gelu epilogue agree to the last bit).
|
||||
__global__ __launch_bounds__(kThreads) void gelu_mul_kernel(
|
||||
const uint16_t* __restrict__ gu, uint16_t* __restrict__ y,
|
||||
uint32_t n, uint32_t gu_ld, uint32_t y_ld) {
|
||||
const uint32_t m = blockIdx.x;
|
||||
const uint16_t* __restrict__ gr = gu + (size_t)m * gu_ld;
|
||||
uint16_t* __restrict__ yr = y + (size_t)m * y_ld;
|
||||
for (uint32_t i = threadIdx.x; i < n; i += kThreads) {
|
||||
const float g = bf2f(gr[i]);
|
||||
const float k0 = 0.7978845608028654f, k1 = 0.044715f;
|
||||
const float gelu = 0.5f * g * (1.0f + tanhf(k0 * (g + k1 * g * g * g)));
|
||||
yr[i] = f32_to_bf16(gelu * bf2f(gr[n + i]));
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- rope
|
||||
// ref_rope, in place over a fused [n_head + 2*n_head_kv] head row -- the V heads at the end are
|
||||
// left alone, which is the whole reason the op takes the fused projection rather than two tensors.
|
||||
@@ -337,8 +778,10 @@ __global__ __launch_bounds__(kThreads) void silu_mul_kernel(
|
||||
// (rad_block_attn_gated.h says so and says what would have to change first), so the shim maps it.
|
||||
//
|
||||
// PARTIAL ROTARY. `rot` may be less than head_dim -- 64 of 256 on this target -- and the tail of
|
||||
// the head is untouched. The frequency exponent divides by `rot`, not by head_dim: the rotated
|
||||
// prefix is a complete rotary of its own width.
|
||||
// the head is untouched. The base ladder's exponent divides by `den`, which `ladder` resolves:
|
||||
// `rot` for `rotary` (the rotated prefix, a complete rotary of its own width) and `head_dim` for
|
||||
// `head` (the proportional variant, a prefix of the full-width table). `den` = `rot` on the
|
||||
// default path, so existing models are bit-for-bit unchanged.
|
||||
//
|
||||
// One thread a PAIR. The pair's two loads and two stores are the whole body, so there is no
|
||||
// reduction and no LDS; the grid is (M, heads).
|
||||
@@ -362,7 +805,7 @@ __device__ __forceinline__ int rope_comp(int mode, uint32_t i, const int* sec, i
|
||||
|
||||
__global__ __launch_bounds__(kThreads) void rope_kernel(
|
||||
uint16_t* __restrict__ qkv, const int32_t* __restrict__ pos,
|
||||
uint32_t head_dim, uint32_t n_rope_heads, uint32_t rot, int gptj,
|
||||
uint32_t head_dim, uint32_t n_rope_heads, uint32_t rot, int den, int gptj,
|
||||
float theta, float rscale, uint32_t row_pitch,
|
||||
int mode, int s0, int s1, int s2, int n_sec, uint32_t plane, RadYarn yarn) {
|
||||
const uint32_t m = blockIdx.x;
|
||||
@@ -375,7 +818,7 @@ __global__ __launch_bounds__(kThreads) void rope_kernel(
|
||||
t += kThreads * gridDim.y) {
|
||||
const uint32_t h = t / half, i = t % half;
|
||||
uint16_t* __restrict__ hd = qkv + (size_t)m * row_pitch + (size_t)h * head_dim;
|
||||
float inv = 1.0f / powf(theta, (float)(2 * i) / (float)rot);
|
||||
float inv = 1.0f / powf(theta, (float)(2 * i) / (float)den);
|
||||
float p = p0;
|
||||
if (plane) {
|
||||
uint32_t j = i;
|
||||
@@ -621,6 +1064,13 @@ static int embed_lookup_q_emit(const int32_t* tok, const void* wte, bool q, cons
|
||||
return rc == RAD_OK ? 0 : -4;
|
||||
}
|
||||
|
||||
extern "C" int r4d_embed_lookup_bf16_scaled(long tok, long wte, long x, int M, int n_embd,
|
||||
int n_vocab, int vocab_off, int x_ld, float scale,
|
||||
long stream) {
|
||||
R4dSink sk; sk.stream = (RadStream)(uintptr_t)stream;
|
||||
return embed_lookup_bf16_emit(tok, wte, x, M, n_embd, n_vocab, vocab_off, x_ld, scale, sk);
|
||||
}
|
||||
|
||||
static int gather_rows_bf16_emit(long x, long idx, long y, int M, int n, int src_rows,
|
||||
int x_ld, int y_ld, const R4dSink& sk) {
|
||||
if (!x || !idx || !y) return -1;
|
||||
@@ -717,6 +1167,22 @@ extern "C" int r4d_rmsnorm_bf16(long x, long w, long y, int M, int n, float eps,
|
||||
return r4d_rmsnorm_mult_bf16(x, w, y, M, n, eps, wadd, 1.0f, w_f32, x_ld, y_ld, stream);
|
||||
}
|
||||
|
||||
// The weightless norm: rmsnorm without the gain multiply. It is not templated on a thread count
|
||||
// the way rmsnorm is, because rmsnorm's width is pinned to the fused rmsnorm_quant_fp8 by their
|
||||
// shared byte-identical requirement, and rmsnorm_p has no fused quantiser counterpart to match --
|
||||
// kThreads is the same choice the other non-templated row kernels (binary, sigmoid, silu_mul) make.
|
||||
extern "C" int r4d_rmsnorm_p_bf16(long x, long y, int M, int n, float eps,
|
||||
int x_ld, int y_ld, long stream) {
|
||||
if (!x || !y) return -1;
|
||||
if (M <= 0 || n <= 0) return -2;
|
||||
if (!x_ld) x_ld = n;
|
||||
if (!y_ld) y_ld = n;
|
||||
hipLaunchKernelGGL(rmsnorm_p_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream,
|
||||
(const uint16_t*)x, (uint16_t*)y, (uint32_t)n, eps,
|
||||
(uint32_t)x_ld, (uint32_t)y_ld);
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
// `op` is 0 for a sum and 1 for a product. `b_ld` of 0 with the same n is the broadcast form: the
|
||||
// caller passes a b_ld of zero and every row reads the same n elements.
|
||||
// b_ld -1 is a ONE-ELEMENT b, the scalar broadcast; 0 is one row broadcast down the rows.
|
||||
@@ -771,6 +1237,48 @@ extern "C" int r4d_fill_bf16(long y, int M, int n, int y_ld, float value, long s
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
extern "C" int r4d_logit_softcap_bf16(long x, long y, int M, int n, float cap,
|
||||
int x_ld, int y_ld, long stream) {
|
||||
if (!x || !y) return -1;
|
||||
if (M <= 0 || n <= 0) return -2;
|
||||
if (!(cap > 0.0f)) return -3;
|
||||
if (!x_ld) x_ld = n;
|
||||
if (!y_ld) y_ld = n;
|
||||
hipLaunchKernelGGL(logit_softcap_kernel, dim3((uint32_t)M), dim3(kThreads), 0,
|
||||
(hipStream_t)stream,
|
||||
(const uint16_t*)x, (uint16_t*)y, (uint32_t)n, cap,
|
||||
(uint32_t)x_ld, (uint32_t)y_ld);
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
extern "C" int r4d_logit_softcap_f32(long x, long y, int M, int n, float cap,
|
||||
int x_ld, int y_ld, long stream) {
|
||||
if (!x || !y) return -1;
|
||||
if (M <= 0 || n <= 0) return -2;
|
||||
if (!(cap > 0.0f)) return -3;
|
||||
if (!x_ld) x_ld = n;
|
||||
if (!y_ld) y_ld = n;
|
||||
hipLaunchKernelGGL(logit_softcap_kernel_f32, dim3((uint32_t)M), dim3(kThreads), 0,
|
||||
(hipStream_t)stream,
|
||||
(const float*)x, (float*)y, (uint32_t)n, cap,
|
||||
(uint32_t)x_ld, (uint32_t)y_ld);
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
extern "C" int r4d_scale_bf16(long x, long s, uint32_t s_dt, long y, int M, int n,
|
||||
int x_ld, int y_ld, long stream) {
|
||||
if (!x || !s || !y) return -1;
|
||||
if (M <= 0 || n <= 0) return -2;
|
||||
if (s_dt != RAD_F32 && s_dt != RAD_BF16) return -3;
|
||||
if (!x_ld) x_ld = n;
|
||||
if (!y_ld) y_ld = n;
|
||||
hipLaunchKernelGGL(scale_kernel, dim3((uint32_t)M), dim3(kThreads), 0,
|
||||
(hipStream_t)stream,
|
||||
(const uint16_t*)x, (const void*)s, s_dt, (uint16_t*)y, (uint32_t)n,
|
||||
(uint32_t)x_ld, (uint32_t)y_ld);
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
extern "C" int r4d_silu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y_ld, long stream) {
|
||||
if (!gu || !y) return -1;
|
||||
if (M <= 0 || n <= 0) return -2;
|
||||
@@ -782,19 +1290,35 @@ extern "C" int r4d_silu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
// GELU-gated product, the gemma FFN activation. Same shape and order-lock as silu_mul (the gate
|
||||
// is the first half of the fused [M, 2n] row); the only difference is the nonlinearity, which is
|
||||
// the tanh approximation, not the erf one, to match ref_gelu_mul's act_gelu_tanh.
|
||||
extern "C" int r4d_gelu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y_ld, long stream) {
|
||||
if (!gu || !y) return -1;
|
||||
if (M <= 0 || n <= 0) return -2;
|
||||
if (!gu_ld) gu_ld = 2 * n;
|
||||
if (!y_ld) y_ld = n;
|
||||
hipLaunchKernelGGL(gelu_mul_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream,
|
||||
(const uint16_t*)gu, (uint16_t*)y, (uint32_t)n,
|
||||
(uint32_t)gu_ld, (uint32_t)y_ld);
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
// `n_rope_heads` is n_head + n_head_kv: the Q heads and the K heads of a fused projection, or just
|
||||
// the one buffer's heads when q and k are separate tensors (which is what the gated block does).
|
||||
extern "C" int r4d_rope_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads,
|
||||
int rot, int gptj, float theta, float rscale, int row_pitch,
|
||||
long stream) {
|
||||
return r4d_rope_mc_bf16(qkv, pos, M, head_dim, n_rope_heads, rot, gptj, theta, rscale,
|
||||
return r4d_rope_mc_bf16(qkv, pos, M, head_dim, n_rope_heads, rot, rot, gptj, theta, rscale,
|
||||
row_pitch, 0, nullptr, 0, 0, stream);
|
||||
}
|
||||
|
||||
// THE ONE LAUNCH OF rope_kernel. `yarn` with factor 0 is the plain rotary: the kernel's YaRN
|
||||
// blend returns the frequency it was given and the magnitude is not applied, so the C entry points
|
||||
// below and the op without YaRN run the same arithmetic with the same arguments.
|
||||
static int rope_launch(long qkv, long pos, int M, int head_dim, int n_rope_heads, int rot,
|
||||
// below and the op without YaRN run the same arithmetic with the same arguments. `den` is the
|
||||
// ladder's width (`rot` for `rotary`, `head_dim` for `head`) -- the multi-component form passes
|
||||
// the caller's, and the plain entry passes `rot`, as it always has.
|
||||
static int rope_launch(long qkv, long pos, int M, int head_dim, int n_rope_heads, int rot, int den,
|
||||
int gptj, float theta, float rscale, int row_pitch, int mode,
|
||||
const int* sec, int n_sec, int plane, RadYarn yarn, long stream) {
|
||||
if (!qkv || !pos) return -1;
|
||||
@@ -807,7 +1331,7 @@ static int rope_launch(long qkv, long pos, int M, int head_dim, int n_rope_heads
|
||||
const int s0 = n_sec > 0 ? sec[0] : 0, s1 = n_sec > 1 ? sec[1] : 0, s2 = n_sec > 2 ? sec[2] : 0;
|
||||
hipLaunchKernelGGL(rope_kernel, dim3((uint32_t)M, gy), dim3(kThreads), 0, (hipStream_t)stream,
|
||||
(uint16_t*)qkv, (const int32_t*)pos, (uint32_t)head_dim,
|
||||
(uint32_t)n_rope_heads, (uint32_t)rot, gptj, theta, rscale,
|
||||
(uint32_t)n_rope_heads, (uint32_t)rot, (int)den, gptj, theta, rscale,
|
||||
(uint32_t)row_pitch, mode, s0, s1, s2, n_sec, (uint32_t)plane, yarn);
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
@@ -815,10 +1339,24 @@ static int rope_launch(long qkv, long pos, int M, int head_dim, int n_rope_heads
|
||||
// The multi-component form: `mode` 2 mrope, 3 imrope, 4 axial, `sec[0..n_sec)` the sections and
|
||||
// `plane` the component pitch of `pos`; plane 0 is the one-component rotary above.
|
||||
extern "C" int r4d_rope_mc_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads,
|
||||
int rot, int gptj, float theta, float rscale, int row_pitch,
|
||||
int mode, const int* sec, int n_sec, int plane, long stream) {
|
||||
return rope_launch(qkv, pos, M, head_dim, n_rope_heads, rot, gptj, theta, rscale, row_pitch,
|
||||
mode, sec, n_sec, plane, RadYarn{}, stream);
|
||||
int rot, int den, int gptj, float theta, float rscale,
|
||||
int row_pitch, int mode, const int* sec, int n_sec, int plane,
|
||||
long stream) {
|
||||
return rope_launch(qkv, pos, M, head_dim, n_rope_heads, rot, den, gptj, theta, rscale,
|
||||
row_pitch, mode, sec, n_sec, plane, RadYarn{}, stream);
|
||||
}
|
||||
|
||||
// Copy n bf16 from a (possibly host-page-table-unmapped) device VA into a regular allocation.
|
||||
// The device kernel reads via the DEVICE page table (mapped); a host DtoH copy on such a VA faults.
|
||||
__global__ void r4d_kv_copy_kernel(const uint16_t* __restrict__ src, uint16_t* __restrict__ dst, size_t n) {
|
||||
for (size_t i = blockIdx.x * (size_t)kThreads + threadIdx.x; i < n;
|
||||
i += (size_t)gridDim.x * kThreads)
|
||||
dst[i] = src[i];
|
||||
}
|
||||
__global__ void r4d_kv_copy8_kernel(const uint8_t* __restrict__ src, uint8_t* __restrict__ dst, size_t n) {
|
||||
for (size_t i = blockIdx.x * (size_t)kThreads + threadIdx.x; i < n;
|
||||
i += (size_t)gridDim.x * kThreads)
|
||||
dst[i] = src[i];
|
||||
}
|
||||
|
||||
extern "C" int r4d_kv_store_bf16(long k, long v, long slot, long kv, int M, int head_dim,
|
||||
@@ -840,6 +1378,57 @@ extern "C" int r4d_kv_store_bf16(long k, long v, long slot, long kv, int M, int
|
||||
(const uint16_t*)k, (const uint16_t*)v, (const int32_t*)slot,
|
||||
(uint16_t*)kv, (uint32_t)head_dim, (uint32_t)kv_heads,
|
||||
(uint32_t)block_size, (uint32_t)n_blocks, (uint32_t)k_ld, (uint32_t)v_ld);
|
||||
/* ==== TEMP DIAGNOSTIC (degenerate-output investigation): the store-populate check. ====
|
||||
* Established: kv/k/v/slot are DEVICE pointers; the store kernel launches+completes clean;
|
||||
* a DtoH copy from `slot` succeeds but a DtoH copy from `kv` FAULTS; kv is not a VMM allocation
|
||||
* (hipMemRetainAllocationHandle=invalid). Coherent reading: the cache is mapped in the DEVICE
|
||||
* page table (device kernels read/write it fine -> the model runs) and NOT in the HOST page
|
||||
* table (host copies fault). So the model's cache is fine; the degenerate output is a forward
|
||||
* bug. To confirm the store kernel POPULATED the cache, read it via a DEVICE copy kernel (the
|
||||
* device page table is mapped -> succeeds) into a regular allocation, then DtoH that regular
|
||||
* buffer. Compare the cached K against the store kernel's input k. Gated: R4D_DIAG=1. */
|
||||
if (r4d_diag_on()) {
|
||||
static int s_kvchk = 0;
|
||||
if (s_kvchk < 2) {
|
||||
++s_kvchk;
|
||||
hipDeviceSynchronize();
|
||||
const size_t blk_elems = (size_t)kv_heads * block_size * 2 * head_dim; // stride[0]
|
||||
uint16_t* reg = nullptr;
|
||||
hipError_t am = hipMalloc(®, blk_elems * 2);
|
||||
fprintf(stderr, "[KVCHK] call=%d M=%d hd=%d kvh=%d bs=%d nb=%d kld=%d vld=%d malloc=%d reg=%p\n",
|
||||
s_kvchk, M, head_dim, kv_heads, block_size, n_blocks, k_ld, v_ld, (int)am, (void*)reg);
|
||||
fflush(stderr);
|
||||
if (am == hipSuccess && reg) {
|
||||
r4d_kv_copy_kernel<<<(unsigned)((blk_elems + kThreads - 1) / kThreads), kThreads>>>(
|
||||
(const uint16_t*)kv, reg, blk_elems);
|
||||
hipError_t cs = hipDeviceSynchronize();
|
||||
std::vector<uint16_t> kv_h(blk_elems);
|
||||
hipError_t kc = hipMemcpy(kv_h.data(), reg, blk_elems * 2, hipMemcpyDeviceToHost);
|
||||
fprintf(stderr, "[KVCHK] call=%d devcopy_sync=%d kvcopy=%d\n", s_kvchk, (int)cs, (int)kc);
|
||||
fflush(stderr);
|
||||
if (cs == hipSuccess && kc == hipSuccess) {
|
||||
std::vector<int32_t> slot_h(M);
|
||||
hipMemcpy(slot_h.data(), (const int32_t*)(uintptr_t)slot, M * 4, hipMemcpyDeviceToHost);
|
||||
std::vector<uint16_t> k_h((size_t)M * k_ld);
|
||||
hipMemcpy(k_h.data(), (const uint16_t*)(uintptr_t)k, k_h.size() * 2, hipMemcpyDeviceToHost);
|
||||
for (int t = 0; t < M && t < 6; ++t) {
|
||||
int s = slot_h[t];
|
||||
if (s < 0) continue;
|
||||
const int blk = s / block_size, off = s % block_size;
|
||||
const size_t base = ((size_t)blk * kv_heads * block_size + (size_t)off) * 2 * head_dim;
|
||||
if (base + 2 * head_dim > kv_h.size()) break;
|
||||
fprintf(stderr, "[KVCHK] call=%d t=%d slot=%d blk=%d off=%d cacheK[0..3]=", s_kvchk, t, s, blk, off);
|
||||
for (int i = 0; i < 4; ++i) fprintf(stderr, " %.4f", attn_verify_bf16(kv_h[base + i]));
|
||||
fprintf(stderr, " inputK[0..3]=");
|
||||
for (int i = 0; i < 4; ++i) fprintf(stderr, " %.4f", attn_verify_bf16(k_h[(size_t)t * k_ld + i]));
|
||||
fprintf(stderr, "\n");
|
||||
}
|
||||
fflush(stderr);
|
||||
}
|
||||
}
|
||||
if (reg) hipFree(reg);
|
||||
}
|
||||
}
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
@@ -956,6 +1545,53 @@ extern "C" int r4d_logits_gemm_bf16(long a, long w, long c, int M, int K, int N,
|
||||
hipLaunchKernelGGL(logits_gemm_kernel, dim3((uint32_t)N), dim3(kThreads), 0,
|
||||
(hipStream_t)stream, (const uint16_t*)a, (const uint16_t*)w, (float*)c,
|
||||
(uint32_t)M, (uint32_t)K, (uint32_t)N, (uint32_t)a_ld, (uint32_t)c_ld);
|
||||
/* ==== TEMP DIAGNOSTIC (degenerate-output investigation): is the final hidden state featureless? ====
|
||||
* KV store + attention verified fine; the logits are near-flat (top-5 within a few points) ->
|
||||
* a near-constant hidden state would make every logit the same. a is a regular device buffer
|
||||
* (DtoH succeeds). Dump per-row mean/std over K + a few elements: std~0 = featureless (forward
|
||||
* collapses); std large = hidden state varies and the flat logits come from elsewhere.
|
||||
* Gated: R4D_DIAG=1. */
|
||||
if (r4d_diag_on()) {
|
||||
static int s_hidd = 0;
|
||||
if (s_hidd < 2) {
|
||||
++s_hidd;
|
||||
hipDeviceSynchronize();
|
||||
const int M1 = (M < 2) ? M : 2;
|
||||
std::vector<uint16_t> a_h((size_t)M1 * a_ld);
|
||||
hipMemcpy(a_h.data(), (const uint16_t*)a, a_h.size() * 2, hipMemcpyDeviceToHost);
|
||||
for (int r = 0; r < M1; ++r) {
|
||||
double s = 0, s2 = 0;
|
||||
for (int d = 0; d < K; ++d) { double v = attn_verify_bf16(a_h[(size_t)r * a_ld + d]); s += v; s2 += v * v; }
|
||||
const double mean = s / K, var = s2 / K - mean * mean;
|
||||
fprintf(stderr, "[HIDD] call=%d M=%d K=%d r=%d mean=%.4f std=%.4f a[0..7]=", s_hidd, M, K, r, mean, sqrt(var));
|
||||
for (int d = 0; d < 8 && d < K; ++d) fprintf(stderr, " %.4f", attn_verify_bf16(a_h[(size_t)r * a_ld + d]));
|
||||
fprintf(stderr, "\n");
|
||||
}
|
||||
fflush(stderr);
|
||||
}
|
||||
}
|
||||
/* ==== TEMP DIAGNOSTIC (degenerate-output investigation): the logits-GEMM output. ====
|
||||
* Hidden state verified RICH (std~4.6). A rich hidden state + a correct logits GEMM => sharp
|
||||
* logits; observed logits are near-flat (top-5 within a few points). Dump c (f32, regular
|
||||
* buffer, DtoH succeeds): mean/std over the full vocab + max/argmax. std~0 => GEMM output flat
|
||||
* (kernel bug); std large => GEMM fine and the sampler/softcap downstream is the suspect.
|
||||
* Gated: R4D_DIAG=1. */
|
||||
if (r4d_diag_on()) {
|
||||
static int s_log = 0;
|
||||
if (s_log < 2) {
|
||||
++s_log;
|
||||
hipDeviceSynchronize();
|
||||
std::vector<float> c_h((size_t)N);
|
||||
hipMemcpy(c_h.data(), (const float*)c, (size_t)N * 4, hipMemcpyDeviceToHost);
|
||||
long double s = 0, s2 = 0; float mx = -1e30f; int mi = 0;
|
||||
for (int j = 0; j < N; ++j) { const double v = c_h[j]; s += v; s2 += v * v; if (c_h[j] > mx) { mx = c_h[j]; mi = j; } }
|
||||
const double mean = (double)(s / N), var = (double)(s2 / N) - mean * mean;
|
||||
fprintf(stderr, "[LOGITS] call=%d c=%p N=%d ld=%d mean=%.4f std=%.4f max=%.4f argmax=%d c[0..7]=", s_log, (void*)(uintptr_t)c, N, c_ld, mean, sqrt(var), mx, mi);
|
||||
for (int j = 0; j < 8 && j < N; ++j) fprintf(stderr, " %.4f", c_h[j]);
|
||||
fprintf(stderr, "\n");
|
||||
fflush(stderr);
|
||||
}
|
||||
}
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
@@ -1263,6 +1899,32 @@ extern "C" int r4d_rad_rmsnorm(const RadArgs* a, RadStream s) {
|
||||
: RAD_E_DEVICE;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ rmsnorm_p */
|
||||
|
||||
extern "C" int r4d_rad_rmsnorm_p(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* x = r4d_opt(a, 0);
|
||||
const RadTensor* y = r4d_opt(a, 1);
|
||||
if (!x || !y) return R4D_NO(RAD_E_INVAL);
|
||||
R4D_NEED(dt_bf16(x));
|
||||
R4D_NEED(dt_bf16(y));
|
||||
|
||||
const long long n = r4d_geti_or(a, "n", r4d_dim(x, (int)x->rank - 1));
|
||||
if (n <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
long long M = 0, My = 0;
|
||||
const long long x_ld = r4d_rows_pitch(x, n, &M);
|
||||
const long long y_ld = r4d_rows_pitch(y, n, &My);
|
||||
if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
if (M <= 0 || My < M) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
const float eps = (float)r4d_getf(a, "eps", 1e-6);
|
||||
const int rc = r4d_rmsnorm_p_bf16(r4d_addr(x), r4d_addr(y), (int)M, (int)n, eps,
|
||||
(int)x_ld, (int)y_ld, (long)(uintptr_t)s);
|
||||
if (rc != 0) return RAD_E_DEVICE;
|
||||
verify_rmsnorm_p((const uint16_t*)(uintptr_t)r4d_addr(x), (const uint16_t*)(uintptr_t)r4d_addr(y),
|
||||
(int)M, (int)n, (int)x_ld, (int)y_ld, eps, (long)(uintptr_t)s);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ add / mul */
|
||||
|
||||
enum { BI_A = 0, BI_B, BI_Y };
|
||||
@@ -1375,6 +2037,76 @@ extern "C" int r4d_rad_fill(const RadArgs* a, RadStream s) {
|
||||
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ logit_softcap */
|
||||
|
||||
extern "C" int r4d_rad_logit_softcap(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* x = r4d_opt(a, 0);
|
||||
const RadTensor* y = r4d_opt(a, 1);
|
||||
if (!x || !y) return R4D_NO(RAD_E_INVAL);
|
||||
/* Two legs, one op: bf16 (the logits buffer as the gemm writes it on the bf16 chain) and f32
|
||||
* (the 1.3.0 sampling chain, where the gemm hands the sampler f32 rows). The dtype check
|
||||
* moved from the entry to the call below because the legs differ, not the geometry. */
|
||||
const bool leg_bf16 = (x->dtype == RAD_BF16) && (y->dtype == RAD_BF16);
|
||||
const bool leg_f32 = (x->dtype == RAD_F32) && (y->dtype == RAD_F32);
|
||||
if (!leg_bf16 && !leg_f32) return R4D_NO(RAD_E_DTYPE);
|
||||
|
||||
/* `cap` is where the model lives: Gemma 4 issues it at 30.0. The default exists for the same
|
||||
* reason every other one here does (a direct call with no declare in front), and the `> 0`
|
||||
* test is load-bearing: a zero cap is a division by zero in every lane, not a bad answer. */
|
||||
const float cap = (float)r4d_getf(a, "cap", 30.0);
|
||||
if (!(cap > 0.0f)) return R4D_NO(RAD_E_INVAL);
|
||||
|
||||
/* ROW-WISE WITH A PITCH, same as sigmoid: issued against a column slice there is no contiguous
|
||||
* extent to walk, and the contiguous case costs nothing. */
|
||||
const long long n = r4d_geti_or(a, "n", r4d_dim(y, (int)y->rank - 1));
|
||||
if (n <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
long long M = 0, My = 0;
|
||||
const long long x_ld = r4d_rows_pitch(x, n, &M);
|
||||
const long long y_ld = r4d_rows_pitch(y, n, &My);
|
||||
if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
if (M <= 0 || My < M) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
const int rc = leg_bf16
|
||||
? r4d_logit_softcap_bf16(r4d_addr(x), r4d_addr(y), (int)M, (int)n, cap,
|
||||
(int)x_ld, (int)y_ld, (long)(uintptr_t)s)
|
||||
: r4d_logit_softcap_f32(r4d_addr(x), r4d_addr(y), (int)M, (int)n, cap,
|
||||
(int)x_ld, (int)y_ld, (long)(uintptr_t)s);
|
||||
return rc == 0 ? RAD_OK : RAD_E_DEVICE;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ scale */
|
||||
|
||||
extern "C" int r4d_rad_scale(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* x = r4d_opt(a, 0);
|
||||
const RadTensor* sc = r4d_opt(a, 1);
|
||||
const RadTensor* y = r4d_opt(a, 2);
|
||||
if (!x || !sc || !y) return R4D_NO(RAD_E_INVAL);
|
||||
R4D_NEED(dt_bf16(x));
|
||||
R4D_NEED(dt_bf16(y));
|
||||
|
||||
/* `s` is a [1] weight, f32 or bf16 (the layer_scalar weight is bf16 in the checkpoint). A
|
||||
* scalar with no element is a shape error, not a broadcast of zero -- a zero scalar would be
|
||||
* a plausible number, which is the thing the oracle rules out. Read on the device (the kernel
|
||||
* reads s[0] once per block) rather than a host copy: a device-to-host copy of one element is
|
||||
* a synchronisation on the step path, and the per-block read is cached. */
|
||||
if (sc->dtype != RAD_F32 && sc->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE);
|
||||
if (r4d_numel(sc) < 1) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
/* ROW-WISE WITH A PITCH, same as sigmoid: issued against the residual stream at the end of a
|
||||
* layer there is no contiguous extent to walk, and the contiguous case costs nothing. */
|
||||
const long long n = r4d_geti_or(a, "n", r4d_dim(y, (int)y->rank - 1));
|
||||
if (n <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
long long M = 0, My = 0;
|
||||
const long long x_ld = r4d_rows_pitch(x, n, &M);
|
||||
const long long y_ld = r4d_rows_pitch(y, n, &My);
|
||||
if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
if (M <= 0 || My < M) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
return r4d_scale_bf16(r4d_addr(x), r4d_addr(sc), sc->dtype, r4d_addr(y), (int)M, (int)n,
|
||||
(int)x_ld, (int)y_ld,
|
||||
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ silu_mul */
|
||||
|
||||
extern "C" int r4d_rad_silu_mul(const RadArgs* a, RadStream s) {
|
||||
@@ -1396,6 +2128,31 @@ extern "C" int r4d_rad_silu_mul(const RadArgs* a, RadStream s) {
|
||||
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ gelu_mul */
|
||||
|
||||
extern "C" int r4d_rad_gelu_mul(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* gu = r4d_opt(a, 0);
|
||||
const RadTensor* y = r4d_opt(a, 1);
|
||||
if (!gu || !y) return R4D_NO(RAD_E_INVAL);
|
||||
R4D_NEED(dt_bf16(gu));
|
||||
R4D_NEED(dt_bf16(y));
|
||||
|
||||
const long long n = r4d_geti_or(a, "n", r4d_dim(y, (int)y->rank - 1));
|
||||
if (n <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
long long M = 0, Mg = 0;
|
||||
const long long y_ld = r4d_rows_pitch(y, n, &M);
|
||||
const long long gu_ld = r4d_rows_pitch(gu, 2 * n, &Mg);
|
||||
if (y_ld < 0 || gu_ld < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
if (M <= 0 || Mg < M) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
const int rc = r4d_gelu_mul_bf16(r4d_addr(gu), r4d_addr(y), (int)M, (int)n, (int)gu_ld, (int)y_ld,
|
||||
(long)(uintptr_t)s);
|
||||
if (rc != 0) return RAD_E_DEVICE;
|
||||
verify_gelu_mul((const uint16_t*)(uintptr_t)r4d_addr(gu), (const uint16_t*)(uintptr_t)r4d_addr(y),
|
||||
(int)M, (int)n, (int)gu_ld, (int)y_ld, (long)(uintptr_t)s);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ rope */
|
||||
|
||||
enum { RP_QKV = 0, RP_POS };
|
||||
@@ -1415,6 +2172,16 @@ extern "C" int r4d_rad_rope(const RadArgs* a, RadStream s) {
|
||||
if (head_dim <= 0 || n_head <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
if (rot <= 0 || rot > head_dim || (rot & 1)) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
/* `ladder`: `rotary` (default) measures the base ladder in `rot`; `head` in `head_dim`, the
|
||||
* proportional variant. head_dim is already validated above, so `den = head_dim` is safe. */
|
||||
const char* lad = r4d_gets(a, "ladder");
|
||||
long long den = rot;
|
||||
if (lad) {
|
||||
if (!std::strcmp(lad, "head")) den = head_dim;
|
||||
else if (std::strcmp(lad, "rotary") && std::strcmp(lad, "head"))
|
||||
return R4D_NO(RAD_E_UNSUPPORTED);
|
||||
}
|
||||
|
||||
/* THE MODE, and with it how many components a position has. With [M] positions -- one
|
||||
* component a token -- mrope and imrope ARE neox: every frequency reads the same position and
|
||||
* the ladder is the same. With [C, M] positions and `sections`, each frequency reads the
|
||||
@@ -1465,9 +2232,10 @@ extern "C" int r4d_rad_rope(const RadArgs* a, RadStream s) {
|
||||
/* The Q heads and the K heads rotate; the V heads that follow them do not, which is the whole
|
||||
* reason this op takes the fused projection rather than two tensors. */
|
||||
return rope_launch(r4d_addr(qkv), r4d_addr(pos), (int)Mp, (int)head_dim,
|
||||
(int)(n_head + n_head_kv), (int)rot, gptj, theta, rscale, (int)pitch,
|
||||
mc, sec, n_sec, plane, yarn, (long)(uintptr_t)s) == 0 ? RAD_OK
|
||||
: RAD_E_DEVICE;
|
||||
(int)(n_head + n_head_kv), (int)rot, (int)den, gptj, theta, rscale,
|
||||
(int)pitch, mc, sec, n_sec, plane, yarn, (long)(uintptr_t)s) == 0
|
||||
? RAD_OK
|
||||
: RAD_E_DEVICE;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ kv_store */
|
||||
|
||||
+211
-6
@@ -277,11 +277,13 @@ static const RadParamSpec pRopeTable[] = {
|
||||
{ "rot", RAD_P_INT, RAD_REQUIRED },
|
||||
P_F64("theta"),
|
||||
P_F64("scale"),
|
||||
{ "dtype", RAD_P_STR, RAD_REQUIRED },
|
||||
{ "yarn_factor", RAD_P_F64, RAD_OPTIONAL },
|
||||
{ "yarn_low", RAD_P_F64, RAD_OPTIONAL },
|
||||
{ "yarn_high", RAD_P_F64, RAD_OPTIONAL },
|
||||
{ "dtype", RAD_P_STR, RAD_REQUIRED },
|
||||
{ "yarn_factor", RAD_P_F64, RAD_OPTIONAL },
|
||||
{ "yarn_low", RAD_P_F64, RAD_OPTIONAL },
|
||||
{ "yarn_high", RAD_P_F64, RAD_OPTIONAL },
|
||||
{ "yarn_magnitude", RAD_P_F64, RAD_OPTIONAL },
|
||||
{ "head_dim", RAD_P_INT, RAD_OPTIONAL }, /* needed only by the `head` ladder */
|
||||
{ "ladder", RAD_P_STR, RAD_OPTIONAL }, /* the base ladder's width: rotary|head */
|
||||
};
|
||||
static const RadOperandSpec oRopeTable[] = {
|
||||
{ "positions", RAD_OPD_IN, 0 },
|
||||
@@ -1536,6 +1538,16 @@ static const RadParamSpec pMnDtype[] = {
|
||||
{ "n", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "dtype", RAD_P_STR, RAD_REQUIRED },
|
||||
};
|
||||
/* `logit_softcap`'s, matched field for field to ref's `pMnCap` so the two plugins agree (spec
|
||||
* §2.3). `cap` is required and must be > 0; a non-positive cap is a division by zero in every
|
||||
* lane, so the op refuses it rather than answering with NaNs. */
|
||||
static const RadParamSpec pMnCap[] = {
|
||||
{ "M", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "n", RAD_P_INT, RAD_REQUIRED },
|
||||
P_F64("cap"),
|
||||
{ "dtype", RAD_P_STR, RAD_REQUIRED },
|
||||
};
|
||||
|
||||
static const RadOperandSpec oBinary[] = {
|
||||
{ "a", RAD_OPD_IN, 0 },
|
||||
{ "b", RAD_OPD_IN, 0 },
|
||||
@@ -1640,6 +1652,11 @@ static const RadParamSpec pFill[] = {
|
||||
static const RadOperandSpec oFill[] = {
|
||||
{ "y", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
static const RadOperandSpec oScale[] = {
|
||||
{ "x", RAD_OPD_IN, 0 },
|
||||
{ "s", RAD_OPD_WEIGHT, 0 },
|
||||
{ "y", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
/* `cast`'s two dtype keys are STRINGS and not one `dtype`, because the whole point of the op is
|
||||
* that the two ends differ. ref's spelling, matched field for field so the two plugins agree. */
|
||||
static const RadParamSpec pCast[] = {
|
||||
@@ -1674,6 +1691,7 @@ static const RadParamSpec pRope[] = {
|
||||
{ "yarn_low", RAD_P_F64, RAD_OPTIONAL },
|
||||
{ "yarn_high", RAD_P_F64, RAD_OPTIONAL },
|
||||
{ "yarn_magnitude", RAD_P_F64, RAD_OPTIONAL },
|
||||
{ "ladder", RAD_P_STR, RAD_OPTIONAL }, /* the base ladder's width: rotary|head */
|
||||
};
|
||||
|
||||
/* ---------------------------------------------------------------------- the vision tower */
|
||||
@@ -1738,7 +1756,7 @@ static const RadParamSpec pEmbed[] = {
|
||||
{ "dtype", RAD_P_STR, RAD_REQUIRED },
|
||||
{ "vocab_offset", RAD_P_INT, RAD_OPTIONAL }, /* first GLOBAL row; vocab-parallel embedding */
|
||||
/* The scale embed_lookup_q's layout quantises with. That op shares this parameter list and
|
||||
* libref fixes it for both, so it is spelled here to match; embed_lookup reads no scale. */
|
||||
* libref fixes it for both, so it is spelled here to match. */
|
||||
{ "wscale", RAD_P_F64, RAD_OPTIONAL },
|
||||
};
|
||||
/* embed_lookup's own: pEmbed and `mult`, the factor every gathered row is multiplied by (Gemma's
|
||||
@@ -1944,6 +1962,11 @@ static const RadOpSchema kSchemas[] = {
|
||||
SCHEMA("rmsnorm", pRmsNorm, oRmsNorm,
|
||||
"y = x * rsqrt(mean(x^2) + eps) * (w + wadd). `wadd` is GemmaRMSNorm's `1 +`, added in "
|
||||
"f32 after the load because forming it in bf16 first costs 0.3% per channel."),
|
||||
SCHEMA("rmsnorm_p", pLayernorm, oUnary,
|
||||
"y = x * rsqrt(mean(x^2) + eps); an rmsnorm with NO gain tensor at all. 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."),
|
||||
SCHEMA("add", pMnDtype, oBinary,
|
||||
"y = a + b. `b` carrying exactly n elements against an output of M rows broadcasts "
|
||||
"along rows, and nothing else broadcasts at all."),
|
||||
@@ -1953,7 +1976,12 @@ static const RadOpSchema kSchemas[] = {
|
||||
"(broadcast down the rows): a learned gain on an activation. f32 product, rounded once."),
|
||||
SCHEMA("silu_mul", pMnDtype, 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_proj and up_proj in."),
|
||||
"which is the order rad-convert fuses gate_proj and up_proj in."),
|
||||
SCHEMA("gelu_mul", pMnDtype, 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."),
|
||||
SCHEMA("act_mul", pActMul, oBinary,
|
||||
"y = act(a) * b, the activation (silu, gelu, gelu_tanh) rounded to y's dtype before "
|
||||
"the product: silu_mul with its two halves in two operands."),
|
||||
@@ -1991,6 +2019,12 @@ static const RadOpSchema kSchemas[] = {
|
||||
"y = value, every element of an [M, n] extent (default 0). The op a rank issues where "
|
||||
"it computes nothing and a reader downstream -- an all-reduce, a residual -- still "
|
||||
"expects a defined buffer: a wire shared across layers cannot be zeroed once a step."),
|
||||
SCHEMA("logit_softcap", pMnCap, oUnary,
|
||||
"y = cap * tanh(x / cap); the final-logit softcap. `cap` is required and > 0."),
|
||||
SCHEMA("scale", pMnDtype, 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."),
|
||||
|
||||
SCHEMA("cast", pCast, oUnary,
|
||||
"y = x, converted. `from` and `to` are for the selector; the bytes are described by the "
|
||||
"tensors' own dtypes and those are what the kernel reads."),
|
||||
@@ -2428,6 +2462,32 @@ static const RadConstraint cAttnDecodeH128Bf16[] = {
|
||||
C_GE("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 4), C_EQ("block_size", 16),
|
||||
C_GE("causal", 0), C_LE("q_len", 16), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
|
||||
};
|
||||
/* Gemma 4 dense sliding window: head_dim 256, 2 queries per kv head, windowed decode
|
||||
* (r4d_attn_paged_h256_gqa2.hip). window is a launch argument -- 1024 in the model, 0 = full
|
||||
* attention -- so it is constrained on both sides like the drafter leg, not fixed. q_len <= 32 is
|
||||
* the q_len*gqa <= 64 of the prose at gqa 2, and the bucket boundary that keeps prefill out. */
|
||||
static const RadConstraint cAttnDecodeH256Gqa2Fp8[] = {
|
||||
C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16),
|
||||
C_GE("causal", 0), C_LE("q_len", 32), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"),
|
||||
};
|
||||
static const RadConstraint cAttnDecodeH256Gqa2Bf16[] = {
|
||||
C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16),
|
||||
C_GE("causal", 0), C_LE("q_len", 32), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
|
||||
};
|
||||
/* Gemma 4 dense sliding-window PREFILL (r4d_attn_paged_h256_gqa2.hip): the same geometry as the
|
||||
* decode leg above, but no q_len bound -- it serves the prefill band (q_len > 32, the bucket the
|
||||
* decode leg's C_LE leaves). window is a launch argument (1024 in the model) exactly as on the
|
||||
* decode leg, so C_GE on both sides; the kernel's WIN bit masks the window and skips the below-
|
||||
* window tiles. This was the band the decode-only leg left as a hole: a base-model prefill with no
|
||||
* device kernel is fatal (spec §17 -- libref is an opt-in fallback the engine refuses by default). */
|
||||
static const RadConstraint cAttnPrefillH256Gqa2Fp8[] = {
|
||||
C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16),
|
||||
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"),
|
||||
};
|
||||
static const RadConstraint cAttnPrefillH256Gqa2Bf16[] = {
|
||||
C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16),
|
||||
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
|
||||
};
|
||||
/* EIGHT QUERIES PER KV HEAD, at both head widths (r4d_attn_paged_gqa8.hip). q_len <= 8 is the
|
||||
* `q_len * gqa <= 64` of the prose at gqa 8, and the difference from the gqa6 leg's 10 is the whole
|
||||
* of what the ratio changes: a decode workgroup holds 64 rows and the verify width is how many of
|
||||
@@ -2469,6 +2529,25 @@ static const RadConstraint cAttnDecodeH256G4Bf16[] = {
|
||||
C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 4), C_EQ("block_size", 16),
|
||||
C_GE("causal", 0), C_LE("q_len", 16), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
|
||||
};
|
||||
/* Gemma 4 dense GLOBAL layers: head_dim 512, 8 queries per KV head, full attention
|
||||
* (r4d_attn_paged_h512_gqa8.hip). The `q_len <= 8` bound is the gqa verify width again; window
|
||||
* stays 0, which is what separates this from the sliding leg and why it needs no windowed form. */
|
||||
static const RadConstraint cAttnPrefillH512G8Fp8[] = {
|
||||
C_EQ("window", 0), C_EQ("head_dim", 512), C_EQ("gqa", 8), C_EQ("block_size", 16),
|
||||
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"),
|
||||
};
|
||||
static const RadConstraint cAttnPrefillH512G8Bf16[] = {
|
||||
C_EQ("window", 0), C_EQ("head_dim", 512), C_EQ("gqa", 8), C_EQ("block_size", 16),
|
||||
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
|
||||
};
|
||||
static const RadConstraint cAttnDecodeH512G8Fp8[] = {
|
||||
C_EQ("window", 0), C_EQ("head_dim", 512), C_EQ("gqa", 8), C_EQ("block_size", 16),
|
||||
C_GE("causal", 0), C_LE("q_len", 8), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"),
|
||||
};
|
||||
static const RadConstraint cAttnDecodeH512G8Bf16[] = {
|
||||
C_EQ("window", 0), C_EQ("head_dim", 512), C_EQ("gqa", 8), C_EQ("block_size", 16),
|
||||
C_GE("causal", 0), C_LE("q_len", 8), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
|
||||
};
|
||||
/* TWELVE QUERIES PER KV HEAD, head_dim 256 (r4d_attn_paged_h256_gqa12.hip) -- Qwen3.8-Flash-Next's
|
||||
* QSA layers, 24 query heads over 2. `q_len <= 5` is the same `q_len * gqa <= 64` bound the two
|
||||
* ratios above state, and it is TIGHTER than the legal speculation depths: a verify of depth 7 is
|
||||
@@ -3381,6 +3460,7 @@ static const RadTunable tMv[] = {
|
||||
* cannot match a query that forgot to say what it wanted -- the same reasoning cSampleChain gives.
|
||||
* n_cand is bounded because the top-k's bitonic sort runs in LDS over a power-of-two padding. */
|
||||
static const RadConstraint cBf16Row[] = { C_IN("dtype", "bf16") };
|
||||
static const RadConstraint cF32Row[] = { C_IN("dtype", "f32") };
|
||||
/* bf16 rows over the byte copy, which moves four bytes a thread: an even width. */
|
||||
static const RadConstraint cBf16Row2[] = { C_IN("dtype", "bf16"), C_DIV("n", 2) };
|
||||
/* Opaque byte rows, four at a time. The width constraint is the vectorised copy's
|
||||
@@ -3666,6 +3746,15 @@ static const RadKernelInfo kKernels[] = {
|
||||
nullptr, nullptr, r4d_rad_rmsnorm, nullptr, nullptr, nullptr,
|
||||
r4d_shape_rmsnorm },
|
||||
|
||||
{ "rmsnorm_p_bf16", "rmsnorm_p", "norm",
|
||||
"weightless root-mean-square norm (no gain), two passes over the row",
|
||||
"any n; the sum of squares accumulates in f32 and only the store narrows",
|
||||
"bf16 x / y, fp32 reduction",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cBf16Row), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_rmsnorm_p, nullptr, nullptr, nullptr,
|
||||
r4d_shape_unary },
|
||||
|
||||
{ "layernorm_bf16", "layernorm", "norm",
|
||||
"layer norm with a gain and an optional bias, two passes over the row",
|
||||
"any n; mean and variance accumulate in f32 and only the store narrows",
|
||||
@@ -3739,6 +3828,33 @@ static const RadKernelInfo kKernels[] = {
|
||||
nullptr, nullptr, r4d_rad_sigmoid, nullptr, nullptr, nullptr,
|
||||
r4d_shape_unary },
|
||||
|
||||
{ "logit_softcap_bf16", "logit_softcap", "elem",
|
||||
"cap * tanh(x / cap), the final-logit softcap, grid-strided over the whole extent",
|
||||
"any extent; contiguous in and out",
|
||||
"bf16 in and out, fp32 arithmetic",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cBf16Row), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_logit_softcap, nullptr, nullptr, nullptr,
|
||||
r4d_shape_unary },
|
||||
|
||||
{ "logit_softcap_f32", "logit_softcap", "elem",
|
||||
"cap * tanh(x / cap), the final-logit softcap, grid-strided over the whole extent",
|
||||
"any extent; contiguous in and out",
|
||||
"f32 in and out — the 1.3.0 sampling chain carries the logits as f32 from the gemm",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cF32Row), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_logit_softcap, nullptr, nullptr, nullptr,
|
||||
r4d_shape_unary },
|
||||
|
||||
{ "scale_bf16", "scale", "elem",
|
||||
"x * s, s a [1] weight broadcast over the whole extent, grid-strided",
|
||||
"any extent; contiguous in and out",
|
||||
"bf16 in and out, fp32 arithmetic, s f32 or bf16",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cBf16Row), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_scale, nullptr, nullptr, nullptr,
|
||||
r4d_shape_scale },
|
||||
|
||||
{ "silu_mul_bf16", "silu_mul", "elem",
|
||||
"silu-gated product over a fused [M, 2n] gate_up",
|
||||
"any n; the gate is the first half",
|
||||
@@ -3748,6 +3864,15 @@ static const RadKernelInfo kKernels[] = {
|
||||
nullptr, nullptr, r4d_rad_silu_mul, nullptr, nullptr, nullptr,
|
||||
r4d_shape_silu_mul },
|
||||
|
||||
{ "gelu_mul_bf16", "gelu_mul", "elem",
|
||||
"gelu-gated product over a fused [M, 2n] gate_up",
|
||||
"any n; the gate is the first half",
|
||||
"bf16 in and out, fp32 arithmetic",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cBf16Row), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_gelu_mul, nullptr, nullptr, nullptr,
|
||||
r4d_shape_silu_mul },
|
||||
|
||||
{ "rope_bf16", "rope", "attn",
|
||||
"rotary embedding in place, one thread a rotated pair",
|
||||
"any head_dim; rotary_dim even and no wider than head_dim -- the frequency exponent divides by "
|
||||
@@ -4021,6 +4146,48 @@ static const RadKernelInfo kKernels[] = {
|
||||
nullptr, nullptr,
|
||||
r4d_shape_attn_paged },
|
||||
|
||||
{ "attn_prefill_h256_gqa2_fp8kv", "attn_paged", "attn",
|
||||
"paged causal attention with a sliding window, query-tiled (prefill / chunked prefill)",
|
||||
"head_dim 256, 2 queries per kv head, paged block 16, varlen, "
|
||||
"window taken from the launch argument (0 = full attention)",
|
||||
"bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL,
|
||||
ROW(cAttnPrefillH256Gqa2Fp8), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_prefill_h256_gqa2_fp8, nullptr, nullptr, nullptr,
|
||||
r4d_shape_attn_paged },
|
||||
|
||||
{ "attn_prefill_h256_gqa2_bf16kv", "attn_paged", "attn",
|
||||
"paged causal attention with a sliding window, query-tiled (prefill / chunked prefill)",
|
||||
"head_dim 256, 2 queries per kv head, paged block 16, varlen, "
|
||||
"window taken from the launch argument (0 = full attention)",
|
||||
"bf16 query, bf16 kv cache, bf16 out",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL,
|
||||
ROW(cAttnPrefillH256Gqa2Bf16), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_prefill_h256_gqa2_bf16, nullptr, nullptr, nullptr,
|
||||
r4d_shape_attn_paged },
|
||||
|
||||
{ "attn_decode_h256_gqa2_fp8kv", "attn_paged", "attn",
|
||||
"paged causal attention with a sliding window, split-KV (decode / verify)",
|
||||
"head_dim 256, 2 queries per kv head, paged block 16, q_len*gqa <= 64, "
|
||||
"window taken from the launch argument (0 = full attention)",
|
||||
"bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out, f16 partials",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
|
||||
ROW(cAttnDecodeH256Gqa2Fp8), ROW(tAttnSplit), nullptr,
|
||||
nullptr, nullptr, r4d_rad_attn_decode_h256_gqa2_fp8, r4d_rad_attn_decode_h256_gqa2_scratch,
|
||||
nullptr, nullptr,
|
||||
r4d_shape_attn_paged },
|
||||
|
||||
{ "attn_decode_h256_gqa2_bf16kv", "attn_paged", "attn",
|
||||
"paged causal attention with a sliding window, split-KV (decode / verify)",
|
||||
"head_dim 256, 2 queries per kv head, paged block 16, q_len*gqa <= 64, "
|
||||
"window taken from the launch argument (0 = full attention)",
|
||||
"bf16 query, bf16 kv cache, bf16 out, f16 partials",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
|
||||
ROW(cAttnDecodeH256Gqa2Bf16), ROW(tAttnSplit), nullptr,
|
||||
nullptr, nullptr, r4d_rad_attn_decode_h256_gqa2_bf16, r4d_rad_attn_decode_h256_gqa2_scratch,
|
||||
nullptr, nullptr,
|
||||
r4d_shape_attn_paged },
|
||||
|
||||
{ "attn_prefill_h256_gqa8_fp8kv", "attn_paged", "attn",
|
||||
"paged causal attention, query-tiled (prefill / chunked prefill)",
|
||||
"head_dim 256, 8 queries per kv head, paged block 16, varlen",
|
||||
@@ -4097,6 +4264,44 @@ static const RadKernelInfo kKernels[] = {
|
||||
nullptr, nullptr,
|
||||
r4d_shape_attn_paged },
|
||||
|
||||
{ "attn_prefill_h512_gqa8_fp8kv", "attn_paged", "attn",
|
||||
"paged causal attention, query-tiled (prefill / chunked prefill)",
|
||||
"head_dim 512, 8 queries per kv head, paged block 16, varlen",
|
||||
"bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL,
|
||||
ROW(cAttnPrefillH512G8Fp8), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_prefill_h512_gqa8_fp8, nullptr, nullptr, nullptr,
|
||||
r4d_shape_attn_paged },
|
||||
|
||||
{ "attn_prefill_h512_gqa8_bf16kv", "attn_paged", "attn",
|
||||
"paged causal attention, query-tiled (prefill / chunked prefill)",
|
||||
"head_dim 512, 8 queries per kv head, paged block 16, varlen",
|
||||
"bf16 query, bf16 kv cache, bf16 out",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL,
|
||||
ROW(cAttnPrefillH512G8Bf16), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_prefill_h512_gqa8_bf16, nullptr, nullptr, nullptr,
|
||||
r4d_shape_attn_paged },
|
||||
|
||||
{ "attn_decode_h512_gqa8_fp8kv", "attn_paged", "attn",
|
||||
"paged attention, causal or not, split-KV (decode / speculative verify / draft block)",
|
||||
"head_dim 512, 8 queries per kv head, paged block 16, q_len*gqa <= 64, no window",
|
||||
"bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out, f16 partials",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
|
||||
ROW(cAttnDecodeH512G8Fp8), ROW(tAttnSplit), nullptr,
|
||||
nullptr, nullptr, r4d_rad_attn_decode_h512_gqa8_fp8, r4d_rad_attn_decode_h512_gqa8_scratch,
|
||||
nullptr, nullptr,
|
||||
r4d_shape_attn_paged },
|
||||
|
||||
{ "attn_decode_h512_gqa8_bf16kv", "attn_paged", "attn",
|
||||
"paged attention, causal or not, split-KV (decode / speculative verify / draft block)",
|
||||
"head_dim 512, 8 queries per kv head, paged block 16, q_len*gqa <= 64, no window",
|
||||
"bf16 query, bf16 kv cache, bf16 out, f16 partials",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
|
||||
ROW(cAttnDecodeH512G8Bf16), ROW(tAttnSplit), nullptr,
|
||||
nullptr, nullptr, r4d_rad_attn_decode_h512_gqa8_bf16, r4d_rad_attn_decode_h512_gqa8_scratch,
|
||||
nullptr, nullptr,
|
||||
r4d_shape_attn_paged },
|
||||
|
||||
{ "attn_prefill_h256_gqa12_fp8kv", "attn_paged", "attn",
|
||||
"paged causal attention, query-tiled (prefill / chunked prefill)",
|
||||
"head_dim 256, 12 queries per kv head, paged block 4, varlen",
|
||||
|
||||
@@ -50,6 +50,9 @@
|
||||
#include "r4d_common.h"
|
||||
|
||||
#include <cfloat>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <vector>
|
||||
|
||||
// THE PARAMS ROW IS THE ENGINE'S STRUCT, not a restatement of it. Two independent declarations of
|
||||
// one wire format drift, and the drift is silent: a sampler reading `top_p` out of `min_p`
|
||||
@@ -1393,6 +1396,38 @@ extern "C" int r4d_rad_sample_argmax(const RadArgs* a, RadStream s) {
|
||||
if (!tok) return R4D_NO(RAD_E_INVAL);
|
||||
R4D_NEED(dt_i32(tok));
|
||||
if (!r4d_contig(tok) || r4d_numel(tok) < M) return R4D_NO(RAD_E_SHAPE);
|
||||
/* DEBUG: dump the sampler's INPUT row 0 at the first two calls (prefill, then first decode),
|
||||
* with the SAME fields as the [LOGITS] dump at the GEMM entry, plus the lg pointer + pitch, so
|
||||
* the two dumps compare pointer-for-pointer and row-for-row in one run. Sync `s` first (the
|
||||
* logits are produced by the logit_softcap op on `s`), then copy. Gated: R4D_DIAG=1.
|
||||
* Findings: sampler input = the GEMM buffer (same pointer); softcap applied (43.02 -> 26.77 =
|
||||
* 30*tanh(43.02/30)); true argmax 100 (prefill) / 45518 (decode) = the GEMM argmax. */
|
||||
static const int r4d_sampin_on = std::getenv("R4D_DIAG") ? 1 : 0;
|
||||
if (r4d_sampin_on) {
|
||||
static int n = 0;
|
||||
if (n < 2) {
|
||||
n++;
|
||||
hipStreamSynchronize((hipStream_t)(long)(uintptr_t)s);
|
||||
const long lgp = r4d_addr(lg);
|
||||
std::vector<float> lh((size_t)M * (size_t)ld);
|
||||
hipMemcpy(lh.data(), (const void*)(uintptr_t)lgp, (size_t)M * (size_t)ld, hipMemcpyDeviceToHost);
|
||||
long double s1 = 0, s2 = 0; float mx = -1e30f; int mi = 0;
|
||||
for (long long v = 0; v < nv; ++v) { const double x = lh[v]; s1 += x; s2 += x * x; if (lh[v] > mx) { mx = lh[v]; mi = (int)v; } }
|
||||
const double mean = (double)(s1 / nv), var = (double)(s2 / nv) - mean * mean;
|
||||
int top[5] = {-1,-1,-1,-1,-1}; float tv[5] = {-1e30f,-1e30f,-1e30f,-1e30f,-1e30f};
|
||||
for (long long v = 0; v < nv; ++v) {
|
||||
float x = lh[v];
|
||||
for (int i = 4; i >= 0; --i) { if (x > tv[i]) { if (i < 4) { tv[i+1] = tv[i]; top[i+1] = top[i]; } tv[i] = x; top[i] = (int)v; break; } }
|
||||
}
|
||||
fprintf(stderr, "[SAMPIN] call=%d lg=%p M=%lld nv=%lld ld=%lld row0 mean=%.4f std=%.4f max=%.4f argmax=%d top5:",
|
||||
n, (void*)(uintptr_t)lgp, M, nv, ld, mean, sqrt(var), mx, mi);
|
||||
for (int i = 0; i < 5; ++i) fprintf(stderr, " (%d,%.4f)", top[i], tv[i]);
|
||||
fprintf(stderr, " row0[0..7]=");
|
||||
for (long long v = 0; v < 8 && v < nv; ++v) fprintf(stderr, " %.4f", lh[v]);
|
||||
fprintf(stderr, "\n");
|
||||
fflush(stderr);
|
||||
}
|
||||
}
|
||||
R4D_LAUNCH(r4d_sample_argmax_f32(r4d_addr(lg), r4d_addr(tok), (int)M, (int)nv, (int)ld,
|
||||
(long)(uintptr_t)s));
|
||||
}
|
||||
|
||||
+613
-2
@@ -711,7 +711,7 @@ static const RadKernelInfo* find(const Plugin& pl, const char* name) {
|
||||
/* ------------------------------------------------------------------ per-family smoke tests */
|
||||
|
||||
static void attn_case(const Plugin& pl, const char* name, int64_t head_dim, int64_t gqa,
|
||||
int64_t q_len, const char* kv_dtype, int prefill) {
|
||||
int64_t q_len, const char* kv_dtype, int prefill, int window = 0) {
|
||||
if (!sel(name)) return;
|
||||
const RadKernelInfo* r = find(pl, name);
|
||||
if (!r) { ok(name, false, "row absent"); return; }
|
||||
@@ -743,7 +743,7 @@ static void attn_case(const Plugin& pl, const char* name, int64_t head_dim, int6
|
||||
absent(ts[6]);
|
||||
std::vector<RadParam> ps = {
|
||||
PI("q_len", q_len), PI("head_dim", head_dim), PI("gqa", gqa), PI("block_size", bs),
|
||||
PI("causal", 1), PI("window", 0), PS("q_dtype", "bf16"), PS("kv_dtype", kv_dtype),
|
||||
PI("causal", 1), PI("window", window), PS("q_dtype", "bf16"), PS("kv_dtype", kv_dtype),
|
||||
};
|
||||
(void)prefill;
|
||||
run_case(r, ts, ps);
|
||||
@@ -824,6 +824,186 @@ static float h_e4m3(uint8_t b) {
|
||||
return sign * (1.0f + (float)mn / 8.0f) * std::ldexp(1.0f, (int)ex - 7);
|
||||
}
|
||||
|
||||
/* Two avalanche-random values for the numeric attention check: a bounded bf16 in [-1, 1] and an
|
||||
* e4m3 code, each a function of its index so a wrong pitch or lane map reads unrelated numbers. */
|
||||
static uint16_t st_rand_bf16(uint32_t i) {
|
||||
const uint32_t x = st_mix32(i);
|
||||
const float f = ((x & 0x00ffffffu) / 16777215.0f) * 2.0f - 1.0f;
|
||||
return h_to_bf16(f);
|
||||
}
|
||||
static uint8_t st_rand_e4m3(uint32_t i) {
|
||||
const uint32_t x = st_mix32(i + 0x9e3779b9u);
|
||||
/* Bounded to [-1, 1] (the positive magnitudes below), mirroring st_rand_bf16. The full e4m3
|
||||
* range (up to 448) makes the attention scores reach ~448*head_dim/sqrt(head_dim), so the
|
||||
* softmax dominates by e^score and a 1-ulp difference between the device's v_cvt_f32_fp8 and
|
||||
* this software h_e4m3 flips the max into a large output error; bounded, the scores stay ~22
|
||||
* (the passing bf16 path) and the comparison is stable. */
|
||||
static const uint8_t mag[] = {
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* subnormal, 0 .. 7/64 */
|
||||
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, /* exp 4, 0.125 .. 0.234375 */
|
||||
0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, /* exp 5, 0.25 .. 0.46875 */
|
||||
0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, /* exp 6, 0.5 .. 0.9375 */
|
||||
0x38, /* exp 7, 1.0 */
|
||||
};
|
||||
const uint8_t m = mag[(x >> 1) % (sizeof mag / sizeof mag[0])];
|
||||
return (uint8_t)(m | (((x >> 8) & 1u) << 7));
|
||||
}
|
||||
|
||||
/* The inline paged-attention oracle: a port of ref_attn_paged (libref/ref_attn.cpp) for the
|
||||
* uniform batch, bf16 q, fp8-e4m3 or bf16 k/v, f32 descales. The selftest does not link libref,
|
||||
* so the reference the kbench byte-equality uses is carried here; the mask, the two-pass softmax
|
||||
* and the k/v dequant are the same, so a wrong kernel fails the comparison. One (row, head) at a
|
||||
* time: `i` is the query's position within its sequence's query, and `pos = ctx - qlen + i`. */
|
||||
static void attn_oracle_one(const uint16_t* qh, const uint8_t* kv, int kv_is_fp8,
|
||||
int64_t head_dim, int64_t kv_heads, int64_t block_size, int64_t kh,
|
||||
const int* block_table, int64_t max_blocks, int ctx,
|
||||
float kds, float vds, int causal, int window, float scale,
|
||||
int64_t qlen, int64_t i, float* out) {
|
||||
const int ew = kv_is_fp8 ? 1 : 2;
|
||||
const int64_t pos = ctx - qlen + i;
|
||||
const int64_t sb = kv_heads * block_size * 2 * head_dim;
|
||||
const int64_t sh = block_size * 2 * head_dim;
|
||||
const int64_t so = 2 * head_dim;
|
||||
const auto kslot = [&](int64_t blk, int64_t slot, int64_t d) {
|
||||
const uint8_t* p = kv + (blk * sb + kh * sh + slot * so + d) * ew;
|
||||
return kv_is_fp8 ? h_e4m3(p[0]) : h_bf16(*(const uint16_t*)p);
|
||||
};
|
||||
const auto vslot = [&](int64_t blk, int64_t slot, int64_t d) {
|
||||
const uint8_t* p = kv + (blk * sb + kh * sh + slot * so + head_dim + d) * ew;
|
||||
return kv_is_fp8 ? h_e4m3(p[0]) : h_bf16(*(const uint16_t*)p);
|
||||
};
|
||||
const auto visible = [&](int64_t j) {
|
||||
if (causal ? (j > pos) : (j >= ctx)) return false;
|
||||
if (window > 0) { const int64_t d = pos - j;
|
||||
if (causal ? (d >= window) : (d >= window || d <= -window)) return false; }
|
||||
return true;
|
||||
};
|
||||
float mx = -INFINITY;
|
||||
for (int64_t j = 0; j < ctx; ++j) {
|
||||
if (!visible(j)) continue;
|
||||
if (j / block_size >= max_blocks) break;
|
||||
int blk = block_table[j / block_size];
|
||||
if (blk < 0) continue;
|
||||
float dot = 0.0f;
|
||||
for (int64_t d = 0; d < head_dim; ++d) dot += h_bf16(qh[d]) * (kslot(blk, j % block_size, d) * kds);
|
||||
dot *= scale;
|
||||
if (dot > mx) mx = dot;
|
||||
}
|
||||
if (mx == -INFINITY) { for (int64_t d = 0; d < head_dim; ++d) out[d] = 0.0f; return; }
|
||||
float sum = 0.0f;
|
||||
for (int64_t d = 0; d < head_dim; ++d) out[d] = 0.0f;
|
||||
for (int64_t j = 0; j < ctx; ++j) {
|
||||
if (!visible(j)) continue;
|
||||
if (j / block_size >= max_blocks) break;
|
||||
int blk = block_table[j / block_size];
|
||||
if (blk < 0) continue;
|
||||
float dot = 0.0f;
|
||||
for (int64_t d = 0; d < head_dim; ++d) dot += h_bf16(qh[d]) * (kslot(blk, j % block_size, d) * kds);
|
||||
const float w = std::exp(dot * scale - mx);
|
||||
sum += w;
|
||||
for (int64_t d = 0; d < head_dim; ++d) out[d] += w * (vslot(blk, j % block_size, d) * vds);
|
||||
}
|
||||
const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
|
||||
for (int64_t d = 0; d < head_dim; ++d) out[d] *= inv;
|
||||
}
|
||||
|
||||
/* The numeric attention check: fill q and the paged k/v with avalanche-random data, run the row,
|
||||
* and compare the bf16 output against the inline oracle above. The launch smoke (attn_case) proves
|
||||
* the kernel starts; this proves it computes. A negative control corrupts a share of the reference
|
||||
* and requires the comparison to FAIL -- the proof the check has teeth. */
|
||||
static void attn_numeric_case(const Plugin& pl, const char* name, int64_t head_dim, int64_t gqa,
|
||||
int64_t q_len, const char* kv_dtype, int window, int64_t ctx = 64) {
|
||||
if (!sel(name)) return;
|
||||
const RadKernelInfo* r = find(pl, name);
|
||||
if (!r) { ok(name, false, "row absent"); return; }
|
||||
const int64_t seqs = 1, kv_heads = 2, bs = 16;
|
||||
const int64_t q_heads = kv_heads * gqa;
|
||||
const int64_t max_blocks = ctx / bs;
|
||||
const int64_t total_q = seqs * q_len;
|
||||
const int kv_is_fp8 = std::strcmp(kv_dtype, "bf16") != 0;
|
||||
const uint32_t kvdt = kv_is_fp8 ? RAD_F8E4M3 : RAD_BF16;
|
||||
const int ew = kv_is_fp8 ? 1 : 2;
|
||||
const float scale = 1.0f / std::sqrt((float)head_dim);
|
||||
|
||||
std::vector<uint16_t> qh((size_t)total_q * q_heads * head_dim);
|
||||
for (size_t i = 0; i < qh.size(); ++i) qh[i] = st_rand_bf16(i);
|
||||
const int64_t nelem = max_blocks * kv_heads * bs * 2 * head_dim;
|
||||
std::vector<uint8_t> kv((size_t)nelem * ew);
|
||||
for (int64_t e = 0; e < nelem; ++e) {
|
||||
const size_t bo = (size_t)e * ew;
|
||||
if (kv_is_fp8) kv[bo] = st_rand_e4m3(e);
|
||||
else { const uint16_t h = st_rand_bf16(e); kv[bo] = (uint8_t)h; kv[bo + 1] = (uint8_t)(h >> 8); }
|
||||
}
|
||||
const std::vector<int32_t> bt = iota_i32(max_blocks);
|
||||
|
||||
void* d_q = dalloc((size_t)total_q * q_heads * head_dim * 2);
|
||||
st_memcpy(d_q, qh.data(), qh.size() * 2, hipMemcpyHostToDevice);
|
||||
void* d_kv = dalloc(kv.size());
|
||||
st_memcpy(d_kv, kv.data(), kv.size(), hipMemcpyHostToDevice);
|
||||
void* d_out = dalloc((size_t)total_q * q_heads * head_dim * 2);
|
||||
|
||||
std::vector<RadTensor> ts = {
|
||||
T(d_q, RAD_BF16, { total_q, q_heads, head_dim }),
|
||||
T(d_kv, kvdt, { max_blocks, kv_heads, bs, 2 * head_dim }),
|
||||
TI32({ seqs, max_blocks }, bt),
|
||||
TI32({ seqs }, rep_i32(seqs, (int32_t)ctx)),
|
||||
TF32({ seqs, kv_heads }, 1.0f),
|
||||
TF32({ seqs, kv_heads }, 1.0f),
|
||||
T(nullptr, RAD_I32, { seqs + 1 }),
|
||||
T(d_out, RAD_BF16, { total_q, q_heads, head_dim }),
|
||||
};
|
||||
if (kvdt == RAD_BF16) { absent(ts[4]); absent(ts[5]); }
|
||||
absent(ts[6]);
|
||||
std::vector<RadParam> ps = {
|
||||
PI("q_len", q_len), PI("head_dim", head_dim), PI("gqa", gqa), PI("block_size", bs),
|
||||
PI("causal", 1), PI("window", window), PS("q_dtype", "bf16"), PS("kv_dtype", kv_dtype),
|
||||
};
|
||||
run_case(r, ts, ps);
|
||||
|
||||
std::vector<uint16_t> oh((size_t)total_q * q_heads * head_dim);
|
||||
st_memcpy(oh.data(), d_out, oh.size() * 2, hipMemcpyDeviceToHost);
|
||||
|
||||
const float abs_tol = 1e-3f, rel_tol = 2e-2f;
|
||||
std::vector<float> oref((size_t)total_q * q_heads * head_dim);
|
||||
float max_err = 0.0f; int nbad = 0;
|
||||
for (int64_t tok = 0; tok < total_q; ++tok)
|
||||
for (int64_t h = 0; h < q_heads; ++h) {
|
||||
const int64_t kh = h / gqa;
|
||||
float o[512];
|
||||
attn_oracle_one(&qh[(tok * q_heads + h) * head_dim], kv.data(), kv_is_fp8,
|
||||
head_dim, kv_heads, bs, kh, bt.data(), max_blocks, ctx,
|
||||
1.0f, 1.0f, 1, window, scale, q_len, tok, o);
|
||||
for (int64_t d = 0; d < head_dim; ++d) {
|
||||
const size_t idx = (size_t)(tok * q_heads + h) * head_dim + d;
|
||||
oref[idx] = o[d];
|
||||
const float got = h_bf16(oh[idx]);
|
||||
const float diff = std::fabs(got - o[d]);
|
||||
if (diff > abs_tol + rel_tol * std::fabs(o[d])) ++nbad;
|
||||
if (diff > max_err) max_err = diff;
|
||||
}
|
||||
}
|
||||
char nm[160];
|
||||
std::snprintf(nm, sizeof nm, "%s numeric", name);
|
||||
ok(nm, nbad == 0,
|
||||
fmt("max_err=%.5g bad=%d/%d", max_err, nbad, (int)oref.size()));
|
||||
|
||||
/* Negative control: corrupt a share of the reference and require the comparison to FAIL -- the
|
||||
* proof the check has teeth, since a broken (always-passing) comparison would flag nothing. */
|
||||
for (size_t idx = 0; idx < oref.size(); ++idx)
|
||||
if ((idx & 7) == 0) oref[idx] += 0.5f;
|
||||
float nmax = 0.0f; int nbadc = 0;
|
||||
for (size_t idx = 0; idx < oref.size(); ++idx) {
|
||||
const float got = h_bf16(oh[idx]);
|
||||
const float diff = std::fabs(got - oref[idx]);
|
||||
if (diff > abs_tol + rel_tol * std::fabs(oref[idx])) ++nbadc;
|
||||
if (diff > nmax) nmax = diff;
|
||||
}
|
||||
std::snprintf(nm, sizeof nm, "%s numeric-negctl", name);
|
||||
ok(nm, nbadc > 0,
|
||||
fmt("corrupted ref must fail: max_err=%.5g bad=%d", nmax, nbadc));
|
||||
}
|
||||
|
||||
|
||||
/* ================================================================== a weight's canonical planes
|
||||
*
|
||||
* A container holds a weight as the planes of its encoding, row-major (spec §4.1), and a kernel's
|
||||
@@ -4107,6 +4287,375 @@ static void bf16_tiled_identity(const Plugin& pl, int64_t M, int64_t N, int64_t
|
||||
ok(nm, all, d);
|
||||
}
|
||||
|
||||
/* logit_softcap, against an f64 evaluation of the same formula.
|
||||
*
|
||||
* THE CAP IS THE PARAMETER THE MODEL LIVES IN (Gemma 4's graph issues it at 30.0), so the case
|
||||
* runs at two values: the model's, and a smaller one that moves every answer -- a kernel that
|
||||
* hard-wires 30.0, or one that swaps `cap` with its inverse, passes one cap and fails the other.
|
||||
*
|
||||
* The inputs are 0, half, one, two and five TIMES THE CAP, signed: x/cap is then an exact small
|
||||
* half-integer, the f64 oracle cap * tanh(x/cap) is five constants deep, and the only room for an
|
||||
* error in the comparison is the kernel's own f32 arithmetic and its bf16 store. The tolerance is
|
||||
* this file's f32-against-f64 one (1% relative, 1e-3 absolute). */
|
||||
static void logit_softcap_case(const Plugin& pl) {
|
||||
const char* what = "logit_softcap vs an f64 evaluation of the same formula";
|
||||
/* Both device legs run the case: bf16 (the gemm's own dtype) and f32 (the 1.3.0 sampling
|
||||
* chain, where the logits reach the softcap as f32 rows). The f32 leg answers in the
|
||||
* arithmetic dtype itself, so its oracle compare reads f32, not a bf16 round trip. */
|
||||
for (const uint32_t dt : { (uint32_t)RAD_BF16, (uint32_t)RAD_F32 }) {
|
||||
const char* row = dt == RAD_BF16 ? "logit_softcap_bf16" : "logit_softcap_f32";
|
||||
const size_t es = dt == RAD_BF16 ? 2 : 4;
|
||||
const RadKernelInfo* r = find(pl, row);
|
||||
if (!r) { ok(what, false, std::string("row absent: ") + row); return; }
|
||||
|
||||
const int64_t M = 7, n = 128;
|
||||
for (const double capd : { 30.0, 10.0 }) {
|
||||
std::vector<uint16_t> xh((size_t)M * n);
|
||||
std::vector<float> xf((size_t)M * n);
|
||||
std::vector<double> want((size_t)M * n);
|
||||
const double mags[5] = { 0.0, 0.5, 1.0, 2.0, 5.0 };
|
||||
for (int64_t i = 0; i < M * n; ++i) {
|
||||
const double mag = mags[(int)((i * 31) % 5)];
|
||||
const double sgn = (mag == 0.0 || (i * 17) % 2 == 0) ? 1.0 : -1.0;
|
||||
const double xv = sgn * mag * capd;
|
||||
xh[(size_t)i] = h_to_bf16((float)xv);
|
||||
xf[(size_t)i] = (float)xv;
|
||||
want[(size_t)i] = capd * std::tanh(xv / capd);
|
||||
}
|
||||
|
||||
void* d_x = dalloc((size_t)(M * n) * es);
|
||||
void* d_o = dalloc((size_t)(M * n) * es);
|
||||
if (!d_x || !d_o) { ok(what, false, "hipMalloc failed"); return; }
|
||||
st_memcpy(d_x, dt == RAD_BF16 ? (const void*)xh.data() : (const void*)xf.data(),
|
||||
(size_t)(M * n) * es, hipMemcpyHostToDevice);
|
||||
|
||||
std::vector<RadTensor> ts = {
|
||||
T(d_x, dt, { M, n }),
|
||||
T(d_o, dt, { M, n }),
|
||||
};
|
||||
std::vector<RadParam> ps = { PI("n", n), PF("cap", capd) };
|
||||
RadArgs a;
|
||||
std::memset(&a, 0, sizeof(a));
|
||||
a.t = ts.data(); a.n_t = (int)ts.size();
|
||||
a.p = ps.data(); a.n_p = (int)ps.size();
|
||||
|
||||
const int rc = r->launch(&a, nullptr);
|
||||
st_stream_sync(nullptr);
|
||||
if (rc != RAD_OK) {
|
||||
ok(what, false, "launch rc=" + std::to_string(rc) + " cap=" + std::to_string(capd));
|
||||
return;
|
||||
}
|
||||
|
||||
std::vector<uint16_t> got((size_t)(M * n));
|
||||
std::vector<float> gotf((size_t)(M * n));
|
||||
st_memcpy(dt == RAD_BF16 ? (void*)got.data() : (void*)gotf.data(), d_o,
|
||||
(size_t)(M * n) * es, hipMemcpyDeviceToHost);
|
||||
double worst = 0.0;
|
||||
int64_t bad = 0;
|
||||
for (int64_t i = 0; i < M * n; ++i) {
|
||||
const double v = dt == RAD_BF16 ? (double)h_bf16(got[(size_t)i])
|
||||
: (double)gotf[(size_t)i];
|
||||
const double e = v - want[(size_t)i];
|
||||
if (std::fabs(e) > worst) worst = std::fabs(e);
|
||||
if (std::fabs(e) > 1e-2 * (std::fabs(want[(size_t)i]) + 1e-3)) ++bad;
|
||||
}
|
||||
ok(what, bad == 0, std::string(row) + " cap=" + std::to_string(capd) +
|
||||
" worst_abs=" + std::to_string(worst) + " bad=" + std::to_string(bad));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* rmsnorm_p, against an f64 evaluation of the weightless normalisation.
|
||||
*
|
||||
* THE EPS IS THE PARAMETER THE MODEL LIVES IN (Gemma 4 issues it at 1e-6), so the case runs at
|
||||
* two values: the model's, and a larger one (1e-2) that moves every answer -- a kernel that hard-
|
||||
* wires 1e-6, or one that drops the +eps and answers a bare 1/rms, passes the small one and fails
|
||||
* the large.
|
||||
*
|
||||
* The inputs are a fixed set of magnitudes, signed, so the f64 oracle x * rsqrt(mean(x^2) + eps)
|
||||
* is exact and the only room for an error in the comparison is the kernel's own f32 accumulation
|
||||
* and its bf16 store. The oracle is computed from the bf16 values the kernel actually reads. The
|
||||
* tolerance is this file's f32-against-f64 one (1% relative, 1e-3 absolute). */
|
||||
static void rmsnorm_p_case(const Plugin& pl) {
|
||||
const char* what = "rmsnorm_p vs an f64 evaluation of the weightless normalisation";
|
||||
const RadKernelInfo* r = find(pl, "rmsnorm_p_bf16");
|
||||
if (!r) { ok(what, false, "row absent"); return; }
|
||||
|
||||
const int64_t M = 7, n = 640;
|
||||
for (const double epsd : { 1e-6, 1e-2 }) {
|
||||
std::vector<uint16_t> xh((size_t)M * n);
|
||||
const double mags[5] = { 0.0, 0.5, 1.0, 2.0, 5.0 };
|
||||
for (int64_t i = 0; i < M * n; ++i) {
|
||||
const double mag = mags[(int)((i * 31) % 5)];
|
||||
const double sgn = (mag == 0.0 || (i * 17) % 2 == 0) ? 1.0 : -1.0;
|
||||
xh[(size_t)i] = h_to_bf16((float)(sgn * mag));
|
||||
}
|
||||
|
||||
// f64 oracle from the bf16 values the kernel reads: y = x * rsqrt(mean(x^2) + eps).
|
||||
std::vector<double> want((size_t)M * n);
|
||||
for (int64_t m = 0; m < M; ++m) {
|
||||
double ss = 0.0;
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const double v = (double)h_bf16(xh[(size_t)m * n + i]);
|
||||
ss += v * v;
|
||||
}
|
||||
const double s = 1.0 / std::sqrt(ss / (double)n + epsd);
|
||||
for (int64_t i = 0; i < n; ++i)
|
||||
want[(size_t)m * n + i] = (double)h_bf16(xh[(size_t)m * n + i]) * s;
|
||||
}
|
||||
|
||||
void* d_x = dalloc(xh.size() * 2);
|
||||
void* d_o = dalloc((size_t)(M * n) * 2);
|
||||
if (!d_x || !d_o) { ok(what, false, "hipMalloc failed"); return; }
|
||||
st_memcpy(d_x, xh.data(), xh.size() * 2, hipMemcpyHostToDevice);
|
||||
|
||||
std::vector<RadTensor> ts = {
|
||||
T(d_x, RAD_BF16, { M, n }),
|
||||
T(d_o, RAD_BF16, { M, n }),
|
||||
};
|
||||
std::vector<RadParam> ps = { PI("n", n), PF("eps", epsd) };
|
||||
RadArgs a;
|
||||
std::memset(&a, 0, sizeof(a));
|
||||
a.t = ts.data(); a.n_t = (int)ts.size();
|
||||
a.p = ps.data(); a.n_p = (int)ps.size();
|
||||
|
||||
const int rc = r->launch(&a, nullptr);
|
||||
st_stream_sync(nullptr);
|
||||
if (rc != RAD_OK) {
|
||||
ok(what, false, "launch rc=" + std::to_string(rc) + " eps=" + std::to_string(epsd));
|
||||
return;
|
||||
}
|
||||
|
||||
std::vector<uint16_t> got((size_t)(M * n));
|
||||
st_memcpy(got.data(), d_o, got.size() * 2, hipMemcpyDeviceToHost);
|
||||
double worst = 0.0;
|
||||
int64_t bad = 0;
|
||||
for (int64_t i = 0; i < M * n; ++i) {
|
||||
const double e = (double)h_bf16(got[(size_t)i]) - want[(size_t)i];
|
||||
if (std::fabs(e) > worst) worst = std::fabs(e);
|
||||
if (std::fabs(e) > 1e-2 * (std::fabs(want[(size_t)i]) + 1e-3)) ++bad;
|
||||
}
|
||||
ok(what, bad == 0, "eps=" + std::to_string(epsd) +
|
||||
" worst_abs=" + std::to_string(worst) + " bad=" + std::to_string(bad));
|
||||
}
|
||||
}
|
||||
|
||||
/* gelu_mul, against an f64 evaluation of the tanh-approximation GELU.
|
||||
*
|
||||
* The inputs are a fixed set of magnitudes, signed, for both the gate and the up half, so the f64
|
||||
* oracle 0.5*g*(1 + tanh(0.7978845608028654*(g + 0.044715*g^3))) * u is exact and the only room for
|
||||
* an error in the comparison is the kernel's own f32 tanhf and its bf16 store. The oracle is computed
|
||||
* from the bf16 values the kernel reads; the gate is the first half of the [M, 2n] row. The
|
||||
* tolerance is this file's f32-against-f64 one (1% relative, 1e-3 absolute). */
|
||||
static void gelu_mul_case(const Plugin& pl) {
|
||||
const char* what = "gelu_mul vs an f64 evaluation of the tanh GELU";
|
||||
const RadKernelInfo* r = find(pl, "gelu_mul_bf16");
|
||||
if (!r) { ok(what, false, "row absent"); return; }
|
||||
|
||||
const int64_t M = 7, n = 640;
|
||||
std::vector<uint16_t> gh((size_t)M * 2 * n);
|
||||
const double mags[5] = { 0.0, 0.5, 1.0, 2.0, 5.0 };
|
||||
for (int64_t i = 0; i < M * 2 * n; ++i) {
|
||||
const double mag = mags[(int)((i * 31) % 5)];
|
||||
const double sgn = (mag == 0.0 || (i * 17) % 2 == 0) ? 1.0 : -1.0;
|
||||
gh[(size_t)i] = h_to_bf16((float)(sgn * mag));
|
||||
}
|
||||
|
||||
// f64 oracle from the bf16 values the kernel reads: y = gelu_tanh(gate) * up, gate the first half.
|
||||
std::vector<double> want((size_t)M * n);
|
||||
const double k0 = 0.7978845608028654, k1 = 0.044715;
|
||||
for (int64_t m = 0; m < M; ++m) {
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const double g = (double)h_bf16(gh[(size_t)m * 2 * n + i]);
|
||||
const double u = (double)h_bf16(gh[(size_t)m * 2 * n + n + i]);
|
||||
const double gelu = 0.5 * g * (1.0 + std::tanh(k0 * (g + k1 * g * g * g)));
|
||||
want[(size_t)m * n + i] = gelu * u;
|
||||
}
|
||||
}
|
||||
|
||||
void* d_g = dalloc(gh.size() * 2);
|
||||
void* d_o = dalloc((size_t)(M * n) * 2);
|
||||
if (!d_g || !d_o) { ok(what, false, "hipMalloc failed"); return; }
|
||||
st_memcpy(d_g, gh.data(), gh.size() * 2, hipMemcpyHostToDevice);
|
||||
|
||||
std::vector<RadTensor> ts = {
|
||||
T(d_g, RAD_BF16, { M, 2 * n }),
|
||||
T(d_o, RAD_BF16, { M, n }),
|
||||
};
|
||||
std::vector<RadParam> ps = { PI("n", n) };
|
||||
RadArgs a;
|
||||
std::memset(&a, 0, sizeof(a));
|
||||
a.t = ts.data(); a.n_t = (int)ts.size();
|
||||
a.p = ps.data(); a.n_p = (int)ps.size();
|
||||
|
||||
const int rc = r->launch(&a, nullptr);
|
||||
st_stream_sync(nullptr);
|
||||
if (rc != RAD_OK) {
|
||||
ok(what, false, "launch rc=" + std::to_string(rc));
|
||||
return;
|
||||
}
|
||||
|
||||
std::vector<uint16_t> got((size_t)(M * n));
|
||||
st_memcpy(got.data(), d_o, got.size() * 2, hipMemcpyDeviceToHost);
|
||||
double worst = 0.0;
|
||||
int64_t bad = 0;
|
||||
for (int64_t i = 0; i < M * n; ++i) {
|
||||
const double e = (double)h_bf16(got[(size_t)i]) - want[(size_t)i];
|
||||
if (std::fabs(e) > worst) worst = std::fabs(e);
|
||||
if (std::fabs(e) > 1e-2 * (std::fabs(want[(size_t)i]) + 1e-3)) ++bad;
|
||||
}
|
||||
ok(what, bad == 0, "worst_abs=" + std::to_string(worst) + " bad=" + std::to_string(bad));
|
||||
}
|
||||
|
||||
/* scale, against an f64 evaluation of the same multiply.
|
||||
*
|
||||
* THE SCALAR IS THE [1] WEIGHT THE MODEL LIVES IN (Gemma 4's per-layer scalar, 0.03-0.99), so the
|
||||
* case runs at three values: two positive of different magnitude (a kernel that hard-wires one of
|
||||
* them, or one that squares the scalar, passes one and fails the other) and a negative (a kernel
|
||||
* that drops the sign passes the positives and fails this).
|
||||
*
|
||||
* The inputs are a fixed set of magnitudes, signed, so the f64 oracle x * s is five constants deep
|
||||
* and the only room for an error in the comparison is the kernel's own f32 arithmetic and its bf16
|
||||
* store. The tolerance is this file's f32-against-f64 one (1% relative, 1e-3 absolute). The scalar
|
||||
* is stored as f32 (the kernel's branch reads it as such); a bf16 `s` takes the other branch and is
|
||||
* not exercised here, which is fine -- the multiply is the same either way. */
|
||||
static void scale_case(const Plugin& pl) {
|
||||
const char* what = "scale vs an f64 evaluation of the same multiply";
|
||||
const RadKernelInfo* r = find(pl, "scale_bf16");
|
||||
if (!r) { ok(what, false, "row absent"); return; }
|
||||
|
||||
const int64_t M = 7, n = 128;
|
||||
for (const double sv : { 2.0, 0.5, -1.5 }) {
|
||||
std::vector<uint16_t> xh((size_t)M * n);
|
||||
std::vector<double> want((size_t)M * n);
|
||||
const double mags[5] = { 0.0, 0.5, 1.0, 2.0, 3.0 };
|
||||
for (int64_t i = 0; i < M * n; ++i) {
|
||||
const double mag = mags[(int)((i * 31) % 5)];
|
||||
const double sgn = (mag == 0.0 || (i * 17) % 2 == 0) ? 1.0 : -1.0;
|
||||
const double xv = sgn * mag;
|
||||
xh[(size_t)i] = h_to_bf16((float)xv);
|
||||
want[(size_t)i] = xv * sv;
|
||||
}
|
||||
|
||||
void* d_x = dalloc(xh.size() * 2);
|
||||
void* d_s = dalloc(4);
|
||||
void* d_o = dalloc((size_t)(M * n) * 2);
|
||||
if (!d_x || !d_s || !d_o) { ok(what, false, "hipMalloc failed"); return; }
|
||||
st_memcpy(d_x, xh.data(), xh.size() * 2, hipMemcpyHostToDevice);
|
||||
const float sf = (float)sv;
|
||||
st_memcpy(d_s, &sf, 4, hipMemcpyHostToDevice);
|
||||
|
||||
std::vector<RadTensor> ts = {
|
||||
T(d_x, RAD_BF16, { M, n }),
|
||||
T(d_s, RAD_F32, { 1 }),
|
||||
T(d_o, RAD_BF16, { M, n }),
|
||||
};
|
||||
std::vector<RadParam> ps = { PI("n", n) };
|
||||
RadArgs a;
|
||||
std::memset(&a, 0, sizeof(a));
|
||||
a.t = ts.data(); a.n_t = (int)ts.size();
|
||||
a.p = ps.data(); a.n_p = (int)ps.size();
|
||||
|
||||
const int rc = r->launch(&a, nullptr);
|
||||
st_stream_sync(nullptr);
|
||||
if (rc != RAD_OK) {
|
||||
ok(what, false, "launch rc=" + std::to_string(rc) + " s=" + std::to_string(sv));
|
||||
return;
|
||||
}
|
||||
|
||||
std::vector<uint16_t> got((size_t)(M * n));
|
||||
st_memcpy(got.data(), d_o, got.size() * 2, hipMemcpyDeviceToHost);
|
||||
double worst = 0.0;
|
||||
int64_t bad = 0;
|
||||
for (int64_t i = 0; i < M * n; ++i) {
|
||||
const double e = (double)h_bf16(got[(size_t)i]) - want[(size_t)i];
|
||||
if (std::fabs(e) > worst) worst = std::fabs(e);
|
||||
if (std::fabs(e) > 1e-2 * (std::fabs(want[(size_t)i]) + 1e-3)) ++bad;
|
||||
}
|
||||
ok(what, bad == 0, "s=" + std::to_string(sv) +
|
||||
" worst_abs=" + std::to_string(worst) + " bad=" + std::to_string(bad));
|
||||
}
|
||||
}
|
||||
|
||||
/* rope_bf16, against an f32 mirror of rope_kernel at each ladder width. `den` is the ladder's
|
||||
* width -- `rot` for `rotary`/absent and `head_dim` for `head` -- so the same kernel body is
|
||||
* checked under both. The V head is untouched in every case; the absences there would be invisible
|
||||
* in magnitude (the rotation preserves length) and rel_l2 is what sees the angle itself. */
|
||||
static void rope_ladder_case(const Plugin& pl) {
|
||||
const char* what = "rope ladder vs an f32 mirror of rope_kernel at each width";
|
||||
const RadKernelInfo* r = find(pl, "rope_bf16");
|
||||
if (!r) { ok(what, false, "row absent"); return; }
|
||||
|
||||
const int64_t M = 5, hd = 64, rot = 32, half = rot / 2;
|
||||
const int64_t n_head = 2, nkv = 1, n_rope = n_head + nkv; /* 3 rotate, one V does not */
|
||||
const int64_t row = (n_head + 2 * nkv) * hd;
|
||||
const float theta = 10000.0f;
|
||||
const int32_t pos[5] = { 0, 1, 7, 128, 4096 };
|
||||
|
||||
for (const char* lad : std::initializer_list<const char*>{ nullptr, "rotary", "head" }) {
|
||||
const int64_t den = (lad && !std::strcmp(lad, "head")) ? hd : rot;
|
||||
const char* tag = lad ? lad : "absent";
|
||||
|
||||
std::vector<uint16_t> saved((size_t)M * row);
|
||||
for (int64_t i = 0; i < M * row; ++i) {
|
||||
float v = (float)(((i * 5) % 17) - 8) / 9.0f;
|
||||
if (i % 13 == 0) v *= 4.0f; /* a few big channels */
|
||||
saved[(size_t)i] = h_to_bf16(v);
|
||||
}
|
||||
|
||||
void* d_qkv = dalloc(saved.size() * 2);
|
||||
void* d_pos = dalloc(M * 4);
|
||||
if (!d_qkv || !d_pos) { ok(what, false, "hipMalloc failed"); return; }
|
||||
st_memcpy(d_qkv, saved.data(), saved.size() * 2, hipMemcpyHostToDevice);
|
||||
st_memcpy(d_pos, pos, M * 4, hipMemcpyHostToDevice);
|
||||
|
||||
std::vector<RadTensor> ts = { T(d_qkv, RAD_BF16, { M, row }), T(d_pos, RAD_I32, { M }) };
|
||||
std::vector<RadParam> ps = { PI("M", M), PI("head_dim", hd), PI("n_head", n_head),
|
||||
PI("n_head_kv", nkv), PF("theta", (double)theta),
|
||||
PF("scale", 1.0), PS("mode", "neox"),
|
||||
PI("rotary_dim", rot) };
|
||||
if (lad) ps.push_back(PS("ladder", lad));
|
||||
RadArgs a;
|
||||
std::memset(&a, 0, sizeof(a));
|
||||
a.t = ts.data(); a.n_t = (int)ts.size();
|
||||
a.p = ps.data(); a.n_p = (int)ps.size();
|
||||
|
||||
const int rc = r->launch(&a, nullptr);
|
||||
st_stream_sync(nullptr);
|
||||
if (rc != RAD_OK) { ok(what, false, std::string("ladder=") + tag + " rc=" + std::to_string(rc)); return; }
|
||||
|
||||
std::vector<uint16_t> got((size_t)M * row);
|
||||
st_memcpy(got.data(), d_qkv, got.size() * 2, hipMemcpyDeviceToHost);
|
||||
|
||||
double num = 0.0, dnorm = 0.0;
|
||||
int64_t untouched_bad = 0;
|
||||
for (int64_t m = 0; m < M; ++m) {
|
||||
const size_t base = (size_t)m * row;
|
||||
for (int64_t h = 0; h < n_rope; ++h) {
|
||||
for (int64_t i = 0; i < half; ++i) {
|
||||
const size_t i0 = base + (size_t)h * hd + i;
|
||||
const size_t i1 = i0 + half;
|
||||
const float x0 = h_bf16(saved[(size_t)i0]), x1 = h_bf16(saved[(size_t)i1]);
|
||||
const float inv = 1.0f / powf(theta, (float)(2 * i) / (float)den);
|
||||
float s, c;
|
||||
sincosf((float)pos[(size_t)m] * inv, &s, &c);
|
||||
const float w0 = x0 * c - x1 * s, w1 = x0 * s + x1 * c;
|
||||
const float g0 = h_bf16(got[(size_t)i0]), g1 = h_bf16(got[(size_t)i1]);
|
||||
num += (double)(g0 - w0) * (double)(g0 - w0) +
|
||||
(double)(g1 - w1) * (double)(g1 - w1);
|
||||
dnorm += (double)w0 * w0 + (double)w1 * w1;
|
||||
}
|
||||
}
|
||||
for (int64_t e = 0; e < hd; ++e) /* the V head is untouched, so exact */
|
||||
if (got[base + (size_t)n_rope * hd + e] != saved[base + (size_t)n_rope * hd + e])
|
||||
++untouched_bad;
|
||||
}
|
||||
const double rel = dnorm > 0.0 ? std::sqrt(num / dnorm) : 0.0;
|
||||
ok(what, rel < 2e-3 && untouched_bad == 0, std::string("ladder=") + tag + " rel_l2=" +
|
||||
std::to_string(rel) + " vhead-moved=" + std::to_string(untouched_bad));
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- the two fp8 fusions, against the pair each one replaces -------------------------------- */
|
||||
//
|
||||
// THE INVARIANT IS NOT "CLOSE", IT IS BYTE-IDENTICAL, which is why this compares against the
|
||||
@@ -11246,6 +11795,43 @@ static void device_phase(const Plugin& pl) {
|
||||
attn_case(pl, "attn_decode_h256_gqa6_bf16kv", 256, 6, 1, "bf16", 0);
|
||||
attn_case(pl, "attn_decode_h128_gqa4_fp8kv", 128, 4, 1, "fp8_e4m3", 0);
|
||||
attn_case(pl, "attn_decode_h128_gqa4_bf16kv", 128, 4, 1, "bf16", 0);
|
||||
/* Gemma 4 dense sliding window: decode only, so the window is threaded through -- 1024 is the
|
||||
* model's window. It exercises the windowed split law and the WIN=1 template the way the
|
||||
* drafter leg does; max_ctx here is smaller than the window, so the span clamps to the context. */
|
||||
attn_case(pl, "attn_decode_h256_gqa2_fp8kv", 256, 2, 1, "fp8_e4m3", 0, 1024);
|
||||
attn_case(pl, "attn_decode_h256_gqa2_bf16kv", 256, 2, 1, "bf16", 0, 1024);
|
||||
/* Gemma 4 dense sliding window: the PREFILL leg (Path 2). The decode leg above was decode-only,
|
||||
* leaving the prefill band (q_len > 32) with no device kernel -- fatal, since libref is an
|
||||
* opt-in fallback the engine refuses by default (spec §17). This is the windowed query-tiled
|
||||
* prefill kernel; window 1024 is the model's, threaded through to instantiate WIN=1 the way the
|
||||
* decode leg does. max_ctx here (64) is smaller than the window, so the span clamps to the
|
||||
* context and the launch is the full-attention form. */
|
||||
attn_case(pl, "attn_prefill_h256_gqa2_fp8kv", 256, 2, 32, "fp8_e4m3", 1, 1024);
|
||||
attn_case(pl, "attn_prefill_h256_gqa2_bf16kv", 256, 2, 32, "bf16", 1, 1024);
|
||||
/* Gemma 4 dense global: head_dim 512, full attention. The one head_dim with no fixture yet, so
|
||||
* these launch-only cases are its box coverage -- the numeric byte-equality gate is the 3a GPU
|
||||
* step, not here. Prefill at q_len 32, decode at 1, mirroring the gqa6 leg's pair. */
|
||||
attn_case(pl, "attn_prefill_h512_gqa8_fp8kv", 512, 8, 32, "fp8_e4m3", 1);
|
||||
attn_case(pl, "attn_prefill_h512_gqa8_bf16kv", 512, 8, 32, "bf16", 1);
|
||||
attn_case(pl, "attn_decode_h512_gqa8_fp8kv", 512, 8, 1, "fp8_e4m3", 0);
|
||||
attn_case(pl, "attn_decode_h512_gqa8_bf16kv", 512, 8, 1, "bf16", 0);
|
||||
/* The numeric attention check (Phase 3): the same rows, but with random data and a comparison
|
||||
* against the inline oracle, plus a negative control. h512 is prefill + decode; h256/gqa2 is
|
||||
* decode-only (the windowed sliding-window leg, window 1024). */
|
||||
attn_numeric_case(pl, "attn_prefill_h512_gqa8_fp8kv", 512, 8, 32, "fp8_e4m3", 0);
|
||||
attn_numeric_case(pl, "attn_prefill_h512_gqa8_bf16kv", 512, 8, 32, "bf16", 0);
|
||||
attn_numeric_case(pl, "attn_decode_h512_gqa8_fp8kv", 512, 8, 1, "fp8_e4m3", 0);
|
||||
attn_numeric_case(pl, "attn_decode_h512_gqa8_bf16kv", 512, 8, 1, "bf16", 0);
|
||||
/* The h256/gqa2 PREFILL numeric check. Unlike the decode leg (ctx 64 < window, so the window
|
||||
* clamps to the context), ctx here is 2048 > window 1024, so the window actually bites: for
|
||||
* query row 0, pos = 2048-64 = 1984 and the visible keys are [961..1984], so the kernel's
|
||||
* wlo0 = 961 and tstart = 961/48 = 20 -- exercising both the window mask (keys below 961 are
|
||||
* masked) and the below-window tile skip (tiles 0..19 are never walked). The oracle's
|
||||
* visible() is the same bound, so the two agree. */
|
||||
attn_numeric_case(pl, "attn_prefill_h256_gqa2_fp8kv", 256, 2, 64, "fp8_e4m3", 1024, 2048);
|
||||
attn_numeric_case(pl, "attn_prefill_h256_gqa2_bf16kv", 256, 2, 64, "bf16", 1024, 2048);
|
||||
attn_numeric_case(pl, "attn_decode_h256_gqa2_fp8kv", 256, 2, 1, "fp8_e4m3", 1024);
|
||||
attn_numeric_case(pl, "attn_decode_h256_gqa2_bf16kv", 256, 2, 1, "bf16", 1024);
|
||||
attn_gq_fold_case(pl, 3, false);
|
||||
attn_gq_fold_case(pl, 24, false);
|
||||
attn_gq_fold_case(pl, 3, true);
|
||||
@@ -12529,6 +13115,31 @@ static void device_phase(const Plugin& pl) {
|
||||
qsa_block_key_yarn_case(pl);
|
||||
}
|
||||
|
||||
if (sel("logit_softcap_bf16")) {
|
||||
if (!g_case) std::printf("\nthe final-logit softcap, against the formula it implements\n");
|
||||
logit_softcap_case(pl);
|
||||
}
|
||||
|
||||
if (sel("rmsnorm_p_bf16")) {
|
||||
if (!g_case) std::printf("\nthe weightless RMS norm, against the formula it implements\n");
|
||||
rmsnorm_p_case(pl);
|
||||
}
|
||||
|
||||
if (sel("gelu_mul_bf16")) {
|
||||
if (!g_case) std::printf("\nthe gelu-gated product, against the formula it implements\n");
|
||||
gelu_mul_case(pl);
|
||||
}
|
||||
|
||||
if (sel("scale_bf16")) {
|
||||
if (!g_case) std::printf("\nthe per-tensor scalar scale, against the multiply it implements\n");
|
||||
scale_case(pl);
|
||||
}
|
||||
|
||||
if (sel("rope_bf16")) {
|
||||
if (!g_case) std::printf("\nthe rotary ladder, against an f32 mirror of the kernel at each width\n");
|
||||
rope_ladder_case(pl);
|
||||
}
|
||||
|
||||
if (sel("moe_gemm_w4a8")) {
|
||||
if (!g_case) std::printf("\nthe 4-bit grouped MoE GEMM, against a host decode\n");
|
||||
/* One geometry; a gate/up pair whose odd experts are half as wide; a down projection
|
||||
|
||||
@@ -1272,6 +1272,17 @@ extern "C" int r4d_shape_scale_rows(const RadParam* p, int n_p, int operand, Rad
|
||||
R4D_PICK(l);
|
||||
}
|
||||
|
||||
/* The per-tensor scalar: one [1] weight broadcast over the whole [M, n] extent. `s` is the middle
|
||||
* operand; its extent is 1, not M (that would be scale_rows) and not M*n (that would be a
|
||||
* per-element mask). The scalar's dtype is the stream's, so a bf16 or f32 `s` both read. */
|
||||
extern "C" int r4d_shape_scale(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n");
|
||||
if (M <= 0 || n <= 0) return RAD_E_UNSUPPORTED;
|
||||
const uint32_t D = dt_act(p, n_p, "dtype");
|
||||
const RadOpdDesc l[] = { opd(D, M, n), opd(D, 1), opd(D, M, n) };
|
||||
R4D_PICK(l);
|
||||
}
|
||||
|
||||
extern "C" int r4d_shape_router_topk(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = pi(p, n_p, "M");
|
||||
const int64_t ne = pi(p, n_p, "n_expert");
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
@@ -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",
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
+134
-4
@@ -254,10 +254,11 @@ TEST(plugin_surface) {
|
||||
* which is a decision and not an oversight (docs/OPS.md). */
|
||||
TEST(op_vocabulary) {
|
||||
static const char* kOps[] = {
|
||||
"rmsnorm", "rmsnorm_add", "hc_enter", "hc_read", "hc_write", "mtp_enter",
|
||||
"layernorm", "add", "mul", "mul_weight", "silu_mul", "act_mul", "seg_mean", "pool_rows",
|
||||
"relu", "clamp", "conv2d", "conv1d_dw", "rel_sinusoid", "attn_local_rel", "gelu", "silu",
|
||||
"sigmoid", "fill", "gather_rows", "scatter_rows", "ngram_ids", "ple_gate", "ple_conv",
|
||||
"rmsnorm", "rmsnorm_p", "rmsnorm_add", "hc_enter", "hc_read", "hc_write", "mtp_enter",
|
||||
"layernorm", "add", "mul", "mul_weight", "silu_mul", "gelu_mul", "act_mul", "seg_mean",
|
||||
"pool_rows", "relu", "clamp", "conv2d", "conv1d_dw", "rel_sinusoid", "attn_local_rel",
|
||||
"gelu", "silu", "sigmoid", "logit_softcap", "scale", "fill",
|
||||
"gather_rows", "scatter_rows", "ngram_ids", "ple_gate", "ple_conv",
|
||||
"embed_lookup_q", "cast",
|
||||
"scale_rows",
|
||||
"softmax",
|
||||
@@ -448,6 +449,24 @@ TEST(op_rmsnorm) {
|
||||
CHECK_NEAR(y2.at(3), 4 * s, 1e-6);
|
||||
}
|
||||
|
||||
/* The weightless rmsnorm: same normalisation as rmsnorm with no gain, so the row divides by its
|
||||
* rms and stops. The literals are exactly op_rmsnorm's, because a plain norm IS rmsnorm whose gain
|
||||
* is one. */
|
||||
TEST(op_rmsnorm_p) {
|
||||
T x(RAD_F32, {1, 4}); x.f({1, 2, 3, 4});
|
||||
T y(RAD_F32, {1, 4});
|
||||
A a; a.t(x).t(y).i("M", 1).i("n", 4).d("eps", 0).s("dtype", "f32");
|
||||
CHECK_OK(run("rmsnorm_p", a));
|
||||
/* rms = sqrt((1+4+9+16)/4) = sqrt(7.5) = 2.7386128 */
|
||||
const float s = 1.0f / 2.7386128f;
|
||||
CHECK_NEAR(y.at(0), 1 * s, 1e-6);
|
||||
CHECK_NEAR(y.at(3), 4 * s, 1e-6);
|
||||
|
||||
/* A non-positive n is not a normalisation, so it is refused rather than answered. */
|
||||
A bb; bb.t(x).t(y).i("M", 1).i("n", 0).d("eps", 0).s("dtype", "f32");
|
||||
CHECK(run("rmsnorm_p", bb) != RAD_OK);
|
||||
}
|
||||
|
||||
TEST(op_rmsnorm_add) {
|
||||
T x(RAD_F32, {1, 2}); x.f({1, 3});
|
||||
T res(RAD_F32, {1, 2}); res.f({1, 1});
|
||||
@@ -521,6 +540,70 @@ TEST(op_silu_mul_and_unary) {
|
||||
CHECK_NEAR(s.at(1), 0.73105858f, 1e-6);
|
||||
}
|
||||
|
||||
/* Gemma's gated FFN, on paper: same fused layout as silu_mul (gate the first half, up the second)
|
||||
* but the gate runs the tanh GELU, not silu. gelu_tanh matches the gemm_nt_bias tanh epilogue and
|
||||
* differs from the unary `gelu` (exact erf) -- the check at 1.0 pins that difference: erf gelu(1) is
|
||||
* 0.84134..., the tanh form is 0.84119.... */
|
||||
TEST(op_gelu_mul) {
|
||||
T gu(RAD_F32, {1, 4}); gu.f({1, 2, 3, 4}); /* gate [1,2], up [3,4] */
|
||||
T y(RAD_F32, {1, 2});
|
||||
A a; a.t(gu).t(y).i("M", 1).i("n", 2).s("dtype", "f32");
|
||||
CHECK_OK(run("gelu_mul", a));
|
||||
CHECK_NEAR(y.at(0), 0.84119199f * 3.0f, 1e-6); /* gelu_tanh(1) * up */
|
||||
CHECK_NEAR(y.at(1), 1.95459769f * 4.0f, 1e-6); /* gelu_tanh(2) * up */
|
||||
/* And the negative side, where tanh gelu and erf gelu drift furthest. */
|
||||
T gx(RAD_F32, {1, 4}); gx.f({-2, -1, 3, 4}); /* gate [-2,-1], up [3,4] */
|
||||
T gy(RAD_F32, {1, 2});
|
||||
A b; b.t(gx).t(gy).i("M", 1).i("n", 2).s("dtype", "f32");
|
||||
CHECK_OK(run("gelu_mul", b));
|
||||
CHECK_NEAR(gy.at(0), -0.04540231f * 3.0f, 1e-6); /* gelu_tanh(-2) * up */
|
||||
CHECK_NEAR(gy.at(1), -0.15880801f * 4.0f, 1e-6); /* gelu_tanh(-1) * up */
|
||||
}
|
||||
|
||||
/* The final-logit softcap, on paper. `cap` at 30 -- Gemma's value -- and the input the kernel
|
||||
* actually sees after a logits_gemm, reduced to the five ratios the formula can take: 0, cap/2,
|
||||
* both signs of cap, and 2 cap. Every ratio is exact in f32, so the literals below are tanh of a
|
||||
* small integer, and the check is the f32 rounding of the product and nothing else. */
|
||||
TEST(op_logit_softcap) {
|
||||
T x(RAD_F32, {5}); x.f({ 0.0f, 15.0f, 30.0f, -30.0f, 60.0f });
|
||||
T y(RAD_F32, {5});
|
||||
A a; a.t(x).t(y).i("M", 1).i("n", 5).d("cap", 30.0).s("dtype", "f32");
|
||||
CHECK_OK(run("logit_softcap", a));
|
||||
CHECK_EQ(y.at(0), 0.0f);
|
||||
CHECK_NEAR(y.at(1), 30.0f * 0.4621171573f, 1e-5); /* tanh(1/2) */
|
||||
CHECK_NEAR(y.at(2), 30.0f * 0.7615941560f, 1e-5); /* tanh(1) */
|
||||
CHECK_NEAR(y.at(3), -30.0f * 0.7615941560f, 1e-5); /* tanh(-1) */
|
||||
CHECK_NEAR(y.at(4), 30.0f * 0.9640275801f, 1e-5); /* tanh(2) */
|
||||
|
||||
/* A non-positive cap is a division by zero in every lane, so it is refused, not answered. */
|
||||
T y2(RAD_F32, {5});
|
||||
A b; b.t(x).t(y2).i("M", 1).i("n", 5).d("cap", 0.0).s("dtype", "f32");
|
||||
CHECK(run("logit_softcap", b) != RAD_OK);
|
||||
}
|
||||
|
||||
/* The per-tensor scalar scale. `s` is a [1] weight broadcast over every element, so the answer is
|
||||
* a literal times the literal -- not a second call into the same multiply. The negative case is a
|
||||
* scalar with no element: that is a shape error, not a broadcast of zero (a zero scalar would be a
|
||||
* plausible number, which is the thing this file's rule exists to rule out). */
|
||||
TEST(op_scale) {
|
||||
T x(RAD_F32, {5}); x.f({ 0.0f, 2.0f, 4.0f, -6.0f, 8.0f });
|
||||
T s(RAD_F32, {1}); s.f({ 3.0f });
|
||||
T y(RAD_F32, {5});
|
||||
A a; a.t(x).t(s).t(y).i("M", 1).i("n", 5).s("dtype", "f32");
|
||||
CHECK_OK(run("scale", a));
|
||||
CHECK_EQ(y.at(0), 0.0f);
|
||||
CHECK_EQ(y.at(1), 6.0f);
|
||||
CHECK_EQ(y.at(2), 12.0f);
|
||||
CHECK_EQ(y.at(3), -18.0f);
|
||||
CHECK_EQ(y.at(4), 24.0f);
|
||||
|
||||
/* A scalar with no element is a shape error, not a broadcast of zero. */
|
||||
T s0(RAD_F32, {0});
|
||||
T y2(RAD_F32, {5});
|
||||
A b; b.t(x).t(s0).t(y2).i("M", 1).i("n", 5).s("dtype", "f32");
|
||||
CHECK(run("scale", b) != RAD_OK);
|
||||
}
|
||||
|
||||
/* The quantised gather. Three things, and the scale is the least interesting of them.
|
||||
*
|
||||
* The E4M3 codes are chosen so their VALUES are exact and writable as literals: 0x38 is 1.0,
|
||||
@@ -1598,6 +1681,16 @@ TEST(op_vocab_edges) {
|
||||
CHECK_EQ(x.at(2), 1.0f); CHECK_EQ(x.at(3), 2.0f);
|
||||
CHECK_EQ(x.at(4), 0.0f); CHECK_EQ(x.at(5), 0.0f); /* a negative id is padding */
|
||||
|
||||
/* A runtime gather scale multiplies the rows that are found; a missed row stays zero, not
|
||||
* zero times the scale. Absent it, the lookup is the plain gather (the first block). */
|
||||
T xs(RAD_F32, {3, 2});
|
||||
A as; as.t(tok).t(wte).t(xs).i("M", 3).i("n_embd", 2).i("n_vocab", 3)
|
||||
.s("dtype", "f32").d("mult", 2.0);
|
||||
CHECK_OK(run("embed_lookup", as));
|
||||
CHECK_EQ(xs.at(0), 10.0f); CHECK_EQ(xs.at(1), 12.0f);
|
||||
CHECK_EQ(xs.at(2), 2.0f); CHECK_EQ(xs.at(3), 4.0f);
|
||||
CHECK_EQ(xs.at(4), 0.0f); CHECK_EQ(xs.at(5), 0.0f);
|
||||
|
||||
/* An id at or above n_vocab fails the launch rather than returning a plausible row. */
|
||||
T bad(RAD_I32, {1}); bad.n({7});
|
||||
T x2(RAD_F32, {1, 2});
|
||||
@@ -2347,6 +2440,43 @@ TEST(op_rope_multi_component) {
|
||||
}
|
||||
}
|
||||
|
||||
/* THE PROPORTIONAL LADDER. With head_dim wider than rotary_dim, the two ladders give frequency 1 a
|
||||
* different angle: `rotary` divides by rotary_dim, `head` by head_dim. Frequency 0 is theta^0 under
|
||||
* both, and the tail past rotary_dim is never touched, so those pin the unchanged parts while
|
||||
* frequency 1 pins the switch itself. */
|
||||
TEST(op_rope_ladder) {
|
||||
const int64_t hd = 8, rot = 4; /* two frequencies, a partial rotary (hd > rot) */
|
||||
const float pos = 7.0f;
|
||||
for (const char* lad : { "rotary", "head" }) {
|
||||
const int64_t den = (lad[0] == 'h') ? hd : rot;
|
||||
T got(RAD_F32, { 1, hd });
|
||||
got.f(std::vector<float>(hd, 1.0f));
|
||||
T p1(RAD_I32, { 1 }); p1.n({ 7 });
|
||||
A a; a.t(got).t(p1).i("M", 1).i("head_dim", hd).i("n_head", 1).i("n_head_kv", 0)
|
||||
.d("theta", 100).d("scale", 1).s("mode", "neox").i("rotary_dim", rot)
|
||||
.s("ladder", lad);
|
||||
CHECK_OK(run("rope", a));
|
||||
for (int i = 0; i < rot / 2; ++i) {
|
||||
const float inv = 1.0f / std::pow(100.0f, (float)(2 * i) / (float)den);
|
||||
const float ang = pos * inv;
|
||||
CHECK_NEAR(got.at(i), std::cos(ang) - std::sin(ang), 1e-5);
|
||||
CHECK_NEAR(got.at(i + rot / 2), std::sin(ang) + std::cos(ang), 1e-5);
|
||||
}
|
||||
for (int d = rot; d < hd; ++d) CHECK_EQ(got.at(d), 1.0f); /* untouched tail */
|
||||
}
|
||||
/* absent ladder == rotary: the models that never set it keep the old angles bit-for-bit */
|
||||
{
|
||||
T got(RAD_F32, { 1, hd });
|
||||
got.f(std::vector<float>(hd, 1.0f));
|
||||
T p1(RAD_I32, { 1 }); p1.n({ 7 });
|
||||
A a; a.t(got).t(p1).i("M", 1).i("head_dim", hd).i("n_head", 1).i("n_head_kv", 0)
|
||||
.d("theta", 100).d("scale", 1).s("mode", "neox").i("rotary_dim", rot);
|
||||
CHECK_OK(run("rope", a));
|
||||
const float ang = pos * (1.0f / std::pow(100.0f, (float)(2 * 1) / (float)rot));
|
||||
CHECK_NEAR(got.at(1), std::cos(ang) - std::sin(ang), 1e-5);
|
||||
}
|
||||
}
|
||||
|
||||
/* ALIGNED CORNERS: a grid's first and last rows and columns sit exactly on the table's, so a
|
||||
* corner patch reads one table row whole; an interior one blends four. */
|
||||
TEST(op_grid_embed) {
|
||||
|
||||
Reference in new issue
Block a user