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:
John McDonoughandNunze authored and StillDeadcode committed 2026-10-19 20:13:47 +02:00
1 parent c8311068d0
commit da77f86332
21 files changed
+3217 -19

No files matched your search

+206
View File
@@ -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;
}
+90
View File
@@ -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;
}
+199
View File
@@ -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;
}
+250
View File
@@ -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;
}
+105
View File
@@ -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
View File
@@ -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;
+28
View File
@@ -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);
+106
View File
@@ -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
View File
@@ -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 */