Archived
libref: swiglu_step, router_sigmoid_group_topk and mla_attn_paged
Three ops Ling-3.0 needs, with their references, OPS.md entries and ref_test cases. swiglu_step is the SwiGLU clipped after the SiLU, as vLLM and SGLang serve Ling-3.0. router_sigmoid_group_topk is noaux_tc routing with groups: a group ranks by the sum of its two best biased scores and only the best groups' experts are candidates. mla_attn_paged is dense causal latent attention over a paged cache whose row is the latent then the rotated key part, with an optional head-wise sigmoid gate; it refuses zero rows and reads a gate row at the gate's own pitch.
This commit is contained in:
1 parent
9c5d4a656c
commit
7169c9da0a
7 files changed
+365
-2
No files matched your search
+32
-2
@@ -209,6 +209,7 @@ at once. Run it before adding a kernel plugin; the loader names only the first c
|
||||
| `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` |
|
||||
| `swiglu_step` | `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) |
|
||||
@@ -266,6 +267,12 @@ clip.
|
||||
libr4d's `swiglu_clamped_bf16` serves bf16 in and out at any width, pitched rows, `M` up to
|
||||
65535.
|
||||
|
||||
`swiglu_step` clips in the other order, as Ling-3.0 is served by vLLM and SGLang (vLLM's
|
||||
`SwigluStepAndMul`): `min(silu(gate), limit) * clamp(up, -limit, limit)` in f32, rounded once. The
|
||||
SiLU is taken first and its value clipped above, so a gate far past `limit` gives exactly `limit`
|
||||
where `swiglu_clamped` gives `silu(limit)` (3.93 at a limit of 4). HF's reference model for Ling-3.0
|
||||
ignores the clamp; the served form is the one checkpoints are evaluated with.
|
||||
|
||||
**`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
|
||||
@@ -2062,6 +2069,7 @@ The VAEs' convolutions are `conv3d_ndhwc` with `tpad` and the audio VAE's `conv2
|
||||
| `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` |
|
||||
| `router_sigmoid_group_topk` | `M`(range) `n_expert` `top_k` `n_group` `topk_group` `norm` `route_scale`:f64 `dtype` | `logits`, `bias`w → `ids`, `weights` |
|
||||
| `router_sigmoid_topk_scatter` | `M`(range) `n_expert` `n_local`/opt `top_k` `norm` `route_scale`:f64 `dtype` `expert_base`/opt `protect`:str/opt | `logits`, `bias`w → `ids`, `weights`, `sorted_tok`, `expert_offset`, `expert_count`, `gate`?, `inverse`? |
|
||||
| `moe_scatter_inv` | `M`(range) `n_expert` `top_k` `expert_base`/opt `protect`:str/opt | `expert_ids` → `sorted_tok`, `expert_offset`, `expert_count`, `inverse` |
|
||||
| `moe_gather_inv` | `M`(range) `n` `top_k` `dtype` `act`:str/opt | `y_expert`, `expert_w`, `inverse`, `shared`?, `shared_gate`? → `y` |
|
||||
@@ -2191,8 +2199,8 @@ expert, and the weights are the selected `p`, never the biased ranks. With `norm
|
||||
`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.
|
||||
Grouped selection (`n_group > 1`) is `router_sigmoid_group_topk`, below. GLM-5.3 routes 8 of 288
|
||||
experts in one group with `route_scale` 2.5.
|
||||
|
||||
libr4d's `router_sigmoid_topk_f32` takes up to 512 experts and `top_k` up to 32, f32 logits, bias
|
||||
and weights, i32 ids, pitched rows, `M` up to 65535. It selects in one wave per row: each lane
|
||||
@@ -2201,6 +2209,12 @@ takes the largest key below round `j-1`'s winner. A row without NaN ranks gives
|
||||
serial scan with a strict `>`. A NaN rank is never selected, and a row with fewer than `top_k`
|
||||
other ranks names expert 0 in its empty slots, weighted by expert 0's `p`.
|
||||
|
||||
**`router_sigmoid_group_topk`** is the group-limited form (DeepSeek-V3's `noaux_tc` with
|
||||
`n_group > 1`, Ling-3.0's 8 groups of 64 experts, 4 kept). The experts fall into `n_group` equal
|
||||
groups of at least two; a group's rank is the sum of its two largest `p + bias`; the `topk_group`
|
||||
best groups are kept, ties to the lower group; the selection is `router_sigmoid_topk`'s over the
|
||||
kept groups' experts only, and the weights are the same. `top_k` is at most the kept experts.
|
||||
|
||||
**`router_sigmoid_topk_scatter`** (device-only) is `router_sigmoid_topk` and `moe_scatter` over its
|
||||
`ids` in one launch, and with `gate` `[M, 1]` also the `fill` of an ungated shared arm's gate with
|
||||
1 (GLM-5.3's shared expert has no gate, and the gather reads one). `n_expert`, `n_local`,
|
||||
@@ -2941,6 +2955,7 @@ order, not a slow one.
|
||||
| `dsa_query` | `M`(range) `n` `dtype` | `x` → `q`, `scale` |
|
||||
| `dsa_score` | `M`(range) `n` `heads` `blocks` `seqs` `dtype` `row_part`/opt | `q`, `q_scale`, `gate`, `k`, `k_scale`?, `bt`, `cu`, `nc` → `score`, `cu_part`? |
|
||||
| `mla_attn` | `M`(range) `latent_dim` `heads` `blocks` `block_size` `scale`:f64 `dtype` | `q`, `kv`, `bt`, `length` → `out` |
|
||||
| `mla_attn_paged` | `M`(range) `heads` `latent_dim` `rope_dim` `block_size` `scale`:f64 `dtype` | `q`, `q_rope`?, `kv`, `block_table`, `seqused`, `cu_seqlens`, `gate`? → `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` |
|
||||
@@ -3292,6 +3307,21 @@ runs the matrix row's kernel instead. It also takes multiples of 32 heads (two g
|
||||
workgroup), which no constraint routes to it. GLM-5.3 splits a prefill's MLA by rows under tensor
|
||||
parallelism, so each rank holds all 64 heads of its rows (ARCHITECTURES.md, `glm5next`).
|
||||
|
||||
`mla_attn_paged` is the dense, causal form for a model whose MLA keeps a rotary part beside the
|
||||
latent (Ling-3.0: latent 512, rotary 64, every key visible). A token's cache row is the normed
|
||||
latent followed by the rotated key part, `latent_dim + rope_dim` wide; it is stored as one KV head
|
||||
of half that width, its first half in the K slot and the rest in the V slot, so `kv` is
|
||||
`[pages, 1, block_size, latent_dim + rope_dim]`. `q` is the absorbed query `[M, heads,
|
||||
latent_dim]` and `q_rope` its rotated part `[M, heads, rope_dim]`, each at its own row and head
|
||||
pitch. A score is `scale * (q . latent + q_rope . rope)`, `scale` from the original head width
|
||||
(`(nope + rope)^-0.5`), and the value is the latent. Sequences, positions and the causal bound are
|
||||
`attn_paged`'s: sequence `s` owns query rows `[cu[s], cu[s+1])`, `seqused[s]` is its context after
|
||||
the step, row `i` of it sits at position `seqused[s] - qlen + i` and sees keys `0..position` through
|
||||
`block_table[s]`. An unmapped page contributes nothing and a row with no visible key outputs zero.
|
||||
With `gate` `[M, >= heads]` (a head's gate logit) the output is
|
||||
`bf16(bf16(out) * bf16(sigmoid(gate)))`, Ling's head-wise attention gate taken on the latent, ahead
|
||||
of the expansion. The softmax is f32 and `out` rounded once before the gate.
|
||||
|
||||
`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,
|
||||
|
||||
@@ -68,6 +68,91 @@ int ref_router_sigmoid_topk(const RadArgs* a, RadStream) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Group-limited noaux_tc routing (DeepSeek-V3's, Ling-3.0's): the experts fall into `n_group`
|
||||
* equal groups, a group ranks by the sum of its two highest `p + bias`, and selection runs over
|
||||
* the experts of the `topk_group` best groups only. Weights as in router_sigmoid_topk. */
|
||||
int ref_router_sigmoid_group_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),
|
||||
ng = p_int(a, "n_group", 0), kg = p_int(a, "topk_group", 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 || ng < 1 || ne % ng || ne / ng < 2 || kg < 1 || kg > ng ||
|
||||
k > kg * (ne / ng) || !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;
|
||||
const int64_t gsz = ne / ng;
|
||||
for (int64_t r = 0; r < lg.shape[0]; ++r) {
|
||||
float scores[512], select[512], chosen[512], gscore[512];
|
||||
int index[512];
|
||||
bool keep[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));
|
||||
}
|
||||
for (int64_t gi = 0; gi < ng; ++gi) {
|
||||
float t0 = -INFINITY, t1 = -INFINITY;
|
||||
for (int64_t e = gi * gsz; e < (gi + 1) * gsz; ++e) {
|
||||
if (select[e] > t0) { t1 = t0; t0 = select[e]; }
|
||||
else if (select[e] > t1) t1 = select[e];
|
||||
}
|
||||
gscore[gi] = t0 + t1;
|
||||
}
|
||||
for (int64_t j = 0; j < kg; ++j) {
|
||||
int best = -1;
|
||||
for (int64_t gi = 0; gi < ng; ++gi)
|
||||
if (gscore[gi] > -INFINITY && (best < 0 || gscore[gi] > gscore[best])) best = (int)gi;
|
||||
if (best < 0) return RAD_E_SHAPE;
|
||||
for (int64_t e = best * gsz; e < (best + 1) * gsz; ++e) keep[e] = true;
|
||||
gscore[best] = -INFINITY;
|
||||
}
|
||||
float sum = 0;
|
||||
for (int64_t j = 0; j < k; ++j) {
|
||||
int best = -1;
|
||||
for (int64_t e = 0; e < ne; ++e)
|
||||
if (keep[e] && 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;
|
||||
}
|
||||
|
||||
/* Ling-3.0's clamp: the SiLU is taken first and its value clipped above, the up branch on both
|
||||
* sides (vLLM's SwigluStepAndMul). swiglu_clamped clips the gate before the SiLU instead. */
|
||||
int ref_swiglu_step(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(act_silu(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 * u);
|
||||
}
|
||||
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;
|
||||
|
||||
@@ -50,6 +50,97 @@ int ref_mla_project(const RadArgs* a, RadStream) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Dense causal latent attention over a paged cache whose token row is the normed latent followed
|
||||
* by the rotated key part (Ling-3.0's MLA). A score is scale * (q . latent + q_rope . rope); the
|
||||
* value is the latent. Sequences, positions and the causal bound follow attn_paged: sequence s
|
||||
* owns query rows [cu[s], cu[s+1]), its context after this step is seqused[s], and row i of it
|
||||
* sits at position seqused[s] - qlen + i and sees keys 0..position. With `gate` the rounded output
|
||||
* is multiplied by the rounded sigmoid of the head's gate logit and rounded again. */
|
||||
int ref_mla_attn_paged(const RadArgs* a, RadStream) {
|
||||
/* q_rope (1) is required when rope_dim is nonzero, gate (6) is optional. */
|
||||
if (a->n_t < 8 || !t_in(a, 0) || !t_in(a, 2) || !t_in(a, 3) || !t_in(a, 4) || !t_in(a, 5) ||
|
||||
!t_in(a, 7))
|
||||
return RAD_E_INVAL;
|
||||
RadTensor q = a->t[0], qr = a->t[1], o = a->t[7];
|
||||
const auto &kv = a->t[2], &bt = a->t[3], &su = a->t[4], &cu = a->t[5];
|
||||
const RadTensor* gate = t_in(a, 6);
|
||||
const int64_t h = p_int(a, "heads", 0), L = p_int(a, "latent_dim", 0),
|
||||
R = p_int(a, "rope_dim", 0), bs = p_int(a, "block_size", 0);
|
||||
const float scale = p_f32(a, "scale", 0);
|
||||
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(q, L);
|
||||
heads_view(qr, R);
|
||||
heads_view(o, L);
|
||||
if (h < 1 || L < 1 || L > 2048 || R < 0 || bs < 1 || !std::isfinite(scale) || scale <= 0 ||
|
||||
q.rank != 3 || q.shape[0] < 1 || q.shape[1] != h || q.shape[2] != L || (R && (qr.rank != 3 ||
|
||||
qr.shape[0] != q.shape[0] || qr.shape[1] != h || qr.shape[2] != R)) || kv.rank != 4 ||
|
||||
kv.shape[1] != 1 || kv.shape[2] != bs || kv.shape[3] < L + R || bt.rank != 2 ||
|
||||
su.rank != 1 || cu.rank != 1 || numel(&cu) != numel(&su) + 1 || o.rank != 3 ||
|
||||
o.shape[0] != q.shape[0] || o.shape[1] != h || o.shape[2] != L ||
|
||||
(gate && (gate->rank != 2 || gate->shape[0] != q.shape[0] || gate->shape[1] < h)))
|
||||
return RAD_E_SHAPE;
|
||||
if (!q.data || (R && !qr.data) || !kv.data || !bt.data || !su.data || !cu.data || !o.data)
|
||||
return RAD_E_INVAL;
|
||||
const int64_t n_seq = numel(&su), rows = q.shape[0];
|
||||
if (cu_at(&cu, 0) != 0 || cu_at(&cu, n_seq) != rows) return RAD_E_SHAPE;
|
||||
#pragma omp parallel for schedule(dynamic)
|
||||
for (int64_t job = 0; job < rows * h; ++job) {
|
||||
const int64_t r = job / h, head = job % h;
|
||||
const int64_t s = seq_of(&cu, n_seq, r);
|
||||
const int64_t qlen = cu_at(&cu, s + 1) - cu_at(&cu, s), i = r - cu_at(&cu, s);
|
||||
const int64_t ctx = ld_int(su.dtype, su.data, s * su.stride[0]);
|
||||
const int64_t pos = ctx - qlen + i;
|
||||
const int64_t live = std::min(pos + 1, bt.shape[1] * bs);
|
||||
auto key_offset = [&](int64_t token) -> int64_t {
|
||||
const int64_t page =
|
||||
ld_int(bt.dtype, bt.data, s * 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 score = [&](int64_t base) -> float {
|
||||
float v = 0;
|
||||
for (int64_t c = 0; c < L; ++c)
|
||||
v += ldt(&q, r * q.stride[0] + head * q.stride[1] + c * q.stride[2]) *
|
||||
ldt(&kv, base + c * kv.stride[3]);
|
||||
for (int64_t c = 0; c < R; ++c)
|
||||
v += ldt(&qr, r * qr.stride[0] + head * qr.stride[1] + c * qr.stride[2]) *
|
||||
ldt(&kv, base + (L + 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, score(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(score(base) - max);
|
||||
den += w;
|
||||
for (int64_t c = 0; c < L; ++c) val[c] += w * ldt(&kv, base + c * kv.stride[3]);
|
||||
}
|
||||
const float g = gate ? round_dt(RAD_BF16, act_sigmoid(ldt(gate, r * gate->stride[0] +
|
||||
head * gate->stride[1])))
|
||||
: 1.0f;
|
||||
for (int64_t c = 0; c < L; ++c) {
|
||||
float v = den > 0 ? val[c] / den : 0;
|
||||
if (gate) v = round_dt(RAD_BF16, v) * g;
|
||||
stt(&o, r * o.stride[0] + head * o.stride[1] + c * o.stride[2], v);
|
||||
}
|
||||
}
|
||||
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];
|
||||
|
||||
@@ -77,12 +77,15 @@ 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_router_sigmoid_group_topk(const RadArgs*, RadStream);
|
||||
int ref_swiglu_step (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_mla_attn_paged(const RadArgs*, RadStream);
|
||||
int ref_gelu_mul (const RadArgs*, RadStream);
|
||||
int ref_act_mul (const RadArgs*, RadStream);
|
||||
int ref_mul_weight (const RadArgs*, RadStream);
|
||||
@@ -355,12 +358,15 @@ 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_router_sigmoid_group_topk);
|
||||
REF_SHAPE_FN(ref_swiglu_step);
|
||||
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_mla_attn_paged);
|
||||
REF_SHAPE_FN(ref_gelu_mul);
|
||||
REF_SHAPE_FN(ref_act_mul);
|
||||
REF_SHAPE_FN(ref_mul_weight);
|
||||
|
||||
@@ -170,6 +170,10 @@ static const RadParamSpec pMlaAttn[] = { P_INT("M"), P_INT("latent_dim"), P_INT(
|
||||
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 pMlaAttnPaged[] = { P_INT("M"), P_INT("heads"), P_INT("latent_dim"),
|
||||
P_INT("rope_dim"), P_INT("block_size"), P_F64("scale"), P_STR("dtype") };
|
||||
static const RadOperandSpec oMlaAttnPaged[] = { OPD("q"), OPD_O("q_rope"), OPD("kv"),
|
||||
OPD("block_table"), OPD("seqused"), OPD("cu_seqlens"), OPD_O("gate"), OUT("out") };
|
||||
static const RadParamSpec pDsaScore[] = { P_INT("M"), P_INT("n"), P_INT("heads"),
|
||||
P_INT("blocks"), P_INT("seqs"), P_STR("dtype"), P_INTO("row_part") };
|
||||
static const RadOperandSpec oDsaScore[] = { OPD("q"), OPD("q_scale"), OPD("gate"), OPD("k"),
|
||||
@@ -179,6 +183,8 @@ static const RadOperandSpec oDsaPool[] = { OPD("kg"), WGT("ape"), OUT("q"), OUT(
|
||||
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 pRouterSigmoidGroup[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"),
|
||||
P_INT("n_group"), P_INT("topk_group"), P_INT("norm"), P_F64("route_scale"), P_STR("dtype") };
|
||||
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. */
|
||||
@@ -1240,6 +1246,10 @@ static const RadOpSchema kSchemas[] = {
|
||||
"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_attn_paged", ARR(pMlaAttnPaged), ARR(oMlaAttnPaged),
|
||||
"Dense causal latent attention over a paged cache whose token row is the latent then the rotated "
|
||||
"key part: score = scale * (q . latent + q_rope . rope), value = the latent; sequences as in "
|
||||
"attn_paged. With `gate`, out = bf16(bf16(out) * bf16(sigmoid(gate[head])))." },
|
||||
{ "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),
|
||||
@@ -1248,6 +1258,8 @@ static const RadOpSchema kSchemas[] = {
|
||||
"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_step", ARR(pSwigluClamped), ARR(oGateUp),
|
||||
"min(silu(gate),limit)*clamp(up,-limit,limit); gate is the first half." },
|
||||
{ "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),
|
||||
@@ -1563,6 +1575,9 @@ 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_group_topk", ARR(pRouterSigmoidGroup), ARR(oRouterSigmoid),
|
||||
"Group-limited sigmoid routing: groups rank by the sum of their two best p + bias, selection "
|
||||
"runs over the topk_group best groups; correction bias selects, original scores weight." },
|
||||
{ "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),
|
||||
@@ -2270,6 +2285,10 @@ SIMPLE("ref_dsa_query", "dsa_query", "attn", "normalized FP8 index queries", DT_
|
||||
ref_dsa_query),
|
||||
SIMPLE("ref_gemm_nt_f32", "gemm_nt_f32", "gemm", "F32 routing projection", DT_FLOAT,
|
||||
ref_gemm_nt_f32),
|
||||
SIMPLE("ref_mla_attn_paged", "mla_attn_paged", "attn", "dense paged latent attention with a rotary part",
|
||||
DT_FLOAT, ref_mla_attn_paged),
|
||||
SIMPLE("ref_swiglu_step", "swiglu_step", "elem", "SwiGLU clipped after the SiLU", DT_FLOAT,
|
||||
ref_swiglu_step),
|
||||
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,
|
||||
@@ -2454,6 +2473,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_group_topk", "router_sigmoid_group_topk", "moe",
|
||||
"group-limited sigmoid correction-bias routing", DT_FLOAT, ref_router_sigmoid_group_topk),
|
||||
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,
|
||||
|
||||
@@ -773,6 +773,24 @@ int ref_router_sigmoid_topk_shape(const RadParam* p, int n_p, int operand, RadOp
|
||||
o.t(D, { M, k });
|
||||
return o.finish("router_sigmoid_topk", operand, out);
|
||||
}
|
||||
int ref_swiglu_step_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_group_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), ng = gi(p, n_p, "n_group", 0),
|
||||
kg = gi(p, n_p, "topk_group", 0);
|
||||
if (M < 1 || ne < 1 || ne > 512 || k < 1 || ng < 1 || ne % ng || ne / ng < 2 || kg < 1 ||
|
||||
kg > ng || k > kg * (ne / ng))
|
||||
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_group_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);
|
||||
@@ -840,6 +858,28 @@ int ref_mla_attn_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
|
||||
o.t(dtype, { M, H, D });
|
||||
return o.finish("mla_attn", operand, out);
|
||||
}
|
||||
/* One sequence whose context is its query (a prefill chunk), as attn_paged describes itself; a
|
||||
* harness passes `ctx` for a deeper history. */
|
||||
int ref_mla_attn_paged_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), L = gi(p, n_p, "latent_dim", 0),
|
||||
R = gi(p, n_p, "rope_dim", 0), H = gi(p, n_p, "heads", 0),
|
||||
bs = gi(p, n_p, "block_size", 0);
|
||||
if (M < 1 || L < 1 || L > 2048 || R < 1 || H < 1 || bs < 1) return RAD_E_UNSUPPORTED;
|
||||
int64_t ctx = gi(p, n_p, "ctx", 0);
|
||||
if (ctx < M) ctx = M;
|
||||
const int64_t blocks = (ctx + bs - 1) / bs;
|
||||
const uint32_t dtype = act_dt(p, n_p);
|
||||
Opd o;
|
||||
o.t(dtype, { M, H, L }); /* q */
|
||||
o.t(dtype, { M, H, R }); /* q_rope */
|
||||
o.t(dtype, { blocks, 1, bs, L + R }); /* kv */
|
||||
o.t_idx({ 1, blocks }, blocks, -1, 0); /* block_table */
|
||||
o.t_idx({ 1 }, 0, ctx, 0); /* seqused */
|
||||
o.t_idx({ 2 }, M, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens: [0, M], one sequence */
|
||||
o.skip(); /* gate */
|
||||
o.t(dtype, { M, H, L }); /* out */
|
||||
return o.finish("mla_attn_paged", 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);
|
||||
|
||||
@@ -832,6 +832,88 @@ TEST(swiglu_clamping_is_asymmetric_and_precedes_the_activation) {
|
||||
CHECK_EQ(run("swiglu_clamped", bad), RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
TEST(swiglu_step_clips_the_activation_not_the_gate) {
|
||||
T gu(RAD_F32, { 1, 8 }), y(RAD_F32, { 1, 4 });
|
||||
gu.f({ -20, 2, 4.02f, 20, 9, 9, 9, -9 });
|
||||
A a;
|
||||
a.t(gu).t(y).i("M", 9).i("n", 4).d("limit", 4).s("dtype", "f32");
|
||||
REQUIRE_EQ(run("swiglu_step", a), RAD_OK);
|
||||
auto silu = [](float g) { return g / (1 + std::exp(-g)); };
|
||||
CHECK_NEAR(y.at(0), silu(-20) * 4, 1e-6); // a negative activation is not clipped
|
||||
CHECK_NEAR(y.at(1), silu(2) * 4, 1e-5);
|
||||
CHECK_NEAR(y.at(2), silu(4.02f) * 4, 1e-5); // silu(4.02) is under 4: unclipped
|
||||
CHECK_EQ(y.at(3), -16.0f); // silu(20) clips to exactly 4, up to -4
|
||||
T gc(RAD_F32, { 1, 4 });
|
||||
A c;
|
||||
c.t(gu).t(gc).i("M", 9).i("n", 4).d("limit", 4).s("dtype", "f32");
|
||||
REQUIRE_EQ(run("swiglu_clamped", c), RAD_OK);
|
||||
CHECK(gc.at(3) > y.at(3)); // the gate-first form stops at silu(4) * -4
|
||||
}
|
||||
|
||||
TEST(group_router_selects_only_inside_the_best_groups) {
|
||||
T lg(RAD_F32, { 1, 8 }), bias(RAD_F32, { 8 }), ids(RAD_I32, { 1, 2 }), w(RAD_F32, { 1, 2 });
|
||||
auto logit = [](float p) { return std::log(p / (1 - p)); };
|
||||
// Group sums of the top two: 1.0, 1.5, 0.86, 1.2 -> groups 1 and 3 are kept, so the single
|
||||
// best experts (0 at 0.9, 4 at 0.85) are out and 2 and 3 are chosen.
|
||||
lg.f({ logit(0.9f), logit(0.1f), logit(0.8f), logit(0.7f), logit(0.85f), logit(0.01f),
|
||||
logit(0.6f), logit(0.6f) });
|
||||
bias.f({ 0, 0, 0, 0, 0, 0, 0, 0 });
|
||||
A a;
|
||||
a.t(lg).t(bias).t(ids).t(w).i("M", 1).i("n_expert", 8).i("top_k", 2).i("n_group", 4)
|
||||
.i("topk_group", 2).i("norm", 1).d("route_scale", 2.5).s("dtype", "f32");
|
||||
REQUIRE_EQ(run("router_sigmoid_group_topk", a), RAD_OK);
|
||||
CHECK_EQ(ids.at(0), 2);
|
||||
CHECK_EQ(ids.at(1), 3);
|
||||
CHECK_NEAR(w.at(0), 2.5 * 0.8 / 1.5, 1e-5);
|
||||
CHECK_NEAR(w.at(1), 2.5 * 0.7 / 1.5, 1e-5);
|
||||
// The bias ranks groups and experts and never weights them.
|
||||
bias.f({ 0, 0, 0, 0, 0, 0, 1, 0 });
|
||||
REQUIRE_EQ(run("router_sigmoid_group_topk", a), RAD_OK);
|
||||
CHECK_EQ(ids.at(0), 6);
|
||||
CHECK_EQ(ids.at(1), 2);
|
||||
CHECK_NEAR(w.at(0), 2.5 * 0.6 / 1.4, 1e-5);
|
||||
A bad;
|
||||
bad.t(lg).t(bias).t(ids).t(w).i("M", 1).i("n_expert", 8).i("top_k", 2).i("n_group", 3)
|
||||
.i("topk_group", 2).i("norm", 1).d("route_scale", 2.5).s("dtype", "f32");
|
||||
CHECK_EQ(run("router_sigmoid_group_topk", bad), RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
TEST(paged_latent_attention_is_causal_adds_the_rotary_part_and_gates_per_head) {
|
||||
// One sequence of three tokens, the last two queried (positions 1 and 2). Token 0 and 1 sit
|
||||
// in page 1, token 2 in page 0; a row is the latent (2) then the rotary part (2).
|
||||
T q(RAD_F32, { 2, 1, 2 }), qr(RAD_F32, { 2, 1, 2 }), kv(RAD_F32, { 2, 1, 2, 4 });
|
||||
T bt(RAD_I32, { 1, 2 }), su(RAD_I32, { 1 }), cu(RAD_I32, { 2 }), out(RAD_F32, { 2, 1, 2 });
|
||||
q.f({ 0, 0, 0, 0 });
|
||||
qr.f({ 0, 0, 0, 0 });
|
||||
kv.f({ 5, 6, 0, 0, 77, 77, 77, 77, 1, 2, 1, 0, 3, 4, 0, 0 });
|
||||
bt.n({ 1, 0 });
|
||||
su.n({ 3 });
|
||||
cu.n({ 0, 2 });
|
||||
A a;
|
||||
a.t(q).t(qr).t(kv).t(bt).t(su).t(cu).tnull().t(out).i("M", 9).i("heads", 1)
|
||||
.i("latent_dim", 2).i("rope_dim", 2).i("block_size", 2).d("scale", 1).s("dtype", "f32");
|
||||
REQUIRE_EQ(run("mla_attn_paged", a), RAD_OK);
|
||||
CHECK_NEAR(out.at(0), 2, 1e-6); // position 1 sees tokens 0 and 1
|
||||
CHECK_NEAR(out.at(1), 3, 1e-6);
|
||||
CHECK_NEAR(out.at(2), 3, 1e-6); // position 2 sees all three
|
||||
CHECK_NEAR(out.at(3), 4, 1e-6);
|
||||
// The rotary part alone scores token 0 at ln 3 and token 1 at 0: weights 3/4 and 1/4.
|
||||
qr.f({ std::log(3.0f), 0, 0, 0 });
|
||||
REQUIRE_EQ(run("mla_attn_paged", a), RAD_OK);
|
||||
CHECK_NEAR(out.at(0), 1.5, 1e-6);
|
||||
CHECK_NEAR(out.at(1), 2.5, 1e-6);
|
||||
// A gate logit of 0 halves the head.
|
||||
T gate(RAD_F32, { 2, 1 });
|
||||
gate.f({ 0, 0 });
|
||||
A g;
|
||||
g.t(q).t(qr).t(kv).t(bt).t(su).t(cu).t(gate).t(out).i("M", 9).i("heads", 1)
|
||||
.i("latent_dim", 2).i("rope_dim", 2).i("block_size", 2).d("scale", 1).s("dtype", "f32");
|
||||
REQUIRE_EQ(run("mla_attn_paged", g), RAD_OK);
|
||||
CHECK_NEAR(out.at(0), 0.75, 1e-6);
|
||||
CHECK_NEAR(out.at(1), 1.25, 1e-6);
|
||||
CHECK_NEAR(out.at(2), 1.5, 1e-6);
|
||||
}
|
||||
|
||||
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 });
|
||||
@@ -966,6 +1048,7 @@ TEST(op_vocabulary) {
|
||||
"rmsnorm", "rmsnorm_p", "rmsnorm_add", "hc_enter", "hc_read", "hc_write", "hc_project",
|
||||
"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",
|
||||
"swiglu_step", "router_sigmoid_group_topk", "mla_attn_paged",
|
||||
"kda_update",
|
||||
"layernorm", "add", "mul", "mul_weight", "silu_mul", "gelu_mul", "act_mul", "seg_mean",
|
||||
"seg_softmax_pool",
|
||||
@@ -9894,12 +9977,19 @@ std::vector<Geo> geometries() {
|
||||
.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("mla_attn_paged", "M", 3, a.i("M", R).i("heads", 2).i("latent_dim", 8).i("rope_dim", 4)
|
||||
.i("block_size", 4).d("scale", 0.25).i("ctx", 6)
|
||||
.s("dtype", "f32")),
|
||||
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("swiglu_step", "M", 3, a.i("M", R).i("n", 8).d("limit", 0.5).s("dtype", "f32")),
|
||||
G("router_sigmoid_group_topk", "M", 3, a.i("M", R).i("n_expert", 8).i("top_k", 2)
|
||||
.i("n_group", 4).i("topk_group", 2).i("norm", 1)
|
||||
.d("route_scale", 2.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)
|
||||
|
||||
Reference in new issue
Block a user