Archived
libref, libavx: GLM-5.3's ops -- mHC, clamped SwiGLU, f32 routing, KDA, the DSA indexer, MLA
The reference and CPU forms of the ops GLM-5.3-Flash's graph needs, with their schemas and shape hooks: mhc_pre / mhc_post / mhc_contract and the column-split pair mhc_pre_partial / mhc_pre_finish; swiglu_clamped; gemm_nt_f32 (bf16 activation, f32 weight and result) for the router logits and the indexer's head gates; router_sigmoid_topk (correction-bias top-k); kda_update with per-channel decay and both state forms; dsa_pool, dsa_query and dsa_score; and mla_attn and mla_project for absorbed latent attention. moe_gather takes f32 expert weights beside bf16, and fp8a8f32 joins the dtype list. docs/OPS.md states each op. ref_test checks every op against hand-computed cases, avx_check_hand the CPU forms against libref, build_test the indexer cache's page size. Co-Authored-By: Nunze <lorenz.lamping1@web.de>
This commit is contained in:
1 parent
c8311068d0
commit
da77f86332
21 files changed
+3217
-19
No files matched your search
+164
-3
@@ -40,9 +40,9 @@ here is such a choice.
|
||||
otherwise; strides are the kernel's business, not the schema's.
|
||||
- Where an op takes `dtype`, it is a string naming the operand combination, so a weight format and
|
||||
an activation format share one key: `bf16`, `f16`/`fp16`, `f32`/`fp32`, `u8`, `fp8_e4m3`,
|
||||
`fp8a8`, `fp8a16`, `i8a8`, `i8a8h`, `w4`, `w4a8`, `w4a8_asym`, `w4a8h`, `w8a8`, `w4a16`,
|
||||
`w8a16`, `w2a8`, `mxfp4a8`, `w5a16`, `w4a16_asym`, `w5a8i8`, `w4a8i8_asym`, and the codebook
|
||||
expert forms `w4nla8h`, `w4nl64a8h`, `w4nl32a8h`, `w5nl64a8h` (`docs/MOE-W4.md`).
|
||||
`fp8a8`, `fp8a8f32`, `fp8a16`, `i8a8`, `i8a8h`, `w4`, `w4a8`, `w4a8_asym`, `w4a8h`, `w8a8`,
|
||||
`w4a16`, `w8a16`, `w2a8`, `mxfp4a8`, `w5a16`, `w4a16_asym`, `w5a8i8`, `w4a8i8_asym`, and the
|
||||
codebook expert forms `w4nla8h`, `w4nl64a8h`, `w4nl32a8h`, `w5nl64a8h` (`docs/MOE-W4.md`).
|
||||
- `w4a8h` is `w4a8` with a `group`-wide Walsh–Hadamard along K baked into the stored weight
|
||||
(`docs/MOE-W4.md`).
|
||||
- `i8a8` is an i8 weight with a bf16 scale per (row, 128 of K) against an int8 activation on
|
||||
@@ -50,6 +50,7 @@ here is such a choice.
|
||||
carrying the 1/128 (libquant's `transform=fwht128`), met by `had_quant_act_i8g`.
|
||||
- `w4a8_asym` is the unsigned-nibble-minus-zero-point grid instead of the symmetric one.
|
||||
- `fp8a8` and `fp8a16` say whether a block-scaled E4M3 weight meets an fp8 or a bf16 activation.
|
||||
- `fp8a8f32` is `fp8a8` with f32 weight scales on the 128x128 block grid.
|
||||
- `w5a16` and `w4a16_asym` are ParoQuant's int5 and z-lab's int4 (u5 / u4 codes, an f16 scale and
|
||||
a u8 zero point per 128 of K) against an f16 activation; `w5a8i8` and `w4a8i8_asym` are the same
|
||||
weights against an int8 activation with an f32 scale per (row, 128 of K).
|
||||
@@ -191,6 +192,11 @@ at once. Run it before adding a kernel plugin; the loader names only the first c
|
||||
| `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` |
|
||||
| `mhc_pre` | `M`(range) `n` `hc` `iterations` `eps`:f64 `hc_eps`:f64 `dtype` | `h`, `fn`w, `scale`w, `base`w → `x`, `post`, `comb` |
|
||||
| `mhc_pre_partial` | `M`(range) `n` `hc` `chunk` `first` `chunks` `dtype` | `h`, `fn`w → `part` |
|
||||
| `mhc_pre_finish` | `M`(range) `n` `hc` `iterations` `eps`:f64 `hc_eps`:f64 `chunk` `dtype` | `part`, `h`, `scale`w, `base`w → `x`, `post`, `comb` |
|
||||
| `mhc_post` | `M`(range) `n` `hc` `dtype` | `x`, `h`, `post`, `comb` → `out` |
|
||||
| `mhc_contract` | `M`(range) `n` `hc` `dtype` | `h` → `x` |
|
||||
| `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`? |
|
||||
| `hc_write` | `M`(range) `n` `hc` `dtype` | `y`, `inj`, `h`:inout |
|
||||
| `layernorm` | `M`(range) `n` `eps`:f64 `dtype` | `x`, `w`w, `b`w? → `y` |
|
||||
@@ -199,6 +205,7 @@ at once. Run it before adding a kernel plugin; the loader names only the first c
|
||||
| `add` | `M`(range) `n` `dtype` `div`:f64/opt | `a`, `b` → `y` |
|
||||
| `mul` | `M`(range) `n` `dtype` | `a`, `b` → `y` |
|
||||
| `silu_mul` | `M`(range) `n` `dtype` | `gate_up` → `y` (splits `[M,2n]` into gate·up) |
|
||||
| `swiglu_clamped` | `M`(range) `n` `limit`:f64 `dtype` | `gate_up` → `y` |
|
||||
| `mul_weight` | `M`(range) `n` `dtype` `scalar`/opt | `x`, `w`w → `y` (w one element or one row) |
|
||||
| `act_mul` | `M`(range) `n` `act` `dtype` | `a`, `b` → `y` (act(a)·b, two operands) |
|
||||
| `seg_mean` | `M`(range) `n` `dtype` | `x`, `cu_seqlens` → `y` (one mean row a segment) |
|
||||
@@ -239,6 +246,11 @@ does it. A plugin asks for it first and falls back to `add` + `rmsnorm` (`spec.m
|
||||
`gelu_pytorch_tanh`, while the unary `gelu` is the exact erf form. Both split the fused `gate_up`
|
||||
with the gate in the first half.
|
||||
|
||||
`swiglu_clamped` splits `[M, 2n]` as gate then up, as `silu_mul` does, and computes
|
||||
`silu(min(gate, limit)) * clamp(up, -limit, limit)` in f32, rounded once to `y`'s dtype. `limit`
|
||||
is positive and finite (GLM-5.3's is 10). The clip precedes the SiLU, and the gate has no lower
|
||||
clip.
|
||||
|
||||
**`add` and `mul`** broadcast a `b` of exactly `n` elements along the rows of a taller output (a
|
||||
bias add). Nothing else broadcasts, in these or any other elementwise op. `add`'s `div` divides
|
||||
the sum after its rounding, `y = rd(rd(a + b) / div)` with `rd` `y`'s dtype (absent, 1: the plain
|
||||
@@ -319,6 +331,34 @@ is easy to miss.
|
||||
and an f32 scale plane (a group of 128 for `mix_down`, a quarter row for `mix_up`), which a host
|
||||
kernel reads joined (Weights of several planes).
|
||||
|
||||
**mHC** (manifold-constrained hyper-connections) keeps `hc` residual streams in one `[M, hc*n]`
|
||||
row and is a separate family from `hc_read`/`hc_write`. `mhc_pre` projects the whole row with the
|
||||
f32 matrix `fn` `[hc*(hc+2), hc*n]` and multiplies each projection by
|
||||
`1 / sqrt(sum(h^2) / (hc*n) + eps)`, giving coefficients `c`. `scale` holds three f32 scalars and
|
||||
`base` `hc*(hc+2)` f32 biases: the pre gates are `sigmoid(c[j]*scale[0] + base[j]) + hc_eps` and
|
||||
the post gates `2*sigmoid(c[hc+j]*scale[1] + base[hc+j])` for `j < hc`, and the remaining `hc*hc`
|
||||
coefficients, times `scale[2]` plus their bias, are the mixing logits indexed
|
||||
`[source, destination]`. The first Sinkhorn pass is a row softmax plus `hc_eps`, then column
|
||||
normalization; every later pass normalizes the rows, then the columns; each normalization divides
|
||||
by the sum plus `hc_eps`. `iterations` counts the passes, the first included. `x` is the sum of the
|
||||
streams weighted by the pre gates, rounded once to `dtype`; `post` `[M, hc]` and `comb`
|
||||
`[M, hc*hc]` stay f32. Transposing `comb` leaves every shape valid and changes the model.
|
||||
`mhc_post` writes `out[dst, i] = post[dst]*x[i] + sum_src comb[src, dst]*h[src, i]` into a
|
||||
separate buffer (`out` must not alias `h`), with no normalization of the stream. `mhc_contract` is
|
||||
the mean over the streams, rounded once.
|
||||
|
||||
`mhc_pre_partial` and `mhc_pre_finish` are `mhc_pre` split by residual columns, so
|
||||
tensor-parallel ranks share its projection instead of each computing it whole. Chunk `c` covers
|
||||
columns `[c*chunk, (c+1)*chunk)` of the `hc*n` row (`chunk` divides it). `mhc_pre_partial`
|
||||
computes chunks `[first, first+chunks)`: `part[m, (c-first)*S + j]` is the chunk's sum of
|
||||
`h*fn[j]` for `j < hc*(hc+2)` and of `h*h` for `j = hc*(hc+2)`, with `S = hc*(hc+2)+1` rounded up
|
||||
to a multiple of four and the slots past the last zero, so a gathered payload is defined. A
|
||||
row-interleaved `all_gather` with `row = chunks*S` joins the ranks' matrices into
|
||||
`[M, (hc*n/chunk)*S]`, which `mhc_pre_finish` reads: each coefficient and the sum of squares is
|
||||
the sum of its chunks' partials, then `mhc_pre`'s gates, Sinkhorn mixing and collapse. The order
|
||||
of that sum is the implementation's, so the pair matches `mhc_pre` to rounding, and bit for bit
|
||||
only where an implementation says so.
|
||||
|
||||
### Gemma 4's audio tower
|
||||
|
||||
- **`relu`** is `max(x, 0)` at each operand's own row pitch.
|
||||
@@ -449,6 +489,11 @@ a weight layout the stored WMMA fragment order does not provide, so it is not us
|
||||
quantises the activation for an integer weight it is int8: `quant_act_i8` for `w4a8`, `w8a8` and
|
||||
`w2a8`, `quant_act_i8g` for `i8a8`.
|
||||
|
||||
`fp8a8f32` is `fp8a8`'s E4M3 activation against an E4M3 weight whose 128x128 block scales are
|
||||
f32, read as the checkpoint stores them. A scale that bf16 cannot represent exactly keeps its
|
||||
value, which `fp8a8`'s bf16 scale plane would round. It applies to `gemm_nt_q` and `moe_gemm_q`
|
||||
with `group` 128.
|
||||
|
||||
**`group` has different meanings in this table.** A kernel that reads it the other way is wrong,
|
||||
not slow. `libref/ref_quant.cpp` is the definition.
|
||||
|
||||
@@ -587,6 +632,7 @@ may not have arrived.
|
||||
| op | params | operands |
|
||||
|---|---|---|
|
||||
| `gemm_nt` | `M`(range) `N` `K` `dtype` | `a`, `b`w → `y` |
|
||||
| `gemm_nt_f32` | `M`(range) `N` `K` `dtype` | `a`, `b`w → `y` |
|
||||
| `gemm_nt_bias` | `M`(range) `N` `K` `dtype` `act`/opt | `a`, `b`w, `bias`w, `res`? → `y` |
|
||||
| `gemm_nt_q` | `M`(range) `N` `K` `group` `dtype` `pb1`/opt `pb2`/opt | `a`, `a_scale`?, `b`w, `b_scale`w → `y`; `a_sum`?, `b_ref`w? |
|
||||
| `gemm_nt_q_bias` | `M`(range) `N` `K` `group` `dtype` | `a`, `a_scale`, `b`w, `b_scale`w, `bias`w → `y` |
|
||||
@@ -636,6 +682,11 @@ what a separate tensor would hold, so the fused form equals the unfused chain bi
|
||||
may be `y` itself, the residual stream updated in place (the encoder towers' layers do this), so an
|
||||
implementation reads `res` before it stores the product over it.
|
||||
|
||||
`gemm_nt_f32` is `y[M, N] = a[M, K] @ b[N, K]^T` with a bf16 activation, an f32 weight, f32
|
||||
accumulation and an f32 `y`; `dtype` (`bf16`) names the activation. It exists for the projections
|
||||
whose weights and results must not narrow to bf16: GLM's router logits and its indexer's signed
|
||||
head gates.
|
||||
|
||||
### Runtime LoRA: `lora_shrink` and `lora_expand`
|
||||
|
||||
| op | params | operands |
|
||||
@@ -1356,6 +1407,7 @@ Every op honours its activation operands' row pitches. `rd` is a rounding into t
|
||||
| `router_topk_scatter` | `M`(range) `n_expert` `n_local`/opt `top_k` `norm` `dtype` `expert_base`/opt `protect`:str/opt | `logits` → `expert_ids`, `expert_w`, `sorted_tok`, `expert_offset`, `expert_count` |
|
||||
| `router_gemm_topk_scatter` | `M`(range) `K` `n_expert` `n_local`/opt `top_k` `norm` `dtype` `expert_base`/opt `protect`:str/opt | `a`, `b`w, `gate_b`w? → `logits`, `expert_ids`, `expert_w`, `sorted_tok`, `expert_offset`, `expert_count`, `gate`? |
|
||||
| `moe_gemm` | `M`(range) `N` `K` `n_expert` `top_k` `a_order` `dtype` | `a`, `w`wt, `sorted_tok`, `expert_offset` → `y` |
|
||||
| `router_sigmoid_topk` | `M`(range) `n_expert` `top_k` `norm` `route_scale`:f64 `dtype` | `logits`, `bias`w → `ids`, `weights` |
|
||||
| `moe_gather` | `M`(range) `n` `top_k` `dtype` `act`:str/opt | `y_expert`, `expert_w`, `sorted_tok`, `shared`?, `shared_gate`? → `y` |
|
||||
| `row_topk` | `M`(range) `N` `R` `vocab_off`/opt `dtype` | `x` → `idx`, `val`, `pairs`? |
|
||||
| `row_topk_merge` | `M` `R` `world_size` `dtype` | `gathered` → `idx`, `val` |
|
||||
@@ -1447,6 +1499,9 @@ product before the sum, so carrying either in f32 moves the last bit. `act` is `
|
||||
runs on one rank, so the op this replaces is a dispatch every other rank waits out inside the
|
||||
block's all-reduce.
|
||||
|
||||
With bf16 expert outputs, `expert_w` may be bf16 or f32. f32 mixture weights stay f32 through
|
||||
the sum; only the gathered result narrows to bf16, as with bf16 weights.
|
||||
|
||||
### Quantised experts and the row gate
|
||||
|
||||
| op | params | operands |
|
||||
@@ -1468,6 +1523,20 @@ gate/up); the output is `max(N, N_odd)` wide, and a narrower class fills the lea
|
||||
output part and writes zeros after them, so the gated quantiser behind it reads one layout for every
|
||||
row. The weight list is the even class's codes, its scales, then the odd class's codes and scales.
|
||||
|
||||
**`router_sigmoid_topk`** is single-group correction-bias routing, all in f32. The scores are
|
||||
`p = sigmoid(logits)`; the selection takes the `top_k` largest `p + bias`, ties to the lower
|
||||
expert, and the weights are the selected `p`, never the biased ranks. With `norm` 1 a weight is
|
||||
`p * (route_scale / (sum + 1e-20))` over the row's selected `p`, with `norm` 0 `p * route_scale`;
|
||||
`route_scale` is positive and finite. A rank that is NaN or `-inf` is never selected, and a row
|
||||
with fewer than `top_k` selectable experts has no defined selection (libref refuses it).
|
||||
Grouped selection (`n_group > 1`) is not this op. GLM-5.3 routes 8 of 288 experts in one group
|
||||
with `route_scale` 2.5.
|
||||
|
||||
At `dtype=mxfp4a8`, `w` and `w_odd` are OCP e2m1 codes and `w_scale` and `w_odd_scale` hold one
|
||||
E8M0 exponent per (row, 32 of K), typed `e8m0` or raw `u8`; either way a byte is an exponent, not
|
||||
an integer multiplier. `a` and `a_scale` are `quant_act_fp8`'s pair, and `group` is that
|
||||
activation's scale group, independent of the weight's 32-wide grid.
|
||||
|
||||
**`moe_gemm_q_mod4`** is the same GEMM over four classes by the expert's number mod 4. `w`/`w_scale`
|
||||
hold class 0 at `[N, K]` and `w_q`/`w_q_scale` class `q` at `[N_q, K_q]` (defaulting to `N`, `K`);
|
||||
expert `e` is entry `e / 4` of class `e % 4`, so class `q` holds `ceil((n_expert - q) / 4)` of them.
|
||||
@@ -1538,6 +1607,7 @@ wrong.
|
||||
|
||||
| op | params | operands |
|
||||
|---|---|---|
|
||||
| `kda_update` | `M`(range) `heads` `head_k` `head_v` `lower_bound`:f64 `scale`:f64 `l2_eps`:f64 `mode` `dtype` `state_form`/opt | `q`, `k`, `v`, `a`, `b`, `A_log`w, `dt_bias`w, `state`:inout, `state_idx`, `cu`, `num_accepted`?, `has_init`? → `o` |
|
||||
| `gdn_conv_prep` | `M`(range) `head_k` `head_v` `chunk`/der `conv_width` `l2_eps`:f64/opt `softplus_thr`:f64/opt | `x`, `w`w, `b`w?, `A_log`w, `dt_bias`w, `conv_state`:inout, `cu`, `a`?, `b_gate`?, `cache_idx`?, `has_init`? → `q`,`k`,`v`,`g`,`beta` |
|
||||
| `gdn_conv_update` | `q_len`(range) `head_k` `head_v` `conv_width` `max_query_len`/opt | `x`, `w`w, `b`w?, `conv_state`:inout, `state_idx`, `num_accepted`, `cu` → `q`,`k`,`v` |
|
||||
| `gdn_kkt_solve` | `M`(range) `head_k` `chunk`/der | `k`, `beta`, `g`, `cu` → `A` |
|
||||
@@ -1546,6 +1616,32 @@ wrong.
|
||||
| `gdn_conv_recurrent_update` | `q_len`(range) `head_k` `head_v` `conv_width` `n_head_v`/opt `scale`:f64/opt `eps`:f64/opt `l2_eps`:f64/opt `softplus_thr`:f64/opt `act`:str/opt `state_fp16`/opt `state_form`:str/opt | `x`, `conv_w`w, `conv_b`w?, `conv_state`:inout, `conv_idx`, `a`,`b`,`A_log`w,`dt_bias`w,`state`:inout,`state_idx`,`num_accepted`,`cu`,`z`,`norm_w`w → `o`,`o_q`?,`o_scale`? |
|
||||
| `gdn_gated_rmsnorm` | `M`(range) `channels` `eps`:f64 `act`:str | `x`, `z`, `w`w → `o` |
|
||||
|
||||
**`kda_update` is Kimi delta attention with per-channel decay.** Per token and head it
|
||||
L2-normalizes `q` and `k` with `l2_eps`, scales `q` by `scale`, and forms the decay
|
||||
`exp(lower_bound * sigmoid(exp(A_log[h]) * (a[d] + dt_bias[h, d])))` per K channel `d`
|
||||
(`lower_bound` negative and finite) and `beta = sigmoid(b[h])`. For each value row `e` of the
|
||||
state it decays the row by channel, computes `delta = beta * (v[e] - dot(S[e], k))`, adds
|
||||
`delta * k`, and writes `o[e] = dot(S[e], q)`. `state` is f32 `[slots, heads, head_v, head_k]`;
|
||||
`q`, `k`, `v` and `a` may be `[M, heads, width]` or flattened `[M, heads*width]`, and `b` is one
|
||||
value per (token, head). `o` excludes the model's gated RMS norm. `cu` holds absolute token
|
||||
offsets, so a call can cover a slice of a mixed batch. `mode=verify` reads column
|
||||
`num_accepted - 1` of the sequence's `state_idx` row (`num_accepted` absent is 1) and writes the
|
||||
state after token `t` of the window to column `t`; `mode=prefill` reads column zero and writes only
|
||||
the final state there. `has_init` 0 starts from a zero state, a negative read slot gives zero
|
||||
output, and a negative write slot is skipped.
|
||||
|
||||
`state_form` is `gdn_recurrent_update`'s (below): `per_candidate` when absent, and with `anchor`
|
||||
one committed state and one scratch slot per sequence. Under `anchor`, column zero of `state_idx`
|
||||
is the committed state and column `width/2` the scratch; the two must differ, and both forms need
|
||||
`head_k = head_v = 128`. The scratch holds, per head, one f32 replay count and then one record of
|
||||
385 f32 per token: the normalized key, the raw value, the per-channel decay and beta, 32 records
|
||||
at most, which fits one 128 x 128 head block. `mode=verify` first replays the previous window's
|
||||
accepted prefix (`num_accepted` records, at most the stored count) onto the committed state and
|
||||
stores it back, then runs the window from it, writing each token's record and the window length
|
||||
as the new count; the committed state does not advance past the accepted prefix, and a window has
|
||||
at most 32 tokens. `mode=prefill` commits its final state and sets the count to zero. A zeroed
|
||||
scratch slot replays nothing.
|
||||
|
||||
**Speculative rollback is part of the schema** (`spec.md` §10). The recurrent state and the conv
|
||||
window have already absorbed rejected tokens, so the state cache is a rolling window of
|
||||
`conv_width-1 + n_spec` entries read at the slot the last accepted token left, and a rejection is a
|
||||
@@ -2037,6 +2133,11 @@ order, not a slow one.
|
||||
| op | params | operands |
|
||||
|---|---|---|
|
||||
| `qsa_block_key` | `M`(range) `n` `ratio` `rotary_dim` `pos0`/opt `block_size`/opt `eps`:f64 `theta`:f64 `scale`:f64/opt `wadd`:f64/opt `dtype` `mode`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt | `k`, `w`w, `page`?, `pos`? → `out` |
|
||||
| `dsa_pool` | `M`(range) `n` `ratio` `dtype` `block_size`/opt | `kg`, `ape`w → `q`, `scale`; `page`?, `cache`:inout? |
|
||||
| `dsa_query` | `M`(range) `n` `dtype` | `x` → `q`, `scale` |
|
||||
| `dsa_score` | `M`(range) `n` `heads` `blocks` `seqs` `dtype` | `q`, `q_scale`, `gate`, `k`, `k_scale`?, `bt`, `cu`, `nc` → `score` |
|
||||
| `mla_attn` | `M`(range) `latent_dim` `heads` `blocks` `block_size` `scale`:f64 `dtype` | `q`, `kv`, `bt`, `length` → `out` |
|
||||
| `mla_project` | `M`(range) `heads` `head_dim` `latent_dim` `mode` `dtype` | `a`, `b`w → `y` |
|
||||
| `qsa_score` | `M`(range) `n` `heads` `blocks` `seqs` `dtype` | `q`, `bk`, `bt`, `cu`, `nc` → `score` |
|
||||
| `qsa_select` | `M`(range) `blocks` `topk` `ratio` `seqs` `signed`/opt | `score`, `bt`, `nc`, `pos`, `cu` → `sel`, `nsel`, `seqused` |
|
||||
| `qsa_tail_store` | `M`(range) `n` `ratio` `ring` `seqs` `dtype` | `k`, `pos`, `cu`, `state`:inout, `sidx` |
|
||||
@@ -2231,6 +2332,66 @@ block-key kernel with two sources, a per-key source selector and a tail layout.
|
||||
selection both need and this op computes on the way. It is not the number of blocks that completed
|
||||
this step; the two agree only for a sequence that starts at zero.
|
||||
|
||||
### GLM-5.3's indexer and latent attention
|
||||
|
||||
GLM's sparse attention keeps QSA's selection (`qsa_select` with `signed` 1) and replaces the
|
||||
block keys, the queries and the score. Its indexer applies no RoPE, and the layer norm of the raw
|
||||
keys precedes `dsa_pool`.
|
||||
|
||||
`dsa_pool` compresses `ratio` key rows into one. `kg` is `[M*ratio, 2n]` bf16, each row a
|
||||
normalized key followed by its channel-wise gate logits. The learned f32 `ape` `[ratio, n]` is
|
||||
added to the gate logits, which are softmaxed over the `ratio` axis per channel; the keys are
|
||||
pooled with those probabilities and rounded to bf16, then rotated by the ascending-stride
|
||||
Walsh-Hadamard transform, multiplied by `1/sqrt(n)` and rounded to bf16 again. Each row is
|
||||
quantised to E4M3 with `scale = 2^ceil(log2(max(amax, 1e-4) / 448))`, codes rounded to nearest
|
||||
even: `q` `[M, n]`, `scale` `[M, 1]` f32. `n` is a power of two up to 256, `ratio` 2 to 16.
|
||||
|
||||
`page` and `cache`, both or neither, also store the result into the indexer's paged key cache, at
|
||||
`n` 128 and `ratio` 4 only. `page[M]` names each row's destination page, which must be unique
|
||||
within the call; a negative or out-of-range id is skipped. `cache` is u8 `[pages, 1, 4, 34]` with
|
||||
contiguous inner rows and a four-byte-aligned page pitch of at least 136 bytes: a page holds the
|
||||
128 codes, then the f32 scale at byte 128, and its last four bytes and any pitch padding are left
|
||||
untouched. That is one block-size-4 group of the indexer's KV, with no separate scale allocation.
|
||||
`block_size`, when given, is 4 and names the consuming layout to the cache planner.
|
||||
|
||||
`dsa_query` rotates each bf16 query head by the same normalized Walsh-Hadamard transform, rounds
|
||||
to bf16, and quantises to E4M3 with the same power-of-two scale: `x` `[M, n]`, `q` `[M, n]`,
|
||||
`scale` `[M, 1]`, token and head flattened into `M`. There is no RoPE and no RMS norm. Unlike
|
||||
`had_quant_act_fp8`, both the normalization of the rotation and the power-of-two scale are part of
|
||||
the op. `n` is a power of two up to 256.
|
||||
|
||||
`dsa_score` takes E4M3 queries `[M, heads, n]` with f32 scales and signed f32 gates `[M, heads]`,
|
||||
E4M3 pooled keys `[pages, n]` with f32 scales `[pages]`. `bt[seqs, blocks]` names key pages,
|
||||
`cu[seqs+1]` holds absolute query offsets and `nc[seqs]` bounds the live blocks. The score of block
|
||||
`b` is `k_scale * sum_h(gate_h * q_scale_h * relu(dot(q_h, k))) / sqrt(heads*n)`: the ReLU comes
|
||||
before the head weighting, so a negative gate can make a block's score negative. A block past
|
||||
`nc`, a negative page id or one past the key rows scores `-inf`. `score` is f32 `[M, blocks]` and
|
||||
may have fewer columns than `bt` with its own row pitch, so an architecture can bound it by the
|
||||
current history. `qsa_select` applies each query's causal bound, so scoring a chunk's shared
|
||||
history makes no future block eligible.
|
||||
|
||||
`k` may instead be the packed u8 cache `dsa_pool` writes, with `k_scale` absent: the codes and the
|
||||
embedded scale are read in place. `q` may be flattened `[M*heads, n]` with `q_scale`
|
||||
`[M*heads, 1]`, each with its own row pitch, which is `dsa_query`'s output as written.
|
||||
|
||||
`mla_attn` is absorbed latent attention: one latent vector per token is both key and value.
|
||||
`q` and `out` are `[M, heads, latent_dim]`, `kv` is `[pages, 1, block_size, latent_dim]`, and
|
||||
`bt[M, blocks]` is each query's own page table, the selected complete pages followed by its tail.
|
||||
`length[M]` counts the table's visible tokens (every selected complete page and the visible part of
|
||||
the tail) and is the causal bound: no slot at or past it is read. A missing or out-of-range page
|
||||
contributes nothing, and a row with no visible key outputs zero. The softmax is f32 and `out` is
|
||||
rounded once. `scale` is positive and finite and comes from the original query/key head width,
|
||||
not the latent width (GLM: `1/sqrt(256)` against a latent of 512).
|
||||
|
||||
`mla_project` moves a query into the latent and a latent result out of it, through the bf16
|
||||
weight `b` `[heads*2*head_dim, latent_dim]` that stores each head's key rows, then its value rows.
|
||||
`mode=absorb` multiplies `a` `[M, heads, head_dim]` by the head's key block as stored,
|
||||
`[head_dim, latent_dim]`, giving `[M, heads, latent_dim]`; `mode=expand` multiplies
|
||||
`a` `[M, heads, latent_dim]` by the transposed value block, giving `[M, heads, head_dim]`. Both
|
||||
accumulate in f32 and round once to bf16. The KV cache stays latent; only this weight carries the
|
||||
per-head width. Its rows are head-major, so a tensor-parallel slice of whole heads is a row range.
|
||||
`a` and `y` may also be `[M, heads*width]`, heads contiguous, with their own token pitch.
|
||||
|
||||
## Draft heads
|
||||
|
||||
A drafter is an ordinary graph over ordinary ops except at its two ends: what proposes the
|
||||
|
||||
@@ -37,6 +37,9 @@ set(AVX_KERNEL_SRC
|
||||
avx_elementwise.cpp
|
||||
avx_norm.cpp
|
||||
avx_hc.cpp
|
||||
avx_glm.cpp
|
||||
avx_dsa.cpp
|
||||
avx_mla.cpp
|
||||
avx_quant.cpp
|
||||
avx_gemm.cpp
|
||||
avx_gemm_tile.cpp
|
||||
|
||||
+45
-1
@@ -113,6 +113,39 @@ std::vector<Case> build_cases() {
|
||||
* on is the trunk case, off the final mixer; they differ in the operand list. */
|
||||
for (const char* dt : { "f32", "bf16" }) {
|
||||
add("hc_enter", { HI("M", 5), HI("n", 128), HI("hc", 4), HS("dtype", dt) });
|
||||
add("swiglu_clamped", { HI("M", 5), HI("n", 259), HF("limit", 0.5), HS("dtype", dt) });
|
||||
if (!std::strcmp(dt, "bf16"))
|
||||
add("dsa_pool", { HI("M", 7), HI("n", 128), HI("ratio", 4), HS("dtype", "bf16") });
|
||||
if (!std::strcmp(dt, "bf16"))
|
||||
add("dsa_query", { HI("M", 7), HI("n", 128), HS("dtype", "bf16") });
|
||||
if (!std::strcmp(dt, "bf16"))
|
||||
add("gemm_nt_f32", { HI("M", 4), HI("N", 32), HI("K", 129), HS("dtype", "bf16") });
|
||||
if (!std::strcmp(dt, "bf16"))
|
||||
for (const char* mode : { "absorb", "expand" })
|
||||
add("mla_project", { HI("M", 3), HI("heads", 2), HI("head_dim", 17),
|
||||
HI("latent_dim", 31), HS("mode", mode), HS("dtype", "bf16") });
|
||||
if (!std::strcmp(dt, "bf16"))
|
||||
add("dsa_score", { HI("M", 3), HI("n", 128), HI("heads", 32), HI("blocks", 17),
|
||||
HI("seqs", 2), HS("dtype", "fp8_e4m3") });
|
||||
for (int norm : { 0, 1 })
|
||||
add("router_sigmoid_topk",
|
||||
{ HI("M", 5), HI("n_expert", 288), HI("top_k", 8), HI("norm", norm),
|
||||
HF("route_scale", 2.5), HS("dtype", dt) });
|
||||
add("mhc_pre", { HI("M", 3), HI("n", 129), HI("hc", 4), HI("iterations", 20),
|
||||
HF("eps", 1e-5), HF("hc_eps", 1e-6), HS("dtype", dt) });
|
||||
add("mhc_pre_partial", { HI("M", 3), HI("n", 129), HI("hc", 4), HI("chunk", 129),
|
||||
HI("first", 1), HI("chunks", 2), HS("dtype", dt) });
|
||||
add("mhc_pre_finish",
|
||||
{ HI("M", 3), HI("n", 129), HI("hc", 4), HI("iterations", 20), HF("eps", 1e-5),
|
||||
HF("hc_eps", 1e-6), HI("chunk", 129), HS("dtype", dt) });
|
||||
add("mhc_post", { HI("M", 3), HI("n", 129), HI("hc", 4), HS("dtype", dt) });
|
||||
add("mhc_contract", { HI("M", 3), HI("n", 129), HI("hc", 4), HS("dtype", dt) });
|
||||
add("mla_attn", { HI("M", 3), HI("latent_dim", 32), HI("heads", 2), HI("blocks", 7),
|
||||
HI("block_size", 4), HF("scale", 0.125), HS("dtype", dt) });
|
||||
for (const char* mode : { "prefill", "verify" })
|
||||
add("kda_update", { HI("M", 3), HI("heads", 2), HI("head_k", 32), HI("head_v", 32),
|
||||
HF("lower_bound", -5), HF("scale", 0.1767766952966369),
|
||||
HF("l2_eps", 1e-6), HS("mode", mode), HS("dtype", dt) });
|
||||
add("hc_write", { HI("M", 5), HI("n", 128), HI("hc", 4), HS("dtype", dt) });
|
||||
add("hc_read", { HI("M", 5), HI("n", 128), HI("hc", 4), HI("lowrank", 8),
|
||||
HF("eps", 1e-6), HS("dtype", dt), HF("wadd", 1), HI("inject", 1),
|
||||
@@ -134,6 +167,10 @@ std::vector<Case> build_cases() {
|
||||
}
|
||||
add("ngram_ids", { HI("M", 9), HI("heads", 3), HI("ngram", 4), HI("eos", 2) });
|
||||
|
||||
for (const char* order : { "token", "sorted" })
|
||||
add("moe_gemm_q",
|
||||
{ HI("M", 9), HI("N", 64), HI("K", 128), HI("n_expert", 8), HI("top_k", 2),
|
||||
HI("group", 128), HS("a_order", order), HS("dtype", "mxfp4a8") });
|
||||
/* One scale per column over the rows: no group. */
|
||||
add("quant_cols_fp8", { HI("M", 5), HI("n", 256), HS("dtype", "bf16") }, EB(5, 256, 2, 1.5));
|
||||
add("quant_cols_fp8", { HI("M", 7), HI("n", 96), HS("dtype", "f32") }, EB(7, 96, 4, 1.25));
|
||||
@@ -214,7 +251,7 @@ std::vector<Case> build_cases() {
|
||||
/* The formats libref describes (ref_shapes.cpp): block fp8, and the int4 and int8 weights
|
||||
* against quant_act_i8's step-ordered codes. The bias form needs `a_scale`, which fp8a16 (a
|
||||
* bf16 activation) does not have, so libref declines it there. */
|
||||
for (const char* dt : { "fp8a8", "fp8a16", "w4a8", "w8a8" })
|
||||
for (const char* dt : { "fp8a8", "fp8a8f32", "fp8a16", "w4a8", "w8a8" })
|
||||
for (int M : { 1, 65 }) {
|
||||
const double fl = 2.0 * M * 96 * 256;
|
||||
add("gemm_nt_q", { HI("M", M), HI("N", 96), HI("K", 256), HI("group", 128),
|
||||
@@ -439,6 +476,10 @@ std::vector<Case> build_cases() {
|
||||
HI("seqs", 3) });
|
||||
add("qsa_select", { HI("M", 2), HI("blocks", 1), HI("topk", 1), HI("ratio", 3),
|
||||
HI("seqs", 1) });
|
||||
add("qsa_select", { HI("M", 4), HI("blocks", 300), HI("topk", 32), HI("ratio", 4),
|
||||
HI("seqs", 1), HI("signed", 1) });
|
||||
add("qsa_select", { HI("M", 7), HI("blocks", 129), HI("topk", 16), HI("ratio", 4),
|
||||
HI("seqs", 3), HI("signed", 1) });
|
||||
add("qsa_tail_store", { HI("M", 3), HI("n", 37), HI("ratio", 2), HI("ring", 2), HI("seqs", 3),
|
||||
HS("dtype", "f32") });
|
||||
add("qsa_work", { HI("M", 3), HI("n", 40), HI("ratio", 2), HI("ring", 3), HI("seqs", 3),
|
||||
@@ -523,6 +564,9 @@ std::vector<Case> build_cases() {
|
||||
add("moe_gemm_q", { HI("M", 9), HI("N", 64), HI("K", 128), HI("n_expert", 8),
|
||||
HI("top_k", 2), HI("group", 128), HS("a_order", order),
|
||||
HS("dtype", "fp8a8") });
|
||||
add("moe_gemm_q",
|
||||
{ HI("M", 9), HI("N", 128), HI("K", 256), HI("n_expert", 8), HI("top_k", 2),
|
||||
HI("group", 128), HS("a_order", order), HS("dtype", "fp8a8f32") });
|
||||
}
|
||||
/* Two classes at different widths: a gate/up pair whose odd experts are half as wide
|
||||
* (the output's second part begins past the odd class's zeros), and a down projection
|
||||
|
||||
@@ -526,6 +526,126 @@ void shape_cases(std::vector<Hand>& hs) {
|
||||
.pi("M", BAND).pi("heads", 4).pi("ngram", 3).pi("eos", 5);
|
||||
hs.push_back(std::move(n));
|
||||
}
|
||||
/* GLM's two-copy speculative state, including a nonempty previous replay window. */
|
||||
for (const char* mode : { "prefill", "verify" })
|
||||
for (int accepted : { 1, 2, 3 })
|
||||
for (int cold : { 0, 1 }) {
|
||||
constexpr int64_t D = 128;
|
||||
Hand h("KDA anchor accepted-prefix replay", "kda_update", 0.01);
|
||||
h.dense(RAD_BF16, { 2, 1, D }, hfill(201, 0.25f))
|
||||
.dense(RAD_BF16, { 2, 1, D }, hfill(202, 0.25f))
|
||||
.dense(RAD_BF16, { 2, 1, D }, hfill(203, 0.25f))
|
||||
.dense(RAD_BF16, { 2, 1, D }, hfill(204, 0.25f))
|
||||
.dense(RAD_BF16, { 2, 1 }, hfill(205, 0.25f))
|
||||
.dense(RAD_F32, { 1 }, [](int64_t) { return 0.0f; })
|
||||
.dense(RAD_F32, { D }, [](int64_t) { return -1.0f; })
|
||||
.dense(
|
||||
RAD_F32, { 2, 1, D, D },
|
||||
[](int64_t i) {
|
||||
if (i < D * D) return 0.125f;
|
||||
i -= D * D;
|
||||
if (!i) return 3.0f;
|
||||
if (i > 3 * 385) return 0.0f;
|
||||
const int at = (int)((i - 1) % 385);
|
||||
return at < 128 ? 0.01f : at < 256 ? 0.125f : at < 384 ? 0.75f : 0.5f;
|
||||
},
|
||||
true)
|
||||
.dense(RAD_I32, { 1, 6 }, [](int64_t i) { return i < 3 ? 0.0f : 1.0f; })
|
||||
.idx({ 0, 2 })
|
||||
.idx({ accepted })
|
||||
.idx({ cold ? 0 : 1 })
|
||||
.dense(RAD_BF16, { 2, 1, D }, hfill(206), true)
|
||||
.pi("M", 2)
|
||||
.pi("heads", 1)
|
||||
.pi("head_k", D)
|
||||
.pi("head_v", D)
|
||||
.pf("lower_bound", -5)
|
||||
.pf("scale", 1.0 / std::sqrt(128.0))
|
||||
.pf("l2_eps", 1e-6)
|
||||
.ps("mode", mode)
|
||||
.ps("dtype", "bf16")
|
||||
.ps("state_form", "anchor");
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
for (const char* mode : { "absorb", "expand" }) {
|
||||
const bool absorb = !std::strcmp(mode, "absorb");
|
||||
const int64_t in = absorb ? 17 : 31, out = absorb ? 31 : 17;
|
||||
Hand h("MLA flattened linear inputs and outputs", "mla_project", 0.01);
|
||||
h.view(RAD_BF16, { 3, 2 * in }, { 2 * in + 7, 1 }, 3 * (2 * in + 7), hfill(215, 0.25f))
|
||||
.dense(RAD_BF16, { 68, 31 }, hfill(216, 0.25f))
|
||||
.view(RAD_BF16, { 3, 2 * out }, { 2 * out + 9, 1 }, 3 * (2 * out + 9), hfill(217), true)
|
||||
.pi("M", 3)
|
||||
.pi("heads", 2)
|
||||
.pi("head_dim", 17)
|
||||
.pi("latent_dim", 31)
|
||||
.ps("mode", mode)
|
||||
.ps("dtype", "bf16");
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
{
|
||||
Hand h("MoE preserves F32 probabilities with BF16 experts", "moe_gather", 1e-5);
|
||||
h.dense(RAD_BF16, { 2, 1 }, [](int64_t i) { return i ? -1024.0f : 1024.0f; })
|
||||
.dense(RAD_F32, { 1, 2 }, [](int64_t i) { return i ? 1.0f : 1.0f + 1.0f / 8192; })
|
||||
.idx({ 0, 1 })
|
||||
.none()
|
||||
.none()
|
||||
.dense(
|
||||
RAD_BF16, { 1, 1 }, [](int64_t) { return 0.0f; }, true)
|
||||
.pi("M", 1)
|
||||
.pi("n", 1)
|
||||
.pi("top_k", 2)
|
||||
.ps("dtype", "bf16");
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
/* Packed index pages share code and scale storage, including pitched cache pages. */
|
||||
{
|
||||
Hand h("DSA pool writes pitched managed pages", "dsa_pool", 0.001);
|
||||
h.dense(RAD_BF16, { 28, 256 }, hfill(211, 0.25f))
|
||||
.dense(RAD_F32, { 4, 128 }, hfill(212, 0.125f))
|
||||
.dense(
|
||||
RAD_F8E4M3, { 7, 128 }, [](int64_t) { return 0.0f; }, true)
|
||||
.dense(
|
||||
RAD_F32, { 7, 1 }, [](int64_t) { return 0.0f; }, true)
|
||||
.idx({ 4, -1, 2, 99, 1, 0, 3 })
|
||||
.view(
|
||||
RAD_U8, { 5, 1, 4, 34 }, { 160, 136, 34, 1 }, 5 * 160,
|
||||
[](int64_t) { return 165.0f; }, true)
|
||||
.pi("M", 7)
|
||||
.pi("n", 128)
|
||||
.pi("ratio", 4)
|
||||
.ps("dtype", "bf16");
|
||||
hs.push_back(std::move(h));
|
||||
Hand s("DSA scorer reads embedded scales", "dsa_score", 1e-5);
|
||||
s.dense(RAD_F8E4M3, { 64, 128 }, hfill(213, 0.25f))
|
||||
.dense(RAD_F32, { 64, 1 }, [](int64_t) { return 0.5f; })
|
||||
.dense(RAD_F32, { 2, 32 }, hfill(214))
|
||||
.view(RAD_U8, { 5, 1, 4, 34 }, { 160, 136, 34, 1 }, 5 * 160,
|
||||
[](int64_t i) {
|
||||
const int d = (int)(i % 160);
|
||||
if (d < 128) return (float)(48 + i % 9);
|
||||
// Little-endian F32 scale 0.5; all padding stays poisoned.
|
||||
return d == 128 || d == 129 ? 0.0f
|
||||
: d == 130 ? 0.0f
|
||||
: d == 131 ? 63.0f
|
||||
: 165.0f;
|
||||
})
|
||||
.none()
|
||||
.dense(RAD_I32, { 1, 4 },
|
||||
[](int64_t i) {
|
||||
return (float)(i == 1 ? -1 : i == 3 ? 99 : i);
|
||||
})
|
||||
.idx({ 0, 2 })
|
||||
.idx({ 4 })
|
||||
.dense(
|
||||
RAD_F32, { 2, 4 }, [](int64_t) { return 0.0f; }, true)
|
||||
.pi("M", 2)
|
||||
.pi("n", 128)
|
||||
.pi("heads", 32)
|
||||
.pi("blocks", 4)
|
||||
.pi("seqs", 1)
|
||||
.ps("dtype", "fp8_e4m3");
|
||||
hs.push_back(std::move(s));
|
||||
}
|
||||
/* ---- packed weight codes at odd element offsets ------------------------------------------ */
|
||||
{
|
||||
const int64_t M = 2, N = 4, K = 33;
|
||||
@@ -2729,6 +2849,69 @@ void qsa_cases(std::vector<Hand>& hs) {
|
||||
.pi("M", M).pi("blocks", nb).pi("topk", topk).pi("ratio", ratio).pi("seqs", 1);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
{
|
||||
/* The signed order, against the rule: row 0 ranks 2 over the tie of -0 and +0 (NaN dead,
|
||||
* -1e31 live), row 1 is all negative with -inf dead and -1e30 live. Under the unsigned
|
||||
* order both rows would rank as zeros. */
|
||||
static const float v[2][8] = {
|
||||
{ -3.0f, -1.0f, -0.0f, 2.0f, -1.0f, 0.0f, NAN, -1e31f },
|
||||
{ -5.0f, -2e30f, -7.0f, -6.0f, -INFINITY, -9.0f, -1e30f, -8.0f } };
|
||||
Hand h("signed: negative scores, -0 tying +0, NaN and -inf dead", "qsa_select", 0.0);
|
||||
h.dense(RAD_F32, { 2, 8 }, [](int64_t i) { return v[i / 8][i % 8]; })
|
||||
.dense(RAD_I32, { 2, 8 }, [](int64_t i) { return (float)(100 + 10 * (i / 8) + i % 8); })
|
||||
.idx({ 8, 8 })
|
||||
.idx({ 31, 31 })
|
||||
.idx({ 0, 1, 2 })
|
||||
.dense(RAD_I32, { 2, 4 }, sent, true)
|
||||
.dense(RAD_I32, { 2 }, sent, true)
|
||||
.dense(RAD_I32, { 2 }, sent, true)
|
||||
.pi("M", 2).pi("blocks", 8).pi("topk", 3).pi("ratio", 4).pi("seqs", 2).pi("signed", 1)
|
||||
.expect(5, { 103, 102, 105, -1, 110, 113, 112, -1 });
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
{
|
||||
/* The column-slice case's scores, shifted to straddle zero, under the signed order. */
|
||||
const int64_t S = 2, M = 6, live = 40, pitch = 56, W = 48, topk = 8, ratio = 4;
|
||||
Hand h("signed: cu from 1, unheld rows, a column slice, ties across zero", "qsa_select",
|
||||
0.0);
|
||||
h.view(RAD_F32, { M, live }, { pitch, 1 }, M * pitch, [=](int64_t i) {
|
||||
switch ((i % pitch + i / pitch) % 9) {
|
||||
case 0: case 1: case 7: return -1.0f;
|
||||
case 2: return NAN;
|
||||
case 3: return INFINITY;
|
||||
case 4: return -0.0f;
|
||||
case 5: return -INFINITY;
|
||||
case 6: return -1.5f;
|
||||
default: return 0.25f * (float)(i % 5) - 0.5f;
|
||||
}
|
||||
})
|
||||
.dense(RAD_I32, { S, W }, [](int64_t i) {
|
||||
return i % 11 == 4 ? -1.0f : (float)((i * 13 + 3) % 500);
|
||||
})
|
||||
.idx({ 40, 25 })
|
||||
.idx({ 160, 98, 99, 161, 40, 7 })
|
||||
.idx({ 1, 3, 5 })
|
||||
.dense(RAD_I32, { M, topk + 1 }, sent, true)
|
||||
.dense(RAD_I32, { M }, sent, true)
|
||||
.dense(RAD_I32, { M }, sent, true)
|
||||
.pi("M", M).pi("blocks", W).pi("topk", topk).pi("ratio", ratio).pi("seqs", S)
|
||||
.pi("signed", 1);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
{
|
||||
Hand h("a `signed` other than 0 or 1 is refused before any write", "qsa_select", 0.0);
|
||||
h.dense(RAD_F32, { 1, 4 }, hfill(208))
|
||||
.dense(RAD_I32, { 1, 4 }, [](int64_t i) { return (float)i; })
|
||||
.idx({ 4 })
|
||||
.idx({ 15 })
|
||||
.idx({ 0, 1 })
|
||||
.dense(RAD_I32, { 1, 3 }, sent, true)
|
||||
.dense(RAD_I32, { 1 }, sent, true)
|
||||
.dense(RAD_I32, { 1 }, sent, true)
|
||||
.pi("M", 1).pi("blocks", 4).pi("topk", 2).pi("ratio", 4).pi("seqs", 1).pi("signed", 2)
|
||||
.refuses(RAD_E_INVAL);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
{
|
||||
Hand h("a negative block count is refused before any write", "qsa_select", 0.0);
|
||||
h.dense(RAD_F32, { 1, 4 }, hfill(207))
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
#include "avx_vec.h"
|
||||
#include "avx_common.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
using namespace avx;
|
||||
|
||||
AVX_KERNEL(dsa_query) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
const auto &x = a->t[0], &q = a->t[1], &s = a->t[2];
|
||||
const int64_t n = p_int(a, "n", 0);
|
||||
if (n < 1 || n > 256 || (n & (n - 1)) || x.rank != 2 || q.rank != 2 || s.rank != 2 ||
|
||||
x.shape[0] < 1 || q.shape[0] != x.shape[0] || x.shape[1] != n || q.shape[1] != n ||
|
||||
s.shape[0] != x.shape[0] || s.shape[1] != 1)
|
||||
return RAD_E_SHAPE;
|
||||
if (x.dtype != RAD_BF16 || q.dtype != RAD_F8E4M3 || s.dtype != RAD_F32) return RAD_E_DTYPE;
|
||||
if (!x.data || !q.data || !s.data) return RAD_E_INVAL;
|
||||
AVX_PARALLEL_FOR_IF(x.shape[0] * n >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < x.shape[0]; ++r) {
|
||||
float v[256];
|
||||
for (int64_t d = 0; d < n; ++d) v[d] = ldt(&x, r * x.stride[0] + d * x.stride[1]);
|
||||
for (int64_t h = 1; h < n; h *= 2)
|
||||
for (int64_t i = 0; i < n; i += 2 * h)
|
||||
for (int64_t j = 0; j < h; ++j) {
|
||||
const float lo = v[i + j], hi = v[i + j + h];
|
||||
v[i + j] = lo + hi;
|
||||
v[i + j + h] = lo - hi;
|
||||
}
|
||||
float am = 1e-4f;
|
||||
const float norm = 1.0f / std::sqrt((float)n);
|
||||
for (int64_t d = 0; d < n; ++d) {
|
||||
v[d] = rad_bf16_to_f32(rad_f32_to_bf16(v[d] * norm));
|
||||
am = std::max(am, std::fabs(v[d]));
|
||||
}
|
||||
int exponent = 0;
|
||||
const float fraction = std::frexp(am * (1.0f / 448.0f), &exponent);
|
||||
const float sc = std::ldexp(1.0f, exponent - (fraction == 0.5f));
|
||||
stt(&s, r * s.stride[0], sc);
|
||||
for (int64_t d = 0; d < n; ++d)
|
||||
stt(&q, r * q.stride[0] + d * q.stride[1], std::clamp(v[d] / sc, -448.0f, 448.0f));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
AVX_KERNEL(dsa_score) {
|
||||
if (!a || !a->t || a->n_t < 9) return RAD_E_INVAL;
|
||||
RadTensor q = a->t[0], qs = a->t[1];
|
||||
const auto& g = a->t[2];
|
||||
RadTensor k = a->t[3], ks = a->t[4];
|
||||
const bool packed = k.dtype == RAD_U8;
|
||||
if (packed) {
|
||||
if (ks.data || k.rank != 4 || k.shape[1] != 1 || k.shape[2] != 4 || k.shape[3] != 34 ||
|
||||
k.stride[3] != 1 || k.stride[2] != 34 || k.stride[0] < 136 || k.stride[0] % 4 ||
|
||||
((uintptr_t)k.data & 3))
|
||||
return RAD_E_SHAPE;
|
||||
ks = {};
|
||||
ks.data = k.data ? (uint8_t*)k.data + 128 : nullptr;
|
||||
ks.dtype = RAD_F32;
|
||||
ks.rank = 1;
|
||||
ks.shape[0] = k.shape[0];
|
||||
ks.stride[0] = k.stride[0] / 4;
|
||||
k.dtype = RAD_F8E4M3;
|
||||
k.rank = 2;
|
||||
k.shape[1] = 128;
|
||||
k.stride[1] = 1;
|
||||
}
|
||||
const auto &bt = a->t[5], &cu = a->t[6], &nc = a->t[7], &out = a->t[8];
|
||||
const int64_t n = p_int(a, "n", 0), h = p_int(a, "heads", 0);
|
||||
if (h > 0 && q.rank == 2 && qs.rank == 2 && qs.shape[1] == 1 &&
|
||||
q.shape[0] == out.shape[0] * h && qs.shape[0] == q.shape[0]) {
|
||||
q.rank = 3;
|
||||
q.shape[0] = out.shape[0];
|
||||
q.shape[2] = q.shape[1];
|
||||
q.shape[1] = h;
|
||||
q.stride[2] = q.stride[1];
|
||||
q.stride[1] = q.stride[0];
|
||||
q.stride[0] *= h;
|
||||
qs.shape[0] = out.shape[0];
|
||||
qs.shape[1] = h;
|
||||
qs.stride[1] = qs.stride[0];
|
||||
qs.stride[0] *= h;
|
||||
}
|
||||
if (n < 1 || h < 1 || h > 64 || q.rank != 3 || q.shape[0] < 1 || q.shape[1] != h ||
|
||||
q.shape[2] != n || qs.rank != 2 || g.rank != 2 || qs.shape[0] != q.shape[0] ||
|
||||
g.shape[0] != q.shape[0] || qs.shape[1] != h || g.shape[1] != h || k.rank != 2 ||
|
||||
k.shape[1] != n || ks.rank != 1 || ks.shape[0] != k.shape[0] || bt.rank != 2 ||
|
||||
cu.rank != 1 || nc.rank != 1 || cu.shape[0] != bt.shape[0] + 1 ||
|
||||
nc.shape[0] != bt.shape[0] || out.rank != 2 || out.shape[0] != q.shape[0] ||
|
||||
out.shape[1] > bt.shape[1])
|
||||
return RAD_E_SHAPE;
|
||||
if (q.dtype != RAD_F8E4M3 || k.dtype != RAD_F8E4M3 || qs.dtype != RAD_F32 ||
|
||||
ks.dtype != RAD_F32 || g.dtype != RAD_F32 || bt.dtype != RAD_I32 || cu.dtype != RAD_I32 ||
|
||||
nc.dtype != RAD_I32 || out.dtype != RAD_F32)
|
||||
return RAD_E_DTYPE;
|
||||
for (int i = 0; i < 9; ++i)
|
||||
if (!(packed && i == 4) && !a->t[i].data) return RAD_E_INVAL;
|
||||
const float norm = 1.0f / std::sqrt((float)(h * n));
|
||||
AVX_PARALLEL_FOR_IF(q.shape[0] * out.shape[1] * h * n >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < q.shape[0]; ++r) {
|
||||
int64_t seq = -1;
|
||||
for (int64_t s = 0; s < bt.shape[0]; ++s)
|
||||
if (r >= ld_int_dt(cu.dtype, cu.data, s * cu.stride[0]) &&
|
||||
r < ld_int_dt(cu.dtype, cu.data, (s + 1) * cu.stride[0])) {
|
||||
seq = s;
|
||||
break;
|
||||
}
|
||||
const int64_t live = seq >= 0 ? ld_int_dt(nc.dtype, nc.data, seq * nc.stride[0]) : 0;
|
||||
for (int64_t b = 0; b < out.shape[1]; ++b) {
|
||||
const int64_t page =
|
||||
seq >= 0 && b < live
|
||||
? ld_int_dt(bt.dtype, bt.data, seq * bt.stride[0] + b * bt.stride[1])
|
||||
: -1;
|
||||
float result = -INFINITY;
|
||||
if (page >= 0 && page < k.shape[0]) {
|
||||
result = 0;
|
||||
for (int64_t head = 0; head < h; ++head) {
|
||||
float dot = 0;
|
||||
for (int64_t d = 0; d < n; ++d)
|
||||
dot += ldt(&q, r * q.stride[0] + head * q.stride[1] + d * q.stride[2]) *
|
||||
ldt(&k, page * k.stride[0] + d * k.stride[1]);
|
||||
result += std::max(dot, 0.0f) *
|
||||
ldt(&qs, r * qs.stride[0] + head * qs.stride[1]) *
|
||||
ldt(&g, r * g.stride[0] + head * g.stride[1]);
|
||||
}
|
||||
result *= ldt(&ks, page * ks.stride[0]) * norm;
|
||||
}
|
||||
stt(&out, r * out.stride[0] + b * out.stride[1], result);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
AVX_KERNEL(dsa_pool) {
|
||||
if (p_int(a, "block_size", 4) != 4) return RAD_E_SHAPE;
|
||||
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
|
||||
const auto &kg = a->t[0], &ape = a->t[1], &q = a->t[2], &s = a->t[3];
|
||||
const int64_t n = p_int(a, "n", 0), ratio = p_int(a, "ratio", 0);
|
||||
const auto *page = rad_arg_in(a, 4), *cache = rad_arg_in(a, 5);
|
||||
if ((page != nullptr) != (cache != nullptr)) return RAD_E_INVAL;
|
||||
if (cache &&
|
||||
(n != 128 || ratio != 4 || page->dtype != RAD_I32 || page->rank != 1 ||
|
||||
page->shape[0] != q.shape[0] || page->stride[0] < 1 || cache->dtype != RAD_U8 ||
|
||||
cache->rank != 4 || cache->shape[0] < 1 || cache->shape[1] != 1 || cache->shape[2] != 4 ||
|
||||
cache->shape[3] != 34 || cache->stride[3] != 1 || cache->stride[2] != 34 ||
|
||||
cache->stride[0] < 136 || cache->stride[0] % 4 || ((uintptr_t)cache->data & 3)))
|
||||
return RAD_E_SHAPE;
|
||||
if (n < 1 || n > 256 || (n & (n - 1)) || ratio < 2 || ratio > 16 || kg.rank != 2 ||
|
||||
ape.rank != 2 || q.rank != 2 || s.rank != 2 || q.shape[0] < 1 || !kg.data || !ape.data ||
|
||||
!q.data || !s.data || kg.dtype != RAD_BF16 || ape.dtype != RAD_F32 ||
|
||||
q.dtype != RAD_F8E4M3 || s.dtype != RAD_F32 || kg.shape[0] != q.shape[0] * ratio ||
|
||||
kg.shape[1] != 2 * n || ape.shape[0] != ratio || ape.shape[1] != n || q.shape[1] != n ||
|
||||
s.shape[0] != q.shape[0] || s.shape[1] != 1)
|
||||
return RAD_E_SHAPE;
|
||||
AVX_PARALLEL_FOR_IF(q.shape[0] * n * ratio >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < q.shape[0]; ++r) {
|
||||
float x[256];
|
||||
for (int64_t d = 0; d < n; ++d) {
|
||||
float g[16], mx = -INFINITY;
|
||||
for (int64_t j = 0; j < ratio; ++j) {
|
||||
g[j] = ldt(&kg, (r * ratio + j) * kg.stride[0] + (n + d) * kg.stride[1]) +
|
||||
ldt(&ape, j * ape.stride[0] + d * ape.stride[1]);
|
||||
mx = std::max(mx, g[j]);
|
||||
}
|
||||
float z = 0, den = 0;
|
||||
for (int64_t j = 0; j < ratio; ++j) {
|
||||
const float p = std::exp(g[j] - mx);
|
||||
z += p * ldt(&kg, (r * ratio + j) * kg.stride[0] + d * kg.stride[1]);
|
||||
den += p;
|
||||
}
|
||||
x[d] = rad_bf16_to_f32(rad_f32_to_bf16(z / den));
|
||||
}
|
||||
for (int64_t step = 1; step < n; step *= 2)
|
||||
for (int64_t base = 0; base < n; base += 2 * step)
|
||||
for (int64_t j = 0; j < step; ++j) {
|
||||
const float lo = x[base + j], hi = x[base + j + step];
|
||||
x[base + j] = lo + hi;
|
||||
x[base + j + step] = lo - hi;
|
||||
}
|
||||
float am = 1e-4f;
|
||||
const float norm = 1.0f / std::sqrt((float)n);
|
||||
for (int64_t d = 0; d < n; ++d) {
|
||||
x[d] = rad_bf16_to_f32(rad_f32_to_bf16(x[d] * norm));
|
||||
am = std::max(am, std::fabs(x[d]));
|
||||
}
|
||||
int exponent = 0;
|
||||
const float fraction = std::frexp(am * (1.0f / 448.0f), &exponent);
|
||||
const float sc = std::ldexp(1.0f, exponent - (fraction == 0.5f));
|
||||
stt(&s, r * s.stride[0], sc);
|
||||
for (int64_t d = 0; d < n; ++d)
|
||||
stt(&q, r * q.stride[0] + d * q.stride[1], std::clamp(x[d] / sc, -448.0f, 448.0f));
|
||||
if (cache) {
|
||||
const int64_t p = ldi(page, r * page->stride[0]);
|
||||
if (p >= 0 && p < cache->shape[0]) {
|
||||
auto* dst = (uint8_t*)cache->data + p * cache->stride[0];
|
||||
for (int d = 0; d < 128; ++d)
|
||||
dst[d] = ((uint8_t*)q.data)[r * q.stride[0] + d * q.stride[1]];
|
||||
std::memcpy(dst + 128, &sc, sizeof(sc));
|
||||
}
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -0,0 +1,507 @@
|
||||
/* Host mHC and bounded KDA. Widen each activation row once, then reduce the
|
||||
* projections and state products with this ISA level's vector operations. */
|
||||
#include "avx_vec.h"
|
||||
#include "avx_common.h"
|
||||
#include <algorithm>
|
||||
|
||||
using namespace avx;
|
||||
|
||||
namespace {
|
||||
bool matrix(const RadTensor& t, int64_t r, int64_t c) {
|
||||
return t.data && t.rank == 2 && t.shape[0] == r && t.shape[1] == c;
|
||||
}
|
||||
float dot(const float* x, const float* y, int64_t n) {
|
||||
vf acc = vf_zero();
|
||||
int64_t i = 0;
|
||||
for (; i + VF_N <= n; i += VF_N) acc = vf_fma(vf_loadu(x + i), vf_loadu(y + i), acc);
|
||||
float s = vf_hsum(acc);
|
||||
for (; i < n; ++i) s += x[i] * y[i];
|
||||
return s;
|
||||
}
|
||||
void sinkhorn(float* c, int h, int repeats, float eps) {
|
||||
for (int r = 0; r < h; ++r) {
|
||||
float max = -INFINITY;
|
||||
for (int k = 0; k < h; ++k) max = std::max(max, c[r * h + k]);
|
||||
float total = 0;
|
||||
for (int k = 0; k < h; ++k) {
|
||||
c[r * h + k] = std::exp(c[r * h + k] - max);
|
||||
total += c[r * h + k];
|
||||
}
|
||||
for (int k = 0; k < h; ++k) c[r * h + k] = c[r * h + k] / total + eps;
|
||||
}
|
||||
for (int it = 0; it < repeats; ++it) {
|
||||
if (it)
|
||||
for (int r = 0; r < h; ++r) {
|
||||
float total = 0;
|
||||
for (int k = 0; k < h; ++k) total += c[r * h + k];
|
||||
for (int k = 0; k < h; ++k) c[r * h + k] /= total + eps;
|
||||
}
|
||||
for (int k = 0; k < h; ++k) {
|
||||
float total = 0;
|
||||
for (int r = 0; r < h; ++r) total += c[r * h + k];
|
||||
for (int r = 0; r < h; ++r) c[r * h + k] /= total + eps;
|
||||
}
|
||||
}
|
||||
}
|
||||
bool headed(const RadTensor& t, int64_t tokens, int64_t heads, int64_t dim) {
|
||||
return t.data && t.shape[0] == tokens &&
|
||||
((t.rank == 3 && t.shape[1] == heads && t.shape[2] == dim) ||
|
||||
(t.rank == 2 && t.shape[1] == heads * dim));
|
||||
}
|
||||
int64_t at(const RadTensor& t, int64_t token, int64_t h, int64_t d, int64_t width) {
|
||||
return token * t.stride[0] + h * (t.rank == 3 ? t.stride[1] : width * t.stride[1]) +
|
||||
d * laststride(&t);
|
||||
}
|
||||
}
|
||||
|
||||
AVX_KERNEL(gemm_nt_f32) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
const auto &x = a->t[0], &w = a->t[1], &y = a->t[2];
|
||||
const int64_t n = p_int(a, "N", 0), k = p_int(a, "K", 0);
|
||||
if (n < 1 || k < 1 || x.rank != 2 || w.rank != 2 || y.rank != 2 || x.shape[0] < 1 ||
|
||||
x.shape[1] != k || w.shape[0] != n || w.shape[1] != k || y.shape[0] != x.shape[0] ||
|
||||
y.shape[1] != n)
|
||||
return RAD_E_SHAPE;
|
||||
if (x.dtype != RAD_BF16 || w.dtype != RAD_F32 || y.dtype != RAD_F32) return RAD_E_DTYPE;
|
||||
if (!x.data || !w.data || !y.data) return RAD_E_INVAL;
|
||||
AVX_PARALLEL_FOR_IF(x.shape[0] * n * k >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < x.shape[0]; ++r) {
|
||||
float* query = scratch_f32((size_t)k);
|
||||
for (int64_t j = 0; j < k; ++j) query[j] = ldt(&x, r * x.stride[0] + j * x.stride[1]);
|
||||
for (int64_t col = 0; col < n; ++col) {
|
||||
float sum = 0;
|
||||
if (w.stride[1] == 1)
|
||||
sum = dot(query, (const float*)w.data + col * w.stride[0], k);
|
||||
else
|
||||
for (int64_t j = 0; j < k; ++j)
|
||||
sum += query[j] * ldt(&w, col * w.stride[0] + j * w.stride[1]);
|
||||
stt(&y, r * y.stride[0] + col * y.stride[1], sum);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
AVX_KERNEL(router_sigmoid_topk) {
|
||||
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
|
||||
const auto &lg = a->t[0], &bias = a->t[1], &ids = a->t[2], &w = a->t[3];
|
||||
const int64_t ne = p_int(a, "n_expert", 0), k = p_int(a, "top_k", 0);
|
||||
const float factor = p_f32(a, "route_scale", 0);
|
||||
if (ne < 1 || ne > 512 || k < 1 || k > ne || !std::isfinite(factor) || factor <= 0 ||
|
||||
lg.rank != 2 || lg.shape[0] < 1 || lg.shape[1] != ne || bias.rank != 1 ||
|
||||
bias.shape[0] != ne || bias.dtype != RAD_F32 || ids.dtype != RAD_I32 ||
|
||||
!matrix(ids, lg.shape[0], k) || !matrix(w, lg.shape[0], k) || !lg.data || !bias.data)
|
||||
return RAD_E_SHAPE;
|
||||
for (int64_t r = 0; r < lg.shape[0]; ++r) {
|
||||
float prob[512], ranked[512], chosen[512];
|
||||
int index[512];
|
||||
for (int64_t e = 0; e < ne; ++e) {
|
||||
prob[e] = 1.0f / (1.0f + std::exp(-ldt(&lg, rowoff(&lg, r, ne) + e * laststride(&lg))));
|
||||
ranked[e] = prob[e] + ldt(&bias, e * laststride(&bias));
|
||||
}
|
||||
float total = 0;
|
||||
for (int64_t j = 0; j < k; ++j) {
|
||||
int winner = -1;
|
||||
for (int64_t e = 0; e < ne; ++e)
|
||||
if (ranked[e] > -INFINITY && (winner < 0 || ranked[e] > ranked[winner]))
|
||||
winner = (int)e;
|
||||
if (winner < 0) return RAD_E_SHAPE;
|
||||
index[j] = winner;
|
||||
chosen[j] = prob[winner];
|
||||
total += chosen[j];
|
||||
ranked[winner] = -INFINITY;
|
||||
}
|
||||
const float mult = p_int(a, "norm", 0) ? factor / (total + 1e-20f) : factor;
|
||||
for (int64_t j = 0; j < k; ++j) {
|
||||
st_int_dt(ids.dtype, ids.data, rowoff(&ids, r, k) + j * laststride(&ids), index[j]);
|
||||
stt(&w, rowoff(&w, r, k) + j * laststride(&w), chosen[j] * mult);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
AVX_KERNEL(swiglu_clamped) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const auto &gu = a->t[0], &y = a->t[1];
|
||||
const int64_t n = p_int(a, "n", 0);
|
||||
const float limit = p_f32(a, "limit", 0);
|
||||
if (n < 1 || !std::isfinite(limit) || limit <= 0 || gu.rank != 2 || y.rank != 2 || !gu.data ||
|
||||
!y.data || y.shape[0] < 1 || gu.shape[0] != y.shape[0] || gu.shape[1] != 2 * n ||
|
||||
y.shape[1] != n)
|
||||
return RAD_E_SHAPE;
|
||||
AVX_PARALLEL_FOR_IF(y.shape[0] * n >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < y.shape[0]; ++r) {
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const int64_t b = rowoff(&gu, r, 2 * n), s = laststride(&gu);
|
||||
const float g = std::min(ldt(&gu, b + i * s), limit);
|
||||
const float u = std::clamp(ldt(&gu, b + (n + i) * s), -limit, limit);
|
||||
stt(&y, rowoff(&y, r, n) + i * laststride(&y), (g / (1.0f + std::exp(-g))) * u);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
namespace {
|
||||
int64_t part_stride(int64_t hc) { return (hc * (hc + 2) + 1 + 3) / 4 * 4; }
|
||||
bool pre_params(const RadArgs* a, int64_t* n, int64_t* hc, int64_t* iters, float* eps,
|
||||
float* heps) {
|
||||
*n = p_int(a, "n", 0);
|
||||
*hc = p_int(a, "hc", 0);
|
||||
*iters = p_int(a, "iterations", 0);
|
||||
*eps = p_f32(a, "eps", 0);
|
||||
*heps = p_f32(a, "hc_eps", 0);
|
||||
return *n >= 1 && *hc >= 2 && *hc <= 8 && *iters >= 1 && *iters <= 256 && std::isfinite(*eps) &&
|
||||
*eps > 0 && std::isfinite(*heps) && *heps >= 0;
|
||||
}
|
||||
bool pre_outputs(const RadTensor& h, const RadTensor& scale, const RadTensor& base,
|
||||
const RadTensor& x, const RadTensor& post, const RadTensor& comb, int64_t rows,
|
||||
int64_t n, int64_t hc) {
|
||||
const int64_t mix = hc * (hc + 2);
|
||||
return matrix(h, rows, hc * n) && scale.rank == 1 && scale.dtype == RAD_F32 &&
|
||||
numel(&scale) == 3 && base.rank == 1 && base.dtype == RAD_F32 && numel(&base) == mix &&
|
||||
matrix(x, rows, n) && matrix(post, rows, hc) && matrix(comb, rows, hc * hc) &&
|
||||
post.dtype == RAD_F32 && comb.dtype == RAD_F32;
|
||||
}
|
||||
/* Row r from its RMS-scaled coefficients and the widened residual row hv. */
|
||||
void finish_row(const float* coeff, const float* hv, const RadTensor& scale, const RadTensor& base,
|
||||
const RadTensor& x, const RadTensor& post, const RadTensor& comb, int64_t r,
|
||||
int64_t n, int64_t hc, int64_t iters, float heps) {
|
||||
float pre[8], c[64];
|
||||
for (int64_t j = 0; j < hc; ++j) {
|
||||
pre[j] =
|
||||
1.0f / (1.0f +
|
||||
std::exp(-(coeff[j] * ldt(&scale, 0) + ldt(&base, j * laststride(&base))))) +
|
||||
heps;
|
||||
const float z = coeff[hc + j] * ldt(&scale, laststride(&scale)) +
|
||||
ldt(&base, (hc + j) * laststride(&base));
|
||||
stt(&post, rowoff(&post, r, hc) + j * laststride(&post), 2.0f / (1.0f + std::exp(-z)));
|
||||
}
|
||||
for (int64_t j = 0; j < hc * hc; ++j)
|
||||
c[j] = coeff[2 * hc + j] * ldt(&scale, 2 * laststride(&scale)) +
|
||||
ldt(&base, (2 * hc + j) * laststride(&base));
|
||||
sinkhorn(c, (int)hc, (int)iters, heps);
|
||||
for (int64_t j = 0; j < hc * hc; ++j)
|
||||
stt(&comb, rowoff(&comb, r, hc * hc) + j * laststride(&comb), c[j]);
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
float v = 0;
|
||||
for (int64_t j = 0; j < hc; ++j) v += pre[j] * hv[j * n + i];
|
||||
stt(&x, rowoff(&x, r, n) + i * laststride(&x), v);
|
||||
}
|
||||
}
|
||||
/* fn row j over columns [lo, lo+len), contiguous or through the scratch fw. */
|
||||
float fn_dot(const float* hv, const RadTensor& fn, int64_t j, int64_t width, int64_t lo,
|
||||
int64_t len, float* fw) {
|
||||
const int64_t fb = rowoff(&fn, j, width);
|
||||
if (laststride(&fn) == 1) return dot(hv + lo, (const float*)fn.data + fb + lo, len);
|
||||
for (int64_t i = 0; i < len; ++i) fw[i] = ldt(&fn, fb + (lo + i) * laststride(&fn));
|
||||
return dot(hv + lo, fw, len);
|
||||
}
|
||||
void widen(const RadTensor& h, int64_t r, int64_t width, float* hv) {
|
||||
for (int64_t i = 0; i < width; ++i) hv[i] = ldt(&h, rowoff(&h, r, width) + i * laststride(&h));
|
||||
}
|
||||
}
|
||||
|
||||
AVX_KERNEL(mhc_pre) {
|
||||
if (!rad_args_have(a, 7)) return RAD_E_INVAL;
|
||||
int64_t n, hc, iters;
|
||||
float eps, heps;
|
||||
if (!pre_params(a, &n, &hc, &iters, &eps, &heps)) return RAD_E_SHAPE;
|
||||
const auto &h = a->t[0], &fn = a->t[1], &scale = a->t[2], &base = a->t[3];
|
||||
const auto &x = a->t[4], &post = a->t[5], &comb = a->t[6];
|
||||
if (h.rank != 2) return RAD_E_SHAPE;
|
||||
const int64_t rows = h.shape[0], width = hc * n, mix = hc * (hc + 2);
|
||||
if (rows < 1 || !matrix(fn, mix, width) || fn.dtype != RAD_F32 ||
|
||||
!pre_outputs(h, scale, base, x, post, comb, rows, n, hc))
|
||||
return RAD_E_SHAPE;
|
||||
AVX_PARALLEL_FOR_IF(rows * width * mix >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
float* scratch = scratch_f32((size_t)(2 * width));
|
||||
float* hv = scratch;
|
||||
float* fw = hv + width;
|
||||
widen(h, r, width, hv);
|
||||
const float norm = 1.0f / std::sqrt(dot(hv, hv, width) / (float)width + eps);
|
||||
float coeff[80];
|
||||
for (int64_t j = 0; j < mix; ++j) coeff[j] = fn_dot(hv, fn, j, width, 0, width, fw) * norm;
|
||||
finish_row(coeff, hv, scale, base, x, post, comb, r, n, hc, iters, heps);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
AVX_KERNEL(mhc_pre_partial) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
const int64_t n = p_int(a, "n", 0), hc = p_int(a, "hc", 0), chunk = p_int(a, "chunk", 0);
|
||||
const int64_t first = p_int(a, "first", -1), count = p_int(a, "chunks", 0);
|
||||
if (n < 1 || hc < 2 || hc > 8 || chunk < 1 || (hc * n) % chunk || first < 0 || count < 1 ||
|
||||
first + count > hc * n / chunk)
|
||||
return RAD_E_SHAPE;
|
||||
const auto &h = a->t[0], &fn = a->t[1], &part = a->t[2];
|
||||
if (h.rank != 2) return RAD_E_SHAPE;
|
||||
const int64_t rows = h.shape[0], width = hc * n, mix = hc * (hc + 2), S = part_stride(hc);
|
||||
if (rows < 1 || !matrix(h, rows, width) || !matrix(fn, mix, width) || fn.dtype != RAD_F32 ||
|
||||
!matrix(part, rows, count * S) || part.dtype != RAD_F32)
|
||||
return RAD_E_SHAPE;
|
||||
AVX_PARALLEL_FOR_IF(rows * count * chunk * mix >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
float* scratch = scratch_f32((size_t)(width + chunk));
|
||||
float* hv = scratch;
|
||||
float* fw = hv + width;
|
||||
widen(h, r, width, hv);
|
||||
const int64_t pb = rowoff(&part, r, count * S), ps = laststride(&part);
|
||||
for (int64_t c = 0; c < count; ++c) {
|
||||
const int64_t lo = (first + c) * chunk;
|
||||
for (int64_t j = 0; j < S; ++j) {
|
||||
const float v = j < mix ? fn_dot(hv, fn, j, width, lo, chunk, fw)
|
||||
: j == mix ? dot(hv + lo, hv + lo, chunk)
|
||||
: 0.0f;
|
||||
stt(&part, pb + (c * S + j) * ps, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
AVX_KERNEL(mhc_pre_finish) {
|
||||
if (!rad_args_have(a, 7)) return RAD_E_INVAL;
|
||||
int64_t n, hc, iters;
|
||||
float eps, heps;
|
||||
if (!pre_params(a, &n, &hc, &iters, &eps, &heps)) return RAD_E_SHAPE;
|
||||
const int64_t chunk = p_int(a, "chunk", 0);
|
||||
if (chunk < 1 || (hc * n) % chunk) return RAD_E_SHAPE;
|
||||
const auto &part = a->t[0], &h = a->t[1], &scale = a->t[2], &base = a->t[3];
|
||||
const auto &x = a->t[4], &post = a->t[5], &comb = a->t[6];
|
||||
if (h.rank != 2) return RAD_E_SHAPE;
|
||||
const int64_t rows = h.shape[0], width = hc * n, mix = hc * (hc + 2), S = part_stride(hc),
|
||||
chunks = width / chunk;
|
||||
if (rows < 1 || !matrix(part, rows, chunks * S) || part.dtype != RAD_F32 ||
|
||||
!pre_outputs(h, scale, base, x, post, comb, rows, n, hc))
|
||||
return RAD_E_SHAPE;
|
||||
AVX_PARALLEL_FOR_IF(rows * width >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
float* hv = scratch_f32((size_t)width);
|
||||
widen(h, r, width, hv);
|
||||
const int64_t pb = rowoff(&part, r, chunks * S), ps = laststride(&part);
|
||||
float sq = 0;
|
||||
for (int64_t c = 0; c < chunks; ++c) sq += ldt(&part, pb + (c * S + mix) * ps);
|
||||
const float norm = 1.0f / std::sqrt(sq / (float)width + eps);
|
||||
float coeff[80];
|
||||
for (int64_t j = 0; j < mix; ++j) {
|
||||
float d = 0;
|
||||
for (int64_t c = 0; c < chunks; ++c) d += ldt(&part, pb + (c * S + j) * ps);
|
||||
coeff[j] = d * norm;
|
||||
}
|
||||
finish_row(coeff, hv, scale, base, x, post, comb, r, n, hc, iters, heps);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
AVX_KERNEL(mhc_post) {
|
||||
if (!rad_args_have(a, 5)) return RAD_E_INVAL;
|
||||
const int64_t n = p_int(a, "n", 0), hc = p_int(a, "hc", 0);
|
||||
if (n < 1 || hc < 2 || hc > 8) return RAD_E_SHAPE;
|
||||
const auto &x = a->t[0], &h = a->t[1], &p = a->t[2], &c = a->t[3], &o = a->t[4];
|
||||
if (x.rank != 2) return RAD_E_SHAPE;
|
||||
const int64_t rows = x.shape[0];
|
||||
if (rows < 1 || !matrix(x, rows, n) || !matrix(h, rows, hc * n) || !matrix(p, rows, hc) ||
|
||||
!matrix(c, rows, hc * hc) || !matrix(o, rows, hc * n) || o.data == h.data ||
|
||||
p.dtype != RAD_F32 || c.dtype != RAD_F32)
|
||||
return RAD_E_SHAPE;
|
||||
AVX_PARALLEL_FOR_IF(rows * n * hc >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
for (int64_t dst = 0; dst < hc; ++dst)
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
float v = 0;
|
||||
for (int64_t src = 0; src < hc; ++src)
|
||||
v += ldt(&c, rowoff(&c, r, hc * hc) + (src * hc + dst) * laststride(&c)) *
|
||||
ldt(&h, rowoff(&h, r, hc * n) + (src * n + i) * laststride(&h));
|
||||
v += ldt(&p, rowoff(&p, r, hc) + dst * laststride(&p)) *
|
||||
ldt(&x, rowoff(&x, r, n) + i * laststride(&x));
|
||||
stt(&o, rowoff(&o, r, hc * n) + (dst * n + i) * laststride(&o), v);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
AVX_KERNEL(mhc_contract) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const int64_t n = p_int(a, "n", 0), hc = p_int(a, "hc", 0);
|
||||
if (n < 1 || hc < 2 || hc > 8) return RAD_E_SHAPE;
|
||||
const auto &h = a->t[0], &x = a->t[1];
|
||||
if (h.rank != 2 || h.shape[0] < 1 || !matrix(h, h.shape[0], hc * n) ||
|
||||
!matrix(x, h.shape[0], n))
|
||||
return RAD_E_SHAPE;
|
||||
AVX_PARALLEL_FOR_IF(h.shape[0] * n * hc >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < h.shape[0]; ++r)
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
float v = 0;
|
||||
for (int64_t j = 0; j < hc; ++j)
|
||||
v += ldt(&h, rowoff(&h, r, hc * n) + (j * n + i) * laststride(&h));
|
||||
stt(&x, rowoff(&x, r, n) + i * laststride(&x), v / (float)hc);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
AVX_KERNEL(kda_update) {
|
||||
if (!a || a->n_t < 13) return RAD_E_INVAL;
|
||||
for (int i = 0; i < 10; ++i)
|
||||
if (!rad_arg_in(a, i)) return RAD_E_INVAL;
|
||||
if (!rad_arg_in(a, 12)) return RAD_E_INVAL;
|
||||
const int64_t H = p_int(a, "heads", 0), K = p_int(a, "head_k", 0), V = p_int(a, "head_v", 0);
|
||||
const float lower = p_f32(a, "lower_bound", 0), eps = p_f32(a, "l2_eps", 1e-6f),
|
||||
scale = p_f32(a, "scale", 1);
|
||||
const char* mode = p_str(a, "mode", "");
|
||||
const bool verify = !std::strcmp(mode, "verify");
|
||||
const char* form = p_str(a, "state_form", "per_candidate");
|
||||
const bool anchor = !std::strcmp(form, "anchor");
|
||||
if (!anchor && std::strcmp(form, "per_candidate")) return RAD_E_INVAL;
|
||||
if (anchor && (K != 128 || V != 128)) return RAD_E_UNSUPPORTED;
|
||||
if (!verify && std::strcmp(mode, "prefill")) return RAD_E_INVAL;
|
||||
if (H < 1 || K < 1 || K > 128 || V < 1 || V > 128 || !std::isfinite(lower) || lower >= 0 ||
|
||||
!std::isfinite(eps) || eps <= 0 || !std::isfinite(scale))
|
||||
return RAD_E_SHAPE;
|
||||
const auto &q = a->t[0], &k = a->t[1], &v = a->t[2], &g = a->t[3], &b = a->t[4];
|
||||
const auto &al = a->t[5], &bias = a->t[6], &s = a->t[7], &idx = a->t[8], &cu = a->t[9],
|
||||
&out = a->t[12];
|
||||
const auto* accepted = rad_arg_in(a, 10);
|
||||
const auto* init = rad_arg_in(a, 11);
|
||||
if (q.rank < 2 || cu.rank != 1 || cu.dtype != RAD_I32 || cu.shape[0] < 2) return RAD_E_SHAPE;
|
||||
const int64_t T = q.shape[0], N = cu.shape[0] - 1, slots = s.shape[0];
|
||||
if (T < 1) return RAD_E_SHAPE;
|
||||
if (!headed(q, T, H, K) || !headed(k, T, H, K) || !headed(v, T, H, V) || !headed(g, T, H, K) ||
|
||||
!headed(b, T, H, 1) || !headed(out, T, H, V) || numel(&al) != H || numel(&bias) != H * K ||
|
||||
s.rank != 4 || s.dtype != RAD_F32 || s.shape[1] != H || s.shape[2] != V ||
|
||||
s.shape[3] != K || idx.rank != 2 || idx.dtype != RAD_I32 || idx.shape[0] < N ||
|
||||
idx.shape[1] < 1 || (accepted && (accepted->dtype != RAD_I32 || numel(accepted) < N)) ||
|
||||
(init && (init->dtype != RAD_I32 || numel(init) < N)))
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t width = idx.shape[1];
|
||||
for (int64_t seq = 0; seq < N; ++seq) {
|
||||
const int64_t begin = ldi(&cu, seq * cu.stride[0]);
|
||||
const int64_t end = ldi(&cu, (seq + 1) * cu.stride[0]);
|
||||
const int64_t na = accepted ? ldi(accepted, offlin(accepted, seq)) : 1;
|
||||
if (begin < 0 || end < begin || end > T || na < 1 || na > (anchor ? 32 : width) ||
|
||||
(verify && end - begin > (anchor ? 32 : width)) || (anchor && width < 2))
|
||||
return RAD_E_SHAPE;
|
||||
for (int64_t j = 0; j < width; ++j)
|
||||
if (ldi(&idx, seq * idx.stride[0] + j * idx.stride[1]) >= slots) return RAD_E_SHAPE;
|
||||
if (anchor) {
|
||||
const int64_t read = ldi(&idx, seq * idx.stride[0]);
|
||||
const int64_t scratch = ldi(&idx, seq * idx.stride[0] + (width / 2) * idx.stride[1]);
|
||||
if (read >= 0 && (scratch < 0 || scratch == read)) return RAD_E_SHAPE;
|
||||
if (verify && read >= 0 && (!init || ldi(init, offlin(init, seq))))
|
||||
for (int64_t h = 0; h < H; ++h) {
|
||||
const float count = ldt(&s, scratch * s.stride[0] + h * s.stride[1]);
|
||||
if (!std::isfinite(count) || count < 0 || count > 32 ||
|
||||
count != std::floor(count) || (count > 0 && na > count))
|
||||
return RAD_E_SHAPE;
|
||||
}
|
||||
}
|
||||
}
|
||||
AVX_PARALLEL_FOR_IF(N * H * V * K >= AVX_PAR_MIN)
|
||||
for (int64_t sh = 0; sh < N * H; ++sh) {
|
||||
const int64_t seq = sh / H, head = sh % H;
|
||||
const int64_t begin = ldi(&cu, seq * cu.stride[0]);
|
||||
const int64_t end = ldi(&cu, (seq + 1) * cu.stride[0]);
|
||||
const int64_t na = accepted ? ldi(accepted, offlin(accepted, seq)) : 1;
|
||||
const int64_t read =
|
||||
ldi(&idx, seq * idx.stride[0] + (verify && !anchor ? na - 1 : 0) * idx.stride[1]);
|
||||
if (read < 0) {
|
||||
for (int64_t t = begin; t < end; ++t)
|
||||
for (int64_t e = 0; e < V; ++e) stt(&out, at(out, t, head, e, V), 0);
|
||||
continue;
|
||||
}
|
||||
float* S = scratch_f32((size_t)(V * K + 3 * K));
|
||||
float* qn = S + V * K;
|
||||
float* kn = qn + K;
|
||||
float* decay = kn + K;
|
||||
const bool warm = !init || ldi(init, offlin(init, seq)) != 0;
|
||||
for (int64_t e = 0; e < V; ++e)
|
||||
for (int64_t d = 0; d < K; ++d)
|
||||
S[e * K + d] = warm ? ldt(&s, read * s.stride[0] + head * s.stride[1] +
|
||||
e * s.stride[2] + d * s.stride[3])
|
||||
: 0;
|
||||
const int64_t scratch =
|
||||
anchor ? ldi(&idx, seq * idx.stride[0] + (width / 2) * idx.stride[1]) : 0;
|
||||
auto factor_at = [&](int64_t i) {
|
||||
return scratch * s.stride[0] + head * s.stride[1] + (i / K) * s.stride[2] +
|
||||
(i % K) * s.stride[3];
|
||||
};
|
||||
constexpr int factors = 385;
|
||||
if (anchor && verify) {
|
||||
const int replay = warm ? (int)ldt(&s, factor_at(0)) : 0;
|
||||
for (int t = 0; t < (replay ? na : 0); ++t) {
|
||||
const int f = 1 + t * factors;
|
||||
for (int d = 0; d < 128; ++d) {
|
||||
kn[d] = ldt(&s, factor_at(f + d));
|
||||
decay[d] = ldt(&s, factor_at(f + 256 + d));
|
||||
}
|
||||
const float bt = ldt(&s, factor_at(f + 384));
|
||||
for (int e = 0; e < 128; ++e) {
|
||||
float* row = S + e * K;
|
||||
for (int d = 0; d < 128; d += VF_N)
|
||||
vf_storeu(row + d, vf_mul(vf_loadu(row + d), vf_loadu(decay + d)));
|
||||
const float delta = bt * (ldt(&s, factor_at(f + 128 + e)) - dot(row, kn, K));
|
||||
for (int d = 0; d < 128; d += VF_N)
|
||||
vf_storeu(row + d,
|
||||
vf_fma(vf_set1(delta), vf_loadu(kn + d), vf_loadu(row + d)));
|
||||
}
|
||||
}
|
||||
for (int e = 0; e < 128; ++e)
|
||||
for (int d = 0; d < 128; ++d)
|
||||
stt(&s,
|
||||
read * s.stride[0] + head * s.stride[1] + e * s.stride[2] + d * s.stride[3],
|
||||
S[e * K + d]);
|
||||
}
|
||||
const float gain = std::exp(ldt(&al, head * laststride(&al)));
|
||||
for (int64_t t = begin; t < end; ++t) {
|
||||
for (int64_t d = 0; d < K; ++d) {
|
||||
qn[d] = ldt(&q, at(q, t, head, d, K));
|
||||
kn[d] = ldt(&k, at(k, t, head, d, K));
|
||||
}
|
||||
const float qi = scale / std::sqrt(dot(qn, qn, K) + eps),
|
||||
ki = 1 / std::sqrt(dot(kn, kn, K) + eps);
|
||||
for (int64_t d = 0; d < K; ++d) {
|
||||
qn[d] *= qi;
|
||||
kn[d] *= ki;
|
||||
const float z = gain * (ldt(&g, at(g, t, head, d, K)) +
|
||||
ldt(&bias, (head * K + d) * laststride(&bias)));
|
||||
decay[d] = std::exp(lower / (1 + std::exp(-z)));
|
||||
}
|
||||
const float beta = 1 / (1 + std::exp(-ldt(&b, at(b, t, head, 0, 1))));
|
||||
if (anchor && verify) {
|
||||
const int f = 1 + (int)(t - begin) * factors;
|
||||
for (int d = 0; d < 128; ++d) {
|
||||
stt(&s, factor_at(f + d), kn[d]);
|
||||
stt(&s, factor_at(f + 256 + d), decay[d]);
|
||||
}
|
||||
for (int e = 0; e < 128; ++e)
|
||||
stt(&s, factor_at(f + 128 + e), ldt(&v, at(v, t, head, e, V)));
|
||||
stt(&s, factor_at(f + 384), beta);
|
||||
}
|
||||
for (int64_t e = 0; e < V; ++e) {
|
||||
float* row = S + e * K;
|
||||
int64_t d = 0;
|
||||
for (; d + VF_N <= K; d += VF_N)
|
||||
vf_storeu(row + d, vf_mul(vf_loadu(row + d), vf_loadu(decay + d)));
|
||||
for (; d < K; ++d) row[d] *= decay[d];
|
||||
const float delta = beta * (ldt(&v, at(v, t, head, e, V)) - dot(row, kn, K));
|
||||
d = 0;
|
||||
for (; d + VF_N <= K; d += VF_N)
|
||||
vf_storeu(row + d, vf_fma(vf_set1(delta), vf_loadu(kn + d), vf_loadu(row + d)));
|
||||
for (; d < K; ++d) row[d] += delta * kn[d];
|
||||
stt(&out, at(out, t, head, e, V), dot(row, qn, K));
|
||||
}
|
||||
if ((!anchor && verify) || (!verify && t + 1 == end)) {
|
||||
const int64_t write =
|
||||
ldi(&idx, seq * idx.stride[0] + (verify ? t - begin : 0) * idx.stride[1]);
|
||||
if (write >= 0)
|
||||
for (int64_t e = 0; e < V; ++e)
|
||||
for (int64_t d = 0; d < K; ++d)
|
||||
stt(&s,
|
||||
write * s.stride[0] + head * s.stride[1] + e * s.stride[2] +
|
||||
d * s.stride[3],
|
||||
S[e * K + d]);
|
||||
}
|
||||
}
|
||||
if (anchor) stt(&s, factor_at(0), verify ? (float)(end - begin) : 0.0f);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -71,6 +71,16 @@ int avx_par_force(int threads);
|
||||
/* ---- elementwise and norms */ \
|
||||
X(rmsnorm) X(rmsnorm_p) X(rmsnorm_add) X(hc_enter) \
|
||||
X(hc_read) X(hc_write) X(mtp_enter) X(layernorm) \
|
||||
X(mhc_pre) X(mhc_post) X(mhc_contract) X(kda_update) \
|
||||
X(mhc_pre_partial) X(mhc_pre_finish) \
|
||||
X(swiglu_clamped) \
|
||||
X(router_sigmoid_topk) \
|
||||
X(dsa_pool) \
|
||||
X(dsa_query) \
|
||||
X(gemm_nt_f32) \
|
||||
X(mla_project) \
|
||||
X(dsa_score) \
|
||||
X(mla_attn) \
|
||||
X(add) X(grid_embed) X(grid_embed_aa) X(causal_conv1d) \
|
||||
X(mul) X(silu_mul) X(gelu_mul) X(gelu) \
|
||||
X(silu) X(sigmoid) X(logit_softcap) X(gather_rows) \
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
#include "avx_vec.h"
|
||||
#include "avx_common.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
using namespace avx;
|
||||
|
||||
AVX_KERNEL(mla_project) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
RadTensor x = a->t[0], y = a->t[2];
|
||||
const auto& w = a->t[1];
|
||||
const int64_t h = p_int(a, "heads", 0), d = p_int(a, "head_dim", 0),
|
||||
l = p_int(a, "latent_dim", 0);
|
||||
const char* mode = p_str(a, "mode", "");
|
||||
const bool absorb = !std::strcmp(mode, "absorb"), expand = !std::strcmp(mode, "expand");
|
||||
auto heads_view = [&](RadTensor& t, int64_t width) {
|
||||
if (h > 0 && width > 0 && t.rank == 2 && t.shape[1] == h * width) {
|
||||
t.rank = 3;
|
||||
t.shape[1] = h;
|
||||
t.shape[2] = width;
|
||||
t.stride[2] = t.stride[1];
|
||||
t.stride[1] *= width;
|
||||
}
|
||||
};
|
||||
heads_view(x, absorb ? d : l);
|
||||
heads_view(y, absorb ? l : d);
|
||||
if ((!absorb && !expand) || h < 1 || d < 1 || l < 1 || x.rank != 3 || w.rank != 2 ||
|
||||
y.rank != 3 || x.shape[0] < 1 || x.shape[1] != h || x.shape[2] != (absorb ? d : l) ||
|
||||
w.shape[0] != h * 2 * d || w.shape[1] != l || y.shape[0] != x.shape[0] || y.shape[1] != h ||
|
||||
y.shape[2] != (absorb ? l : d))
|
||||
return RAD_E_SHAPE;
|
||||
if (x.dtype != RAD_BF16 || w.dtype != RAD_BF16 || y.dtype != RAD_BF16) return RAD_E_DTYPE;
|
||||
if (!x.data || !w.data || !y.data) return RAD_E_INVAL;
|
||||
AVX_PARALLEL_FOR_IF(x.shape[0] * h * d * l >= AVX_PAR_MIN)
|
||||
for (int64_t job = 0; job < x.shape[0] * h; ++job) {
|
||||
const int64_t r = job / h, head = job % h;
|
||||
float* tmp = scratch_f32((size_t)(2 * (d + l)));
|
||||
float *query = tmp, *weights = tmp + d + l;
|
||||
for (int64_t j = 0; j < (absorb ? d : l); ++j)
|
||||
query[j] = ldt(&x, r * x.stride[0] + head * x.stride[1] + j * x.stride[2]);
|
||||
for (int64_t col = 0; col < (absorb ? l : d); ++col) {
|
||||
const int64_t nk = absorb ? d : l;
|
||||
for (int64_t j = 0; j < nk; ++j) {
|
||||
const int64_t wr = head * 2 * d + (absorb ? j : d + col), wc = absorb ? col : j;
|
||||
weights[j] = ldt(&w, wr * w.stride[0] + wc * w.stride[1]);
|
||||
}
|
||||
vf acc = vf_zero();
|
||||
int64_t j = 0;
|
||||
for (; j + VF_N <= nk; j += VF_N)
|
||||
acc = vf_fma(vf_loadu(query + j), vf_loadu(weights + j), acc);
|
||||
float sum = vf_hsum(acc);
|
||||
for (; j < nk; ++j) sum += query[j] * weights[j];
|
||||
stt(&y, r * y.stride[0] + head * y.stride[1] + col * y.stride[2], sum);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
AVX_KERNEL(mla_attn) {
|
||||
if (!rad_args_have(a, 5)) return RAD_E_INVAL;
|
||||
const auto &q = a->t[0], &kv = a->t[1], &bt = a->t[2], &len = a->t[3], &out = a->t[4];
|
||||
const int64_t d = p_int(a, "latent_dim", 0), h = p_int(a, "heads", 0),
|
||||
bs = p_int(a, "block_size", 0);
|
||||
const float scale = p_f32(a, "scale", 0);
|
||||
if (d < 1 || d > 2048 || h < 1 || bs < 1 || !std::isfinite(scale) || scale <= 0 ||
|
||||
q.rank != 3 || q.shape[0] < 1 || q.shape[1] != h || q.shape[2] != d || kv.rank != 4 ||
|
||||
kv.shape[1] != 1 || kv.shape[2] != bs || kv.shape[3] != d || bt.rank != 2 ||
|
||||
bt.shape[0] != q.shape[0] || len.rank != 1 || len.shape[0] != q.shape[0] || out.rank != 3 ||
|
||||
out.shape[0] != q.shape[0] || out.shape[1] != h || out.shape[2] != d ||
|
||||
bt.dtype != RAD_I32 || len.dtype != RAD_I32)
|
||||
return RAD_E_SHAPE;
|
||||
for (int i = 0; i < 5; ++i)
|
||||
if (!a->t[i].data) return RAD_E_INVAL;
|
||||
AVX_PARALLEL_FOR_IF(q.shape[0] * h * d * bt.shape[1] * bs >= AVX_PAR_MIN)
|
||||
for (int64_t job = 0; job < q.shape[0] * h; ++job) {
|
||||
const int64_t r = job / h, head = job % h;
|
||||
const int64_t live = std::clamp(ld_int_dt(len.dtype, len.data, r * len.stride[0]),
|
||||
(int64_t)0, bt.shape[1] * bs);
|
||||
float *tmp = scratch_f32((size_t)(3 * d)), *query = tmp, *key = tmp + d,
|
||||
*value = tmp + 2 * d;
|
||||
for (int64_t c = 0; c < d; ++c) {
|
||||
query[c] = ldt(&q, r * q.stride[0] + head * q.stride[1] + c * q.stride[2]);
|
||||
value[c] = 0;
|
||||
}
|
||||
float max = -INFINITY, den = 0;
|
||||
for (int64_t j = 0; j < live; ++j) {
|
||||
const int64_t page =
|
||||
ld_int_dt(bt.dtype, bt.data, r * bt.stride[0] + (j / bs) * bt.stride[1]);
|
||||
if (page < 0 || page >= kv.shape[0]) continue;
|
||||
const int64_t base = page * kv.stride[0] + (j % bs) * kv.stride[2];
|
||||
for (int64_t c = 0; c < d; ++c) key[c] = ldt(&kv, base + c * kv.stride[3]);
|
||||
vf acc = vf_zero();
|
||||
int64_t c = 0;
|
||||
for (; c + VF_N <= d; c += VF_N)
|
||||
acc = vf_fma(vf_loadu(query + c), vf_loadu(key + c), acc);
|
||||
float score = vf_hsum(acc);
|
||||
for (; c < d; ++c) score += query[c] * key[c];
|
||||
score *= scale;
|
||||
const float next = std::max(max, score), old = std::exp(max - next),
|
||||
w = std::exp(score - next);
|
||||
den = den * old + w;
|
||||
max = next;
|
||||
const vf a = vf_set1(old), b = vf_set1(w);
|
||||
c = 0;
|
||||
for (; c + VF_N <= d; c += VF_N)
|
||||
vf_storeu(value + c, vf_fma(vf_loadu(key + c), b, vf_mul(vf_loadu(value + c), a)));
|
||||
for (; c < d; ++c) value[c] = value[c] * old + key[c] * w;
|
||||
}
|
||||
for (int64_t c = 0; c < d; ++c)
|
||||
stt(&out, r * out.stride[0] + head * out.stride[1] + c * out.stride[2],
|
||||
den > 0 ? value[c] / den : 0);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
+2
-2
@@ -1098,7 +1098,7 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) {
|
||||
if (jc > 0 || (ts && cb_joined(wse[e]))) return RAD_E_DTYPE;
|
||||
}
|
||||
mw[e] = as_mat(&we[e], k);
|
||||
SW[e] = make_scales(quant && ts ? &wse[e] : nullptr, n, k, false);
|
||||
SW[e] = make_scales(quant && ts ? &wse[e] : nullptr, n, k, we[e].dtype == RAD_FP4E2M1);
|
||||
/* An activation scale grid finer than an expert's cannot be hoisted out of the group. No
|
||||
* supported format has one, but libref answers it by scaling each element, so the panel
|
||||
* below is scaled as it is packed and the dot reads no activation scale (`SAg`). */
|
||||
@@ -1218,7 +1218,7 @@ AVX_KERNEL(moe_gemm_q_mod4) { return moe_gemm_impl(a, true, 4); }
|
||||
/* y[t] = sum over the token's slots of expert_w[t, j] * y_expert[position of (t, j)], summed in
|
||||
* ascending slot j (see the file header). The inverse permutation is built once per batch. */
|
||||
AVX_KERNEL(moe_gather) {
|
||||
if (!rad_args_have(a, 6)) return RAD_E_INVAL;
|
||||
if (!a || !a->t || a->n_t < 6 || !rad_args_have(a, 3) || !rad_arg_in(a, 5)) return RAD_E_INVAL;
|
||||
const RadTensor *ye = &a->t[0], *ew = &a->t[1], *sorted = &a->t[2], *Y = &a->t[5];
|
||||
/* Optional shared-expert fold: y = narrow(shared * act(gate)) + narrow(gathered). Both
|
||||
* operands or neither, as in libref. */
|
||||
|
||||
@@ -67,6 +67,26 @@ static const RadOperandSpec oHcRead[] = { OPD("h"), WGT("w"), WGT("mix_down"),
|
||||
WGT_O("inject_w"), OUT("x"), OUT_O("inj"), OUT_O("q"),
|
||||
OUT_O("scale"), OUT_O("rq"), OUT_O("rscale") };
|
||||
|
||||
static const RadParamSpec pMhcPre[] = { P_INT("M"), P_INT("n"), P_INT("hc"),
|
||||
P_INT("iterations"), P_F64("eps"), P_F64("hc_eps"), P_STR("dtype") };
|
||||
static const RadOperandSpec oMhcPre[] = { OPD("h"), WGT("fn"), WGT("scale"), WGT("base"),
|
||||
OUT("x"), OUT("post"), OUT("comb") };
|
||||
static const RadParamSpec pMhcPrePartial[] = { P_INT("M"), P_INT("n"), P_INT("hc"),
|
||||
P_INT("chunk"), P_INT("first"), P_INT("chunks"), P_STR("dtype") };
|
||||
static const RadOperandSpec oMhcPrePartial[] = { OPD("h"), WGT("fn"), OUT("part") };
|
||||
static const RadParamSpec pMhcPreFinish[] = { P_INT("M"), P_INT("n"), P_INT("hc"),
|
||||
P_INT("iterations"), P_F64("eps"), P_F64("hc_eps"), P_INT("chunk"), P_STR("dtype") };
|
||||
static const RadOperandSpec oMhcPreFinish[] = { OPD("part"), OPD("h"), WGT("scale"), WGT("base"),
|
||||
OUT("x"), OUT("post"), OUT("comb") };
|
||||
static const RadOperandSpec oMhcPost[] = { OPD("x"), OPD("h"), OPD("post"), OPD("comb"), OUT("out") };
|
||||
static const RadOperandSpec oMhcContract[] = { OPD("h"), OUT("x") };
|
||||
static const RadParamSpec pKdaUpdate[] = { P_INT("M"), P_INT("heads"), P_INT("head_k"),
|
||||
P_INT("head_v"), P_F64("lower_bound"), P_F64("scale"), P_F64("l2_eps"),
|
||||
P_STR("mode"), P_STR("dtype"), P_STRO("state_form") };
|
||||
static const RadOperandSpec oKdaUpdate[] = { OPD("q"), OPD("k"), OPD("v"), OPD("a"), OPD("b"),
|
||||
WGT("A_log"), WGT("dt_bias"), INOUT("state"), OPD("state_idx"), OPD("cu"),
|
||||
OPD_O("num_accepted"), OPD_O("has_init"), OUT("o") };
|
||||
|
||||
static const RadParamSpec pNgramIds[] = { P_INT("M"), P_INT("heads"), P_INT("ngram"),
|
||||
P_INT("eos") };
|
||||
static const RadOperandSpec oNgramIds[] = { OPD("tok"), INOUT("state"), OPD("cu"), WGT("mult"),
|
||||
@@ -110,6 +130,22 @@ static const RadOperandSpec oLayernorm[] = { OPD("x"), WGT("w"), WGT_O("b"), OUT
|
||||
static const RadParamSpec pGridEmbed[] = { P_INT("M"), P_INT("n"), P_INT("side"), P_STR("dtype") };
|
||||
static const RadOperandSpec oGridEmbed[] = { INOUT("x"), WGT("table"), OPD("coord") };
|
||||
|
||||
static const RadParamSpec pSwigluClamped[] = { P_INT("M"), P_INT("n"), P_F64("limit"), P_STR("dtype") };
|
||||
static const RadParamSpec pDsaPool[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), P_STR("dtype"), P_INTO("block_size") };
|
||||
static const RadParamSpec pMlaAttn[] = { P_INT("M"), P_INT("latent_dim"), P_INT("heads"),
|
||||
P_INT("blocks"), P_INT("block_size"), P_F64("scale"), P_STR("dtype") };
|
||||
static const RadParamSpec pMlaProject[] = { P_INT("M"), P_INT("heads"), P_INT("head_dim"),
|
||||
P_INT("latent_dim"), P_STR("mode"), P_STR("dtype") };
|
||||
static const RadOperandSpec oMlaAttn[] = { OPD("q"), OPD("kv"), OPD("bt"), OPD("length"), OUT("out") };
|
||||
static const RadParamSpec pDsaScore[] = { P_INT("M"), P_INT("n"), P_INT("heads"),
|
||||
P_INT("blocks"), P_INT("seqs"), P_STR("dtype") };
|
||||
static const RadOperandSpec oDsaScore[] = { OPD("q"), OPD("q_scale"), OPD("gate"), OPD("k"),
|
||||
OPD_O("k_scale"), OPD("bt"), OPD("cu"), OPD("nc"), OUT("score") };
|
||||
static const RadOperandSpec oDsaPool[] = { OPD("kg"), WGT("ape"), OUT("q"), OUT("scale"),
|
||||
OPD_O("page"), INOUT_O("cache") };
|
||||
static const RadParamSpec pRouterSigmoid[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"),
|
||||
P_INT("norm"), P_F64("route_scale"), P_STR("dtype") };
|
||||
static const RadOperandSpec oRouterSigmoid[] = { OPD("logits"), WGT("bias"), OUT("ids"), OUT("weights") };
|
||||
static const RadParamSpec pMnD[] = { P_INT("M"), P_INT("n"), P_STR("dtype") };
|
||||
/* `add`'s `div` divides the rounded sum (libref's pAdd). */
|
||||
static const RadParamSpec pAdd[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_F64O("div") };
|
||||
@@ -697,6 +733,14 @@ static const RadOpSchema kSchemas[] = {
|
||||
"f32 sum, the multiply from residual_out after narrowing, as libref." },
|
||||
{ "hc_enter", ARR(pHcWrite), ARR(oHcEnter),
|
||||
"h[s] = x for each of the hc streams -- the wide residual stream's first value." },
|
||||
{ "mhc_pre", ARR(pMhcPre), ARR(oMhcPre), "Whole-residual RMS projection, sigmoid gates and Sinkhorn mixing." },
|
||||
{ "mhc_pre_partial", ARR(pMhcPrePartial), ARR(oMhcPrePartial),
|
||||
"mhc_pre's projection over chunks [first, first+chunks) of `chunk` columns, zero-padded per chunk." },
|
||||
{ "mhc_pre_finish", ARR(pMhcPreFinish), ARR(oMhcPreFinish),
|
||||
"mhc_pre from every chunk's partials: chunk sums, gates, Sinkhorn mixing, collapse." },
|
||||
{ "mhc_post", ARR(pHcWrite), ARR(oMhcPost), "Source-to-destination manifold residual update." },
|
||||
{ "mhc_contract", ARR(pHcWrite), ARR(oMhcContract), "Mean over manifold residual streams." },
|
||||
{ "kda_update", ARR(pKdaUpdate), ARR(oKdaUpdate), "Bounded per-channel KDA with candidate-state rollback." },
|
||||
{ "hc_read", ARR(pHcRead), ARR(oHcRead),
|
||||
"The read half of a gated residual: grouped norm, low-rank gate, stream mix, and optionally the "
|
||||
"block-scaled fp8 form of x and its Hadamard-rotated twin. See docs/OPS.md for the three facts "
|
||||
@@ -737,6 +781,20 @@ static const RadOpSchema kSchemas[] = {
|
||||
"local attention with a relative-position term and a softcap (Gemma 4's audio)." },
|
||||
{ "pool_rows", ARR(pPoolRows), ARR(oUnary),
|
||||
"y[r] = the mean of x's rows [r*k, r*k + k), rounded to y's dtype, times mult, rounded again." },
|
||||
{ "mla_attn", ARR(pMlaAttn), ARR(oMlaAttn),
|
||||
"Softmax over selected latent vectors used as both key and value; per-query page tables and visible lengths." },
|
||||
{ "mla_project", ARR(pMlaProject), ARR(oGemm),
|
||||
"Per-head query absorption or value expansion through the shared [head,(K|V),latent] BF16 matrix." },
|
||||
{ "dsa_score", ARR(pDsaScore), ARR(oDsaScore),
|
||||
"Per-head ReLU of FP8 dot products, then signed head gates and scales; invalid history is -inf." },
|
||||
{ "gemm_nt_f32", ARR(pGemm), ARR(oGemm),
|
||||
"BF16 activations times F32 weights, F32 accumulation and output; preserves routing and index gate precision." },
|
||||
{ "dsa_query", ARR(pMnD), ARR(oQuantFp8),
|
||||
"Normalized Hadamard, BF16 boundary and power-of-two E4M3 quantization per query head." },
|
||||
{ "dsa_pool", ARR(pDsaPool), ARR(oDsaPool),
|
||||
"Channel-wise softmax pooling with learned position bias, BF16, normalized Hadamard, BF16, power-of-two FP8." },
|
||||
{ "swiglu_clamped", ARR(pSwigluClamped), ARR(oGateUp),
|
||||
"silu(min(gate,limit))*clamp(up,-limit,limit); gate is the first half." },
|
||||
{ "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),
|
||||
@@ -848,6 +906,8 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "qk_norm_rope", ARR(pQkNormRope), ARR(oQkNormRope), "per-head QK norm then rotary embedding." },
|
||||
{ "scale_rows", ARR(pScaleRows), ARR(oScaleRows),
|
||||
"one scalar per row, optionally through an activation, broadcast across the row." },
|
||||
{ "router_sigmoid_topk", ARR(pRouterSigmoid), ARR(oRouterSigmoid),
|
||||
"Single-group sigmoid routing; correction bias selects experts, original scores weight them." },
|
||||
{ "router_topk", ARR(pRouter), ARR(oRouter), "softmax then exact top-k routing." },
|
||||
{ "moe_scatter", ARR(pScatter), ARR(oScatter),
|
||||
"stable counting sort of routing slots by expert." },
|
||||
@@ -1160,6 +1220,12 @@ SIMPLE("avx_rmsnorm_add", "rmsnorm_add", "norm", "residual add then RMS norm", D
|
||||
L(rmsnorm_add)),
|
||||
SIMPLE("avx_hc_enter", "hc_enter", "norm", "gated residual entry: hc copies of x", DT_FLOAT,
|
||||
L(hc_enter)),
|
||||
SIMPLE("avx_mhc_pre", "mhc_pre", "norm", "manifold gates and Sinkhorn mixing", DT_FLOAT, L(mhc_pre)),
|
||||
SIMPLE("avx_mhc_pre_partial", "mhc_pre_partial", "norm", "manifold projection partials", DT_FLOAT, L(mhc_pre_partial)),
|
||||
SIMPLE("avx_mhc_pre_finish", "mhc_pre_finish", "norm", "manifold gates from projection partials", DT_FLOAT, L(mhc_pre_finish)),
|
||||
SIMPLE("avx_mhc_post", "mhc_post", "norm", "manifold residual update", DT_FLOAT, L(mhc_post)),
|
||||
SIMPLE("avx_mhc_contract", "mhc_contract", "norm", "mean of residual streams", DT_FLOAT, L(mhc_contract)),
|
||||
SIMPLE("avx_kda_update", "kda_update", "gdn", "bounded KDA and candidate-state rollback", DT_FLOAT, L(kda_update)),
|
||||
ROWL("avx_hc_read", "hc_read", "norm",
|
||||
"gated residual read: grouped norm, low-rank gate, stream mix",
|
||||
DT_FLOAT ", or mixing matrices of E4M3 / int8 codes with a scale plane, joined", L(hc_read),
|
||||
@@ -1203,6 +1269,20 @@ SIMPLE("avx_seg_sinusoid", "seg_sinusoid", "elem",
|
||||
SIMPLE("avx_attn_local_rel", "attn_local_rel", "attn",
|
||||
"local attention with a relative-position term and a softcap", DT_FLOAT,
|
||||
L(attn_local_rel)),
|
||||
SIMPLE("avx_mla_attn", "mla_attn", "attn", "absorbed latent MQA attention", DT_FLOAT,
|
||||
L(mla_attn)),
|
||||
SIMPLE("avx_dsa_score", "dsa_score", "attn", "weighted FP8 index scoring", DT_FLOAT,
|
||||
L(dsa_score)),
|
||||
SIMPLE("avx_dsa_pool", "dsa_pool", "attn", "learned compressed FP8 index keys", DT_FLOAT,
|
||||
L(dsa_pool)),
|
||||
SIMPLE("avx_dsa_query", "dsa_query", "attn", "normalized FP8 index queries", DT_FLOAT,
|
||||
L(dsa_query)),
|
||||
SIMPLE("avx_gemm_nt_f32", "gemm_nt_f32", "gemm", "F32 routing projection", DT_FLOAT,
|
||||
L(gemm_nt_f32)),
|
||||
SIMPLE("avx_mla_project", "mla_project", "attn", "absorbed MLA projections", DT_FLOAT,
|
||||
L(mla_project)),
|
||||
SIMPLE("avx_swiglu_clamped", "swiglu_clamped", "elem", "asymmetrically clipped SwiGLU", DT_FLOAT,
|
||||
L(swiglu_clamped)),
|
||||
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,
|
||||
@@ -1325,6 +1405,8 @@ SIMPLE("avx_qsa_work", "qsa_work", "attn",
|
||||
|
||||
SIMPLE("avx_router_topk", "router_topk", "moe", "softmax then exact top-k routing", DT_FLOAT,
|
||||
L(router_topk)),
|
||||
SIMPLE("avx_router_sigmoid_topk", "router_sigmoid_topk", "moe", "sigmoid correction-bias routing", DT_FLOAT,
|
||||
L(router_sigmoid_topk)),
|
||||
SIMPLE("avx_moe_scatter", "moe_scatter", "moe", "stable counting sort of routing slots by expert",
|
||||
"i32 indices", L(moe_scatter)),
|
||||
SIMPLE("avx_moe_gemm", "moe_gemm", "moe", "grouped GEMM over the expert-sorted rows", DT_FLOAT,
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
/* GLM's compressed index keys: channel-wise learned pooling, then a normalized
|
||||
* Hadamard and power-of-two E4M3 quantization. Pooling the raw keys by a mean,
|
||||
* or omitting either BF16 boundary, changes sparse selection. */
|
||||
#include "ref_common.h"
|
||||
#include "ref_ops.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
using namespace ref;
|
||||
|
||||
int ref_dsa_query(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 3)) return RAD_E_INVAL;
|
||||
const auto &x = a->t[0], &q = a->t[1], &s = a->t[2];
|
||||
const int64_t n = p_int(a, "n", 0);
|
||||
if (n < 1 || n > 256 || (n & (n - 1)) || x.rank != 2 || q.rank != 2 || s.rank != 2 ||
|
||||
x.shape[0] < 1 || q.shape[0] != x.shape[0] || x.shape[1] != n || q.shape[1] != n ||
|
||||
s.shape[0] != x.shape[0] || s.shape[1] != 1)
|
||||
return RAD_E_SHAPE;
|
||||
if (x.dtype != RAD_BF16 || q.dtype != RAD_F8E4M3 || s.dtype != RAD_F32) return RAD_E_DTYPE;
|
||||
if (!x.data || !q.data || !s.data) return RAD_E_INVAL;
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t r = 0; r < x.shape[0]; ++r) {
|
||||
float v[256];
|
||||
for (int64_t d = 0; d < n; ++d) v[d] = ldt(&x, r * x.stride[0] + d * x.stride[1]);
|
||||
for (int64_t h = 1; h < n; h *= 2)
|
||||
for (int64_t i = 0; i < n; i += 2 * h)
|
||||
for (int64_t j = 0; j < h; ++j) {
|
||||
const float lo = v[i + j], hi = v[i + j + h];
|
||||
v[i + j] = lo + hi;
|
||||
v[i + j + h] = lo - hi;
|
||||
}
|
||||
float am = 1e-4f;
|
||||
const float norm = 1.0f / std::sqrt((float)n);
|
||||
for (int64_t d = 0; d < n; ++d) {
|
||||
v[d] = bf16_to_f32(f32_to_bf16(v[d] * norm));
|
||||
am = std::max(am, std::fabs(v[d]));
|
||||
}
|
||||
int exponent = 0;
|
||||
const float fraction = std::frexp(am * (1.0f / 448.0f), &exponent);
|
||||
const float sc = std::ldexp(1.0f, exponent - (fraction == 0.5f));
|
||||
stt(&s, r * s.stride[0], sc);
|
||||
for (int64_t d = 0; d < n; ++d)
|
||||
stt(&q, r * q.stride[0] + d * q.stride[1], std::clamp(v[d] / sc, -448.0f, 448.0f));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int ref_dsa_score(const RadArgs* a, RadStream) {
|
||||
if (!a || !a->t || a->n_t < 9) return RAD_E_INVAL;
|
||||
RadTensor q = a->t[0], qs = a->t[1];
|
||||
const auto& gate = a->t[2];
|
||||
RadTensor k = a->t[3], ks = a->t[4];
|
||||
const bool packed = k.dtype == RAD_U8;
|
||||
if (packed) {
|
||||
if (ks.data || k.rank != 4 || k.shape[1] != 1 || k.shape[2] != 4 || k.shape[3] != 34 ||
|
||||
k.stride[3] != 1 || k.stride[2] != 34 || k.stride[0] < 136 || k.stride[0] % 4 ||
|
||||
((uintptr_t)k.data & 3))
|
||||
return RAD_E_SHAPE;
|
||||
ks = {};
|
||||
ks.data = k.data ? (uint8_t*)k.data + 128 : nullptr;
|
||||
ks.dtype = RAD_F32;
|
||||
ks.rank = 1;
|
||||
ks.shape[0] = k.shape[0];
|
||||
ks.stride[0] = k.stride[0] / 4;
|
||||
k.dtype = RAD_F8E4M3;
|
||||
k.rank = 2;
|
||||
k.shape[1] = 128;
|
||||
k.stride[1] = 1;
|
||||
}
|
||||
const auto &bt = a->t[5], &cu = a->t[6], &nc = a->t[7], &out = a->t[8];
|
||||
const int64_t n = p_int(a, "n", 0), h = p_int(a, "heads", 0);
|
||||
if (h > 0 && q.rank == 2 && qs.rank == 2 && qs.shape[1] == 1 &&
|
||||
q.shape[0] == out.shape[0] * h && qs.shape[0] == q.shape[0]) {
|
||||
q.rank = 3;
|
||||
q.shape[0] = out.shape[0];
|
||||
q.shape[2] = q.shape[1];
|
||||
q.shape[1] = h;
|
||||
q.stride[2] = q.stride[1];
|
||||
q.stride[1] = q.stride[0];
|
||||
q.stride[0] *= h;
|
||||
qs.shape[0] = out.shape[0];
|
||||
qs.shape[1] = h;
|
||||
qs.stride[1] = qs.stride[0];
|
||||
qs.stride[0] *= h;
|
||||
}
|
||||
if (n < 1 || h < 1 || h > 64 || q.rank != 3 || q.shape[0] < 1 || q.shape[1] != h ||
|
||||
q.shape[2] != n || qs.rank != 2 || gate.rank != 2 || qs.shape[0] != q.shape[0] ||
|
||||
gate.shape[0] != q.shape[0] || qs.shape[1] != h || gate.shape[1] != h || k.rank != 2 ||
|
||||
k.shape[1] != n || ks.rank != 1 || ks.shape[0] != k.shape[0] || bt.rank != 2 ||
|
||||
cu.rank != 1 || nc.rank != 1 || cu.shape[0] != bt.shape[0] + 1 ||
|
||||
nc.shape[0] != bt.shape[0] || out.rank != 2 || out.shape[0] != q.shape[0] ||
|
||||
out.shape[1] > bt.shape[1])
|
||||
return RAD_E_SHAPE;
|
||||
if (q.dtype != RAD_F8E4M3 || k.dtype != RAD_F8E4M3 || qs.dtype != RAD_F32 ||
|
||||
ks.dtype != RAD_F32 || gate.dtype != RAD_F32 || bt.dtype != RAD_I32 ||
|
||||
cu.dtype != RAD_I32 || nc.dtype != RAD_I32 || out.dtype != RAD_F32)
|
||||
return RAD_E_DTYPE;
|
||||
for (int i = 0; i < 9; ++i)
|
||||
if (!(packed && i == 4) && !a->t[i].data) return RAD_E_INVAL;
|
||||
const float norm = 1.0f / std::sqrt((float)(h * n));
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t r = 0; r < q.shape[0]; ++r) {
|
||||
int64_t seq = -1;
|
||||
for (int64_t s = 0; s < bt.shape[0]; ++s)
|
||||
if (r >= ld_int(cu.dtype, cu.data, s * cu.stride[0]) &&
|
||||
r < ld_int(cu.dtype, cu.data, (s + 1) * cu.stride[0])) {
|
||||
seq = s;
|
||||
break;
|
||||
}
|
||||
const int64_t live = seq >= 0 ? ld_int(nc.dtype, nc.data, seq * nc.stride[0]) : 0;
|
||||
for (int64_t b = 0; b < out.shape[1]; ++b) {
|
||||
const int64_t page =
|
||||
seq >= 0 && b < live
|
||||
? ld_int(bt.dtype, bt.data, seq * bt.stride[0] + b * bt.stride[1])
|
||||
: -1;
|
||||
float result = -INFINITY;
|
||||
if (page >= 0 && page < k.shape[0]) {
|
||||
result = 0;
|
||||
for (int64_t head = 0; head < h; ++head) {
|
||||
float dot = 0;
|
||||
for (int64_t d = 0; d < n; ++d)
|
||||
dot += ldt(&q, r * q.stride[0] + head * q.stride[1] + d * q.stride[2]) *
|
||||
ldt(&k, page * k.stride[0] + d * k.stride[1]);
|
||||
result += std::max(dot, 0.0f) *
|
||||
ldt(&qs, r * qs.stride[0] + head * qs.stride[1]) *
|
||||
ldt(&gate, r * gate.stride[0] + head * gate.stride[1]);
|
||||
}
|
||||
result *= ldt(&ks, page * ks.stride[0]) * norm;
|
||||
}
|
||||
stt(&out, r * out.stride[0] + b * out.stride[1], result);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int ref_dsa_pool(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 4)) return RAD_E_INVAL;
|
||||
const auto &kg = a->t[0], &ape = a->t[1], &q = a->t[2], &s = a->t[3];
|
||||
const int64_t n = p_int(a, "n", 0), ratio = p_int(a, "ratio", 0);
|
||||
if (p_int(a, "block_size", 4) != 4) return RAD_E_SHAPE;
|
||||
const auto *page = rad_arg_in(a, 4), *cache = rad_arg_in(a, 5);
|
||||
if ((page != nullptr) != (cache != nullptr)) return RAD_E_INVAL;
|
||||
if (cache &&
|
||||
(n != 128 || ratio != 4 || page->dtype != RAD_I32 || page->rank != 1 ||
|
||||
page->shape[0] != q.shape[0] || page->stride[0] < 1 || cache->dtype != RAD_U8 ||
|
||||
cache->rank != 4 || cache->shape[0] < 1 || cache->shape[1] != 1 || cache->shape[2] != 4 ||
|
||||
cache->shape[3] != 34 || cache->stride[3] != 1 || cache->stride[2] != 34 ||
|
||||
cache->stride[0] < 136 || cache->stride[0] % 4 || ((uintptr_t)cache->data & 3)))
|
||||
return RAD_E_SHAPE;
|
||||
if (n < 1 || n > 256 || (n & (n - 1)) || ratio < 2 || ratio > 16 || kg.rank != 2 ||
|
||||
ape.rank != 2 || q.rank != 2 || s.rank != 2 || q.shape[0] < 1 || !kg.data || !ape.data ||
|
||||
!q.data || !s.data || kg.dtype != RAD_BF16 || ape.dtype != RAD_F32 ||
|
||||
q.dtype != RAD_F8E4M3 || s.dtype != RAD_F32 || kg.shape[0] != q.shape[0] * ratio ||
|
||||
kg.shape[1] != 2 * n || ape.shape[0] != ratio || ape.shape[1] != n || q.shape[1] != n ||
|
||||
s.shape[0] != q.shape[0] || s.shape[1] != 1)
|
||||
return RAD_E_SHAPE;
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t r = 0; r < q.shape[0]; ++r) {
|
||||
float v[256];
|
||||
for (int64_t d = 0; d < n; ++d) {
|
||||
float gate[16], mx = -INFINITY;
|
||||
for (int64_t j = 0; j < ratio; ++j) {
|
||||
gate[j] = ldt(&kg, rowoff(&kg, r * ratio + j, 2 * n) + (n + d) * laststride(&kg)) +
|
||||
ldt(&ape, rowoff(&ape, j, n) + d * laststride(&ape));
|
||||
mx = std::max(mx, gate[j]);
|
||||
}
|
||||
float num = 0, den = 0;
|
||||
for (int64_t j = 0; j < ratio; ++j) {
|
||||
const float p = std::exp(gate[j] - mx);
|
||||
num += p * ldt(&kg, rowoff(&kg, r * ratio + j, 2 * n) + d * laststride(&kg));
|
||||
den += p;
|
||||
}
|
||||
v[d] = bf16_to_f32(f32_to_bf16(num / den));
|
||||
}
|
||||
for (int64_t h = 1; h < n; h *= 2)
|
||||
for (int64_t i = 0; i < n; i += 2 * h)
|
||||
for (int64_t j = 0; j < h; ++j) {
|
||||
const float x = v[i + j], y = v[i + j + h];
|
||||
v[i + j] = x + y;
|
||||
v[i + j + h] = x - y;
|
||||
}
|
||||
float am = 1e-4f;
|
||||
const float norm = 1.0f / std::sqrt((float)n);
|
||||
for (int64_t d = 0; d < n; ++d) {
|
||||
v[d] = bf16_to_f32(f32_to_bf16(v[d] * norm));
|
||||
am = std::max(am, std::fabs(v[d]));
|
||||
}
|
||||
const float target = am * (1.0f / 448.0f);
|
||||
int exp = 0;
|
||||
const float frac = std::frexp(target, &exp);
|
||||
const float scale = std::ldexp(1.0f, exp - (frac == 0.5f));
|
||||
stt(&s, rowoff(&s, r, 1), scale);
|
||||
for (int64_t d = 0; d < n; ++d)
|
||||
stt(&q, rowoff(&q, r, n) + d * laststride(&q),
|
||||
std::clamp(v[d] / scale, -448.0f, 448.0f));
|
||||
if (cache) {
|
||||
const int64_t p = ld_int(page->dtype, page->data, r * page->stride[0]);
|
||||
if (p >= 0 && p < cache->shape[0]) {
|
||||
auto* dst = (uint8_t*)cache->data + p * cache->stride[0];
|
||||
for (int d = 0; d < 128; ++d)
|
||||
dst[d] = ((uint8_t*)q.data)[r * q.stride[0] + d * q.stride[1]];
|
||||
std::memcpy(dst + 128, &scale, sizeof(scale));
|
||||
}
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
#include "ref_common.h"
|
||||
#include "ref_ops.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
using namespace ref;
|
||||
|
||||
/* Routing and index head gates are F32 projections in GLM, even with BF16 hidden states. */
|
||||
int ref_gemm_nt_f32(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 3)) return RAD_E_INVAL;
|
||||
const auto &x = a->t[0], &w = a->t[1], &y = a->t[2];
|
||||
const int64_t n = p_int(a, "N", 0), k = p_int(a, "K", 0);
|
||||
if (n < 1 || k < 1 || x.rank != 2 || w.rank != 2 || y.rank != 2 || x.shape[0] < 1 ||
|
||||
x.shape[1] != k || w.shape[0] != n || w.shape[1] != k || y.shape[0] != x.shape[0] ||
|
||||
y.shape[1] != n)
|
||||
return RAD_E_SHAPE;
|
||||
if (x.dtype != RAD_BF16 || w.dtype != RAD_F32 || y.dtype != RAD_F32) return RAD_E_DTYPE;
|
||||
if (!x.data || !w.data || !y.data) return RAD_E_INVAL;
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t r = 0; r < x.shape[0]; ++r)
|
||||
for (int64_t col = 0; col < n; ++col) {
|
||||
float sum = 0;
|
||||
for (int64_t j = 0; j < k; ++j)
|
||||
sum += ldt(&x, r * x.stride[0] + j * x.stride[1]) *
|
||||
ldt(&w, col * w.stride[0] + j * w.stride[1]);
|
||||
stt(&y, r * y.stride[0] + col * y.stride[1], sum);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Single-group noaux_tc routing: correction changes selection, never the mixture weights. */
|
||||
int ref_router_sigmoid_topk(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 4)) return RAD_E_INVAL;
|
||||
const auto &lg = a->t[0], &bias = a->t[1], &ids = a->t[2], &weights = a->t[3];
|
||||
const int64_t ne = p_int(a, "n_expert", 0), k = p_int(a, "top_k", 0);
|
||||
const float scale = p_f32(a, "route_scale", 0);
|
||||
const bool norm = p_int(a, "norm", 0) != 0;
|
||||
if (ne < 1 || ne > 512 || k < 1 || k > ne || !std::isfinite(scale) || scale <= 0 ||
|
||||
lg.rank != 2 || lg.shape[0] < 1 || lg.shape[1] != ne || bias.rank != 1 ||
|
||||
bias.shape[0] != ne || bias.dtype != RAD_F32 || ids.dtype != RAD_I32 || ids.rank != 2 ||
|
||||
weights.rank != 2 || ids.shape[0] != lg.shape[0] || weights.shape[0] != lg.shape[0] ||
|
||||
ids.shape[1] != k || weights.shape[1] != k || !lg.data || !bias.data || !ids.data ||
|
||||
!weights.data)
|
||||
return RAD_E_SHAPE;
|
||||
for (int64_t r = 0; r < lg.shape[0]; ++r) {
|
||||
float scores[512], select[512], chosen[512];
|
||||
int index[512];
|
||||
for (int64_t e = 0; e < ne; ++e) {
|
||||
scores[e] = act_sigmoid(ldt(&lg, rowoff(&lg, r, ne) + e * laststride(&lg)));
|
||||
select[e] = scores[e] + ldt(&bias, e * laststride(&bias));
|
||||
}
|
||||
float sum = 0;
|
||||
for (int64_t j = 0; j < k; ++j) {
|
||||
int best = -1;
|
||||
for (int64_t e = 0; e < ne; ++e)
|
||||
if (select[e] > -INFINITY && (best < 0 || select[e] > select[best])) best = (int)e;
|
||||
if (best < 0) return RAD_E_SHAPE;
|
||||
index[j] = best;
|
||||
chosen[j] = scores[best];
|
||||
sum += chosen[j];
|
||||
select[best] = -INFINITY;
|
||||
}
|
||||
for (int64_t j = 0; j < k; ++j) {
|
||||
st_int(ids.dtype, ids.data, rowoff(&ids, r, k) + j * laststride(&ids), index[j]);
|
||||
stt(&weights, rowoff(&weights, r, k) + j * laststride(&weights),
|
||||
chosen[j] * (norm ? scale / (sum + 1e-20f) : scale));
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* GLM clamps the gate only above, but clamps the up branch on both sides. */
|
||||
int ref_swiglu_clamped(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 2)) return RAD_E_INVAL;
|
||||
const auto &gu = a->t[0], &y = a->t[1];
|
||||
const int64_t n = p_int(a, "n", 0);
|
||||
const float limit = p_f32(a, "limit", 0);
|
||||
if (n < 1 || !std::isfinite(limit) || limit <= 0 || gu.rank != 2 || y.rank != 2 || !gu.data ||
|
||||
!y.data || y.shape[0] < 1 || gu.shape[0] != y.shape[0] || gu.shape[1] != 2 * n ||
|
||||
y.shape[1] != n)
|
||||
return RAD_E_SHAPE;
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t r = 0; r < y.shape[0]; ++r)
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const int64_t b = rowoff(&gu, r, 2 * n), s = laststride(&gu);
|
||||
const float g = std::min(ldt(&gu, b + i * s), limit);
|
||||
const float u = std::clamp(ldt(&gu, b + (n + i) * s), -limit, limit);
|
||||
stt(&y, rowoff(&y, r, n) + i * laststride(&y), act_silu(g) * u);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
/* Bounded per-channel Kimi Delta Attention. Cache rows are complete candidate states,
|
||||
* so the accepted-prefix index restores the recurrence without trying to invert a delta.
|
||||
* Prefill commits only its final state; verify preserves every candidate for rejection. */
|
||||
#include "ref_common.h"
|
||||
#include "ref_ops.h"
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
|
||||
using namespace ref;
|
||||
|
||||
namespace {
|
||||
bool headed(const RadTensor& t, int64_t tokens, int64_t heads, int64_t dim) {
|
||||
return t.data && t.shape[0] == tokens &&
|
||||
((t.rank == 3 && t.shape[1] == heads && t.shape[2] == dim) ||
|
||||
(t.rank == 2 && t.shape[1] == heads * dim));
|
||||
}
|
||||
int64_t off(const RadTensor& t, int64_t token, int64_t head, int64_t d, int64_t width) {
|
||||
return token * t.stride[0] + head * (t.rank == 3 ? t.stride[1] : width * t.stride[1]) +
|
||||
d * laststride(&t);
|
||||
}
|
||||
}
|
||||
|
||||
int ref_kda_update(const RadArgs* a, RadStream) {
|
||||
if (!a || a->n_t < 13) return RAD_E_INVAL;
|
||||
for (int i = 0; i < 10; ++i)
|
||||
if (!rad_arg_in(a, i)) return RAD_E_INVAL;
|
||||
if (!rad_arg_in(a, 12)) return RAD_E_INVAL;
|
||||
const int64_t H = p_int(a, "heads", 0), K = p_int(a, "head_k", 0), V = p_int(a, "head_v", 0);
|
||||
const float lower = p_f32(a, "lower_bound", 0), eps = p_f32(a, "l2_eps", 1e-6f);
|
||||
const float scale = p_f32(a, "scale", 1.0f);
|
||||
const char* mode = p_str(a, "mode", "");
|
||||
const bool verify = !std::strcmp(mode, "verify");
|
||||
const char* form = p_str(a, "state_form", "per_candidate");
|
||||
const bool anchor = !std::strcmp(form, "anchor");
|
||||
if (!anchor && std::strcmp(form, "per_candidate")) return RAD_E_INVAL;
|
||||
if (anchor && (K != 128 || V != 128)) return RAD_E_UNSUPPORTED;
|
||||
if (!verify && std::strcmp(mode, "prefill")) return RAD_E_INVAL;
|
||||
if (H <= 0 || K <= 0 || K > 128 || V <= 0 || V > 128 || !std::isfinite(lower) || lower >= 0 ||
|
||||
!std::isfinite(eps) || eps <= 0 || !std::isfinite(scale))
|
||||
return RAD_E_SHAPE;
|
||||
const auto &q = a->t[0], &k = a->t[1], &v = a->t[2], &g = a->t[3], &beta = a->t[4];
|
||||
const auto &alog = a->t[5], &bias = a->t[6], &state = a->t[7], &idx = a->t[8], &cu = a->t[9];
|
||||
const RadTensor *accepted = rad_arg_in(a, 10), *init = rad_arg_in(a, 11);
|
||||
const auto& out = a->t[12];
|
||||
if (q.rank < 2 || cu.rank != 1 || cu.dtype != RAD_I32 || cu.shape[0] < 2) return RAD_E_SHAPE;
|
||||
const int64_t T = q.shape[0], N = cu.shape[0] - 1;
|
||||
if (T < 1) return RAD_E_SHAPE;
|
||||
if (!headed(q, T, H, K) || !headed(k, T, H, K) || !headed(v, T, H, V) || !headed(g, T, H, K) ||
|
||||
!headed(beta, T, H, 1) || !headed(out, T, H, V) || numel(&alog) != H ||
|
||||
numel(&bias) != H * K || state.rank != 4 || state.dtype != RAD_F32 || state.shape[1] != H ||
|
||||
state.shape[2] != V || state.shape[3] != K || idx.dtype != RAD_I32 || idx.rank != 2 ||
|
||||
idx.shape[0] < N || idx.shape[1] < 1 ||
|
||||
(accepted && (accepted->dtype != RAD_I32 || numel(accepted) < N)) ||
|
||||
(init && (init->dtype != RAD_I32 || numel(init) < N)))
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t width = idx.shape[1], slots = state.shape[0];
|
||||
/* Check every address before writing any state, so a malformed batch cannot leave a
|
||||
* partially committed prefix when the host reference reports an error. */
|
||||
for (int64_t seq = 0; seq < N; ++seq) {
|
||||
const int64_t begin = ld_int(cu.dtype, cu.data, seq * cu.stride[0]);
|
||||
const int64_t end = ld_int(cu.dtype, cu.data, (seq + 1) * cu.stride[0]);
|
||||
const int64_t na =
|
||||
accepted ? ld_int(accepted->dtype, accepted->data, offlin(accepted, seq)) : 1;
|
||||
if (begin < 0 || end < begin || end > T || na < 1 || na > (anchor ? 32 : width) ||
|
||||
(verify && end - begin > (anchor ? 32 : width)) || (anchor && width < 2))
|
||||
return RAD_E_SHAPE;
|
||||
for (int64_t j = 0; j < width; ++j)
|
||||
if (ld_int(idx.dtype, idx.data, seq * idx.stride[0] + j * idx.stride[1]) >= slots)
|
||||
return RAD_E_SHAPE;
|
||||
if (anchor) {
|
||||
const int64_t read = ld_int(idx.dtype, idx.data, seq * idx.stride[0]);
|
||||
const int64_t scratch =
|
||||
ld_int(idx.dtype, idx.data, seq * idx.stride[0] + (width / 2) * idx.stride[1]);
|
||||
if (read >= 0 && (scratch < 0 || scratch == read)) return RAD_E_SHAPE;
|
||||
if (verify && read >= 0 &&
|
||||
(!init || ld_int(init->dtype, init->data, offlin(init, seq))))
|
||||
for (int64_t h = 0; h < H; ++h) {
|
||||
const float count =
|
||||
ldt(&state, scratch * state.stride[0] + h * state.stride[1]);
|
||||
if (!std::isfinite(count) || count < 0 || count > 32 ||
|
||||
count != std::floor(count) || (count > 0 && na > count))
|
||||
return RAD_E_SHAPE;
|
||||
}
|
||||
}
|
||||
}
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t sh = 0; sh < N * H; ++sh) {
|
||||
const int64_t seq = sh / H, head = sh % H;
|
||||
const int64_t begin = ld_int(cu.dtype, cu.data, seq * cu.stride[0]);
|
||||
const int64_t end = ld_int(cu.dtype, cu.data, (seq + 1) * cu.stride[0]);
|
||||
if (begin == end) continue;
|
||||
const int64_t na =
|
||||
accepted ? ld_int(accepted->dtype, accepted->data, offlin(accepted, seq)) : 1;
|
||||
const int64_t read =
|
||||
ld_int(idx.dtype, idx.data,
|
||||
seq * idx.stride[0] + (verify && !anchor ? na - 1 : 0) * idx.stride[1]);
|
||||
if (read < 0) {
|
||||
for (int64_t t = begin; t < end; ++t)
|
||||
for (int64_t e = 0; e < V; ++e) stt(&out, off(out, t, head, e, V), 0);
|
||||
continue;
|
||||
}
|
||||
float S[128 * 128], qn[128], kn[128], decay[128];
|
||||
const bool initialized = !init || ld_int(init->dtype, init->data, offlin(init, seq)) != 0;
|
||||
const int64_t sb = read * state.stride[0] + head * state.stride[1];
|
||||
for (int64_t e = 0; e < V; ++e)
|
||||
for (int64_t d = 0; d < K; ++d)
|
||||
S[e * K + d] =
|
||||
initialized ? ldt(&state, sb + e * state.stride[2] + d * state.stride[3]) : 0;
|
||||
const int64_t scratch =
|
||||
anchor ? ld_int(idx.dtype, idx.data, seq * idx.stride[0] + (width / 2) * idx.stride[1])
|
||||
: 0;
|
||||
auto factor_at = [&](int64_t i) {
|
||||
return scratch * state.stride[0] + head * state.stride[1] + (i / K) * state.stride[2] +
|
||||
(i % K) * state.stride[3];
|
||||
};
|
||||
constexpr int factors = 385;
|
||||
if (anchor && verify) {
|
||||
const int replay = initialized ? (int)ldt(&state, factor_at(0)) : 0;
|
||||
for (int t = 0; t < (replay ? na : 0); ++t) {
|
||||
const int f = 1 + t * factors;
|
||||
for (int d = 0; d < 128; ++d) {
|
||||
kn[d] = ldt(&state, factor_at(f + d));
|
||||
decay[d] = ldt(&state, factor_at(f + 256 + d));
|
||||
}
|
||||
const float bt = ldt(&state, factor_at(f + 384));
|
||||
for (int e = 0; e < 128; ++e) {
|
||||
float prediction = 0;
|
||||
for (int d = 0; d < 128; ++d) {
|
||||
S[e * K + d] *= decay[d];
|
||||
prediction += S[e * K + d] * kn[d];
|
||||
}
|
||||
const float delta = bt * (ldt(&state, factor_at(f + 128 + e)) - prediction);
|
||||
for (int d = 0; d < 128; ++d) S[e * K + d] += delta * kn[d];
|
||||
}
|
||||
}
|
||||
// Publish only the accepted prefix. Current candidates remain in registers.
|
||||
for (int e = 0; e < 128; ++e)
|
||||
for (int d = 0; d < 128; ++d)
|
||||
stt(&state, sb + e * state.stride[2] + d * state.stride[3], S[e * K + d]);
|
||||
}
|
||||
const float gain = std::exp(ldt(&alog, head * laststride(&alog)));
|
||||
for (int64_t t = begin; t < end; ++t) {
|
||||
float qs = 0, ks = 0;
|
||||
for (int64_t d = 0; d < K; ++d) {
|
||||
qn[d] = ldt(&q, off(q, t, head, d, K));
|
||||
kn[d] = ldt(&k, off(k, t, head, d, K));
|
||||
qs += qn[d] * qn[d];
|
||||
ks += kn[d] * kn[d];
|
||||
}
|
||||
const float qi = scale / std::sqrt(qs + eps), ki = 1.0f / std::sqrt(ks + eps);
|
||||
for (int64_t d = 0; d < K; ++d) {
|
||||
qn[d] *= qi;
|
||||
kn[d] *= ki;
|
||||
const float z = gain * (ldt(&g, off(g, t, head, d, K)) +
|
||||
ldt(&bias, (head * K + d) * laststride(&bias)));
|
||||
decay[d] = std::exp(lower / (1.0f + std::exp(-z)));
|
||||
}
|
||||
const float bt = 1.0f / (1.0f + std::exp(-ldt(&beta, off(beta, t, head, 0, 1))));
|
||||
if (anchor && verify) {
|
||||
const int f = 1 + (int)(t - begin) * factors;
|
||||
for (int d = 0; d < 128; ++d) {
|
||||
stt(&state, factor_at(f + d), kn[d]);
|
||||
stt(&state, factor_at(f + 256 + d), decay[d]);
|
||||
}
|
||||
for (int e = 0; e < 128; ++e)
|
||||
stt(&state, factor_at(f + 128 + e), ldt(&v, off(v, t, head, e, V)));
|
||||
stt(&state, factor_at(f + 384), bt);
|
||||
}
|
||||
for (int64_t e = 0; e < V; ++e) {
|
||||
float predicted = 0;
|
||||
for (int64_t d = 0; d < K; ++d) {
|
||||
S[e * K + d] *= decay[d];
|
||||
predicted += S[e * K + d] * kn[d];
|
||||
}
|
||||
const float delta = bt * (ldt(&v, off(v, t, head, e, V)) - predicted);
|
||||
float result = 0;
|
||||
for (int64_t d = 0; d < K; ++d) {
|
||||
S[e * K + d] += delta * kn[d];
|
||||
result += S[e * K + d] * qn[d];
|
||||
}
|
||||
stt(&out, off(out, t, head, e, V), result);
|
||||
}
|
||||
if ((!anchor && verify) || (!verify && t + 1 == end)) {
|
||||
const int64_t write =
|
||||
ld_int(idx.dtype, idx.data,
|
||||
seq * idx.stride[0] + (verify ? t - begin : 0) * idx.stride[1]);
|
||||
if (write >= 0)
|
||||
for (int64_t e = 0; e < V; ++e)
|
||||
for (int64_t d = 0; d < K; ++d)
|
||||
stt(&state,
|
||||
write * state.stride[0] + head * state.stride[1] +
|
||||
e * state.stride[2] + d * state.stride[3],
|
||||
S[e * K + d]);
|
||||
}
|
||||
}
|
||||
if (anchor) stt(&state, factor_at(0), verify ? (float)(end - begin) : 0.0f);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
/* Manifold-constrained hyper-connections. The residual mixing matrix is indexed
|
||||
* [source, destination]; transposing it leaves every shape valid and changes the model.
|
||||
* The first Sinkhorn pass is softmax + eps, then column normalization. Later passes
|
||||
* add eps to both denominators. These are separate operations from Qwen's hc_read/write. */
|
||||
#include "ref_common.h"
|
||||
#include "ref_ops.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
using namespace ref;
|
||||
|
||||
namespace {
|
||||
bool matrix(const RadTensor& t, int64_t rows, int64_t cols) {
|
||||
return t.data && t.rank == 2 && t.shape[0] == rows && t.shape[1] == cols;
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
int64_t part_stride(int64_t hc) { return (hc * (hc + 2) + 1 + 3) / 4 * 4; }
|
||||
|
||||
bool pre_params(const RadArgs* a, int64_t* n, int64_t* hc, int64_t* iters, float* eps,
|
||||
float* heps) {
|
||||
*n = p_int(a, "n", 0);
|
||||
*hc = p_int(a, "hc", 0);
|
||||
*iters = p_int(a, "iterations", 0);
|
||||
*eps = p_f32(a, "eps", 0);
|
||||
*heps = p_f32(a, "hc_eps", 0);
|
||||
return *n > 0 && *hc >= 2 && *hc <= 8 && *iters >= 1 && *iters <= 256 && std::isfinite(*eps) &&
|
||||
std::isfinite(*heps) && *eps > 0 && *heps >= 0;
|
||||
}
|
||||
|
||||
/* The outputs' shapes, shared by mhc_pre and mhc_pre_finish. */
|
||||
bool pre_outputs(const RadTensor& h, const RadTensor& scale, const RadTensor& base,
|
||||
const RadTensor& x, const RadTensor& post, const RadTensor& comb, int64_t rows,
|
||||
int64_t n, int64_t hc) {
|
||||
const int64_t mix = hc * (hc + 2);
|
||||
return matrix(h, rows, hc * n) && scale.rank == 1 && scale.dtype == RAD_F32 &&
|
||||
numel(&scale) == 3 && base.rank == 1 && base.dtype == RAD_F32 && numel(&base) == mix &&
|
||||
matrix(x, rows, n) && matrix(post, rows, hc) && matrix(comb, rows, hc * hc) &&
|
||||
post.dtype == RAD_F32 && comb.dtype == RAD_F32;
|
||||
}
|
||||
|
||||
/* Row r from its RMS-scaled coefficients: gates, Sinkhorn mixing and the collapse of h. */
|
||||
void finish_row(const float* coeff, const RadTensor& h, const RadTensor& scale,
|
||||
const RadTensor& base, const RadTensor& x, const RadTensor& post,
|
||||
const RadTensor& comb, int64_t r, int64_t n, int64_t hc, int64_t iters,
|
||||
float heps) {
|
||||
float pre[8], c[64];
|
||||
const int64_t hb = rowoff(&h, r, hc * n), hs = laststride(&h);
|
||||
for (int64_t j = 0; j < hc; ++j) {
|
||||
pre[j] =
|
||||
1.0f / (1.0f +
|
||||
std::exp(-(coeff[j] * ldt(&scale, 0) + ldt(&base, j * laststride(&base))))) +
|
||||
heps;
|
||||
const float z = coeff[hc + j] * ldt(&scale, laststride(&scale)) +
|
||||
ldt(&base, (hc + j) * laststride(&base));
|
||||
stt(&post, rowoff(&post, r, hc) + j * laststride(&post), 2.0f / (1.0f + std::exp(-z)));
|
||||
}
|
||||
for (int64_t j = 0; j < hc; ++j) {
|
||||
float mx = -INFINITY;
|
||||
for (int64_t k = 0; k < hc; ++k) {
|
||||
const int64_t q = 2 * hc + j * hc + k;
|
||||
c[j * hc + k] =
|
||||
coeff[q] * ldt(&scale, 2 * laststride(&scale)) + ldt(&base, q * laststride(&base));
|
||||
mx = std::max(mx, c[j * hc + k]);
|
||||
}
|
||||
float sum = 0;
|
||||
for (int64_t k = 0; k < hc; ++k) {
|
||||
c[j * hc + k] = std::exp(c[j * hc + k] - mx);
|
||||
sum += c[j * hc + k];
|
||||
}
|
||||
for (int64_t k = 0; k < hc; ++k) c[j * hc + k] = c[j * hc + k] / sum + heps;
|
||||
}
|
||||
for (int64_t it = 0; it < iters; ++it) {
|
||||
if (it)
|
||||
for (int64_t j = 0; j < hc; ++j) {
|
||||
float sum = 0;
|
||||
for (int64_t k = 0; k < hc; ++k) sum += c[j * hc + k];
|
||||
for (int64_t k = 0; k < hc; ++k) c[j * hc + k] /= sum + heps;
|
||||
}
|
||||
for (int64_t k = 0; k < hc; ++k) {
|
||||
float sum = 0;
|
||||
for (int64_t j = 0; j < hc; ++j) sum += c[j * hc + k];
|
||||
for (int64_t j = 0; j < hc; ++j) c[j * hc + k] /= sum + heps;
|
||||
}
|
||||
}
|
||||
const int64_t cb = rowoff(&comb, r, hc * hc), cs = laststride(&comb);
|
||||
for (int64_t j = 0; j < hc * hc; ++j) stt(&comb, cb + j * cs, c[j]);
|
||||
const int64_t xb = rowoff(&x, r, n), xs = laststride(&x);
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
float v = 0;
|
||||
for (int64_t j = 0; j < hc; ++j) v += pre[j] * ldt(&h, hb + (j * n + i) * hs);
|
||||
stt(&x, xb + i * xs, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int ref_mhc_pre(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 7)) return RAD_E_INVAL;
|
||||
int64_t n, hc, iters;
|
||||
float eps, heps;
|
||||
if (!pre_params(a, &n, &hc, &iters, &eps, &heps)) return RAD_E_SHAPE;
|
||||
const auto &h = a->t[0], &fn = a->t[1], &scale = a->t[2], &base = a->t[3];
|
||||
const auto &x = a->t[4], &post = a->t[5], &comb = a->t[6];
|
||||
const int64_t width = hc * n, mix = hc * (hc + 2);
|
||||
if (h.rank != 2) return RAD_E_SHAPE;
|
||||
const int64_t rows = h.shape[0];
|
||||
if (rows < 1 || !matrix(fn, mix, width) || fn.dtype != RAD_F32 ||
|
||||
!pre_outputs(h, scale, base, x, post, comb, rows, n, hc))
|
||||
return RAD_E_SHAPE;
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
float coeff[80];
|
||||
const int64_t hb = rowoff(&h, r, width), hs = laststride(&h);
|
||||
float sq = 0;
|
||||
for (int64_t i = 0; i < width; ++i) {
|
||||
const float v = ldt(&h, hb + i * hs);
|
||||
sq += v * v;
|
||||
}
|
||||
const float inv = 1.0f / std::sqrt(sq / (float)width + eps);
|
||||
for (int64_t j = 0; j < mix; ++j) {
|
||||
float dot = 0;
|
||||
const int64_t fb = rowoff(&fn, j, width), fs = laststride(&fn);
|
||||
for (int64_t i = 0; i < width; ++i) dot += ldt(&h, hb + i * hs) * ldt(&fn, fb + i * fs);
|
||||
coeff[j] = dot * inv;
|
||||
}
|
||||
finish_row(coeff, h, scale, base, x, post, comb, r, n, hc, iters, heps);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int ref_mhc_pre_partial(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 3)) return RAD_E_INVAL;
|
||||
const int64_t n = p_int(a, "n", 0), hc = p_int(a, "hc", 0), chunk = p_int(a, "chunk", 0);
|
||||
const int64_t first = p_int(a, "first", -1), count = p_int(a, "chunks", 0);
|
||||
if (n <= 0 || hc < 2 || hc > 8 || chunk <= 0 || (hc * n) % chunk || first < 0 || count < 1 ||
|
||||
first + count > hc * n / chunk)
|
||||
return RAD_E_SHAPE;
|
||||
const auto &h = a->t[0], &fn = a->t[1], &part = a->t[2];
|
||||
const int64_t width = hc * n, mix = hc * (hc + 2), S = part_stride(hc);
|
||||
if (h.rank != 2) return RAD_E_SHAPE;
|
||||
const int64_t rows = h.shape[0];
|
||||
if (rows < 1 || !matrix(h, rows, width) || !matrix(fn, mix, width) || fn.dtype != RAD_F32 ||
|
||||
!matrix(part, rows, count * S) || part.dtype != RAD_F32)
|
||||
return RAD_E_SHAPE;
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
const int64_t hb = rowoff(&h, r, width), hs = laststride(&h);
|
||||
const int64_t pb = rowoff(&part, r, count * S), ps = laststride(&part);
|
||||
for (int64_t c = 0; c < count; ++c) {
|
||||
const int64_t lo = (first + c) * chunk;
|
||||
for (int64_t j = 0; j < S; ++j) {
|
||||
float sum = 0;
|
||||
if (j < mix) {
|
||||
const int64_t fb = rowoff(&fn, j, width), fs = laststride(&fn);
|
||||
for (int64_t i = lo; i < lo + chunk; ++i)
|
||||
sum += ldt(&h, hb + i * hs) * ldt(&fn, fb + i * fs);
|
||||
} else if (j == mix) {
|
||||
for (int64_t i = lo; i < lo + chunk; ++i) {
|
||||
const float v = ldt(&h, hb + i * hs);
|
||||
sum += v * v;
|
||||
}
|
||||
}
|
||||
stt(&part, pb + (c * S + j) * ps, sum);
|
||||
}
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int ref_mhc_pre_finish(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 7)) return RAD_E_INVAL;
|
||||
int64_t n, hc, iters;
|
||||
float eps, heps;
|
||||
if (!pre_params(a, &n, &hc, &iters, &eps, &heps)) return RAD_E_SHAPE;
|
||||
const int64_t chunk = p_int(a, "chunk", 0);
|
||||
if (chunk <= 0 || (hc * n) % chunk) return RAD_E_SHAPE;
|
||||
const auto &part = a->t[0], &h = a->t[1], &scale = a->t[2], &base = a->t[3];
|
||||
const auto &x = a->t[4], &post = a->t[5], &comb = a->t[6];
|
||||
const int64_t width = hc * n, mix = hc * (hc + 2), S = part_stride(hc), chunks = width / chunk;
|
||||
if (h.rank != 2) return RAD_E_SHAPE;
|
||||
const int64_t rows = h.shape[0];
|
||||
if (rows < 1 || !matrix(part, rows, chunks * S) || part.dtype != RAD_F32 ||
|
||||
!pre_outputs(h, scale, base, x, post, comb, rows, n, hc))
|
||||
return RAD_E_SHAPE;
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
float coeff[80];
|
||||
const int64_t pb = rowoff(&part, r, chunks * S), ps = laststride(&part);
|
||||
float sq = 0;
|
||||
for (int64_t c = 0; c < chunks; ++c) sq += ldt(&part, pb + (c * S + mix) * ps);
|
||||
const float inv = 1.0f / std::sqrt(sq / (float)width + eps);
|
||||
for (int64_t j = 0; j < mix; ++j) {
|
||||
float dot = 0;
|
||||
for (int64_t c = 0; c < chunks; ++c) dot += ldt(&part, pb + (c * S + j) * ps);
|
||||
coeff[j] = dot * inv;
|
||||
}
|
||||
finish_row(coeff, h, scale, base, x, post, comb, r, n, hc, iters, heps);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int ref_mhc_post(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 5)) return RAD_E_INVAL;
|
||||
const int64_t n = p_int(a, "n", 0), hc = p_int(a, "hc", 0);
|
||||
if (n <= 0 || hc < 2 || hc > 8) return RAD_E_SHAPE;
|
||||
const auto &x = a->t[0], &h = a->t[1], &post = a->t[2], &comb = a->t[3], &out = a->t[4];
|
||||
if (x.rank != 2) return RAD_E_SHAPE;
|
||||
const int64_t rows = x.shape[0];
|
||||
if (rows < 1 || !matrix(x, rows, n) || !matrix(h, rows, hc * n) || !matrix(post, rows, hc) ||
|
||||
!matrix(comb, rows, hc * hc) || !matrix(out, rows, hc * n) || out.data == h.data ||
|
||||
post.dtype != RAD_F32 || comb.dtype != RAD_F32)
|
||||
return RAD_E_SHAPE;
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
const int64_t hb = rowoff(&h, r, hc * n), cb = rowoff(&comb, r, hc * hc);
|
||||
const int64_t pb = rowoff(&post, r, hc), xb = rowoff(&x, r, n);
|
||||
const int64_t ob = rowoff(&out, r, hc * n);
|
||||
for (int64_t k = 0; k < hc; ++k)
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
float v = 0;
|
||||
for (int64_t j = 0; j < hc; ++j)
|
||||
v += ldt(&comb, cb + (j * hc + k) * laststride(&comb)) *
|
||||
ldt(&h, hb + (j * n + i) * laststride(&h));
|
||||
v += ldt(&post, pb + k * laststride(&post)) * ldt(&x, xb + i * laststride(&x));
|
||||
stt(&out, ob + (k * n + i) * laststride(&out), v);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int ref_mhc_contract(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 2)) return RAD_E_INVAL;
|
||||
const int64_t n = p_int(a, "n", 0), hc = p_int(a, "hc", 0);
|
||||
if (n <= 0 || hc < 2 || hc > 8) return RAD_E_SHAPE;
|
||||
const auto &h = a->t[0], &x = a->t[1];
|
||||
if (h.rank != 2 || h.shape[0] < 1 || !matrix(h, h.shape[0], hc * n) ||
|
||||
!matrix(x, h.shape[0], n))
|
||||
return RAD_E_SHAPE;
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t r = 0; r < h.shape[0]; ++r)
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
float v = 0;
|
||||
for (int64_t j = 0; j < hc; ++j)
|
||||
v += ldt(&h, rowoff(&h, r, hc * n) + (j * n + i) * laststride(&h));
|
||||
stt(&x, rowoff(&x, r, n) + i * laststride(&x), v / (float)hc);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
/* Absorbed MLA: one latent vector is both the attention key and value. The
|
||||
* per-query table already contains the selected complete pages plus its tail.
|
||||
* `scale` comes from the original query/key head width, NOT the latent width. */
|
||||
#include "ref_common.h"
|
||||
#include "ref_ops.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
using namespace ref;
|
||||
|
||||
/* Both projections share the checkpoint's [head,(K|V),latent] matrix.
|
||||
* Absorb: q @ Wk. Expand: attention_latent @ Wv^T. No per-head KV cache. */
|
||||
int ref_mla_project(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 3)) return RAD_E_INVAL;
|
||||
RadTensor x = a->t[0], y = a->t[2];
|
||||
const auto& w = a->t[1];
|
||||
const int64_t h = p_int(a, "heads", 0), d = p_int(a, "head_dim", 0),
|
||||
l = p_int(a, "latent_dim", 0);
|
||||
const char* mode = p_str(a, "mode", "");
|
||||
const bool absorb = !std::strcmp(mode, "absorb"), expand = !std::strcmp(mode, "expand");
|
||||
auto heads_view = [&](RadTensor& t, int64_t width) {
|
||||
if (h > 0 && width > 0 && t.rank == 2 && t.shape[1] == h * width) {
|
||||
t.rank = 3;
|
||||
t.shape[1] = h;
|
||||
t.shape[2] = width;
|
||||
t.stride[2] = t.stride[1];
|
||||
t.stride[1] *= width;
|
||||
}
|
||||
};
|
||||
heads_view(x, absorb ? d : l);
|
||||
heads_view(y, absorb ? l : d);
|
||||
if ((!absorb && !expand) || h < 1 || d < 1 || l < 1 || x.rank != 3 || w.rank != 2 ||
|
||||
y.rank != 3 || x.shape[0] < 1 || x.shape[1] != h || x.shape[2] != (absorb ? d : l) ||
|
||||
w.shape[0] != h * 2 * d || w.shape[1] != l || y.shape[0] != x.shape[0] || y.shape[1] != h ||
|
||||
y.shape[2] != (absorb ? l : d))
|
||||
return RAD_E_SHAPE;
|
||||
if (x.dtype != RAD_BF16 || w.dtype != RAD_BF16 || y.dtype != RAD_BF16) return RAD_E_DTYPE;
|
||||
if (!x.data || !w.data || !y.data) return RAD_E_INVAL;
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t r = 0; r < x.shape[0]; ++r)
|
||||
for (int64_t head = 0; head < h; ++head)
|
||||
for (int64_t col = 0; col < (absorb ? l : d); ++col) {
|
||||
float sum = 0;
|
||||
for (int64_t j = 0; j < (absorb ? d : l); ++j) {
|
||||
const int64_t wr = head * 2 * d + (absorb ? j : d + col), wc = absorb ? col : j;
|
||||
sum += ldt(&x, r * x.stride[0] + head * x.stride[1] + j * x.stride[2]) *
|
||||
ldt(&w, wr * w.stride[0] + wc * w.stride[1]);
|
||||
}
|
||||
stt(&y, r * y.stride[0] + head * y.stride[1] + col * y.stride[2], sum);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int ref_mla_attn(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 5)) return RAD_E_INVAL;
|
||||
const auto &q = a->t[0], &kv = a->t[1], &bt = a->t[2], &len = a->t[3], &out = a->t[4];
|
||||
const int64_t d = p_int(a, "latent_dim", 0), h = p_int(a, "heads", 0),
|
||||
bs = p_int(a, "block_size", 0);
|
||||
const float scale = p_f32(a, "scale", 0);
|
||||
if (d < 1 || d > 2048 || h < 1 || bs < 1 || !std::isfinite(scale) || scale <= 0 ||
|
||||
q.rank != 3 || q.shape[0] < 1 || q.shape[1] != h || q.shape[2] != d || kv.rank != 4 ||
|
||||
kv.shape[1] != 1 || kv.shape[2] != bs || kv.shape[3] != d || bt.rank != 2 ||
|
||||
bt.shape[0] != q.shape[0] || len.rank != 1 || len.shape[0] != q.shape[0] || out.rank != 3 ||
|
||||
out.shape[0] != q.shape[0] || out.shape[1] != h || out.shape[2] != d ||
|
||||
bt.dtype != RAD_I32 || len.dtype != RAD_I32)
|
||||
return RAD_E_SHAPE;
|
||||
for (int i = 0; i < 5; ++i)
|
||||
if (!a->t[i].data) return RAD_E_INVAL;
|
||||
#pragma omp parallel for schedule(static)
|
||||
for (int64_t job = 0; job < q.shape[0] * h; ++job) {
|
||||
const int64_t r = job / h, head = job % h;
|
||||
const int64_t live = std::clamp(ld_int(len.dtype, len.data, r * len.stride[0]), (int64_t)0,
|
||||
bt.shape[1] * bs);
|
||||
auto key_offset = [&](int64_t token) -> int64_t {
|
||||
const int64_t page =
|
||||
ld_int(bt.dtype, bt.data, r * bt.stride[0] + (token / bs) * bt.stride[1]);
|
||||
return page < 0 || page >= kv.shape[0]
|
||||
? -1
|
||||
: page * kv.stride[0] + (token % bs) * kv.stride[2];
|
||||
};
|
||||
auto dot = [&](int64_t base) -> float {
|
||||
float v = 0;
|
||||
for (int64_t c = 0; c < d; ++c)
|
||||
v += ldt(&q, r * q.stride[0] + head * q.stride[1] + c * q.stride[2]) *
|
||||
ldt(&kv, base + c * kv.stride[3]);
|
||||
return v * scale;
|
||||
};
|
||||
float max = -INFINITY;
|
||||
for (int64_t j = 0; j < live; ++j) {
|
||||
const auto base = key_offset(j);
|
||||
if (base >= 0) max = std::max(max, dot(base));
|
||||
}
|
||||
float val[2048] = {}, den = 0;
|
||||
for (int64_t j = 0; j < live; ++j) {
|
||||
const auto base = key_offset(j);
|
||||
if (base < 0) continue;
|
||||
const float w = std::exp(dot(base) - max);
|
||||
den += w;
|
||||
for (int64_t c = 0; c < d; ++c) val[c] += w * ldt(&kv, base + c * kv.stride[3]);
|
||||
}
|
||||
for (int64_t c = 0; c < d; ++c)
|
||||
stt(&out, r * out.stride[0] + head * out.stride[1] + c * out.stride[2],
|
||||
den > 0 ? val[c] / den : 0);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
+2
-1
@@ -492,7 +492,8 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) {
|
||||
if (ts && cb_joined(wse[(size_t)e])) return RAD_E_DTYPE;
|
||||
}
|
||||
mw[(size_t)e] = as_mat(&we[(size_t)e], k);
|
||||
SW[(size_t)e] = make_scales(quant && ts ? &wse[(size_t)e] : nullptr, n, k, false);
|
||||
SW[(size_t)e] = make_scales(quant && ts ? &wse[(size_t)e] : nullptr, n, k,
|
||||
we[(size_t)e].dtype == RAD_FP4E2M1);
|
||||
}
|
||||
|
||||
const int64_t fy = N / parts;
|
||||
|
||||
@@ -59,6 +59,12 @@ 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_mhc_pre (const RadArgs*, RadStream);
|
||||
int ref_mhc_pre_partial (const RadArgs*, RadStream);
|
||||
int ref_mhc_pre_finish (const RadArgs*, RadStream);
|
||||
int ref_mhc_post (const RadArgs*, RadStream);
|
||||
int ref_mhc_contract (const RadArgs*, RadStream);
|
||||
int ref_kda_update (const RadArgs*, RadStream);
|
||||
int ref_hc_read (const RadArgs*, RadStream);
|
||||
int ref_hc_write (const RadArgs*, RadStream);
|
||||
int ref_mtp_enter (const RadArgs*, RadStream);
|
||||
@@ -68,6 +74,14 @@ int ref_grid_embed_aa (const RadArgs*, RadStream);
|
||||
int ref_add (const RadArgs*, RadStream);
|
||||
int ref_mul (const RadArgs*, RadStream);
|
||||
int ref_silu_mul (const RadArgs*, RadStream);
|
||||
int ref_swiglu_clamped (const RadArgs*, RadStream);
|
||||
int ref_router_sigmoid_topk(const RadArgs*, RadStream);
|
||||
int ref_dsa_pool(const RadArgs*, RadStream);
|
||||
int ref_dsa_query(const RadArgs*, RadStream);
|
||||
int ref_gemm_nt_f32(const RadArgs*, RadStream);
|
||||
int ref_mla_project(const RadArgs*, RadStream);
|
||||
int ref_dsa_score(const RadArgs*, RadStream);
|
||||
int ref_mla_attn(const RadArgs*, RadStream);
|
||||
int ref_gelu_mul (const RadArgs*, RadStream);
|
||||
int ref_act_mul (const RadArgs*, RadStream);
|
||||
int ref_mul_weight (const RadArgs*, RadStream);
|
||||
@@ -267,6 +281,12 @@ 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_mhc_pre);
|
||||
REF_SHAPE_FN(ref_mhc_pre_partial);
|
||||
REF_SHAPE_FN(ref_mhc_pre_finish);
|
||||
REF_SHAPE_FN(ref_mhc_post);
|
||||
REF_SHAPE_FN(ref_mhc_contract);
|
||||
REF_SHAPE_FN(ref_kda_update);
|
||||
REF_SHAPE_FN(ref_hc_read);
|
||||
REF_SHAPE_FN(ref_hc_write);
|
||||
REF_SHAPE_FN(ref_mtp_enter);
|
||||
@@ -276,6 +296,14 @@ REF_SHAPE_FN(ref_grid_embed_aa);
|
||||
REF_SHAPE_FN(ref_add);
|
||||
REF_SHAPE_FN(ref_mul);
|
||||
REF_SHAPE_FN(ref_silu_mul);
|
||||
REF_SHAPE_FN(ref_swiglu_clamped);
|
||||
REF_SHAPE_FN(ref_router_sigmoid_topk);
|
||||
REF_SHAPE_FN(ref_dsa_pool);
|
||||
REF_SHAPE_FN(ref_dsa_query);
|
||||
REF_SHAPE_FN(ref_gemm_nt_f32);
|
||||
REF_SHAPE_FN(ref_mla_project);
|
||||
REF_SHAPE_FN(ref_dsa_score);
|
||||
REF_SHAPE_FN(ref_mla_attn);
|
||||
REF_SHAPE_FN(ref_gelu_mul);
|
||||
REF_SHAPE_FN(ref_act_mul);
|
||||
REF_SHAPE_FN(ref_mul_weight);
|
||||
|
||||
@@ -120,6 +120,25 @@ static const RadOperandSpec oCausalConv[] = { OPD("x"), WGT("w"), INOUT("conv_st
|
||||
static const RadParamSpec pHcWrite[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_STR("dtype") };
|
||||
static const RadOperandSpec oHcEnter[] = { OPD("x"), OUT("h") };
|
||||
static const RadOperandSpec oHcWrite[] = { OPD("y"), OPD("inj"), INOUT("h") };
|
||||
static const RadParamSpec pMhcPre[] = { P_INT("M"), P_INT("n"), P_INT("hc"),
|
||||
P_INT("iterations"), P_F64("eps"), P_F64("hc_eps"), P_STR("dtype") };
|
||||
static const RadOperandSpec oMhcPre[] = { OPD("h"), WGT("fn"), WGT("scale"), WGT("base"),
|
||||
OUT("x"), OUT("post"), OUT("comb") };
|
||||
static const RadParamSpec pMhcPrePartial[] = { P_INT("M"), P_INT("n"), P_INT("hc"),
|
||||
P_INT("chunk"), P_INT("first"), P_INT("chunks"), P_STR("dtype") };
|
||||
static const RadOperandSpec oMhcPrePartial[] = { OPD("h"), WGT("fn"), OUT("part") };
|
||||
static const RadParamSpec pMhcPreFinish[] = { P_INT("M"), P_INT("n"), P_INT("hc"),
|
||||
P_INT("iterations"), P_F64("eps"), P_F64("hc_eps"), P_INT("chunk"), P_STR("dtype") };
|
||||
static const RadOperandSpec oMhcPreFinish[] = { OPD("part"), OPD("h"), WGT("scale"), WGT("base"),
|
||||
OUT("x"), OUT("post"), OUT("comb") };
|
||||
static const RadOperandSpec oMhcPost[] = { OPD("x"), OPD("h"), OPD("post"), OPD("comb"), OUT("out") };
|
||||
static const RadOperandSpec oMhcContract[] = { OPD("h"), OUT("x") };
|
||||
static const RadParamSpec pKdaUpdate[] = { P_INT("M"), P_INT("heads"), P_INT("head_k"),
|
||||
P_INT("head_v"), P_F64("lower_bound"), P_F64("scale"), P_F64("l2_eps"),
|
||||
P_STR("mode"), P_STR("dtype"), P_STRO("state_form") };
|
||||
static const RadOperandSpec oKdaUpdate[] = { OPD("q"), OPD("k"), OPD("v"), OPD("a"), OPD("b"),
|
||||
WGT("A_log"), WGT("dt_bias"), INOUT("state"), OPD("state_idx"), OPD("cu"),
|
||||
OPD_O("num_accepted"), OPD_O("has_init"), OUT("o") };
|
||||
/* The MTP head's entry for a wide residual stream. `ngroup` is hc for a grouped norm over the
|
||||
* sub-streams, 1 for a flat one over the whole row (see ref_hc.cpp). */
|
||||
static const RadParamSpec pMtpEnter[] = { P_INT("M"), P_INT("n"), P_INT("hc"),
|
||||
@@ -137,6 +156,22 @@ static const RadOperandSpec oLayernorm[] = { OPD("x"), WGT("w"), WGT_O("b"), OUT
|
||||
static const RadParamSpec pGridEmbed[] = { P_INT("M"), P_INT("n"), P_INT("side"), P_STR("dtype") };
|
||||
static const RadOperandSpec oGridEmbed[] = { INOUT("x"), WGT("table"), OPD("coord") };
|
||||
|
||||
static const RadParamSpec pSwigluClamped[] = { P_INT("M"), P_INT("n"), P_F64("limit"), P_STR("dtype") };
|
||||
static const RadParamSpec pDsaPool[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), P_STR("dtype"), P_INTO("block_size") };
|
||||
static const RadParamSpec pMlaAttn[] = { P_INT("M"), P_INT("latent_dim"), P_INT("heads"),
|
||||
P_INT("blocks"), P_INT("block_size"), P_F64("scale"), P_STR("dtype") };
|
||||
static const RadParamSpec pMlaProject[] = { P_INT("M"), P_INT("heads"), P_INT("head_dim"),
|
||||
P_INT("latent_dim"), P_STR("mode"), P_STR("dtype") };
|
||||
static const RadOperandSpec oMlaAttn[] = { OPD("q"), OPD("kv"), OPD("bt"), OPD("length"), OUT("out") };
|
||||
static const RadParamSpec pDsaScore[] = { P_INT("M"), P_INT("n"), P_INT("heads"),
|
||||
P_INT("blocks"), P_INT("seqs"), P_STR("dtype") };
|
||||
static const RadOperandSpec oDsaScore[] = { OPD("q"), OPD("q_scale"), OPD("gate"), OPD("k"),
|
||||
OPD_O("k_scale"), OPD("bt"), OPD("cu"), OPD("nc"), OUT("score") };
|
||||
static const RadOperandSpec oDsaPool[] = { OPD("kg"), WGT("ape"), OUT("q"), OUT("scale"),
|
||||
OPD_O("page"), INOUT_O("cache") };
|
||||
static const RadParamSpec pRouterSigmoid[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"),
|
||||
P_INT("norm"), P_F64("route_scale"), P_STR("dtype") };
|
||||
static const RadOperandSpec oRouterSigmoid[] = { OPD("logits"), WGT("bias"), OUT("ids"), OUT("weights") };
|
||||
static const RadParamSpec pMnD[] = { P_INT("M"), P_INT("n"), P_STR("dtype") };
|
||||
/* `div` divides the rounded sum, rounded again (default 1, the plain sum): a mean of branches
|
||||
* summed pairwise, as a vocoder averages its residual blocks. */
|
||||
@@ -850,6 +885,33 @@ static const RadOpSchema kSchemas[] = {
|
||||
"is what every fused implementation does." },
|
||||
{ "hc_enter", ARR(pHcWrite), ARR(oHcEnter),
|
||||
"h[s] = x for each of the hc streams -- the wide residual stream's first value. Shares `hc_write`'s parameter list." },
|
||||
{ "mhc_pre", ARR(pMhcPre), ARR(oMhcPre),
|
||||
"Manifold hyper-connection read: RMS-scaled projection of the whole hc*n residual, sigmoid "
|
||||
"pre/post gates and Sinkhorn mixing. x has dtype, post and comb are f32. comb is indexed "
|
||||
"[source,destination]. First pass is row softmax + hc_eps then column normalization; later "
|
||||
"passes add hc_eps to both normalization denominators. hc is 2..8; iterations is 1..256." },
|
||||
{ "mhc_pre_partial", ARR(pMhcPrePartial), ARR(oMhcPrePartial),
|
||||
"mhc_pre's projection split by residual columns. Chunk c covers columns [c*chunk, (c+1)*chunk) "
|
||||
"of the hc*n row; for chunks [first, first+chunks) part[m, (c-first)*S + j] is the sum over the "
|
||||
"chunk of h*fn[j] for j < hc*(hc+2) and of h*h for j = hc*(hc+2), with S = hc*(hc+2)+1 rounded "
|
||||
"up to a multiple of 4 and the slots past the last zero. chunk divides hc*n. Tensor-parallel "
|
||||
"ranks each compute their chunks and an all_gather (row = chunks*S) joins them." },
|
||||
{ "mhc_pre_finish", ARR(pMhcPreFinish), ARR(oMhcPreFinish),
|
||||
"mhc_pre from mhc_pre_partial's matrix over all hc*n/chunk chunks: each coefficient and the sum "
|
||||
"of squares is the sum of its chunks' partials (the order is the implementation's), then "
|
||||
"mhc_pre's gates, Sinkhorn mixing and collapse of h. part and mhc_pre_partial over every chunk "
|
||||
"together are mhc_pre." },
|
||||
{ "mhc_post", ARR(pHcWrite), ARR(oMhcPost),
|
||||
"out[dst,i] = post[dst]*x[i] + sum_src comb[src,dst]*h[src,i]. post and comb are f32; "
|
||||
"out must not alias h. No normalization of the residual stream." },
|
||||
{ "mhc_contract", ARR(pHcWrite), ARR(oMhcContract),
|
||||
"x[i] = mean over hc streams h[stream,i], rounded once to dtype." },
|
||||
{ "kda_update", ARR(pKdaUpdate), ARR(oKdaUpdate),
|
||||
"L2-normalized KDA: per-channel decay exp(lower_bound*sigmoid(exp(A_log)*(a+dt_bias))), "
|
||||
"beta=sigmoid(b), S*=decay; S+=beta*(v-S*k)*k; o=scale*S*q. State is f32 [slot,heads,V,K]. "
|
||||
"verify reads state_idx[seq,num_accepted-1] and writes each candidate state_idx[seq,t]; "
|
||||
"prefill reads/writes column zero, committing only the final state. cu offsets are absolute; "
|
||||
"has_init=0 starts from zero and a negative initial slot emits zero output. No output norm." },
|
||||
{ "hc_read", ARR(pHcRead), ARR(oHcRead),
|
||||
"The read half of a gated residual. N = grouped_rmsnorm(h) -- one rsqrt per `n`-wide stream, "
|
||||
"one gain of hc*n over all of them, `w + wadd`; g = sigmoid(mix_up @ silu(mix_down @ N / hc)); "
|
||||
@@ -929,6 +991,18 @@ static const RadOpSchema kSchemas[] = {
|
||||
"keys j with 0 <= i - j <= left (`right` 0). qf = q * head_dim^-0.5/ln2 * softplus(pds); logit "
|
||||
"= qf.k * ln(1+e)/ln2 + qf.relk[i-j]; softcap * tanh(logit / softcap); softmax; .v. f32, one "
|
||||
"rounding." },
|
||||
{ "mla_attn", ARR(pMlaAttn), ARR(oMlaAttn),
|
||||
"Softmax over selected latent vectors used as both key and value; per-query page tables and visible lengths." },
|
||||
{ "mla_project", ARR(pMlaProject), ARR(oGemm),
|
||||
"Per-head query absorption or value expansion through the shared [head,(K|V),latent] BF16 matrix." },
|
||||
{ "dsa_score", ARR(pDsaScore), ARR(oDsaScore),
|
||||
"Per-head ReLU of FP8 dot products, then signed head gates and scales; invalid history is -inf." },
|
||||
{ "dsa_query", ARR(pMnD), ARR(oQuantFp8),
|
||||
"Normalized Hadamard, BF16 boundary and power-of-two E4M3 quantization per query head." },
|
||||
{ "dsa_pool", ARR(pDsaPool), ARR(oDsaPool),
|
||||
"Channel-wise softmax pooling with learned position bias, BF16, normalized Hadamard, BF16, power-of-two FP8." },
|
||||
{ "swiglu_clamped", ARR(pSwigluClamped), ARR(oGateUp),
|
||||
"silu(min(gate,limit))*clamp(up,-limit,limit); gate is the first half." },
|
||||
{ "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." },
|
||||
@@ -1095,6 +1169,8 @@ static const RadOpSchema kSchemas[] = {
|
||||
"y = q * scale, the inverse of quant_act_i8g. It does NOT undo a rotation." },
|
||||
|
||||
{ "gemm_nt", ARR(pGemm), ARR(oGemm), "y[M,N] = a[M,K] @ b[N,K]^T, f32 accumulate." },
|
||||
{ "gemm_nt_f32", ARR(pGemm), ARR(oGemm),
|
||||
"BF16 activations times F32 weights, F32 accumulation and output; preserves routing and index gate precision." },
|
||||
{ "gemm_nt_bias", ARR(pGemmBias), ARR(oGemmBias),
|
||||
"gemm_nt with a per-column bias added in f32, rounded to y's dtype; then, optionally, `act` of "
|
||||
"that (\"gelu\" exact, \"gelu_tanh\" the tanh approximation, \"none\"), rounded; then `res` "
|
||||
@@ -1184,6 +1260,8 @@ static const RadOpSchema kSchemas[] = {
|
||||
"when rows == n. `act` is \"sigmoid\" or \"none\", and it applies to the SCALAR. With `add` "
|
||||
"present the form is y = bf16(x * act(s)) + add -- the product NARROWED before the sum, which "
|
||||
"is what makes the fused form bit-identical to the pair it replaces." },
|
||||
{ "router_sigmoid_topk", ARR(pRouterSigmoid), ARR(oRouterSigmoid),
|
||||
"Single-group sigmoid routing; correction bias selects experts, original scores weight them." },
|
||||
{ "router_topk", ARR(pRouter), ARR(oRouter),
|
||||
"Softmax over ALL n_expert logits, then the top_k by probability with ties to the lower expert "
|
||||
"id, then -- if `norm` -- renormalise the kept weights to sum to one." },
|
||||
@@ -1691,6 +1769,18 @@ SIMPLE("ref_rmsnorm_add", "rmsnorm_add", "norm", "residual add then RMS norm", D
|
||||
ref_rmsnorm_add),
|
||||
SIMPLE("ref_hc_enter", "hc_enter", "norm", "gated residual entry: hc copies of x", DT_FLOAT,
|
||||
ref_hc_enter),
|
||||
SIMPLE("ref_mhc_pre", "mhc_pre", "norm", "manifold residual gates and Sinkhorn mixing", DT_FLOAT,
|
||||
ref_mhc_pre),
|
||||
SIMPLE("ref_mhc_pre_partial", "mhc_pre_partial", "norm", "manifold residual projection partials", DT_FLOAT,
|
||||
ref_mhc_pre_partial),
|
||||
SIMPLE("ref_mhc_pre_finish", "mhc_pre_finish", "norm", "manifold residual gates from projection partials", DT_FLOAT,
|
||||
ref_mhc_pre_finish),
|
||||
SIMPLE("ref_mhc_post", "mhc_post", "norm", "manifold residual source-to-destination update", DT_FLOAT,
|
||||
ref_mhc_post),
|
||||
SIMPLE("ref_mhc_contract", "mhc_contract", "norm", "mean of manifold residual streams", DT_FLOAT,
|
||||
ref_mhc_contract),
|
||||
SIMPLE("ref_kda_update", "kda_update", "gdn", "bounded per-channel delta recurrence and candidate rollback", DT_FLOAT,
|
||||
ref_kda_update),
|
||||
ROWL("ref_hc_read", "hc_read", "norm",
|
||||
"gated residual read: grouped norm, low-rank gate, stream mix",
|
||||
DT_FLOAT ", or mixing matrices of E4M3 / int8 codes with a scale plane, joined",
|
||||
@@ -1710,6 +1800,20 @@ SIMPLE("ref_grid_embed_aa", "grid_embed_aa", "elem",
|
||||
ref_grid_embed_aa),
|
||||
SIMPLE("ref_add", "add", "elem", "elementwise sum", DT_FLOAT, ref_add),
|
||||
SIMPLE("ref_mul", "mul", "elem", "elementwise product", DT_FLOAT, ref_mul),
|
||||
SIMPLE("ref_mla_attn", "mla_attn", "attn", "absorbed latent MQA attention", DT_FLOAT,
|
||||
ref_mla_attn),
|
||||
SIMPLE("ref_dsa_score", "dsa_score", "attn", "weighted FP8 index scoring", DT_FLOAT,
|
||||
ref_dsa_score),
|
||||
SIMPLE("ref_dsa_pool", "dsa_pool", "attn", "learned compressed FP8 index keys", DT_FLOAT,
|
||||
ref_dsa_pool),
|
||||
SIMPLE("ref_dsa_query", "dsa_query", "attn", "normalized FP8 index queries", DT_FLOAT,
|
||||
ref_dsa_query),
|
||||
SIMPLE("ref_gemm_nt_f32", "gemm_nt_f32", "gemm", "F32 routing projection", DT_FLOAT,
|
||||
ref_gemm_nt_f32),
|
||||
SIMPLE("ref_mla_project", "mla_project", "attn", "absorbed MLA projections", DT_FLOAT,
|
||||
ref_mla_project),
|
||||
SIMPLE("ref_swiglu_clamped", "swiglu_clamped", "elem", "asymmetrically clipped SwiGLU", DT_FLOAT,
|
||||
ref_swiglu_clamped),
|
||||
SIMPLE("ref_silu_mul", "silu_mul", "elem", "silu-gated product over a fused gate_up", DT_FLOAT,
|
||||
ref_silu_mul),
|
||||
SIMPLE("ref_act_mul", "act_mul", "elem", "act(a) * b over two operands", DT_FLOAT, ref_act_mul),
|
||||
@@ -1847,6 +1951,8 @@ SIMPLE("ref_qk_norm_rope", "qk_norm_rope", "attn", "per-head QK norm then rotary
|
||||
|
||||
SIMPLE("ref_scale_rows", "scale_rows", "elem", "one scalar per row, broadcast across the row",
|
||||
DT_FLOAT, ref_scale_rows),
|
||||
SIMPLE("ref_router_sigmoid_topk", "router_sigmoid_topk", "moe", "sigmoid correction-bias routing", DT_FLOAT,
|
||||
ref_router_sigmoid_topk),
|
||||
SIMPLE("ref_router_topk", "router_topk", "moe", "softmax then exact top-k routing", DT_FLOAT,
|
||||
ref_router_topk),
|
||||
SIMPLE("ref_moe_scatter", "moe_scatter", "moe", "stable counting sort of routing slots by expert",
|
||||
|
||||
+201
-9
@@ -336,6 +336,95 @@ int ref_hc_enter_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
|
||||
return o.finish("hc_enter", operand, out);
|
||||
}
|
||||
|
||||
int ref_kda_update_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const char* form = gs(p, n_p, "state_form");
|
||||
// Replay records and aliased engine index columns require a hand-built fixture.
|
||||
if (form && !std::strcmp(form,"anchor")) return RAD_E_UNSUPPORTED;
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const int64_t M = gi(p, n_p, "M", 0), H = gi(p, n_p, "heads", 0);
|
||||
const int64_t K = gi(p, n_p, "head_k", 0), V = gi(p, n_p, "head_v", 0);
|
||||
if (M < 1 || H < 1 || K < 1 || K > 128 || V < 1 || V > 128) return RAD_E_UNSUPPORTED;
|
||||
const char* mode = gs(p, n_p, "mode");
|
||||
const int64_t history = mode && !std::strcmp(mode, "verify") ? M : 1;
|
||||
Opd o;
|
||||
o.t(D, {M, H, K}); o.t(D, {M, H, K}); o.t(D, {M, H, V});
|
||||
o.t(D, {M, H, K}); o.t(D, {M, H});
|
||||
o.t((uint32_t)RAD_F32, {H}); o.t((uint32_t)RAD_F32, {H * K});
|
||||
o.t((uint32_t)RAD_F32, {history + 1, H, V, K});
|
||||
o.t_idx({1, history}, history + 1, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE);
|
||||
o.t_idx({2}, M, -1, (uint32_t)RAD_OPD_F_IDX_CU);
|
||||
o.t_idx({1}, 0, 1, 0); o.t_idx({1}, 0, 1, 0);
|
||||
o.t(D, {M, H, V});
|
||||
return o.finish("kda_update", operand, out);
|
||||
}
|
||||
|
||||
int ref_mhc_pre_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), hc = gi(p, n_p, "hc", 0);
|
||||
if (M <= 0 || n <= 0 || hc < 2 || hc > 8) return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
o.t(D, {M, hc * n});
|
||||
o.t((uint32_t)RAD_F32, {hc * (hc + 2), hc * n});
|
||||
o.t((uint32_t)RAD_F32, {3});
|
||||
o.t((uint32_t)RAD_F32, {hc * (hc + 2)});
|
||||
o.t(D, {M, n});
|
||||
o.t((uint32_t)RAD_F32, {M, hc});
|
||||
o.t((uint32_t)RAD_F32, {M, hc * hc});
|
||||
return o.finish("mhc_pre", operand, out);
|
||||
}
|
||||
|
||||
static int64_t mhc_part_stride(int64_t hc) { return (hc * (hc + 2) + 1 + 3) / 4 * 4; }
|
||||
|
||||
int ref_mhc_pre_partial_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), hc = gi(p, n_p, "hc", 0);
|
||||
const int64_t chunk = gi(p, n_p, "chunk", 0), chunks = gi(p, n_p, "chunks", 0);
|
||||
if (M <= 0 || n <= 0 || hc < 2 || hc > 8 || chunk <= 0 || (hc * n) % chunk || chunks <= 0)
|
||||
return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
o.t(D, {M, hc * n});
|
||||
o.t((uint32_t)RAD_F32, {hc * (hc + 2), hc * n});
|
||||
o.t((uint32_t)RAD_F32, {M, chunks * mhc_part_stride(hc)});
|
||||
return o.finish("mhc_pre_partial", operand, out);
|
||||
}
|
||||
|
||||
int ref_mhc_pre_finish_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), hc = gi(p, n_p, "hc", 0);
|
||||
const int64_t chunk = gi(p, n_p, "chunk", 0);
|
||||
if (M <= 0 || n <= 0 || hc < 2 || hc > 8 || chunk <= 0 || (hc * n) % chunk)
|
||||
return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
o.t((uint32_t)RAD_F32, {M, hc * n / chunk * mhc_part_stride(hc)});
|
||||
o.t(D, {M, hc * n});
|
||||
o.t((uint32_t)RAD_F32, {3});
|
||||
o.t((uint32_t)RAD_F32, {hc * (hc + 2)});
|
||||
o.t(D, {M, n});
|
||||
o.t((uint32_t)RAD_F32, {M, hc});
|
||||
o.t((uint32_t)RAD_F32, {M, hc * hc});
|
||||
return o.finish("mhc_pre_finish", operand, out);
|
||||
}
|
||||
|
||||
int ref_mhc_post_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), hc = gi(p, n_p, "hc", 0);
|
||||
if (M <= 0 || n <= 0 || hc < 2 || hc > 8) return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
o.t(D, {M, n}); o.t(D, {M, hc * n});
|
||||
o.t((uint32_t)RAD_F32, {M, hc}); o.t((uint32_t)RAD_F32, {M, hc * hc});
|
||||
o.t(D, {M, hc * n});
|
||||
return o.finish("mhc_post", operand, out);
|
||||
}
|
||||
|
||||
int ref_mhc_contract_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), hc = gi(p, n_p, "hc", 0);
|
||||
if (M <= 0 || n <= 0 || hc < 2 || hc > 8) return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
o.t(D, {M, hc * n}); o.t(D, {M, n});
|
||||
return o.finish("mhc_contract", operand, out);
|
||||
}
|
||||
|
||||
int ref_hc_write_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);
|
||||
@@ -573,6 +662,87 @@ int ref_attn_local_rel_shape(const RadParam* p, int n_p, int operand, RadOpdDesc
|
||||
return o.finish("attn_local_rel", operand, out);
|
||||
}
|
||||
|
||||
int ref_swiglu_clamped_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
return ref_silu_mul_shape(p, n_p, operand, out);
|
||||
}
|
||||
int ref_router_sigmoid_topk_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), ne = gi(p, n_p, "n_expert", 0),
|
||||
k = gi(p, n_p, "top_k", 0);
|
||||
if (M < 1 || ne < 1 || ne > 512 || k < 1 || k > ne) return RAD_E_UNSUPPORTED;
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
Opd o;
|
||||
o.t(D, { M, ne });
|
||||
o.t(RAD_F32, { ne });
|
||||
o.t_idx({ M, k }, ne, -1, 0);
|
||||
o.t(D, { M, k });
|
||||
return o.finish("router_sigmoid_topk", operand, out);
|
||||
}
|
||||
int ref_mla_project_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), h = gi(p, n_p, "heads", 0), d = gi(p, n_p, "head_dim", 0),
|
||||
l = gi(p, n_p, "latent_dim", 0);
|
||||
const char* mode = gs(p, n_p, "mode");
|
||||
const bool absorb = mode && !std::strcmp(mode, "absorb"),
|
||||
expand = mode && !std::strcmp(mode, "expand");
|
||||
if (M < 1 || h < 1 || d < 1 || l < 1 || (!absorb && !expand)) return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
o.t(RAD_BF16, { M, h, absorb ? d : l });
|
||||
o.t(RAD_BF16, { h * 2 * d, l });
|
||||
o.t(RAD_BF16, { M, h, absorb ? l : d });
|
||||
return o.finish("mla_project", operand, out);
|
||||
}
|
||||
int ref_dsa_query_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 < 1 || n < 1 || n > 256 || (n & (n - 1))) return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
o.t(RAD_BF16, { M, n });
|
||||
o.t(RAD_F8E4M3, { M, n });
|
||||
o.t(RAD_F32, { M, 1 });
|
||||
return o.finish("dsa_query", operand, out);
|
||||
}
|
||||
int ref_dsa_pool_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), ratio = gi(p, n_p, "ratio", 0);
|
||||
if (M < 1 || n < 1 || n > 256 || (n & (n - 1)) || ratio < 2 || ratio > 16)
|
||||
return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
o.t(RAD_BF16, { M * ratio, 2 * n });
|
||||
o.t(RAD_F32, { ratio, n });
|
||||
o.t(RAD_F8E4M3, { M, n });
|
||||
o.t(RAD_F32, { M, 1 });
|
||||
o.skip();
|
||||
o.skip(); // Optional paged cache writes use a hand-built unique page list.
|
||||
return o.finish("dsa_pool", operand, out);
|
||||
}
|
||||
int ref_dsa_score_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), H = gi(p, n_p, "heads", 0);
|
||||
const int64_t B = gi(p, n_p, "blocks", 0), S = gi(p, n_p, "seqs", 0), pages = S * B;
|
||||
if (M < 1 || n < 1 || H < 1 || H > 64 || B < 1 || S < 1 || S > M) return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
o.t(RAD_F8E4M3, { M, H, n });
|
||||
o.t_fill(RAD_F32, { M, H }, RAD_FILL_SIGMOID, 0);
|
||||
o.t(RAD_F32, { M, H });
|
||||
o.t(RAD_F8E4M3, { pages, n });
|
||||
o.t_fill(RAD_F32, { pages }, RAD_FILL_SIGMOID, 0);
|
||||
o.t_idx({ S, B }, pages, -1, 0);
|
||||
o.t_idx({ S + 1 }, M, -1, RAD_OPD_F_IDX_CU);
|
||||
o.t_idx({ S }, 0, B, 0);
|
||||
o.t(RAD_F32, { M, B });
|
||||
return o.finish("dsa_score", operand, out);
|
||||
}
|
||||
int ref_mla_attn_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), D = gi(p, n_p, "latent_dim", 0),
|
||||
H = gi(p, n_p, "heads", 0);
|
||||
const int64_t B = gi(p, n_p, "blocks", 0), bs = gi(p, n_p, "block_size", 0),
|
||||
pages = std::max((int64_t)2, B * M);
|
||||
if (M < 1 || D < 1 || D > 2048 || H < 1 || B < 1 || bs < 1) return RAD_E_UNSUPPORTED;
|
||||
const uint32_t dtype = act_dt(p, n_p);
|
||||
Opd o;
|
||||
o.t(dtype, { M, H, D });
|
||||
o.t(dtype, { pages, 1, bs, D });
|
||||
o.t_idx({ M, B }, pages, -1, 0);
|
||||
o.t_idx({ M }, 0, B * bs, 0);
|
||||
o.t(dtype, { M, H, D });
|
||||
return o.finish("mla_attn", operand, out);
|
||||
}
|
||||
int ref_silu_mul_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
|
||||
@@ -931,6 +1101,15 @@ int ref_dequant_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
|
||||
|
||||
/* ================================================================== gemm */
|
||||
|
||||
int ref_gemm_nt_f32_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), K = gi(p, n_p, "K", 0);
|
||||
if (M < 1 || N < 1 || K < 1) return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
o.t(RAD_BF16, { M, K });
|
||||
o.t(RAD_F32, { N, K });
|
||||
o.t(RAD_F32, { M, N });
|
||||
return o.finish("gemm_nt_f32", operand, out);
|
||||
}
|
||||
int ref_gemm_nt_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), K = gi(p, n_p, "K", 0);
|
||||
@@ -971,7 +1150,8 @@ static int gemm_q_shape(const RadParam* p, int n_p, int operand, bool bias, RadO
|
||||
const int64_t group = gi(p, n_p, "group", 0);
|
||||
const char* q = gs(p, n_p, "dtype");
|
||||
auto is = [&](const char* s) { return q && std::strcmp(q, s) == 0; };
|
||||
const bool a8 = is("fp8a8"), a16 = is("fp8a16"), w4 = is("w4a8"), w8 = is("w8a8");
|
||||
const bool f32s = is("fp8a8f32");
|
||||
const bool a8 = is("fp8a8") || f32s, a16 = is("fp8a16"), w4 = is("w4a8"), w8 = is("w8a8");
|
||||
/* i8a8h is i8a8's operands; its rotation is in the values. */
|
||||
const bool i8 = is("i8a8") || is("i8a8h"), mx = is("mxfp4a8");
|
||||
if ((!a8 && !a16 && !w4 && !w8 && !i8 && !mx) || N <= 0 || K <= 0 || group <= 0)
|
||||
@@ -1015,7 +1195,8 @@ static int gemm_q_shape(const RadParam* p, int n_p, int operand, bool bias, RadO
|
||||
o.skip(); /* a_scale */
|
||||
}
|
||||
o.t((uint32_t)RAD_F8E4M3, { N, K }); /* b -- the checkpoint's own bytes */
|
||||
o.t((uint32_t)RAD_BF16, { nb, kb }); /* b_scale -- weight_scale_inv, per 128x128 */
|
||||
/* b_scale -- weight_scale_inv, per 128x128; f32 at fp8a8f32 */
|
||||
o.t(f32s ? (uint32_t)RAD_F32 : (uint32_t)RAD_BF16, { nb, kb });
|
||||
}
|
||||
if (bias) {
|
||||
o.t((uint32_t)RAD_BF16, { N }); /* bias */
|
||||
@@ -1460,7 +1641,8 @@ struct MoeScaleGrid { int64_t rows, k; };
|
||||
static MoeScaleGrid moe_scale_grid(const RadParam* p, int n_p, int64_t g) {
|
||||
const char* d = gs(p, n_p, "dtype");
|
||||
auto is = [&](const char* s) { return d && std::strcmp(d, s) == 0; };
|
||||
if (is("fp8a8")) return { g, g };
|
||||
if (is("fp8a8") || is("fp8a8f32")) return { g, g };
|
||||
if (is("mxfp4a8")) return { 1, 32 };
|
||||
if (is("w4a8") || is("w4a8h") || is("w4nla8h")) return { 1, g };
|
||||
if (is("w4nl64a8h") || is("w5nl64a8h")) return { 1, g / 2 };
|
||||
if (is("w4nl32a8h")) return { 1, g / 4 };
|
||||
@@ -1490,14 +1672,21 @@ int ref_moe_gemm_q_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
Opd o;
|
||||
const int64_t AR = sorted_a_order(p, n_p) ? M * k : M;
|
||||
const char* kind = gs(p, n_p, "dtype");
|
||||
const bool mx = kind && !std::strcmp(kind, "mxfp4a8");
|
||||
const auto SD = kind && !std::strcmp(kind, "fp8a8f32") ? (uint32_t)RAD_F32 : D;
|
||||
o.t((uint32_t)RAD_F8E4M3, { AR, K }); /* a -- E4M3 codes, see `a_order` */
|
||||
o.t((uint32_t)RAD_F32, { AR, (K + g - 1) / g }); /* a_scale */
|
||||
o.t((uint32_t)RAD_F8E4M3, { ne0, N0, K0 }); /* w -- the even experts */
|
||||
o.t(D, { ne0, (N0 + sg.rows - 1) / sg.rows, (K0 + sg.k - 1) / sg.k }); /* w_scale */
|
||||
/* w -- the even experts; mxfp4a8 carries e2m1 codes with an E8M0 byte per (row, 32 of K) */
|
||||
o.t(mx ? (uint32_t)RAD_FP4E2M1 : (uint32_t)RAD_F8E4M3, { ne0, N0, K0 });
|
||||
if (mx) o.t_idx_dt(RAD_U8, { ne0, N0, (K0 + 31) / 32 }, 0, 127, 0); /* w_scale */
|
||||
else o.t(SD, { ne0, (N0 + sg.rows - 1) / sg.rows, (K0 + sg.k - 1) / sg.k });
|
||||
o.t_idx({ M * k }, M * k, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* sorted_tok */
|
||||
o.t_idx({ ne + 1 }, M * k + 1, -1, (uint32_t)RAD_OPD_F_IDX_PREFIX); /* expert_offset */
|
||||
o.t((uint32_t)RAD_F8E4M3, { ne1, N1, K1 }); /* w_odd -- the odd experts */
|
||||
o.t(D, { ne1, (N1 + sg.rows - 1) / sg.rows, (K1 + sg.k - 1) / sg.k }); /* w_odd_scale */
|
||||
/* w_odd -- the odd experts */
|
||||
o.t(mx ? (uint32_t)RAD_FP4E2M1 : (uint32_t)RAD_F8E4M3, { ne1, N1, K1 });
|
||||
if (mx) o.t_idx_dt(RAD_U8, { ne1, N1, (K1 + 31) / 32 }, 0, 127, 0); /* w_odd_scale */
|
||||
else o.t(SD, { ne1, (N1 + sg.rows - 1) / sg.rows, (K1 + sg.k - 1) / sg.k });
|
||||
o.t(D, { M * k, N }); /* y -- in sorted order */
|
||||
return o.finish("moe_gemm_q", operand, out);
|
||||
}
|
||||
@@ -1525,10 +1714,13 @@ int ref_moe_gemm_q_mod4_shape(const RadParam* p, int n_p, int operand, RadOpdDes
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
Opd o;
|
||||
const int64_t AR = sorted_a_order(p, n_p) ? M * k : M;
|
||||
const char* kind = gs(p, n_p, "dtype");
|
||||
const bool mx = kind && !std::strcmp(kind, "mxfp4a8");
|
||||
auto cls = [&](int q) {
|
||||
const int64_t nq = (ne + 3 - q) / 4;
|
||||
o.t((uint32_t)RAD_F8E4M3, { nq, Nq[q], Kq[q] });
|
||||
o.t(D, { nq, (Nq[q] + sg.rows - 1) / sg.rows, (Kq[q] + sg.k - 1) / sg.k });
|
||||
o.t(mx ? (uint32_t)RAD_FP4E2M1 : (uint32_t)RAD_F8E4M3, { nq, Nq[q], Kq[q] });
|
||||
if (mx) o.t_idx_dt(RAD_U8, {nq, Nq[q], (Kq[q] + 31) / 32}, 0, 127, 0);
|
||||
else o.t(D, { nq, (Nq[q] + sg.rows - 1) / sg.rows, (Kq[q] + sg.k - 1) / sg.k });
|
||||
};
|
||||
o.t((uint32_t)RAD_F8E4M3, { AR, K }); /* a -- E4M3 codes, see `a_order` */
|
||||
o.t((uint32_t)RAD_F32, { AR, (K + g - 1) / g }); /* a_scale */
|
||||
|
||||
@@ -751,6 +751,34 @@ TEST(kv_block_size_comes_off_the_kernel) {
|
||||
CHECK_EQ((int)gi.layers.size(), 2);
|
||||
}
|
||||
|
||||
TEST(glm_index_cache_pages_are_sized_by_the_real_pool_consumer) {
|
||||
Registry reg;
|
||||
REQUIRE_EQ(reg.load_dir(home() + "/kernels", { "libref" }), RAD_OK);
|
||||
Builder b(reg, make_meta(), make_ctx());
|
||||
RadKVGroupDecl kd{};
|
||||
kd.kind = RAD_KV_FULL;
|
||||
kd.dtype = RAD_U8;
|
||||
kd.n_head_kv = 1;
|
||||
kd.head_dim = 17;
|
||||
const auto group = b.decl_kv_group("glm_index", &kd);
|
||||
RadWeightDecl wd{};
|
||||
wd.dtype = RAD_F32;
|
||||
wd.rank = 2;
|
||||
wd.shape[0] = 4;
|
||||
wd.shape[1] = 128;
|
||||
wd.access = RAD_ACCESS_PER_TOKEN;
|
||||
wd.shard = RAD_SHARD_NONE;
|
||||
const auto ape = b.decl_weight("pool_ape", &wd);
|
||||
const RadParam params[] = { RAD_RANGE("M", 1, 12), RAD_INT("n", 128), RAD_INT("ratio", 4),
|
||||
RAD_STR("dtype", "bf16"), RAD_INT("block_size", 4) };
|
||||
REQUIRE(b.decl_op("dsa_pool", params, 5, &ape, 1));
|
||||
CHECK_EQ(b.kv_block_size(group), 4);
|
||||
CHECK_OK(b.bind_layer_kv(0, group));
|
||||
CHECK_OK(b.bind_layer_kv(1, group));
|
||||
REQUIRE_EQ(b.finish(), RAD_OK);
|
||||
CHECK_EQ(b.program().kv_groups[group].bytes_per_block, (int64_t)(2 * 136));
|
||||
}
|
||||
|
||||
TEST(a_kv_group_with_no_layers_is_an_error) {
|
||||
NEED_PLUGIN(reg)
|
||||
Builder b(reg, make_meta(), make_ctx());
|
||||
|
||||
+692
-3
@@ -229,6 +229,669 @@ int run(const char* op, A& args, int rank = 0, int world = 1) {
|
||||
|
||||
} /* namespace */
|
||||
|
||||
TEST(manifold_read_uses_whole_stream_rms_and_unaveraged_pre_mix) {
|
||||
T h(RAD_F32, {1, 2}); h.f({1, 3});
|
||||
T fn(RAD_F32, {8, 2});
|
||||
fn.f({3.0f * std::log(3.0f), 0});
|
||||
T scale(RAD_F32, {3}); scale.f({1, 1, 1});
|
||||
T base(RAD_F32, {8}); base.f({0, 0, std::log(3.0f), 0, 0, 0, 0, 0});
|
||||
T x(RAD_F32, {1, 1}), post(RAD_F32, {1, 2}), comb(RAD_F32, {1, 4});
|
||||
A a; a.t(h).t(fn).t(scale).t(base).t(x).t(post).t(comb)
|
||||
.i("M", 1).i("n", 1).i("hc", 2).i("iterations", 20)
|
||||
.d("eps", 4).d("hc_eps", 0).s("dtype", "f32");
|
||||
REQUIRE_EQ(run("mhc_pre", a), RAD_OK);
|
||||
/* RMS inverse = 1/3, pre = [3/4,1/2], post = [3/2,1]. */
|
||||
CHECK_NEAR(x.at(0), 2.25f, 1e-6);
|
||||
CHECK_NEAR(post.at(0), 1.5f, 1e-6);
|
||||
CHECK_EQ(post.at(1), 1.0f);
|
||||
for (int i = 0; i < 4; ++i) CHECK_EQ(comb.at(i), 0.5f);
|
||||
a.ps[3].ival = 0;
|
||||
CHECK_EQ(run("mhc_pre", a), RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
/* Two ranks each project half of the chunks; their partials, joined row by row as the
|
||||
* row-interleaved all_gather lays them out, finish to mhc_pre. Quarter-step inputs keep every
|
||||
* product and sum exact, so the split is compared bit for bit. */
|
||||
TEST(manifold_read_split_by_chunks_finishes_to_the_whole_read) {
|
||||
const int64_t M = 3, n = 8, hc = 4, W = hc * n, mix = hc * (hc + 2), S = 28;
|
||||
T h(RAD_F32, {M, W}), fn(RAD_F32, {mix, W}), scale(RAD_F32, {3}), base(RAD_F32, {mix});
|
||||
std::vector<float> hv((size_t)(M * W)), fv((size_t)(mix * W)), bv((size_t)mix);
|
||||
for (size_t i = 0; i < hv.size(); ++i) hv[i] = (float)((int)((i * 7) % 9) - 4) * 0.25f;
|
||||
for (size_t i = 0; i < fv.size(); ++i) fv[i] = (float)((int)((i * 5) % 7) - 3) * 0.125f;
|
||||
for (size_t i = 0; i < bv.size(); ++i) bv[i] = (float)((int)(i % 5) - 2) * 0.5f;
|
||||
h.f(hv); fn.f(fv); scale.f({0.5f, 0.25f, 1.0f}); base.f(bv);
|
||||
T x(RAD_F32, {M, n}), post(RAD_F32, {M, hc}), comb(RAD_F32, {M, hc * hc});
|
||||
A whole; whole.t(h).t(fn).t(scale).t(base).t(x).t(post).t(comb)
|
||||
.i("M", M).i("n", n).i("hc", hc).i("iterations", 20)
|
||||
.d("eps", 1e-5).d("hc_eps", 1e-6).s("dtype", "f32");
|
||||
REQUIRE_EQ(run("mhc_pre", whole), RAD_OK);
|
||||
T gathered(RAD_F32, {M, 4 * S});
|
||||
for (int rank = 0; rank < 2; ++rank) {
|
||||
T part(RAD_F32, {M, 2 * S});
|
||||
part.f(std::vector<float>((size_t)(M * 2 * S), 9.0f));
|
||||
A pa; pa.t(h).t(fn).t(part).i("M", M).i("n", n).i("hc", hc).i("chunk", 8)
|
||||
.i("first", 2 * rank).i("chunks", 2).s("dtype", "f32");
|
||||
REQUIRE_EQ(run("mhc_pre_partial", pa), RAD_OK);
|
||||
for (int64_t r = 0; r < M; ++r) for (int64_t c = 0; c < 2; ++c)
|
||||
for (int64_t j = mix + 1; j < S; ++j) CHECK_EQ(part.at(r * 2 * S + c * S + j), 0.0f);
|
||||
for (int64_t r = 0; r < M; ++r) for (int64_t i = 0; i < 2 * S; ++i)
|
||||
st_dt(RAD_F32, gathered.t.data, r * 4 * S + rank * 2 * S + i, part.at(r * 2 * S + i));
|
||||
}
|
||||
T x2(RAD_F32, {M, n}), post2(RAD_F32, {M, hc}), comb2(RAD_F32, {M, hc * hc});
|
||||
A fa; fa.t(gathered).t(h).t(scale).t(base).t(x2).t(post2).t(comb2)
|
||||
.i("M", M).i("n", n).i("hc", hc).i("iterations", 20)
|
||||
.d("eps", 1e-5).d("hc_eps", 1e-6).i("chunk", 8).s("dtype", "f32");
|
||||
REQUIRE_EQ(run("mhc_pre_finish", fa), RAD_OK);
|
||||
for (int64_t i = 0; i < M * n; ++i) CHECK_EQ(x2.at(i), x.at(i));
|
||||
for (int64_t i = 0; i < M * hc; ++i) CHECK_EQ(post2.at(i), post.at(i));
|
||||
for (int64_t i = 0; i < M * hc * hc; ++i) CHECK_EQ(comb2.at(i), comb.at(i));
|
||||
/* A chunk that does not divide the residual, or a range past its end, is refused. */
|
||||
T part(RAD_F32, {M, 2 * S});
|
||||
A bad; bad.t(h).t(fn).t(part).i("M", M).i("n", n).i("hc", hc).i("chunk", 8)
|
||||
.i("first", 3).i("chunks", 2).s("dtype", "f32");
|
||||
CHECK_EQ(run("mhc_pre_partial", bad), RAD_E_SHAPE);
|
||||
fa.ps[6].ival = 7;
|
||||
CHECK_EQ(run("mhc_pre_finish", fa), RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
TEST(manifold_post_mixes_sources_into_destinations_and_contracts_by_mean) {
|
||||
T h(RAD_F32, {1, 6}); h.f({10, 20, 30, 40, 50, 60});
|
||||
T x(RAD_F32, {1, 2}); x.f({2, 4});
|
||||
T post(RAD_F32, {1, 3}); post.f({1, 2, 3});
|
||||
T comb(RAD_F32, {1, 9}); comb.f({0, 1, 0, 0, 0, 1, 1, 0, 0});
|
||||
T out(RAD_F32, {1, 6});
|
||||
A a; a.t(x).t(h).t(post).t(comb).t(out).i("M", 1).i("n", 2).i("hc", 3).s("dtype", "f32");
|
||||
REQUIRE_EQ(run("mhc_post", a), RAD_OK);
|
||||
const float expected[] = {52, 64, 14, 28, 36, 52};
|
||||
for (int i = 0; i < 6; ++i) CHECK_EQ(out.at(i), expected[i]);
|
||||
/* The input remains the unnormalized residual. */
|
||||
CHECK_EQ(h.at(0), 10.0f);
|
||||
a.ts[4] = h.t;
|
||||
CHECK_EQ(run("mhc_post", a), RAD_E_SHAPE);
|
||||
T contracted(RAD_F32, {1, 2});
|
||||
A c; c.t(h).t(contracted).i("M", 1).i("n", 2).i("hc", 3).s("dtype", "f32");
|
||||
REQUIRE_EQ(run("mhc_contract", c), RAD_OK);
|
||||
CHECK_EQ(contracted.at(0), 30.0f);
|
||||
CHECK_EQ(contracted.at(1), 40.0f);
|
||||
}
|
||||
|
||||
TEST(manifold_sinkhorn_first_pass_and_epsilon_are_distinct) {
|
||||
T h(RAD_F32, {1, 2}); h.f({1, 3});
|
||||
T fn(RAD_F32, {8, 2}), scale(RAD_F32, {3}); scale.f({1, 1, 1});
|
||||
T base(RAD_F32, {8}); base.f({0, 0, 0, 0, std::log(3.0f), 0, 0, 0});
|
||||
T x(RAD_F32, {1, 1}), post(RAD_F32, {1, 2}), comb(RAD_F32, {1, 4});
|
||||
A a; a.t(h).t(fn).t(scale).t(base).t(x).t(post).t(comb)
|
||||
.i("M", 1).i("n", 1).i("hc", 2).i("iterations", 1)
|
||||
.d("eps", 1e-5).d("hc_eps", 0).s("dtype", "f32");
|
||||
REQUIRE_EQ(run("mhc_pre", a), RAD_OK);
|
||||
const float first[] = {0.6f, 1.0f / 3, 0.4f, 2.0f / 3};
|
||||
for (int i = 0; i < 4; ++i) CHECK_NEAR(comb.at(i), first[i], 1e-6);
|
||||
a.ps[3].ival = 20;
|
||||
REQUIRE_EQ(run("mhc_pre", a), RAD_OK);
|
||||
CHECK_NEAR(comb.at(0), 0.633974596f, 1e-6);
|
||||
CHECK_NEAR(comb.at(1), 0.366025404f, 1e-6);
|
||||
/* Uniform logits: first pass is (.5 + .25) / (1.5 + .25) = 3/7. */
|
||||
base.f({0, 0, 0, 0, 0, 0, 0, 0});
|
||||
a.ps[3].ival = 1;
|
||||
a.ps[5].dval = 0.25;
|
||||
REQUIRE_EQ(run("mhc_pre", a), RAD_OK);
|
||||
CHECK_EQ(x.at(0), 3.0f);
|
||||
for (int i = 0; i < 4; ++i) CHECK_NEAR(comb.at(i), 3.0f / 7, 1e-6);
|
||||
}
|
||||
|
||||
TEST(kda_candidate_states_restore_the_accepted_prefix) {
|
||||
T q(RAD_F32, {2, 1, 2}); q.f({1, 0, 1, 0});
|
||||
T k(RAD_F32, {2, 1, 2}); k.f({1, 0, 1, 0});
|
||||
T v(RAD_F32, {2, 1, 1}); v.f({2, 2});
|
||||
T g(RAD_F32, {2, 1, 2}); g.f({0, std::log(3.0f), 0, std::log(3.0f)});
|
||||
T b(RAD_F32, {2, 1}), alog(RAD_F32, {1}), bias(RAD_F32, {2});
|
||||
T state(RAD_F32, {3, 1, 1, 2}); state.f({4, 8, 0, 0, 123, 456});
|
||||
T idx(RAD_I32, {1, 2}); idx.n({0, 1});
|
||||
T cu(RAD_I32, {2}); cu.n({0, 2});
|
||||
T accepted(RAD_I32, {1}); accepted.n({1});
|
||||
T out(RAD_F32, {2, 1, 1});
|
||||
A a; a.t(q).t(k).t(v).t(g).t(b).t(alog).t(bias).t(state).t(idx).t(cu).t(accepted).tnull().t(out)
|
||||
.i("M", 2).i("heads", 1).i("head_k", 2).i("head_v", 1)
|
||||
.d("lower_bound", -std::log(16.0)).d("scale", 1).d("l2_eps", 1e-6)
|
||||
.s("mode", "verify").s("dtype", "f32");
|
||||
REQUIRE_EQ(run("kda_update", a), RAD_OK);
|
||||
/* Decays [1/4,1/8] distinguish the per-channel gate from a scalar gate. */
|
||||
CHECK_NEAR(out.at(0), 1.5f, 3e-6);
|
||||
CHECK_NEAR(out.at(1), 1.1875f, 3e-6);
|
||||
CHECK_NEAR(state.at(0), 1.5f, 3e-6);
|
||||
CHECK_NEAR(state.at(1), 1.0f, 3e-6);
|
||||
CHECK_NEAR(state.at(2), 1.1875f, 3e-6);
|
||||
CHECK_NEAR(state.at(3), 0.125f, 3e-6);
|
||||
CHECK_EQ(state.at(4), 123.0f);
|
||||
CHECK_EQ(state.at(5), 456.0f);
|
||||
/* The next step rejects candidate 1 and reads candidate 0, then writes candidate 0's slot. */
|
||||
cu.n({0, 1});
|
||||
REQUIRE_EQ(run("kda_update", a), RAD_OK);
|
||||
CHECK_NEAR(out.at(0), 1.1875f, 3e-6);
|
||||
/* Accepting both candidates instead starts from slot 1. */
|
||||
accepted.n({2});
|
||||
REQUIRE_EQ(run("kda_update", a), RAD_OK);
|
||||
CHECK_NEAR(out.at(0), 1.1484375f, 3e-6);
|
||||
accepted.n({3});
|
||||
CHECK_EQ(run("kda_update", a), RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
TEST(kda_prefill_commits_final_state_and_uses_absolute_cu_offsets) {
|
||||
T q(RAD_F32, {3, 1, 2}); q.f({1000, 1000, 1, 0, 1, 0});
|
||||
T k(RAD_F32, {3, 1, 2}); k.f({1000, 1000, 1, 0, 1, 0});
|
||||
T v(RAD_F32, {3, 1, 1}); v.f({1000, 2, 2});
|
||||
T g(RAD_F32, {3, 1, 2}); g.f({0, 0, 0, std::log(3.0f), 0, std::log(3.0f)});
|
||||
T b(RAD_F32, {3, 1}), alog(RAD_F32, {1}), bias(RAD_F32, {2});
|
||||
T state(RAD_F32, {2, 1, 1, 2}); state.f({4, 8, 123, 456});
|
||||
T idx(RAD_I32, {1, 1}); idx.n({0});
|
||||
T cu(RAD_I32, {2}); cu.n({1, 3});
|
||||
T init(RAD_I32, {1}); init.n({1});
|
||||
T out(RAD_F32, {3, 1, 1}); out.f({77, 77, 77});
|
||||
A a; a.t(q).t(k).t(v).t(g).t(b).t(alog).t(bias).t(state).t(idx).t(cu).tnull().t(init).t(out)
|
||||
.i("M", 3).i("heads", 1).i("head_k", 2).i("head_v", 1)
|
||||
.d("lower_bound", -std::log(16.0)).d("scale", 1).d("l2_eps", 1e-6)
|
||||
.s("mode", "prefill").s("dtype", "f32");
|
||||
REQUIRE_EQ(run("kda_update", a), RAD_OK);
|
||||
CHECK_EQ(out.at(0), 77.0f);
|
||||
CHECK_NEAR(out.at(1), 1.5f, 3e-6);
|
||||
CHECK_NEAR(out.at(2), 1.1875f, 3e-6);
|
||||
CHECK_NEAR(state.at(0), 1.1875f, 3e-6);
|
||||
CHECK_NEAR(state.at(1), 0.125f, 3e-6);
|
||||
CHECK_EQ(state.at(2), 123.0f);
|
||||
init.n({0});
|
||||
REQUIRE_EQ(run("kda_update", a), RAD_OK);
|
||||
CHECK_NEAR(out.at(1), 1.0f, 3e-6);
|
||||
CHECK_NEAR(out.at(2), 1.125f, 3e-6);
|
||||
idx.n({-1});
|
||||
REQUIRE_EQ(run("kda_update", a), RAD_OK);
|
||||
CHECK_EQ(out.at(1), 0.0f);
|
||||
CHECK_EQ(out.at(2), 0.0f);
|
||||
}
|
||||
|
||||
TEST(mla_attention_reads_one_latent_and_masks_the_last_selected_page) {
|
||||
T q(RAD_F32, { 1, 1, 2 }), kv(RAD_F32, { 2, 1, 2, 2 }), bt(RAD_I32, { 1, 2 });
|
||||
T len(RAD_I32, { 1 }), out(RAD_F32, { 1, 1, 2 });
|
||||
q.f({ 0, 0 });
|
||||
kv.f({ 3, 5, 1000, -1000, 1, 0, 0, 1 });
|
||||
bt.n({ 1, 0 });
|
||||
len.n({ 3 });
|
||||
A a;
|
||||
a.t(q)
|
||||
.t(kv)
|
||||
.t(bt)
|
||||
.t(len)
|
||||
.t(out)
|
||||
.i("M", 7)
|
||||
.i("latent_dim", 2)
|
||||
.i("heads", 1)
|
||||
.i("blocks", 2)
|
||||
.i("block_size", 2)
|
||||
.d("scale", 1)
|
||||
.s("dtype", "f32");
|
||||
REQUIRE_EQ(run("mla_attn", a), RAD_OK);
|
||||
CHECK_NEAR(out.at(0), 4.0 / 3, 1e-6);
|
||||
CHECK_EQ(out.at(1), 2);
|
||||
q.f({ std::log(3.0f), 0 });
|
||||
kv.f({ 0, 0, 1000, -1000, 1, 0, 0, 0 });
|
||||
len.n({ 2 });
|
||||
REQUIRE_EQ(run("mla_attn", a), RAD_OK);
|
||||
CHECK_NEAR(out.at(0), 0.75, 1e-6);
|
||||
CHECK_EQ(out.at(1), 0);
|
||||
len.n({ 0 });
|
||||
REQUIRE_EQ(run("mla_attn", a), RAD_OK);
|
||||
CHECK_EQ(out.at(0), 0);
|
||||
CHECK_EQ(out.at(1), 0);
|
||||
len.n({ 3 });
|
||||
bt.n({ -1, 99 });
|
||||
REQUIRE_EQ(run("mla_attn", a), RAD_OK);
|
||||
CHECK_EQ(out.at(0), 0);
|
||||
CHECK_EQ(out.at(1), 0);
|
||||
}
|
||||
|
||||
TEST(dsa_score_relu_is_per_head_before_signed_weights_and_masks_invalid_history) {
|
||||
T q(RAD_F8E4M3, { 2, 2, 2 }), qs(RAD_F32, { 2, 2 }), gate(RAD_F32, { 2, 2 });
|
||||
T k(RAD_F8E4M3, { 3, 2 }), ks(RAD_F32, { 3 }), bt(RAD_I32, { 2, 3 });
|
||||
T cu(RAD_I32, { 3 }), nc(RAD_I32, { 2 }), out(RAD_F32, { 2, 3 });
|
||||
q.f({ 1, 0, 0, 1, -1, 0, 0, -1 });
|
||||
qs.f({ 2, 0.5, 1, 1 });
|
||||
gate.f({ -1, 4, 2, -1 });
|
||||
k.f({ 1, -1, 2, 3, -2, -4 });
|
||||
ks.f({ 0.25, 0.5, 1 });
|
||||
bt.n({ 0, 1, -1, 2, 0, 1 });
|
||||
cu.n({ 0, 1, 2 });
|
||||
nc.n({ 2, 1 });
|
||||
A a;
|
||||
a.t(q)
|
||||
.t(qs)
|
||||
.t(gate)
|
||||
.t(k)
|
||||
.t(ks)
|
||||
.t(bt)
|
||||
.t(cu)
|
||||
.t(nc)
|
||||
.t(out)
|
||||
.i("M", 9)
|
||||
.i("n", 2)
|
||||
.i("heads", 2)
|
||||
.i("blocks", 3)
|
||||
.i("seqs", 2)
|
||||
.s("dtype", "fp8_e4m3");
|
||||
REQUIRE_EQ(run("dsa_score", a), RAD_OK);
|
||||
CHECK_EQ(out.at(0), -0.25f);
|
||||
CHECK_EQ(out.at(1), 0.5f);
|
||||
CHECK_EQ(out.at(3), 0);
|
||||
for (int i : { 2, 4, 5 }) CHECK_EQ(out.at(i), -INFINITY);
|
||||
bt.n({ 99, 1, -1, 2, 0, 1 });
|
||||
REQUIRE_EQ(run("dsa_score", a), RAD_OK);
|
||||
CHECK_EQ(out.at(0), -INFINITY);
|
||||
}
|
||||
|
||||
TEST(kda_anchor_replays_only_the_accepted_prefix_of_the_previous_window) {
|
||||
constexpr int D = 128;
|
||||
for (int accepted : { 1, 2, 3 }) {
|
||||
T q(RAD_BF16, { 3, 1, D }), k(RAD_BF16, { 3, 1, D }), v(RAD_BF16, { 3, 1, D }),
|
||||
g(RAD_BF16, { 3, 1, D });
|
||||
T beta(RAD_BF16, { 3, 1 }), al(RAD_F32, { 1 }), bias(RAD_F32, { D });
|
||||
T anchor(RAD_F32, { 2, 1, D, D }), candidate(RAD_F32, { 3, 1, D, D });
|
||||
T ai(RAD_I32, { 1, 6 }), ci(RAD_I32, { 1, 3 }), cu(RAD_I32, { 2 }), na(RAD_I32, { 1 }),
|
||||
init(RAD_I32, { 1 });
|
||||
T ao(RAD_BF16, { 3, 1, D }), co(RAD_BF16, { 3, 1, D });
|
||||
std::vector<float> values(3 * D);
|
||||
for (int j = 0; j < 3 * D; ++j) values[j] = (float)(j % 17 - 8) * 0.125f;
|
||||
q.f(values);
|
||||
v.f(values);
|
||||
for (int j = 0; j < 3 * D; ++j) values[j] = (float)(j % 11 - 5) * 0.25f;
|
||||
k.f(values);
|
||||
g.f(std::vector<float>(3 * D, 0));
|
||||
beta.f({ 0, 0.5f, -0.5f });
|
||||
al.f({ 0 });
|
||||
bias.f(std::vector<float>(D, -1));
|
||||
anchor.f(std::vector<float>(2 * D * D, 0));
|
||||
candidate.f(std::vector<float>(3 * D * D, 0));
|
||||
ai.n({ 0, 0, 0, 1, 1, 1 });
|
||||
ci.n({ 0, 1, 2 });
|
||||
cu.n({ 0, 3 });
|
||||
na.n({ 1 });
|
||||
init.n({ 1 });
|
||||
A a;
|
||||
a.t(q)
|
||||
.t(k)
|
||||
.t(v)
|
||||
.t(g)
|
||||
.t(beta)
|
||||
.t(al)
|
||||
.t(bias)
|
||||
.t(anchor)
|
||||
.t(ai)
|
||||
.t(cu)
|
||||
.t(na)
|
||||
.t(init)
|
||||
.t(ao)
|
||||
.i("M", 3)
|
||||
.i("heads", 1)
|
||||
.i("head_k", D)
|
||||
.i("head_v", D)
|
||||
.d("lower_bound", -5)
|
||||
.d("scale", 1.0 / std::sqrt(128.0))
|
||||
.d("l2_eps", 1e-6)
|
||||
.s("mode", "verify")
|
||||
.s("dtype", "bf16")
|
||||
.s("state_form", "anchor");
|
||||
A c;
|
||||
c.t(q)
|
||||
.t(k)
|
||||
.t(v)
|
||||
.t(g)
|
||||
.t(beta)
|
||||
.t(al)
|
||||
.t(bias)
|
||||
.t(candidate)
|
||||
.t(ci)
|
||||
.t(cu)
|
||||
.t(na)
|
||||
.t(init)
|
||||
.t(co)
|
||||
.i("M", 3)
|
||||
.i("heads", 1)
|
||||
.i("head_k", D)
|
||||
.i("head_v", D)
|
||||
.d("lower_bound", -5)
|
||||
.d("scale", 1.0 / std::sqrt(128.0))
|
||||
.d("l2_eps", 1e-6)
|
||||
.s("mode", "verify")
|
||||
.s("dtype", "bf16");
|
||||
REQUIRE_EQ(run("kda_update", a), RAD_OK);
|
||||
REQUIRE_EQ(run("kda_update", c), RAD_OK);
|
||||
for (int j = 0; j < 3 * D; ++j) CHECK_EQ(ao.at(j), co.at(j));
|
||||
for (int j = 0; j < D * D; ++j) CHECK_EQ(anchor.at(j), 0);
|
||||
std::vector<float> committed(D * D);
|
||||
for (int j = 0; j < D * D; ++j) committed[j] = candidate.at((accepted - 1) * D * D + j);
|
||||
na.n({ accepted });
|
||||
REQUIRE_EQ(run("kda_update", a), RAD_OK);
|
||||
REQUIRE_EQ(run("kda_update", c), RAD_OK);
|
||||
for (int j = 0; j < 3 * D; ++j) CHECK_EQ(ao.at(j), co.at(j));
|
||||
for (int j = 0; j < D * D; ++j) CHECK_EQ(anchor.at(j), committed[j]);
|
||||
const auto saved = anchor.mem;
|
||||
na.n({ 4 });
|
||||
CHECK_EQ(run("kda_update", a), RAD_E_SHAPE);
|
||||
CHECK(anchor.mem == saved);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(mla_projects_the_key_and_value_halves_with_opposite_orientations) {
|
||||
T q(RAD_BF16, { 1, 2, 2 }), w(RAD_BF16, { 8, 3 }), latent(RAD_BF16, { 1, 2, 3 }),
|
||||
out(RAD_BF16, { 1, 2, 2 });
|
||||
q.f({ 2, -1, 3, 1 });
|
||||
w.f({ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, -1, 0, 1, 2, 0, -2, 2, 3, 4, 5, 6, 7 });
|
||||
A a;
|
||||
a.t(q)
|
||||
.t(w)
|
||||
.t(latent)
|
||||
.i("M", 7)
|
||||
.i("heads", 2)
|
||||
.i("head_dim", 2)
|
||||
.i("latent_dim", 3)
|
||||
.s("mode", "absorb")
|
||||
.s("dtype", "bf16");
|
||||
REQUIRE_EQ(run("mla_project", a), RAD_OK);
|
||||
CHECK_EQ(latent.at(0), -2);
|
||||
CHECK_EQ(latent.at(1), -1);
|
||||
CHECK_EQ(latent.at(2), 0);
|
||||
CHECK_EQ(latent.at(3), -1);
|
||||
CHECK_EQ(latent.at(4), 0);
|
||||
CHECK_EQ(latent.at(5), 1);
|
||||
A b;
|
||||
b.t(latent)
|
||||
.t(w)
|
||||
.t(out)
|
||||
.i("M", 7)
|
||||
.i("heads", 2)
|
||||
.i("head_dim", 2)
|
||||
.i("latent_dim", 3)
|
||||
.s("mode", "expand")
|
||||
.s("dtype", "bf16");
|
||||
REQUIRE_EQ(run("mla_project", b), RAD_OK);
|
||||
CHECK_EQ(out.at(0), -22);
|
||||
CHECK_EQ(out.at(1), -31);
|
||||
CHECK_EQ(out.at(2), 2);
|
||||
CHECK_EQ(out.at(3), 2);
|
||||
auto flatten = [](RadTensor& t) {
|
||||
t.rank = 2;
|
||||
t.shape[1] *= t.shape[2];
|
||||
t.stride[1] = t.stride[2];
|
||||
};
|
||||
flatten(a.ts[0]);
|
||||
flatten(a.ts[2]);
|
||||
REQUIRE_EQ(run("mla_project", a), RAD_OK);
|
||||
flatten(b.ts[0]);
|
||||
flatten(b.ts[2]);
|
||||
REQUIRE_EQ(run("mla_project", b), RAD_OK);
|
||||
CHECK_EQ(out.at(0), -22);
|
||||
CHECK_EQ(out.at(1), -31);
|
||||
CHECK_EQ(out.at(2), 2);
|
||||
CHECK_EQ(out.at(3), 2);
|
||||
}
|
||||
|
||||
TEST(moe_gather_preserves_f32_mixture_weights_between_bf16_expert_outputs) {
|
||||
T experts(RAD_BF16, { 2, 1 }), weights(RAD_F32, { 1, 2 }), sorted(RAD_I32, { 2 }),
|
||||
out(RAD_BF16, { 1, 1 });
|
||||
experts.f({ 1024, -1024 });
|
||||
weights.f({ 1.0f + 1.0f / 8192, 1 });
|
||||
sorted.n({ 0, 1 });
|
||||
A a;
|
||||
a.t(experts)
|
||||
.t(weights)
|
||||
.t(sorted)
|
||||
.tnull()
|
||||
.tnull()
|
||||
.t(out)
|
||||
.i("M", 1)
|
||||
.i("n", 1)
|
||||
.i("top_k", 2)
|
||||
.s("dtype", "bf16");
|
||||
REQUIRE_EQ(run("moe_gather", a), RAD_OK);
|
||||
CHECK_EQ(out.at(0), 0.125f);
|
||||
}
|
||||
|
||||
TEST(dsa_query_normalizes_the_rotation_and_rounds_power_of_two_scales) {
|
||||
T x(RAD_BF16, { 1, 4 }), q(RAD_F8E4M3, { 1, 4 }), scale(RAD_F32, { 1, 1 });
|
||||
A a;
|
||||
a.t(x).t(q).t(scale).i("M", 7).i("n", 4).s("dtype", "bf16");
|
||||
x.f({ 3, 4, 7, 7 });
|
||||
REQUIRE_EQ(run("dsa_query", a), RAD_OK);
|
||||
CHECK_EQ(scale.at(0), 1.0f / 32);
|
||||
CHECK_EQ(q.at(0), 320);
|
||||
CHECK_EQ(q.at(1), -16);
|
||||
CHECK_EQ(q.at(2), -112);
|
||||
CHECK_EQ(q.at(3), -16);
|
||||
for (float v : { 0.0f, 224.0f, 225.0f }) {
|
||||
x.f({ v, v, v, v });
|
||||
REQUIRE_EQ(run("dsa_query", a), RAD_OK);
|
||||
CHECK_EQ(scale.at(0), v == 0 ? std::ldexp(1.0f, -22) : v == 224 ? 1.0f : 2.0f);
|
||||
CHECK_EQ(q.at(0), v == 0 ? 0 : v == 224 ? 448 : 224);
|
||||
for (int d = 1; d < 4; ++d) CHECK_EQ(q.at(d), 0);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(f32_projection_preserves_small_weight_differences_and_output_bits) {
|
||||
T x(RAD_BF16, { 1, 2 }), w(RAD_F32, { 2, 2 }), y(RAD_F32, { 1, 2 });
|
||||
x.f({ 1, -1 });
|
||||
w.f({ 1.0001f, 1.0f, 2.0002f, 2.0f });
|
||||
A a;
|
||||
a.t(x).t(w).t(y).i("M", 7).i("N", 2).i("K", 2).s("dtype", "bf16");
|
||||
REQUIRE_EQ(run("gemm_nt_f32", a), RAD_OK);
|
||||
CHECK_EQ(y.at(0), 1.0001f - 1.0f);
|
||||
CHECK_EQ(y.at(1), 2.0002f - 2.0f);
|
||||
}
|
||||
|
||||
TEST(dsa_pool_writes_paged_codes_and_scales_and_the_scorer_reads_them) {
|
||||
T kg(RAD_BF16, { 12, 256 }), ape(RAD_F32, { 4, 128 }), q(RAD_F8E4M3, { 3, 128 }),
|
||||
scales(RAD_F32, { 3, 1 });
|
||||
T pages(RAD_I32, { 3 }), cache(RAD_U8, { 4, 1, 4, 34 });
|
||||
std::vector<float> input(12 * 256, 0);
|
||||
for (int r = 0; r < 12; ++r)
|
||||
for (int d = 0; d < 128; ++d) input[r * 256 + d] = 1;
|
||||
kg.f(input);
|
||||
ape.f(std::vector<float>(512, 0));
|
||||
pages.n({ 2, -1, 9 });
|
||||
std::fill(cache.mem.begin(), cache.mem.end(), 0xa5);
|
||||
A pool;
|
||||
pool.t(kg)
|
||||
.t(ape)
|
||||
.t(q)
|
||||
.t(scales)
|
||||
.t(pages)
|
||||
.t(cache)
|
||||
.i("M", 3)
|
||||
.i("n", 128)
|
||||
.i("ratio", 4)
|
||||
.s("dtype", "bf16");
|
||||
REQUIRE_EQ(run("dsa_pool", pool), RAD_OK);
|
||||
for (int i = 0; i < 4 * 136; ++i)
|
||||
if (i >= 2 * 136 && i < 2 * 136 + 128)
|
||||
CHECK_EQ(cache.mem[i], q.mem[i - 2 * 136]);
|
||||
else if (i < 2 * 136 + 128 || i >= 2 * 136 + 132)
|
||||
CHECK_EQ(cache.mem[i], 0xa5);
|
||||
float stored = 0;
|
||||
std::memcpy(&stored, cache.mem.data() + 2 * 136 + 128, sizeof(stored));
|
||||
CHECK_EQ(stored, scales.at(0));
|
||||
T query(RAD_F8E4M3, { 1, 32, 128 }), qs(RAD_F32, { 1, 32 }), gate(RAD_F32, { 1, 32 });
|
||||
query.f(std::vector<float>(32 * 128, 1));
|
||||
qs.f(std::vector<float>(32, 1));
|
||||
gate.f(std::vector<float>(32, 1));
|
||||
T bt(RAD_I32, { 1, 3 }), cu(RAD_I32, { 2 }), nc(RAD_I32, { 1 }), out(RAD_F32, { 1, 3 });
|
||||
bt.n({ 2, -1, 9 });
|
||||
cu.n({ 0, 1 });
|
||||
nc.n({ 3 });
|
||||
A score;
|
||||
score.t(query)
|
||||
.t(qs)
|
||||
.t(gate)
|
||||
.t(cache)
|
||||
.tnull()
|
||||
.t(bt)
|
||||
.t(cu)
|
||||
.t(nc)
|
||||
.t(out)
|
||||
.i("M", 1)
|
||||
.i("n", 128)
|
||||
.i("heads", 32)
|
||||
.i("blocks", 3)
|
||||
.i("seqs", 1)
|
||||
.s("dtype", "fp8_e4m3");
|
||||
REQUIRE_EQ(run("dsa_score", score), RAD_OK);
|
||||
CHECK_EQ(out.at(0), 5.5f);
|
||||
CHECK(std::isinf(out.at(1)) && out.at(1) < 0);
|
||||
CHECK(std::isinf(out.at(2)) && out.at(2) < 0);
|
||||
}
|
||||
|
||||
TEST(dsa_pool_uses_channel_gates_bf16_boundaries_and_power_of_two_scales) {
|
||||
T kg(RAD_BF16, { 2, 8 }), ape(RAD_F32, { 2, 4 }), q(RAD_F8E4M3, { 1, 4 }),
|
||||
scale(RAD_F32, { 1, 1 });
|
||||
kg.f({ 0, 2, 4, 6, 0, 0, 0, 0, 4, 6, 8, 10, 0, 0, 0, 0 });
|
||||
ape.f({ 0, 0, 0, 0, std::log(3.0f), 0, std::log(3.0f), -std::log(3.0f) });
|
||||
A a;
|
||||
a.t(kg).t(ape).t(q).t(scale).i("M", 7).i("n", 4).i("ratio", 2).s("dtype", "bf16");
|
||||
REQUIRE_EQ(run("dsa_pool", a), RAD_OK);
|
||||
// Pooled [3,4,7,7]; H4/sqrt(4) = [10.5,-.5,-3.5,-.5].
|
||||
// 10.5*32=336 is the FP8 midpoint 320/352, rounded to even 320.
|
||||
CHECK_EQ(scale.at(0), 1.0f / 32);
|
||||
CHECK_EQ(q.at(0), 320);
|
||||
CHECK_EQ(q.at(1), -16);
|
||||
CHECK_EQ(q.at(2), -112);
|
||||
CHECK_EQ(q.at(3), -16);
|
||||
ape.f(std::vector<float>(8, 0));
|
||||
for (float key : { 0.0f, 224.0f, 225.0f }) {
|
||||
kg.f({ key, key, key, key, 0, 0, 0, 0, key, key, key, key, 0, 0, 0, 0 });
|
||||
REQUIRE_EQ(run("dsa_pool", a), RAD_OK);
|
||||
CHECK_EQ(scale.at(0), key == 0 ? std::ldexp(1.0f, -22) : key == 224 ? 1.0f : 2.0f);
|
||||
CHECK_EQ(q.at(0), key == 0 ? 0 : key == 224 ? 448 : 224);
|
||||
for (int i = 1; i < 4; ++i) CHECK_EQ(q.at(i), 0);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(swiglu_clamping_is_asymmetric_and_precedes_the_activation) {
|
||||
T gu(RAD_F32, { 1, 12 }), y(RAD_F32, { 1, 6 });
|
||||
gu.f({ -20, -2, 0, 2, 10, 20, -20, 20, 20, -20, 20, 20 });
|
||||
A a;
|
||||
a.t(gu).t(y).i("M", 9).i("n", 6).d("limit", 10).s("dtype", "f32");
|
||||
REQUIRE_EQ(run("swiglu_clamped", a), RAD_OK);
|
||||
const float gate[] = { -20, -2, 0, 2, 10, 10 }, up[] = { -10, 10, 10, -10, 10, 10 };
|
||||
for (int i = 0; i < 6; ++i)
|
||||
CHECK_NEAR(y.at(i), (gate[i] / (1 + std::exp(-gate[i]))) * up[i], 1e-5);
|
||||
CHECK(y.at(0) > 0 && y.at(0) < 1e-5); // a negative gate must not clamp to -10
|
||||
CHECK_EQ(y.at(4), y.at(5));
|
||||
A bad;
|
||||
bad.t(gu).t(y).i("M", 1).i("n", 6).d("limit", 0).s("dtype", "f32");
|
||||
CHECK_EQ(run("swiglu_clamped", bad), RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
TEST(sigmoid_router_uses_correction_only_for_selection_and_stable_ties) {
|
||||
T lg(RAD_F32, { 1, 4 }), bias(RAD_F32, { 4 }), ids(RAD_I32, { 1, 2 }), w(RAD_F32, { 1, 2 });
|
||||
lg.f({ -std::log(3.0f), std::log(3.0f), 0, 0 });
|
||||
bias.f({ 1, -1, 0, 0 });
|
||||
for (int norm : { 0, 1 }) {
|
||||
A a;
|
||||
a.t(lg)
|
||||
.t(bias)
|
||||
.t(ids)
|
||||
.t(w)
|
||||
.i("M", 9)
|
||||
.i("n_expert", 4)
|
||||
.i("top_k", 2)
|
||||
.i("norm", norm)
|
||||
.d("route_scale", 2.5)
|
||||
.s("dtype", "f32");
|
||||
REQUIRE_EQ(run("router_sigmoid_topk", a), RAD_OK);
|
||||
CHECK_EQ(ids.at(0), 0);
|
||||
CHECK_EQ(ids.at(1), 2);
|
||||
CHECK_NEAR(w.at(0), norm ? 2.5 / 3 : 0.625, 1e-6);
|
||||
CHECK_NEAR(w.at(1), norm ? 5.0 / 3 : 1.25, 1e-6);
|
||||
}
|
||||
lg.f({ 0, 0, 0, 0 });
|
||||
bias.f({ 0, 0, 0, 0 });
|
||||
A tie;
|
||||
tie.t(lg)
|
||||
.t(bias)
|
||||
.t(ids)
|
||||
.t(w)
|
||||
.i("M", 1)
|
||||
.i("n_expert", 4)
|
||||
.i("top_k", 2)
|
||||
.i("norm", 1)
|
||||
.d("route_scale", 2.5)
|
||||
.s("dtype", "f32");
|
||||
REQUIRE_EQ(run("router_sigmoid_topk", tie), RAD_OK);
|
||||
CHECK_EQ(ids.at(0), 0);
|
||||
CHECK_EQ(ids.at(1), 1);
|
||||
CHECK_EQ(w.at(0), 1.25f);
|
||||
CHECK_EQ(w.at(1), 1.25f);
|
||||
}
|
||||
|
||||
TEST(grouped_mxfp4_preserves_e2m1_codes_and_e8m0_scales) {
|
||||
T input(RAD_F8E4M3, { 2, 64 });
|
||||
std::vector<float> values(128, 1.0f);
|
||||
for (int i = 64; i < 128; ++i) values[(size_t)i] = 2;
|
||||
input.f(values);
|
||||
T as(RAD_F32, { 2, 1 });
|
||||
as.f({ 0.5f, 0.5f });
|
||||
T even(RAD_FP4E2M1, { 1, 1, 64 });
|
||||
even.raw(std::vector<uint8_t>(32, 0x22));
|
||||
T odd(RAD_FP4E2M1, { 1, 1, 64 });
|
||||
odd.raw(std::vector<uint8_t>(32, 0x33));
|
||||
T es(RAD_U8, { 1, 1, 2 });
|
||||
es.raw({ 127, 128 });
|
||||
T os(RAD_U8, { 1, 1, 2 });
|
||||
os.raw({ 126, 127 });
|
||||
T sorted(RAD_I32, { 2 });
|
||||
sorted.n({ 1, 0 });
|
||||
T offsets(RAD_I32, { 3 });
|
||||
offsets.n({ 0, 1, 2 });
|
||||
T out(RAD_BF16, { 2, 1 });
|
||||
A a;
|
||||
a.t(input)
|
||||
.t(as)
|
||||
.t(even)
|
||||
.t(es)
|
||||
.t(sorted)
|
||||
.t(offsets)
|
||||
.t(odd)
|
||||
.t(os)
|
||||
.t(out)
|
||||
.i("M", 2)
|
||||
.i("N", 1)
|
||||
.i("K", 64)
|
||||
.i("n_expert", 2)
|
||||
.i("top_k", 1)
|
||||
.i("group", 64)
|
||||
.s("a_order", "token")
|
||||
.s("dtype", "mxfp4a8");
|
||||
REQUIRE_EQ(run("moe_gemm_q", a), RAD_OK);
|
||||
/* E2M1 0x2=1, 0x3=1.5. The second half of each row has its own power-of-two scale. */
|
||||
CHECK_EQ(out.at(0), 96.0f);
|
||||
CHECK_EQ(out.at(1), 36.0f);
|
||||
a.strs.emplace_back("sorted");
|
||||
a.ps[6].sval = a.strs.back().c_str();
|
||||
REQUIRE_EQ(run("moe_gemm_q", a), RAD_OK);
|
||||
CHECK_EQ(out.at(0), 48.0f);
|
||||
CHECK_EQ(out.at(1), 72.0f);
|
||||
/* Each expert may have a separate address, including host-resident weights. */
|
||||
void* wp0[] = { even.t.data };
|
||||
void* wp1[] = { odd.t.data };
|
||||
void* sp0[] = { es.t.data };
|
||||
void* sp1[] = { os.t.data };
|
||||
const int operands[] = { 2, 3, 6, 7 };
|
||||
void* tables[] = { wp0, sp0, wp1, sp1 };
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
a.ts[(size_t)operands[i]].data = tables[i];
|
||||
a.ts[(size_t)operands[i]].stride[0] = 0;
|
||||
}
|
||||
a.ts[3].dtype = a.ts[7].dtype = RAD_E8M0;
|
||||
REQUIRE_EQ(run("moe_gemm_q", a), RAD_OK);
|
||||
CHECK_EQ(out.at(0), 48.0f);
|
||||
CHECK_EQ(out.at(1), 72.0f);
|
||||
}
|
||||
|
||||
/* ================================================================== the plugin surface */
|
||||
TEST(plugin_surface) {
|
||||
CHECK(api().abi_version != nullptr);
|
||||
@@ -255,6 +918,8 @@ TEST(plugin_surface) {
|
||||
TEST(op_vocabulary) {
|
||||
static const char* kOps[] = {
|
||||
"rmsnorm", "rmsnorm_p", "rmsnorm_add", "hc_enter", "hc_read", "hc_write", "mtp_enter",
|
||||
"mhc_pre", "mhc_pre_partial", "mhc_pre_finish", "mhc_post", "mhc_contract", "swiglu_clamped", "router_sigmoid_topk", "dsa_pool", "dsa_query", "dsa_score", "mla_attn", "mla_project", "gemm_nt_f32",
|
||||
"kda_update",
|
||||
"layernorm", "add", "mul", "mul_weight", "silu_mul", "gelu_mul", "act_mul", "seg_mean",
|
||||
"pool_rows", "relu", "clamp", "conv2d", "conv2d_unfold", "conv1d_dw", "rel_sinusoid",
|
||||
"seg_sinusoid", "attn_local_rel", "gelu", "silu", "sigmoid", "logit_softcap", "scale",
|
||||
@@ -3316,7 +3981,7 @@ TEST(op_moe_gemm_q_scale_grid_by_dtype) {
|
||||
/* N 256, K 512, group 128; the last class at N 128, K 256. */
|
||||
const Want wants[] = { { "fp8a8", 2, 4 }, { "w4a8", 256, 4 }, { "w4a8h", 256, 4 },
|
||||
{ "w4nla8h", 256, 4 }, { "w4nl64a8h", 256, 8 }, { "w5nl64a8h", 256, 8 },
|
||||
{ "w4nl32a8h", 256, 16 } };
|
||||
{ "w4nl32a8h", 256, 16 }, { "mxfp4a8", 256, 16 } };
|
||||
for (const char* op : { "moe_gemm_q", "moe_gemm_q_mod4" }) {
|
||||
const RadKernelInfo* k = kern(op);
|
||||
REQUIRE(k != nullptr && k->opd_shape != nullptr);
|
||||
@@ -3332,7 +3997,7 @@ TEST(op_moe_gemm_q_scale_grid_by_dtype) {
|
||||
RadOpdDesc d{}, dl{};
|
||||
REQUIRE_EQ(k->opd_shape(r->p, r->n_p, 3, &d), RAD_OK);
|
||||
REQUIRE_EQ(k->opd_shape(r->p, r->n_p, last, &dl), RAD_OK);
|
||||
CHECK_EQ(d.dtype, (uint32_t)RAD_BF16);
|
||||
CHECK_EQ(d.dtype, !std::strcmp(w.dt, "mxfp4a8") ? (uint32_t)RAD_U8 : (uint32_t)RAD_BF16);
|
||||
CHECK_EQ(d.rank, 3u);
|
||||
CHECK_EQ(d.shape[0], four ? 2LL : 4LL);
|
||||
if (d.shape[1] != w.rows || d.shape[2] != w.cols)
|
||||
@@ -3402,7 +4067,7 @@ TEST(op_moe_gemm_q_scale_grid_by_dtype) {
|
||||
for (const char* op : { "moe_gemm_q", "moe_gemm_q_mod4" }) {
|
||||
const RadKernelInfo* k = kern(op);
|
||||
REQUIRE(k != nullptr && k->opd_shape != nullptr);
|
||||
for (const char* dt : { "w8a8", "mxfp4a8", "" }) {
|
||||
for (const char* dt : { "w8a8", "invalid", "" }) {
|
||||
A a;
|
||||
a.i("M", 2).i("N", 256).i("K", 512).i("n_expert", 8).i("top_k", 2).i("group", 128)
|
||||
.s("a_order", "token");
|
||||
@@ -7038,6 +7703,30 @@ std::vector<Geo> geometries() {
|
||||
G("attn_prefix_self", "q_len", 3, a.i("q_len", R).i("head_dim", 8).i("gqa", 2)
|
||||
.i("block_size", 4).i("causal", 1).s("q_dtype", "bf16")
|
||||
.s("kv_dtype", "bf16").i("n_head", 4).i("ctx", 5)),
|
||||
G("mhc_pre", "M", 3, a.i("M", R).i("n", 8).i("hc", 4).i("iterations", 20).d("eps", 1e-5)
|
||||
.d("hc_eps", 1e-6).s("dtype", "f32")),
|
||||
G("mhc_pre_partial", "M", 3, a.i("M", R).i("n", 8).i("hc", 4).i("chunk", 8).i("first", 1)
|
||||
.i("chunks", 2).s("dtype", "f32")),
|
||||
G("mhc_pre_finish", "M", 3, a.i("M", R).i("n", 8).i("hc", 4).i("iterations", 20)
|
||||
.d("eps", 1e-5).d("hc_eps", 1e-6).i("chunk", 8)
|
||||
.s("dtype", "f32")),
|
||||
G("mhc_post", "M", 3, a.i("M", R).i("n", 8).i("hc", 4).s("dtype", "f32")),
|
||||
G("mhc_contract", "M", 3, a.i("M", R).i("n", 8).i("hc", 4).s("dtype", "f32")),
|
||||
G("kda_update", "M", 3, a.i("M", R).i("heads", 2).i("head_k", 8).i("head_v", 8)
|
||||
.d("lower_bound", -5.0).d("scale", 0.35).d("l2_eps", 1e-6)
|
||||
.s("mode", "prefill").s("dtype", "f32")),
|
||||
G("mla_attn", "M", 3, a.i("M", R).i("latent_dim", 8).i("heads", 2).i("blocks", 2)
|
||||
.i("block_size", 4).d("scale", 0.125).s("dtype", "f32")),
|
||||
G("mla_project", "M", 3, a.i("M", R).i("heads", 2).i("head_dim", 4).i("latent_dim", 6)
|
||||
.s("mode", "absorb").s("dtype", "bf16")),
|
||||
G("dsa_score", "M", 4, a.i("M", R).i("n", 8).i("heads", 2).i("blocks", 3).i("seqs", 2)
|
||||
.s("dtype", "fp8_e4m3")),
|
||||
G("dsa_pool", "M", 3, a.i("M", R).i("n", 8).i("ratio", 4).s("dtype", "bf16")),
|
||||
G("dsa_query", "M", 3, a.i("M", R).i("n", 8).s("dtype", "bf16")),
|
||||
G("gemm_nt_f32", "M", 3, a.i("M", R).i("N", 20).i("K", 40).s("dtype", "bf16")),
|
||||
G("swiglu_clamped", "M", 3, a.i("M", R).i("n", 8).d("limit", 0.5).s("dtype", "f32")),
|
||||
G("router_sigmoid_topk", "M", 3, a.i("M", R).i("n_expert", 6).i("top_k", 2).i("norm", 1)
|
||||
.d("route_scale", 2.5).s("dtype", "f32")),
|
||||
G("conv1d", "M", 8, a.i("M", R).i("cin", 2).i("cout", 3).i("k", 3).i("dil", 1)
|
||||
.s("dtype", "f32")),
|
||||
G("conv_t1d", "M", 8, a.i("M", R).i("cin", 2).i("cout", 3).i("stride", 2).s("dtype", "f32")),
|
||||
|
||||
Reference in new issue
Block a user