Archived
libref, libavx: GLM-5.3's ops -- mHC, clamped SwiGLU, f32 routing, KDA, the DSA indexer, MLA
The reference and CPU forms of the ops GLM-5.3-Flash's graph needs, with their schemas and shape hooks: mhc_pre / mhc_post / mhc_contract and the column-split pair mhc_pre_partial / mhc_pre_finish; swiglu_clamped; gemm_nt_f32 (bf16 activation, f32 weight and result) for the router logits and the indexer's head gates; router_sigmoid_topk (correction-bias top-k); kda_update with per-channel decay and both state forms; dsa_pool, dsa_query and dsa_score; and mla_attn and mla_project for absorbed latent attention. moe_gather takes f32 expert weights beside bf16, and fp8a8f32 joins the dtype list. docs/OPS.md states each op. ref_test checks every op against hand-computed cases, avx_check_hand the CPU forms against libref, build_test the indexer cache's page size. Co-Authored-By: Nunze <lorenz.lamping1@web.de>
This commit is contained in:
1 parent
c8311068d0
commit
da77f86332
21 files changed
+3217
-19
No files matched your search
@@ -37,6 +37,9 @@ set(AVX_KERNEL_SRC
|
||||
avx_elementwise.cpp
|
||||
avx_norm.cpp
|
||||
avx_hc.cpp
|
||||
avx_glm.cpp
|
||||
avx_dsa.cpp
|
||||
avx_mla.cpp
|
||||
avx_quant.cpp
|
||||
avx_gemm.cpp
|
||||
avx_gemm_tile.cpp
|
||||
|
||||
+45
-1
@@ -113,6 +113,39 @@ std::vector<Case> build_cases() {
|
||||
* on is the trunk case, off the final mixer; they differ in the operand list. */
|
||||
for (const char* dt : { "f32", "bf16" }) {
|
||||
add("hc_enter", { HI("M", 5), HI("n", 128), HI("hc", 4), HS("dtype", dt) });
|
||||
add("swiglu_clamped", { HI("M", 5), HI("n", 259), HF("limit", 0.5), HS("dtype", dt) });
|
||||
if (!std::strcmp(dt, "bf16"))
|
||||
add("dsa_pool", { HI("M", 7), HI("n", 128), HI("ratio", 4), HS("dtype", "bf16") });
|
||||
if (!std::strcmp(dt, "bf16"))
|
||||
add("dsa_query", { HI("M", 7), HI("n", 128), HS("dtype", "bf16") });
|
||||
if (!std::strcmp(dt, "bf16"))
|
||||
add("gemm_nt_f32", { HI("M", 4), HI("N", 32), HI("K", 129), HS("dtype", "bf16") });
|
||||
if (!std::strcmp(dt, "bf16"))
|
||||
for (const char* mode : { "absorb", "expand" })
|
||||
add("mla_project", { HI("M", 3), HI("heads", 2), HI("head_dim", 17),
|
||||
HI("latent_dim", 31), HS("mode", mode), HS("dtype", "bf16") });
|
||||
if (!std::strcmp(dt, "bf16"))
|
||||
add("dsa_score", { HI("M", 3), HI("n", 128), HI("heads", 32), HI("blocks", 17),
|
||||
HI("seqs", 2), HS("dtype", "fp8_e4m3") });
|
||||
for (int norm : { 0, 1 })
|
||||
add("router_sigmoid_topk",
|
||||
{ HI("M", 5), HI("n_expert", 288), HI("top_k", 8), HI("norm", norm),
|
||||
HF("route_scale", 2.5), HS("dtype", dt) });
|
||||
add("mhc_pre", { HI("M", 3), HI("n", 129), HI("hc", 4), HI("iterations", 20),
|
||||
HF("eps", 1e-5), HF("hc_eps", 1e-6), HS("dtype", dt) });
|
||||
add("mhc_pre_partial", { HI("M", 3), HI("n", 129), HI("hc", 4), HI("chunk", 129),
|
||||
HI("first", 1), HI("chunks", 2), HS("dtype", dt) });
|
||||
add("mhc_pre_finish",
|
||||
{ HI("M", 3), HI("n", 129), HI("hc", 4), HI("iterations", 20), HF("eps", 1e-5),
|
||||
HF("hc_eps", 1e-6), HI("chunk", 129), HS("dtype", dt) });
|
||||
add("mhc_post", { HI("M", 3), HI("n", 129), HI("hc", 4), HS("dtype", dt) });
|
||||
add("mhc_contract", { HI("M", 3), HI("n", 129), HI("hc", 4), HS("dtype", dt) });
|
||||
add("mla_attn", { HI("M", 3), HI("latent_dim", 32), HI("heads", 2), HI("blocks", 7),
|
||||
HI("block_size", 4), HF("scale", 0.125), HS("dtype", dt) });
|
||||
for (const char* mode : { "prefill", "verify" })
|
||||
add("kda_update", { HI("M", 3), HI("heads", 2), HI("head_k", 32), HI("head_v", 32),
|
||||
HF("lower_bound", -5), HF("scale", 0.1767766952966369),
|
||||
HF("l2_eps", 1e-6), HS("mode", mode), HS("dtype", dt) });
|
||||
add("hc_write", { HI("M", 5), HI("n", 128), HI("hc", 4), HS("dtype", dt) });
|
||||
add("hc_read", { HI("M", 5), HI("n", 128), HI("hc", 4), HI("lowrank", 8),
|
||||
HF("eps", 1e-6), HS("dtype", dt), HF("wadd", 1), HI("inject", 1),
|
||||
@@ -134,6 +167,10 @@ std::vector<Case> build_cases() {
|
||||
}
|
||||
add("ngram_ids", { HI("M", 9), HI("heads", 3), HI("ngram", 4), HI("eos", 2) });
|
||||
|
||||
for (const char* order : { "token", "sorted" })
|
||||
add("moe_gemm_q",
|
||||
{ HI("M", 9), HI("N", 64), HI("K", 128), HI("n_expert", 8), HI("top_k", 2),
|
||||
HI("group", 128), HS("a_order", order), HS("dtype", "mxfp4a8") });
|
||||
/* One scale per column over the rows: no group. */
|
||||
add("quant_cols_fp8", { HI("M", 5), HI("n", 256), HS("dtype", "bf16") }, EB(5, 256, 2, 1.5));
|
||||
add("quant_cols_fp8", { HI("M", 7), HI("n", 96), HS("dtype", "f32") }, EB(7, 96, 4, 1.25));
|
||||
@@ -214,7 +251,7 @@ std::vector<Case> build_cases() {
|
||||
/* The formats libref describes (ref_shapes.cpp): block fp8, and the int4 and int8 weights
|
||||
* against quant_act_i8's step-ordered codes. The bias form needs `a_scale`, which fp8a16 (a
|
||||
* bf16 activation) does not have, so libref declines it there. */
|
||||
for (const char* dt : { "fp8a8", "fp8a16", "w4a8", "w8a8" })
|
||||
for (const char* dt : { "fp8a8", "fp8a8f32", "fp8a16", "w4a8", "w8a8" })
|
||||
for (int M : { 1, 65 }) {
|
||||
const double fl = 2.0 * M * 96 * 256;
|
||||
add("gemm_nt_q", { HI("M", M), HI("N", 96), HI("K", 256), HI("group", 128),
|
||||
@@ -439,6 +476,10 @@ std::vector<Case> build_cases() {
|
||||
HI("seqs", 3) });
|
||||
add("qsa_select", { HI("M", 2), HI("blocks", 1), HI("topk", 1), HI("ratio", 3),
|
||||
HI("seqs", 1) });
|
||||
add("qsa_select", { HI("M", 4), HI("blocks", 300), HI("topk", 32), HI("ratio", 4),
|
||||
HI("seqs", 1), HI("signed", 1) });
|
||||
add("qsa_select", { HI("M", 7), HI("blocks", 129), HI("topk", 16), HI("ratio", 4),
|
||||
HI("seqs", 3), HI("signed", 1) });
|
||||
add("qsa_tail_store", { HI("M", 3), HI("n", 37), HI("ratio", 2), HI("ring", 2), HI("seqs", 3),
|
||||
HS("dtype", "f32") });
|
||||
add("qsa_work", { HI("M", 3), HI("n", 40), HI("ratio", 2), HI("ring", 3), HI("seqs", 3),
|
||||
@@ -523,6 +564,9 @@ std::vector<Case> build_cases() {
|
||||
add("moe_gemm_q", { HI("M", 9), HI("N", 64), HI("K", 128), HI("n_expert", 8),
|
||||
HI("top_k", 2), HI("group", 128), HS("a_order", order),
|
||||
HS("dtype", "fp8a8") });
|
||||
add("moe_gemm_q",
|
||||
{ HI("M", 9), HI("N", 128), HI("K", 256), HI("n_expert", 8), HI("top_k", 2),
|
||||
HI("group", 128), HS("a_order", order), HS("dtype", "fp8a8f32") });
|
||||
}
|
||||
/* Two classes at different widths: a gate/up pair whose odd experts are half as wide
|
||||
* (the output's second part begins past the odd class's zeros), and a down projection
|
||||
|
||||
@@ -526,6 +526,126 @@ void shape_cases(std::vector<Hand>& hs) {
|
||||
.pi("M", BAND).pi("heads", 4).pi("ngram", 3).pi("eos", 5);
|
||||
hs.push_back(std::move(n));
|
||||
}
|
||||
/* GLM's two-copy speculative state, including a nonempty previous replay window. */
|
||||
for (const char* mode : { "prefill", "verify" })
|
||||
for (int accepted : { 1, 2, 3 })
|
||||
for (int cold : { 0, 1 }) {
|
||||
constexpr int64_t D = 128;
|
||||
Hand h("KDA anchor accepted-prefix replay", "kda_update", 0.01);
|
||||
h.dense(RAD_BF16, { 2, 1, D }, hfill(201, 0.25f))
|
||||
.dense(RAD_BF16, { 2, 1, D }, hfill(202, 0.25f))
|
||||
.dense(RAD_BF16, { 2, 1, D }, hfill(203, 0.25f))
|
||||
.dense(RAD_BF16, { 2, 1, D }, hfill(204, 0.25f))
|
||||
.dense(RAD_BF16, { 2, 1 }, hfill(205, 0.25f))
|
||||
.dense(RAD_F32, { 1 }, [](int64_t) { return 0.0f; })
|
||||
.dense(RAD_F32, { D }, [](int64_t) { return -1.0f; })
|
||||
.dense(
|
||||
RAD_F32, { 2, 1, D, D },
|
||||
[](int64_t i) {
|
||||
if (i < D * D) return 0.125f;
|
||||
i -= D * D;
|
||||
if (!i) return 3.0f;
|
||||
if (i > 3 * 385) return 0.0f;
|
||||
const int at = (int)((i - 1) % 385);
|
||||
return at < 128 ? 0.01f : at < 256 ? 0.125f : at < 384 ? 0.75f : 0.5f;
|
||||
},
|
||||
true)
|
||||
.dense(RAD_I32, { 1, 6 }, [](int64_t i) { return i < 3 ? 0.0f : 1.0f; })
|
||||
.idx({ 0, 2 })
|
||||
.idx({ accepted })
|
||||
.idx({ cold ? 0 : 1 })
|
||||
.dense(RAD_BF16, { 2, 1, D }, hfill(206), true)
|
||||
.pi("M", 2)
|
||||
.pi("heads", 1)
|
||||
.pi("head_k", D)
|
||||
.pi("head_v", D)
|
||||
.pf("lower_bound", -5)
|
||||
.pf("scale", 1.0 / std::sqrt(128.0))
|
||||
.pf("l2_eps", 1e-6)
|
||||
.ps("mode", mode)
|
||||
.ps("dtype", "bf16")
|
||||
.ps("state_form", "anchor");
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
for (const char* mode : { "absorb", "expand" }) {
|
||||
const bool absorb = !std::strcmp(mode, "absorb");
|
||||
const int64_t in = absorb ? 17 : 31, out = absorb ? 31 : 17;
|
||||
Hand h("MLA flattened linear inputs and outputs", "mla_project", 0.01);
|
||||
h.view(RAD_BF16, { 3, 2 * in }, { 2 * in + 7, 1 }, 3 * (2 * in + 7), hfill(215, 0.25f))
|
||||
.dense(RAD_BF16, { 68, 31 }, hfill(216, 0.25f))
|
||||
.view(RAD_BF16, { 3, 2 * out }, { 2 * out + 9, 1 }, 3 * (2 * out + 9), hfill(217), true)
|
||||
.pi("M", 3)
|
||||
.pi("heads", 2)
|
||||
.pi("head_dim", 17)
|
||||
.pi("latent_dim", 31)
|
||||
.ps("mode", mode)
|
||||
.ps("dtype", "bf16");
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
{
|
||||
Hand h("MoE preserves F32 probabilities with BF16 experts", "moe_gather", 1e-5);
|
||||
h.dense(RAD_BF16, { 2, 1 }, [](int64_t i) { return i ? -1024.0f : 1024.0f; })
|
||||
.dense(RAD_F32, { 1, 2 }, [](int64_t i) { return i ? 1.0f : 1.0f + 1.0f / 8192; })
|
||||
.idx({ 0, 1 })
|
||||
.none()
|
||||
.none()
|
||||
.dense(
|
||||
RAD_BF16, { 1, 1 }, [](int64_t) { return 0.0f; }, true)
|
||||
.pi("M", 1)
|
||||
.pi("n", 1)
|
||||
.pi("top_k", 2)
|
||||
.ps("dtype", "bf16");
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
/* Packed index pages share code and scale storage, including pitched cache pages. */
|
||||
{
|
||||
Hand h("DSA pool writes pitched managed pages", "dsa_pool", 0.001);
|
||||
h.dense(RAD_BF16, { 28, 256 }, hfill(211, 0.25f))
|
||||
.dense(RAD_F32, { 4, 128 }, hfill(212, 0.125f))
|
||||
.dense(
|
||||
RAD_F8E4M3, { 7, 128 }, [](int64_t) { return 0.0f; }, true)
|
||||
.dense(
|
||||
RAD_F32, { 7, 1 }, [](int64_t) { return 0.0f; }, true)
|
||||
.idx({ 4, -1, 2, 99, 1, 0, 3 })
|
||||
.view(
|
||||
RAD_U8, { 5, 1, 4, 34 }, { 160, 136, 34, 1 }, 5 * 160,
|
||||
[](int64_t) { return 165.0f; }, true)
|
||||
.pi("M", 7)
|
||||
.pi("n", 128)
|
||||
.pi("ratio", 4)
|
||||
.ps("dtype", "bf16");
|
||||
hs.push_back(std::move(h));
|
||||
Hand s("DSA scorer reads embedded scales", "dsa_score", 1e-5);
|
||||
s.dense(RAD_F8E4M3, { 64, 128 }, hfill(213, 0.25f))
|
||||
.dense(RAD_F32, { 64, 1 }, [](int64_t) { return 0.5f; })
|
||||
.dense(RAD_F32, { 2, 32 }, hfill(214))
|
||||
.view(RAD_U8, { 5, 1, 4, 34 }, { 160, 136, 34, 1 }, 5 * 160,
|
||||
[](int64_t i) {
|
||||
const int d = (int)(i % 160);
|
||||
if (d < 128) return (float)(48 + i % 9);
|
||||
// Little-endian F32 scale 0.5; all padding stays poisoned.
|
||||
return d == 128 || d == 129 ? 0.0f
|
||||
: d == 130 ? 0.0f
|
||||
: d == 131 ? 63.0f
|
||||
: 165.0f;
|
||||
})
|
||||
.none()
|
||||
.dense(RAD_I32, { 1, 4 },
|
||||
[](int64_t i) {
|
||||
return (float)(i == 1 ? -1 : i == 3 ? 99 : i);
|
||||
})
|
||||
.idx({ 0, 2 })
|
||||
.idx({ 4 })
|
||||
.dense(
|
||||
RAD_F32, { 2, 4 }, [](int64_t) { return 0.0f; }, true)
|
||||
.pi("M", 2)
|
||||
.pi("n", 128)
|
||||
.pi("heads", 32)
|
||||
.pi("blocks", 4)
|
||||
.pi("seqs", 1)
|
||||
.ps("dtype", "fp8_e4m3");
|
||||
hs.push_back(std::move(s));
|
||||
}
|
||||
/* ---- packed weight codes at odd element offsets ------------------------------------------ */
|
||||
{
|
||||
const int64_t M = 2, N = 4, K = 33;
|
||||
@@ -2729,6 +2849,69 @@ void qsa_cases(std::vector<Hand>& hs) {
|
||||
.pi("M", M).pi("blocks", nb).pi("topk", topk).pi("ratio", ratio).pi("seqs", 1);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
{
|
||||
/* The signed order, against the rule: row 0 ranks 2 over the tie of -0 and +0 (NaN dead,
|
||||
* -1e31 live), row 1 is all negative with -inf dead and -1e30 live. Under the unsigned
|
||||
* order both rows would rank as zeros. */
|
||||
static const float v[2][8] = {
|
||||
{ -3.0f, -1.0f, -0.0f, 2.0f, -1.0f, 0.0f, NAN, -1e31f },
|
||||
{ -5.0f, -2e30f, -7.0f, -6.0f, -INFINITY, -9.0f, -1e30f, -8.0f } };
|
||||
Hand h("signed: negative scores, -0 tying +0, NaN and -inf dead", "qsa_select", 0.0);
|
||||
h.dense(RAD_F32, { 2, 8 }, [](int64_t i) { return v[i / 8][i % 8]; })
|
||||
.dense(RAD_I32, { 2, 8 }, [](int64_t i) { return (float)(100 + 10 * (i / 8) + i % 8); })
|
||||
.idx({ 8, 8 })
|
||||
.idx({ 31, 31 })
|
||||
.idx({ 0, 1, 2 })
|
||||
.dense(RAD_I32, { 2, 4 }, sent, true)
|
||||
.dense(RAD_I32, { 2 }, sent, true)
|
||||
.dense(RAD_I32, { 2 }, sent, true)
|
||||
.pi("M", 2).pi("blocks", 8).pi("topk", 3).pi("ratio", 4).pi("seqs", 2).pi("signed", 1)
|
||||
.expect(5, { 103, 102, 105, -1, 110, 113, 112, -1 });
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
{
|
||||
/* The column-slice case's scores, shifted to straddle zero, under the signed order. */
|
||||
const int64_t S = 2, M = 6, live = 40, pitch = 56, W = 48, topk = 8, ratio = 4;
|
||||
Hand h("signed: cu from 1, unheld rows, a column slice, ties across zero", "qsa_select",
|
||||
0.0);
|
||||
h.view(RAD_F32, { M, live }, { pitch, 1 }, M * pitch, [=](int64_t i) {
|
||||
switch ((i % pitch + i / pitch) % 9) {
|
||||
case 0: case 1: case 7: return -1.0f;
|
||||
case 2: return NAN;
|
||||
case 3: return INFINITY;
|
||||
case 4: return -0.0f;
|
||||
case 5: return -INFINITY;
|
||||
case 6: return -1.5f;
|
||||
default: return 0.25f * (float)(i % 5) - 0.5f;
|
||||
}
|
||||
})
|
||||
.dense(RAD_I32, { S, W }, [](int64_t i) {
|
||||
return i % 11 == 4 ? -1.0f : (float)((i * 13 + 3) % 500);
|
||||
})
|
||||
.idx({ 40, 25 })
|
||||
.idx({ 160, 98, 99, 161, 40, 7 })
|
||||
.idx({ 1, 3, 5 })
|
||||
.dense(RAD_I32, { M, topk + 1 }, sent, true)
|
||||
.dense(RAD_I32, { M }, sent, true)
|
||||
.dense(RAD_I32, { M }, sent, true)
|
||||
.pi("M", M).pi("blocks", W).pi("topk", topk).pi("ratio", ratio).pi("seqs", S)
|
||||
.pi("signed", 1);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
{
|
||||
Hand h("a `signed` other than 0 or 1 is refused before any write", "qsa_select", 0.0);
|
||||
h.dense(RAD_F32, { 1, 4 }, hfill(208))
|
||||
.dense(RAD_I32, { 1, 4 }, [](int64_t i) { return (float)i; })
|
||||
.idx({ 4 })
|
||||
.idx({ 15 })
|
||||
.idx({ 0, 1 })
|
||||
.dense(RAD_I32, { 1, 3 }, sent, true)
|
||||
.dense(RAD_I32, { 1 }, sent, true)
|
||||
.dense(RAD_I32, { 1 }, sent, true)
|
||||
.pi("M", 1).pi("blocks", 4).pi("topk", 2).pi("ratio", 4).pi("seqs", 1).pi("signed", 2)
|
||||
.refuses(RAD_E_INVAL);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
{
|
||||
Hand h("a negative block count is refused before any write", "qsa_select", 0.0);
|
||||
h.dense(RAD_F32, { 1, 4 }, hfill(207))
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
#include "avx_vec.h"
|
||||
#include "avx_common.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
using namespace avx;
|
||||
|
||||
AVX_KERNEL(dsa_query) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
const auto &x = a->t[0], &q = a->t[1], &s = a->t[2];
|
||||
const int64_t n = p_int(a, "n", 0);
|
||||
if (n < 1 || n > 256 || (n & (n - 1)) || x.rank != 2 || q.rank != 2 || s.rank != 2 ||
|
||||
x.shape[0] < 1 || q.shape[0] != x.shape[0] || x.shape[1] != n || q.shape[1] != n ||
|
||||
s.shape[0] != x.shape[0] || s.shape[1] != 1)
|
||||
return RAD_E_SHAPE;
|
||||
if (x.dtype != RAD_BF16 || q.dtype != RAD_F8E4M3 || s.dtype != RAD_F32) return RAD_E_DTYPE;
|
||||
if (!x.data || !q.data || !s.data) return RAD_E_INVAL;
|
||||
AVX_PARALLEL_FOR_IF(x.shape[0] * n >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < x.shape[0]; ++r) {
|
||||
float v[256];
|
||||
for (int64_t d = 0; d < n; ++d) v[d] = ldt(&x, r * x.stride[0] + d * x.stride[1]);
|
||||
for (int64_t h = 1; h < n; h *= 2)
|
||||
for (int64_t i = 0; i < n; i += 2 * h)
|
||||
for (int64_t j = 0; j < h; ++j) {
|
||||
const float lo = v[i + j], hi = v[i + j + h];
|
||||
v[i + j] = lo + hi;
|
||||
v[i + j + h] = lo - hi;
|
||||
}
|
||||
float am = 1e-4f;
|
||||
const float norm = 1.0f / std::sqrt((float)n);
|
||||
for (int64_t d = 0; d < n; ++d) {
|
||||
v[d] = rad_bf16_to_f32(rad_f32_to_bf16(v[d] * norm));
|
||||
am = std::max(am, std::fabs(v[d]));
|
||||
}
|
||||
int exponent = 0;
|
||||
const float fraction = std::frexp(am * (1.0f / 448.0f), &exponent);
|
||||
const float sc = std::ldexp(1.0f, exponent - (fraction == 0.5f));
|
||||
stt(&s, r * s.stride[0], sc);
|
||||
for (int64_t d = 0; d < n; ++d)
|
||||
stt(&q, r * q.stride[0] + d * q.stride[1], std::clamp(v[d] / sc, -448.0f, 448.0f));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
AVX_KERNEL(dsa_score) {
|
||||
if (!a || !a->t || a->n_t < 9) return RAD_E_INVAL;
|
||||
RadTensor q = a->t[0], qs = a->t[1];
|
||||
const auto& g = a->t[2];
|
||||
RadTensor k = a->t[3], ks = a->t[4];
|
||||
const bool packed = k.dtype == RAD_U8;
|
||||
if (packed) {
|
||||
if (ks.data || k.rank != 4 || k.shape[1] != 1 || k.shape[2] != 4 || k.shape[3] != 34 ||
|
||||
k.stride[3] != 1 || k.stride[2] != 34 || k.stride[0] < 136 || k.stride[0] % 4 ||
|
||||
((uintptr_t)k.data & 3))
|
||||
return RAD_E_SHAPE;
|
||||
ks = {};
|
||||
ks.data = k.data ? (uint8_t*)k.data + 128 : nullptr;
|
||||
ks.dtype = RAD_F32;
|
||||
ks.rank = 1;
|
||||
ks.shape[0] = k.shape[0];
|
||||
ks.stride[0] = k.stride[0] / 4;
|
||||
k.dtype = RAD_F8E4M3;
|
||||
k.rank = 2;
|
||||
k.shape[1] = 128;
|
||||
k.stride[1] = 1;
|
||||
}
|
||||
const auto &bt = a->t[5], &cu = a->t[6], &nc = a->t[7], &out = a->t[8];
|
||||
const int64_t n = p_int(a, "n", 0), h = p_int(a, "heads", 0);
|
||||
if (h > 0 && q.rank == 2 && qs.rank == 2 && qs.shape[1] == 1 &&
|
||||
q.shape[0] == out.shape[0] * h && qs.shape[0] == q.shape[0]) {
|
||||
q.rank = 3;
|
||||
q.shape[0] = out.shape[0];
|
||||
q.shape[2] = q.shape[1];
|
||||
q.shape[1] = h;
|
||||
q.stride[2] = q.stride[1];
|
||||
q.stride[1] = q.stride[0];
|
||||
q.stride[0] *= h;
|
||||
qs.shape[0] = out.shape[0];
|
||||
qs.shape[1] = h;
|
||||
qs.stride[1] = qs.stride[0];
|
||||
qs.stride[0] *= h;
|
||||
}
|
||||
if (n < 1 || h < 1 || h > 64 || q.rank != 3 || q.shape[0] < 1 || q.shape[1] != h ||
|
||||
q.shape[2] != n || qs.rank != 2 || g.rank != 2 || qs.shape[0] != q.shape[0] ||
|
||||
g.shape[0] != q.shape[0] || qs.shape[1] != h || g.shape[1] != h || k.rank != 2 ||
|
||||
k.shape[1] != n || ks.rank != 1 || ks.shape[0] != k.shape[0] || bt.rank != 2 ||
|
||||
cu.rank != 1 || nc.rank != 1 || cu.shape[0] != bt.shape[0] + 1 ||
|
||||
nc.shape[0] != bt.shape[0] || out.rank != 2 || out.shape[0] != q.shape[0] ||
|
||||
out.shape[1] > bt.shape[1])
|
||||
return RAD_E_SHAPE;
|
||||
if (q.dtype != RAD_F8E4M3 || k.dtype != RAD_F8E4M3 || qs.dtype != RAD_F32 ||
|
||||
ks.dtype != RAD_F32 || g.dtype != RAD_F32 || bt.dtype != RAD_I32 || cu.dtype != RAD_I32 ||
|
||||
nc.dtype != RAD_I32 || out.dtype != RAD_F32)
|
||||
return RAD_E_DTYPE;
|
||||
for (int i = 0; i < 9; ++i)
|
||||
if (!(packed && i == 4) && !a->t[i].data) return RAD_E_INVAL;
|
||||
const float norm = 1.0f / std::sqrt((float)(h * n));
|
||||
AVX_PARALLEL_FOR_IF(q.shape[0] * out.shape[1] * h * n >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < q.shape[0]; ++r) {
|
||||
int64_t seq = -1;
|
||||
for (int64_t s = 0; s < bt.shape[0]; ++s)
|
||||
if (r >= ld_int_dt(cu.dtype, cu.data, s * cu.stride[0]) &&
|
||||
r < ld_int_dt(cu.dtype, cu.data, (s + 1) * cu.stride[0])) {
|
||||
seq = s;
|
||||
break;
|
||||
}
|
||||
const int64_t live = seq >= 0 ? ld_int_dt(nc.dtype, nc.data, seq * nc.stride[0]) : 0;
|
||||
for (int64_t b = 0; b < out.shape[1]; ++b) {
|
||||
const int64_t page =
|
||||
seq >= 0 && b < live
|
||||
? ld_int_dt(bt.dtype, bt.data, seq * bt.stride[0] + b * bt.stride[1])
|
||||
: -1;
|
||||
float result = -INFINITY;
|
||||
if (page >= 0 && page < k.shape[0]) {
|
||||
result = 0;
|
||||
for (int64_t head = 0; head < h; ++head) {
|
||||
float dot = 0;
|
||||
for (int64_t d = 0; d < n; ++d)
|
||||
dot += ldt(&q, r * q.stride[0] + head * q.stride[1] + d * q.stride[2]) *
|
||||
ldt(&k, page * k.stride[0] + d * k.stride[1]);
|
||||
result += std::max(dot, 0.0f) *
|
||||
ldt(&qs, r * qs.stride[0] + head * qs.stride[1]) *
|
||||
ldt(&g, r * g.stride[0] + head * g.stride[1]);
|
||||
}
|
||||
result *= ldt(&ks, page * ks.stride[0]) * norm;
|
||||
}
|
||||
stt(&out, r * out.stride[0] + b * out.stride[1], result);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
AVX_KERNEL(dsa_pool) {
|
||||
if (p_int(a, "block_size", 4) != 4) return RAD_E_SHAPE;
|
||||
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
|
||||
const auto &kg = a->t[0], &ape = a->t[1], &q = a->t[2], &s = a->t[3];
|
||||
const int64_t n = p_int(a, "n", 0), ratio = p_int(a, "ratio", 0);
|
||||
const auto *page = rad_arg_in(a, 4), *cache = rad_arg_in(a, 5);
|
||||
if ((page != nullptr) != (cache != nullptr)) return RAD_E_INVAL;
|
||||
if (cache &&
|
||||
(n != 128 || ratio != 4 || page->dtype != RAD_I32 || page->rank != 1 ||
|
||||
page->shape[0] != q.shape[0] || page->stride[0] < 1 || cache->dtype != RAD_U8 ||
|
||||
cache->rank != 4 || cache->shape[0] < 1 || cache->shape[1] != 1 || cache->shape[2] != 4 ||
|
||||
cache->shape[3] != 34 || cache->stride[3] != 1 || cache->stride[2] != 34 ||
|
||||
cache->stride[0] < 136 || cache->stride[0] % 4 || ((uintptr_t)cache->data & 3)))
|
||||
return RAD_E_SHAPE;
|
||||
if (n < 1 || n > 256 || (n & (n - 1)) || ratio < 2 || ratio > 16 || kg.rank != 2 ||
|
||||
ape.rank != 2 || q.rank != 2 || s.rank != 2 || q.shape[0] < 1 || !kg.data || !ape.data ||
|
||||
!q.data || !s.data || kg.dtype != RAD_BF16 || ape.dtype != RAD_F32 ||
|
||||
q.dtype != RAD_F8E4M3 || s.dtype != RAD_F32 || kg.shape[0] != q.shape[0] * ratio ||
|
||||
kg.shape[1] != 2 * n || ape.shape[0] != ratio || ape.shape[1] != n || q.shape[1] != n ||
|
||||
s.shape[0] != q.shape[0] || s.shape[1] != 1)
|
||||
return RAD_E_SHAPE;
|
||||
AVX_PARALLEL_FOR_IF(q.shape[0] * n * ratio >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < q.shape[0]; ++r) {
|
||||
float x[256];
|
||||
for (int64_t d = 0; d < n; ++d) {
|
||||
float g[16], mx = -INFINITY;
|
||||
for (int64_t j = 0; j < ratio; ++j) {
|
||||
g[j] = ldt(&kg, (r * ratio + j) * kg.stride[0] + (n + d) * kg.stride[1]) +
|
||||
ldt(&ape, j * ape.stride[0] + d * ape.stride[1]);
|
||||
mx = std::max(mx, g[j]);
|
||||
}
|
||||
float z = 0, den = 0;
|
||||
for (int64_t j = 0; j < ratio; ++j) {
|
||||
const float p = std::exp(g[j] - mx);
|
||||
z += p * ldt(&kg, (r * ratio + j) * kg.stride[0] + d * kg.stride[1]);
|
||||
den += p;
|
||||
}
|
||||
x[d] = rad_bf16_to_f32(rad_f32_to_bf16(z / den));
|
||||
}
|
||||
for (int64_t step = 1; step < n; step *= 2)
|
||||
for (int64_t base = 0; base < n; base += 2 * step)
|
||||
for (int64_t j = 0; j < step; ++j) {
|
||||
const float lo = x[base + j], hi = x[base + j + step];
|
||||
x[base + j] = lo + hi;
|
||||
x[base + j + step] = lo - hi;
|
||||
}
|
||||
float am = 1e-4f;
|
||||
const float norm = 1.0f / std::sqrt((float)n);
|
||||
for (int64_t d = 0; d < n; ++d) {
|
||||
x[d] = rad_bf16_to_f32(rad_f32_to_bf16(x[d] * norm));
|
||||
am = std::max(am, std::fabs(x[d]));
|
||||
}
|
||||
int exponent = 0;
|
||||
const float fraction = std::frexp(am * (1.0f / 448.0f), &exponent);
|
||||
const float sc = std::ldexp(1.0f, exponent - (fraction == 0.5f));
|
||||
stt(&s, r * s.stride[0], sc);
|
||||
for (int64_t d = 0; d < n; ++d)
|
||||
stt(&q, r * q.stride[0] + d * q.stride[1], std::clamp(x[d] / sc, -448.0f, 448.0f));
|
||||
if (cache) {
|
||||
const int64_t p = ldi(page, r * page->stride[0]);
|
||||
if (p >= 0 && p < cache->shape[0]) {
|
||||
auto* dst = (uint8_t*)cache->data + p * cache->stride[0];
|
||||
for (int d = 0; d < 128; ++d)
|
||||
dst[d] = ((uint8_t*)q.data)[r * q.stride[0] + d * q.stride[1]];
|
||||
std::memcpy(dst + 128, &sc, sizeof(sc));
|
||||
}
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -0,0 +1,507 @@
|
||||
/* Host mHC and bounded KDA. Widen each activation row once, then reduce the
|
||||
* projections and state products with this ISA level's vector operations. */
|
||||
#include "avx_vec.h"
|
||||
#include "avx_common.h"
|
||||
#include <algorithm>
|
||||
|
||||
using namespace avx;
|
||||
|
||||
namespace {
|
||||
bool matrix(const RadTensor& t, int64_t r, int64_t c) {
|
||||
return t.data && t.rank == 2 && t.shape[0] == r && t.shape[1] == c;
|
||||
}
|
||||
float dot(const float* x, const float* y, int64_t n) {
|
||||
vf acc = vf_zero();
|
||||
int64_t i = 0;
|
||||
for (; i + VF_N <= n; i += VF_N) acc = vf_fma(vf_loadu(x + i), vf_loadu(y + i), acc);
|
||||
float s = vf_hsum(acc);
|
||||
for (; i < n; ++i) s += x[i] * y[i];
|
||||
return s;
|
||||
}
|
||||
void sinkhorn(float* c, int h, int repeats, float eps) {
|
||||
for (int r = 0; r < h; ++r) {
|
||||
float max = -INFINITY;
|
||||
for (int k = 0; k < h; ++k) max = std::max(max, c[r * h + k]);
|
||||
float total = 0;
|
||||
for (int k = 0; k < h; ++k) {
|
||||
c[r * h + k] = std::exp(c[r * h + k] - max);
|
||||
total += c[r * h + k];
|
||||
}
|
||||
for (int k = 0; k < h; ++k) c[r * h + k] = c[r * h + k] / total + eps;
|
||||
}
|
||||
for (int it = 0; it < repeats; ++it) {
|
||||
if (it)
|
||||
for (int r = 0; r < h; ++r) {
|
||||
float total = 0;
|
||||
for (int k = 0; k < h; ++k) total += c[r * h + k];
|
||||
for (int k = 0; k < h; ++k) c[r * h + k] /= total + eps;
|
||||
}
|
||||
for (int k = 0; k < h; ++k) {
|
||||
float total = 0;
|
||||
for (int r = 0; r < h; ++r) total += c[r * h + k];
|
||||
for (int r = 0; r < h; ++r) c[r * h + k] /= total + eps;
|
||||
}
|
||||
}
|
||||
}
|
||||
bool headed(const RadTensor& t, int64_t tokens, int64_t heads, int64_t dim) {
|
||||
return t.data && t.shape[0] == tokens &&
|
||||
((t.rank == 3 && t.shape[1] == heads && t.shape[2] == dim) ||
|
||||
(t.rank == 2 && t.shape[1] == heads * dim));
|
||||
}
|
||||
int64_t at(const RadTensor& t, int64_t token, int64_t h, int64_t d, int64_t width) {
|
||||
return token * t.stride[0] + h * (t.rank == 3 ? t.stride[1] : width * t.stride[1]) +
|
||||
d * laststride(&t);
|
||||
}
|
||||
}
|
||||
|
||||
AVX_KERNEL(gemm_nt_f32) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
const auto &x = a->t[0], &w = a->t[1], &y = a->t[2];
|
||||
const int64_t n = p_int(a, "N", 0), k = p_int(a, "K", 0);
|
||||
if (n < 1 || k < 1 || x.rank != 2 || w.rank != 2 || y.rank != 2 || x.shape[0] < 1 ||
|
||||
x.shape[1] != k || w.shape[0] != n || w.shape[1] != k || y.shape[0] != x.shape[0] ||
|
||||
y.shape[1] != n)
|
||||
return RAD_E_SHAPE;
|
||||
if (x.dtype != RAD_BF16 || w.dtype != RAD_F32 || y.dtype != RAD_F32) return RAD_E_DTYPE;
|
||||
if (!x.data || !w.data || !y.data) return RAD_E_INVAL;
|
||||
AVX_PARALLEL_FOR_IF(x.shape[0] * n * k >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < x.shape[0]; ++r) {
|
||||
float* query = scratch_f32((size_t)k);
|
||||
for (int64_t j = 0; j < k; ++j) query[j] = ldt(&x, r * x.stride[0] + j * x.stride[1]);
|
||||
for (int64_t col = 0; col < n; ++col) {
|
||||
float sum = 0;
|
||||
if (w.stride[1] == 1)
|
||||
sum = dot(query, (const float*)w.data + col * w.stride[0], k);
|
||||
else
|
||||
for (int64_t j = 0; j < k; ++j)
|
||||
sum += query[j] * ldt(&w, col * w.stride[0] + j * w.stride[1]);
|
||||
stt(&y, r * y.stride[0] + col * y.stride[1], sum);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
AVX_KERNEL(router_sigmoid_topk) {
|
||||
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
|
||||
const auto &lg = a->t[0], &bias = a->t[1], &ids = a->t[2], &w = a->t[3];
|
||||
const int64_t ne = p_int(a, "n_expert", 0), k = p_int(a, "top_k", 0);
|
||||
const float factor = p_f32(a, "route_scale", 0);
|
||||
if (ne < 1 || ne > 512 || k < 1 || k > ne || !std::isfinite(factor) || factor <= 0 ||
|
||||
lg.rank != 2 || lg.shape[0] < 1 || lg.shape[1] != ne || bias.rank != 1 ||
|
||||
bias.shape[0] != ne || bias.dtype != RAD_F32 || ids.dtype != RAD_I32 ||
|
||||
!matrix(ids, lg.shape[0], k) || !matrix(w, lg.shape[0], k) || !lg.data || !bias.data)
|
||||
return RAD_E_SHAPE;
|
||||
for (int64_t r = 0; r < lg.shape[0]; ++r) {
|
||||
float prob[512], ranked[512], chosen[512];
|
||||
int index[512];
|
||||
for (int64_t e = 0; e < ne; ++e) {
|
||||
prob[e] = 1.0f / (1.0f + std::exp(-ldt(&lg, rowoff(&lg, r, ne) + e * laststride(&lg))));
|
||||
ranked[e] = prob[e] + ldt(&bias, e * laststride(&bias));
|
||||
}
|
||||
float total = 0;
|
||||
for (int64_t j = 0; j < k; ++j) {
|
||||
int winner = -1;
|
||||
for (int64_t e = 0; e < ne; ++e)
|
||||
if (ranked[e] > -INFINITY && (winner < 0 || ranked[e] > ranked[winner]))
|
||||
winner = (int)e;
|
||||
if (winner < 0) return RAD_E_SHAPE;
|
||||
index[j] = winner;
|
||||
chosen[j] = prob[winner];
|
||||
total += chosen[j];
|
||||
ranked[winner] = -INFINITY;
|
||||
}
|
||||
const float mult = p_int(a, "norm", 0) ? factor / (total + 1e-20f) : factor;
|
||||
for (int64_t j = 0; j < k; ++j) {
|
||||
st_int_dt(ids.dtype, ids.data, rowoff(&ids, r, k) + j * laststride(&ids), index[j]);
|
||||
stt(&w, rowoff(&w, r, k) + j * laststride(&w), chosen[j] * mult);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
AVX_KERNEL(swiglu_clamped) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const auto &gu = a->t[0], &y = a->t[1];
|
||||
const int64_t n = p_int(a, "n", 0);
|
||||
const float limit = p_f32(a, "limit", 0);
|
||||
if (n < 1 || !std::isfinite(limit) || limit <= 0 || gu.rank != 2 || y.rank != 2 || !gu.data ||
|
||||
!y.data || y.shape[0] < 1 || gu.shape[0] != y.shape[0] || gu.shape[1] != 2 * n ||
|
||||
y.shape[1] != n)
|
||||
return RAD_E_SHAPE;
|
||||
AVX_PARALLEL_FOR_IF(y.shape[0] * n >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < y.shape[0]; ++r) {
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const int64_t b = rowoff(&gu, r, 2 * n), s = laststride(&gu);
|
||||
const float g = std::min(ldt(&gu, b + i * s), limit);
|
||||
const float u = std::clamp(ldt(&gu, b + (n + i) * s), -limit, limit);
|
||||
stt(&y, rowoff(&y, r, n) + i * laststride(&y), (g / (1.0f + std::exp(-g))) * u);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
namespace {
|
||||
int64_t part_stride(int64_t hc) { return (hc * (hc + 2) + 1 + 3) / 4 * 4; }
|
||||
bool pre_params(const RadArgs* a, int64_t* n, int64_t* hc, int64_t* iters, float* eps,
|
||||
float* heps) {
|
||||
*n = p_int(a, "n", 0);
|
||||
*hc = p_int(a, "hc", 0);
|
||||
*iters = p_int(a, "iterations", 0);
|
||||
*eps = p_f32(a, "eps", 0);
|
||||
*heps = p_f32(a, "hc_eps", 0);
|
||||
return *n >= 1 && *hc >= 2 && *hc <= 8 && *iters >= 1 && *iters <= 256 && std::isfinite(*eps) &&
|
||||
*eps > 0 && std::isfinite(*heps) && *heps >= 0;
|
||||
}
|
||||
bool pre_outputs(const RadTensor& h, const RadTensor& scale, const RadTensor& base,
|
||||
const RadTensor& x, const RadTensor& post, const RadTensor& comb, int64_t rows,
|
||||
int64_t n, int64_t hc) {
|
||||
const int64_t mix = hc * (hc + 2);
|
||||
return matrix(h, rows, hc * n) && scale.rank == 1 && scale.dtype == RAD_F32 &&
|
||||
numel(&scale) == 3 && base.rank == 1 && base.dtype == RAD_F32 && numel(&base) == mix &&
|
||||
matrix(x, rows, n) && matrix(post, rows, hc) && matrix(comb, rows, hc * hc) &&
|
||||
post.dtype == RAD_F32 && comb.dtype == RAD_F32;
|
||||
}
|
||||
/* Row r from its RMS-scaled coefficients and the widened residual row hv. */
|
||||
void finish_row(const float* coeff, const float* hv, const RadTensor& scale, const RadTensor& base,
|
||||
const RadTensor& x, const RadTensor& post, const RadTensor& comb, int64_t r,
|
||||
int64_t n, int64_t hc, int64_t iters, float heps) {
|
||||
float pre[8], c[64];
|
||||
for (int64_t j = 0; j < hc; ++j) {
|
||||
pre[j] =
|
||||
1.0f / (1.0f +
|
||||
std::exp(-(coeff[j] * ldt(&scale, 0) + ldt(&base, j * laststride(&base))))) +
|
||||
heps;
|
||||
const float z = coeff[hc + j] * ldt(&scale, laststride(&scale)) +
|
||||
ldt(&base, (hc + j) * laststride(&base));
|
||||
stt(&post, rowoff(&post, r, hc) + j * laststride(&post), 2.0f / (1.0f + std::exp(-z)));
|
||||
}
|
||||
for (int64_t j = 0; j < hc * hc; ++j)
|
||||
c[j] = coeff[2 * hc + j] * ldt(&scale, 2 * laststride(&scale)) +
|
||||
ldt(&base, (2 * hc + j) * laststride(&base));
|
||||
sinkhorn(c, (int)hc, (int)iters, heps);
|
||||
for (int64_t j = 0; j < hc * hc; ++j)
|
||||
stt(&comb, rowoff(&comb, r, hc * hc) + j * laststride(&comb), c[j]);
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
float v = 0;
|
||||
for (int64_t j = 0; j < hc; ++j) v += pre[j] * hv[j * n + i];
|
||||
stt(&x, rowoff(&x, r, n) + i * laststride(&x), v);
|
||||
}
|
||||
}
|
||||
/* fn row j over columns [lo, lo+len), contiguous or through the scratch fw. */
|
||||
float fn_dot(const float* hv, const RadTensor& fn, int64_t j, int64_t width, int64_t lo,
|
||||
int64_t len, float* fw) {
|
||||
const int64_t fb = rowoff(&fn, j, width);
|
||||
if (laststride(&fn) == 1) return dot(hv + lo, (const float*)fn.data + fb + lo, len);
|
||||
for (int64_t i = 0; i < len; ++i) fw[i] = ldt(&fn, fb + (lo + i) * laststride(&fn));
|
||||
return dot(hv + lo, fw, len);
|
||||
}
|
||||
void widen(const RadTensor& h, int64_t r, int64_t width, float* hv) {
|
||||
for (int64_t i = 0; i < width; ++i) hv[i] = ldt(&h, rowoff(&h, r, width) + i * laststride(&h));
|
||||
}
|
||||
}
|
||||
|
||||
AVX_KERNEL(mhc_pre) {
|
||||
if (!rad_args_have(a, 7)) return RAD_E_INVAL;
|
||||
int64_t n, hc, iters;
|
||||
float eps, heps;
|
||||
if (!pre_params(a, &n, &hc, &iters, &eps, &heps)) return RAD_E_SHAPE;
|
||||
const auto &h = a->t[0], &fn = a->t[1], &scale = a->t[2], &base = a->t[3];
|
||||
const auto &x = a->t[4], &post = a->t[5], &comb = a->t[6];
|
||||
if (h.rank != 2) return RAD_E_SHAPE;
|
||||
const int64_t rows = h.shape[0], width = hc * n, mix = hc * (hc + 2);
|
||||
if (rows < 1 || !matrix(fn, mix, width) || fn.dtype != RAD_F32 ||
|
||||
!pre_outputs(h, scale, base, x, post, comb, rows, n, hc))
|
||||
return RAD_E_SHAPE;
|
||||
AVX_PARALLEL_FOR_IF(rows * width * mix >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
float* scratch = scratch_f32((size_t)(2 * width));
|
||||
float* hv = scratch;
|
||||
float* fw = hv + width;
|
||||
widen(h, r, width, hv);
|
||||
const float norm = 1.0f / std::sqrt(dot(hv, hv, width) / (float)width + eps);
|
||||
float coeff[80];
|
||||
for (int64_t j = 0; j < mix; ++j) coeff[j] = fn_dot(hv, fn, j, width, 0, width, fw) * norm;
|
||||
finish_row(coeff, hv, scale, base, x, post, comb, r, n, hc, iters, heps);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
AVX_KERNEL(mhc_pre_partial) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
const int64_t n = p_int(a, "n", 0), hc = p_int(a, "hc", 0), chunk = p_int(a, "chunk", 0);
|
||||
const int64_t first = p_int(a, "first", -1), count = p_int(a, "chunks", 0);
|
||||
if (n < 1 || hc < 2 || hc > 8 || chunk < 1 || (hc * n) % chunk || first < 0 || count < 1 ||
|
||||
first + count > hc * n / chunk)
|
||||
return RAD_E_SHAPE;
|
||||
const auto &h = a->t[0], &fn = a->t[1], &part = a->t[2];
|
||||
if (h.rank != 2) return RAD_E_SHAPE;
|
||||
const int64_t rows = h.shape[0], width = hc * n, mix = hc * (hc + 2), S = part_stride(hc);
|
||||
if (rows < 1 || !matrix(h, rows, width) || !matrix(fn, mix, width) || fn.dtype != RAD_F32 ||
|
||||
!matrix(part, rows, count * S) || part.dtype != RAD_F32)
|
||||
return RAD_E_SHAPE;
|
||||
AVX_PARALLEL_FOR_IF(rows * count * chunk * mix >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
float* scratch = scratch_f32((size_t)(width + chunk));
|
||||
float* hv = scratch;
|
||||
float* fw = hv + width;
|
||||
widen(h, r, width, hv);
|
||||
const int64_t pb = rowoff(&part, r, count * S), ps = laststride(&part);
|
||||
for (int64_t c = 0; c < count; ++c) {
|
||||
const int64_t lo = (first + c) * chunk;
|
||||
for (int64_t j = 0; j < S; ++j) {
|
||||
const float v = j < mix ? fn_dot(hv, fn, j, width, lo, chunk, fw)
|
||||
: j == mix ? dot(hv + lo, hv + lo, chunk)
|
||||
: 0.0f;
|
||||
stt(&part, pb + (c * S + j) * ps, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
AVX_KERNEL(mhc_pre_finish) {
|
||||
if (!rad_args_have(a, 7)) return RAD_E_INVAL;
|
||||
int64_t n, hc, iters;
|
||||
float eps, heps;
|
||||
if (!pre_params(a, &n, &hc, &iters, &eps, &heps)) return RAD_E_SHAPE;
|
||||
const int64_t chunk = p_int(a, "chunk", 0);
|
||||
if (chunk < 1 || (hc * n) % chunk) return RAD_E_SHAPE;
|
||||
const auto &part = a->t[0], &h = a->t[1], &scale = a->t[2], &base = a->t[3];
|
||||
const auto &x = a->t[4], &post = a->t[5], &comb = a->t[6];
|
||||
if (h.rank != 2) return RAD_E_SHAPE;
|
||||
const int64_t rows = h.shape[0], width = hc * n, mix = hc * (hc + 2), S = part_stride(hc),
|
||||
chunks = width / chunk;
|
||||
if (rows < 1 || !matrix(part, rows, chunks * S) || part.dtype != RAD_F32 ||
|
||||
!pre_outputs(h, scale, base, x, post, comb, rows, n, hc))
|
||||
return RAD_E_SHAPE;
|
||||
AVX_PARALLEL_FOR_IF(rows * width >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
float* hv = scratch_f32((size_t)width);
|
||||
widen(h, r, width, hv);
|
||||
const int64_t pb = rowoff(&part, r, chunks * S), ps = laststride(&part);
|
||||
float sq = 0;
|
||||
for (int64_t c = 0; c < chunks; ++c) sq += ldt(&part, pb + (c * S + mix) * ps);
|
||||
const float norm = 1.0f / std::sqrt(sq / (float)width + eps);
|
||||
float coeff[80];
|
||||
for (int64_t j = 0; j < mix; ++j) {
|
||||
float d = 0;
|
||||
for (int64_t c = 0; c < chunks; ++c) d += ldt(&part, pb + (c * S + j) * ps);
|
||||
coeff[j] = d * norm;
|
||||
}
|
||||
finish_row(coeff, hv, scale, base, x, post, comb, r, n, hc, iters, heps);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
AVX_KERNEL(mhc_post) {
|
||||
if (!rad_args_have(a, 5)) return RAD_E_INVAL;
|
||||
const int64_t n = p_int(a, "n", 0), hc = p_int(a, "hc", 0);
|
||||
if (n < 1 || hc < 2 || hc > 8) return RAD_E_SHAPE;
|
||||
const auto &x = a->t[0], &h = a->t[1], &p = a->t[2], &c = a->t[3], &o = a->t[4];
|
||||
if (x.rank != 2) return RAD_E_SHAPE;
|
||||
const int64_t rows = x.shape[0];
|
||||
if (rows < 1 || !matrix(x, rows, n) || !matrix(h, rows, hc * n) || !matrix(p, rows, hc) ||
|
||||
!matrix(c, rows, hc * hc) || !matrix(o, rows, hc * n) || o.data == h.data ||
|
||||
p.dtype != RAD_F32 || c.dtype != RAD_F32)
|
||||
return RAD_E_SHAPE;
|
||||
AVX_PARALLEL_FOR_IF(rows * n * hc >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
for (int64_t dst = 0; dst < hc; ++dst)
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
float v = 0;
|
||||
for (int64_t src = 0; src < hc; ++src)
|
||||
v += ldt(&c, rowoff(&c, r, hc * hc) + (src * hc + dst) * laststride(&c)) *
|
||||
ldt(&h, rowoff(&h, r, hc * n) + (src * n + i) * laststride(&h));
|
||||
v += ldt(&p, rowoff(&p, r, hc) + dst * laststride(&p)) *
|
||||
ldt(&x, rowoff(&x, r, n) + i * laststride(&x));
|
||||
stt(&o, rowoff(&o, r, hc * n) + (dst * n + i) * laststride(&o), v);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
AVX_KERNEL(mhc_contract) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const int64_t n = p_int(a, "n", 0), hc = p_int(a, "hc", 0);
|
||||
if (n < 1 || hc < 2 || hc > 8) return RAD_E_SHAPE;
|
||||
const auto &h = a->t[0], &x = a->t[1];
|
||||
if (h.rank != 2 || h.shape[0] < 1 || !matrix(h, h.shape[0], hc * n) ||
|
||||
!matrix(x, h.shape[0], n))
|
||||
return RAD_E_SHAPE;
|
||||
AVX_PARALLEL_FOR_IF(h.shape[0] * n * hc >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < h.shape[0]; ++r)
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
float v = 0;
|
||||
for (int64_t j = 0; j < hc; ++j)
|
||||
v += ldt(&h, rowoff(&h, r, hc * n) + (j * n + i) * laststride(&h));
|
||||
stt(&x, rowoff(&x, r, n) + i * laststride(&x), v / (float)hc);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
AVX_KERNEL(kda_update) {
|
||||
if (!a || a->n_t < 13) return RAD_E_INVAL;
|
||||
for (int i = 0; i < 10; ++i)
|
||||
if (!rad_arg_in(a, i)) return RAD_E_INVAL;
|
||||
if (!rad_arg_in(a, 12)) return RAD_E_INVAL;
|
||||
const int64_t H = p_int(a, "heads", 0), K = p_int(a, "head_k", 0), V = p_int(a, "head_v", 0);
|
||||
const float lower = p_f32(a, "lower_bound", 0), eps = p_f32(a, "l2_eps", 1e-6f),
|
||||
scale = p_f32(a, "scale", 1);
|
||||
const char* mode = p_str(a, "mode", "");
|
||||
const bool verify = !std::strcmp(mode, "verify");
|
||||
const char* form = p_str(a, "state_form", "per_candidate");
|
||||
const bool anchor = !std::strcmp(form, "anchor");
|
||||
if (!anchor && std::strcmp(form, "per_candidate")) return RAD_E_INVAL;
|
||||
if (anchor && (K != 128 || V != 128)) return RAD_E_UNSUPPORTED;
|
||||
if (!verify && std::strcmp(mode, "prefill")) return RAD_E_INVAL;
|
||||
if (H < 1 || K < 1 || K > 128 || V < 1 || V > 128 || !std::isfinite(lower) || lower >= 0 ||
|
||||
!std::isfinite(eps) || eps <= 0 || !std::isfinite(scale))
|
||||
return RAD_E_SHAPE;
|
||||
const auto &q = a->t[0], &k = a->t[1], &v = a->t[2], &g = a->t[3], &b = a->t[4];
|
||||
const auto &al = a->t[5], &bias = a->t[6], &s = a->t[7], &idx = a->t[8], &cu = a->t[9],
|
||||
&out = a->t[12];
|
||||
const auto* accepted = rad_arg_in(a, 10);
|
||||
const auto* init = rad_arg_in(a, 11);
|
||||
if (q.rank < 2 || cu.rank != 1 || cu.dtype != RAD_I32 || cu.shape[0] < 2) return RAD_E_SHAPE;
|
||||
const int64_t T = q.shape[0], N = cu.shape[0] - 1, slots = s.shape[0];
|
||||
if (T < 1) return RAD_E_SHAPE;
|
||||
if (!headed(q, T, H, K) || !headed(k, T, H, K) || !headed(v, T, H, V) || !headed(g, T, H, K) ||
|
||||
!headed(b, T, H, 1) || !headed(out, T, H, V) || numel(&al) != H || numel(&bias) != H * K ||
|
||||
s.rank != 4 || s.dtype != RAD_F32 || s.shape[1] != H || s.shape[2] != V ||
|
||||
s.shape[3] != K || idx.rank != 2 || idx.dtype != RAD_I32 || idx.shape[0] < N ||
|
||||
idx.shape[1] < 1 || (accepted && (accepted->dtype != RAD_I32 || numel(accepted) < N)) ||
|
||||
(init && (init->dtype != RAD_I32 || numel(init) < N)))
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t width = idx.shape[1];
|
||||
for (int64_t seq = 0; seq < N; ++seq) {
|
||||
const int64_t begin = ldi(&cu, seq * cu.stride[0]);
|
||||
const int64_t end = ldi(&cu, (seq + 1) * cu.stride[0]);
|
||||
const int64_t na = accepted ? ldi(accepted, offlin(accepted, seq)) : 1;
|
||||
if (begin < 0 || end < begin || end > T || na < 1 || na > (anchor ? 32 : width) ||
|
||||
(verify && end - begin > (anchor ? 32 : width)) || (anchor && width < 2))
|
||||
return RAD_E_SHAPE;
|
||||
for (int64_t j = 0; j < width; ++j)
|
||||
if (ldi(&idx, seq * idx.stride[0] + j * idx.stride[1]) >= slots) return RAD_E_SHAPE;
|
||||
if (anchor) {
|
||||
const int64_t read = ldi(&idx, seq * idx.stride[0]);
|
||||
const int64_t scratch = ldi(&idx, seq * idx.stride[0] + (width / 2) * idx.stride[1]);
|
||||
if (read >= 0 && (scratch < 0 || scratch == read)) return RAD_E_SHAPE;
|
||||
if (verify && read >= 0 && (!init || ldi(init, offlin(init, seq))))
|
||||
for (int64_t h = 0; h < H; ++h) {
|
||||
const float count = ldt(&s, scratch * s.stride[0] + h * s.stride[1]);
|
||||
if (!std::isfinite(count) || count < 0 || count > 32 ||
|
||||
count != std::floor(count) || (count > 0 && na > count))
|
||||
return RAD_E_SHAPE;
|
||||
}
|
||||
}
|
||||
}
|
||||
AVX_PARALLEL_FOR_IF(N * H * V * K >= AVX_PAR_MIN)
|
||||
for (int64_t sh = 0; sh < N * H; ++sh) {
|
||||
const int64_t seq = sh / H, head = sh % H;
|
||||
const int64_t begin = ldi(&cu, seq * cu.stride[0]);
|
||||
const int64_t end = ldi(&cu, (seq + 1) * cu.stride[0]);
|
||||
const int64_t na = accepted ? ldi(accepted, offlin(accepted, seq)) : 1;
|
||||
const int64_t read =
|
||||
ldi(&idx, seq * idx.stride[0] + (verify && !anchor ? na - 1 : 0) * idx.stride[1]);
|
||||
if (read < 0) {
|
||||
for (int64_t t = begin; t < end; ++t)
|
||||
for (int64_t e = 0; e < V; ++e) stt(&out, at(out, t, head, e, V), 0);
|
||||
continue;
|
||||
}
|
||||
float* S = scratch_f32((size_t)(V * K + 3 * K));
|
||||
float* qn = S + V * K;
|
||||
float* kn = qn + K;
|
||||
float* decay = kn + K;
|
||||
const bool warm = !init || ldi(init, offlin(init, seq)) != 0;
|
||||
for (int64_t e = 0; e < V; ++e)
|
||||
for (int64_t d = 0; d < K; ++d)
|
||||
S[e * K + d] = warm ? ldt(&s, read * s.stride[0] + head * s.stride[1] +
|
||||
e * s.stride[2] + d * s.stride[3])
|
||||
: 0;
|
||||
const int64_t scratch =
|
||||
anchor ? ldi(&idx, seq * idx.stride[0] + (width / 2) * idx.stride[1]) : 0;
|
||||
auto factor_at = [&](int64_t i) {
|
||||
return scratch * s.stride[0] + head * s.stride[1] + (i / K) * s.stride[2] +
|
||||
(i % K) * s.stride[3];
|
||||
};
|
||||
constexpr int factors = 385;
|
||||
if (anchor && verify) {
|
||||
const int replay = warm ? (int)ldt(&s, factor_at(0)) : 0;
|
||||
for (int t = 0; t < (replay ? na : 0); ++t) {
|
||||
const int f = 1 + t * factors;
|
||||
for (int d = 0; d < 128; ++d) {
|
||||
kn[d] = ldt(&s, factor_at(f + d));
|
||||
decay[d] = ldt(&s, factor_at(f + 256 + d));
|
||||
}
|
||||
const float bt = ldt(&s, factor_at(f + 384));
|
||||
for (int e = 0; e < 128; ++e) {
|
||||
float* row = S + e * K;
|
||||
for (int d = 0; d < 128; d += VF_N)
|
||||
vf_storeu(row + d, vf_mul(vf_loadu(row + d), vf_loadu(decay + d)));
|
||||
const float delta = bt * (ldt(&s, factor_at(f + 128 + e)) - dot(row, kn, K));
|
||||
for (int d = 0; d < 128; d += VF_N)
|
||||
vf_storeu(row + d,
|
||||
vf_fma(vf_set1(delta), vf_loadu(kn + d), vf_loadu(row + d)));
|
||||
}
|
||||
}
|
||||
for (int e = 0; e < 128; ++e)
|
||||
for (int d = 0; d < 128; ++d)
|
||||
stt(&s,
|
||||
read * s.stride[0] + head * s.stride[1] + e * s.stride[2] + d * s.stride[3],
|
||||
S[e * K + d]);
|
||||
}
|
||||
const float gain = std::exp(ldt(&al, head * laststride(&al)));
|
||||
for (int64_t t = begin; t < end; ++t) {
|
||||
for (int64_t d = 0; d < K; ++d) {
|
||||
qn[d] = ldt(&q, at(q, t, head, d, K));
|
||||
kn[d] = ldt(&k, at(k, t, head, d, K));
|
||||
}
|
||||
const float qi = scale / std::sqrt(dot(qn, qn, K) + eps),
|
||||
ki = 1 / std::sqrt(dot(kn, kn, K) + eps);
|
||||
for (int64_t d = 0; d < K; ++d) {
|
||||
qn[d] *= qi;
|
||||
kn[d] *= ki;
|
||||
const float z = gain * (ldt(&g, at(g, t, head, d, K)) +
|
||||
ldt(&bias, (head * K + d) * laststride(&bias)));
|
||||
decay[d] = std::exp(lower / (1 + std::exp(-z)));
|
||||
}
|
||||
const float beta = 1 / (1 + std::exp(-ldt(&b, at(b, t, head, 0, 1))));
|
||||
if (anchor && verify) {
|
||||
const int f = 1 + (int)(t - begin) * factors;
|
||||
for (int d = 0; d < 128; ++d) {
|
||||
stt(&s, factor_at(f + d), kn[d]);
|
||||
stt(&s, factor_at(f + 256 + d), decay[d]);
|
||||
}
|
||||
for (int e = 0; e < 128; ++e)
|
||||
stt(&s, factor_at(f + 128 + e), ldt(&v, at(v, t, head, e, V)));
|
||||
stt(&s, factor_at(f + 384), beta);
|
||||
}
|
||||
for (int64_t e = 0; e < V; ++e) {
|
||||
float* row = S + e * K;
|
||||
int64_t d = 0;
|
||||
for (; d + VF_N <= K; d += VF_N)
|
||||
vf_storeu(row + d, vf_mul(vf_loadu(row + d), vf_loadu(decay + d)));
|
||||
for (; d < K; ++d) row[d] *= decay[d];
|
||||
const float delta = beta * (ldt(&v, at(v, t, head, e, V)) - dot(row, kn, K));
|
||||
d = 0;
|
||||
for (; d + VF_N <= K; d += VF_N)
|
||||
vf_storeu(row + d, vf_fma(vf_set1(delta), vf_loadu(kn + d), vf_loadu(row + d)));
|
||||
for (; d < K; ++d) row[d] += delta * kn[d];
|
||||
stt(&out, at(out, t, head, e, V), dot(row, qn, K));
|
||||
}
|
||||
if ((!anchor && verify) || (!verify && t + 1 == end)) {
|
||||
const int64_t write =
|
||||
ldi(&idx, seq * idx.stride[0] + (verify ? t - begin : 0) * idx.stride[1]);
|
||||
if (write >= 0)
|
||||
for (int64_t e = 0; e < V; ++e)
|
||||
for (int64_t d = 0; d < K; ++d)
|
||||
stt(&s,
|
||||
write * s.stride[0] + head * s.stride[1] + e * s.stride[2] +
|
||||
d * s.stride[3],
|
||||
S[e * K + d]);
|
||||
}
|
||||
}
|
||||
if (anchor) stt(&s, factor_at(0), verify ? (float)(end - begin) : 0.0f);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -71,6 +71,16 @@ int avx_par_force(int threads);
|
||||
/* ---- elementwise and norms */ \
|
||||
X(rmsnorm) X(rmsnorm_p) X(rmsnorm_add) X(hc_enter) \
|
||||
X(hc_read) X(hc_write) X(mtp_enter) X(layernorm) \
|
||||
X(mhc_pre) X(mhc_post) X(mhc_contract) X(kda_update) \
|
||||
X(mhc_pre_partial) X(mhc_pre_finish) \
|
||||
X(swiglu_clamped) \
|
||||
X(router_sigmoid_topk) \
|
||||
X(dsa_pool) \
|
||||
X(dsa_query) \
|
||||
X(gemm_nt_f32) \
|
||||
X(mla_project) \
|
||||
X(dsa_score) \
|
||||
X(mla_attn) \
|
||||
X(add) X(grid_embed) X(grid_embed_aa) X(causal_conv1d) \
|
||||
X(mul) X(silu_mul) X(gelu_mul) X(gelu) \
|
||||
X(silu) X(sigmoid) X(logit_softcap) X(gather_rows) \
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
#include "avx_vec.h"
|
||||
#include "avx_common.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
using namespace avx;
|
||||
|
||||
AVX_KERNEL(mla_project) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
RadTensor x = a->t[0], y = a->t[2];
|
||||
const auto& w = a->t[1];
|
||||
const int64_t h = p_int(a, "heads", 0), d = p_int(a, "head_dim", 0),
|
||||
l = p_int(a, "latent_dim", 0);
|
||||
const char* mode = p_str(a, "mode", "");
|
||||
const bool absorb = !std::strcmp(mode, "absorb"), expand = !std::strcmp(mode, "expand");
|
||||
auto heads_view = [&](RadTensor& t, int64_t width) {
|
||||
if (h > 0 && width > 0 && t.rank == 2 && t.shape[1] == h * width) {
|
||||
t.rank = 3;
|
||||
t.shape[1] = h;
|
||||
t.shape[2] = width;
|
||||
t.stride[2] = t.stride[1];
|
||||
t.stride[1] *= width;
|
||||
}
|
||||
};
|
||||
heads_view(x, absorb ? d : l);
|
||||
heads_view(y, absorb ? l : d);
|
||||
if ((!absorb && !expand) || h < 1 || d < 1 || l < 1 || x.rank != 3 || w.rank != 2 ||
|
||||
y.rank != 3 || x.shape[0] < 1 || x.shape[1] != h || x.shape[2] != (absorb ? d : l) ||
|
||||
w.shape[0] != h * 2 * d || w.shape[1] != l || y.shape[0] != x.shape[0] || y.shape[1] != h ||
|
||||
y.shape[2] != (absorb ? l : d))
|
||||
return RAD_E_SHAPE;
|
||||
if (x.dtype != RAD_BF16 || w.dtype != RAD_BF16 || y.dtype != RAD_BF16) return RAD_E_DTYPE;
|
||||
if (!x.data || !w.data || !y.data) return RAD_E_INVAL;
|
||||
AVX_PARALLEL_FOR_IF(x.shape[0] * h * d * l >= AVX_PAR_MIN)
|
||||
for (int64_t job = 0; job < x.shape[0] * h; ++job) {
|
||||
const int64_t r = job / h, head = job % h;
|
||||
float* tmp = scratch_f32((size_t)(2 * (d + l)));
|
||||
float *query = tmp, *weights = tmp + d + l;
|
||||
for (int64_t j = 0; j < (absorb ? d : l); ++j)
|
||||
query[j] = ldt(&x, r * x.stride[0] + head * x.stride[1] + j * x.stride[2]);
|
||||
for (int64_t col = 0; col < (absorb ? l : d); ++col) {
|
||||
const int64_t nk = absorb ? d : l;
|
||||
for (int64_t j = 0; j < nk; ++j) {
|
||||
const int64_t wr = head * 2 * d + (absorb ? j : d + col), wc = absorb ? col : j;
|
||||
weights[j] = ldt(&w, wr * w.stride[0] + wc * w.stride[1]);
|
||||
}
|
||||
vf acc = vf_zero();
|
||||
int64_t j = 0;
|
||||
for (; j + VF_N <= nk; j += VF_N)
|
||||
acc = vf_fma(vf_loadu(query + j), vf_loadu(weights + j), acc);
|
||||
float sum = vf_hsum(acc);
|
||||
for (; j < nk; ++j) sum += query[j] * weights[j];
|
||||
stt(&y, r * y.stride[0] + head * y.stride[1] + col * y.stride[2], sum);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
AVX_KERNEL(mla_attn) {
|
||||
if (!rad_args_have(a, 5)) return RAD_E_INVAL;
|
||||
const auto &q = a->t[0], &kv = a->t[1], &bt = a->t[2], &len = a->t[3], &out = a->t[4];
|
||||
const int64_t d = p_int(a, "latent_dim", 0), h = p_int(a, "heads", 0),
|
||||
bs = p_int(a, "block_size", 0);
|
||||
const float scale = p_f32(a, "scale", 0);
|
||||
if (d < 1 || d > 2048 || h < 1 || bs < 1 || !std::isfinite(scale) || scale <= 0 ||
|
||||
q.rank != 3 || q.shape[0] < 1 || q.shape[1] != h || q.shape[2] != d || kv.rank != 4 ||
|
||||
kv.shape[1] != 1 || kv.shape[2] != bs || kv.shape[3] != d || bt.rank != 2 ||
|
||||
bt.shape[0] != q.shape[0] || len.rank != 1 || len.shape[0] != q.shape[0] || out.rank != 3 ||
|
||||
out.shape[0] != q.shape[0] || out.shape[1] != h || out.shape[2] != d ||
|
||||
bt.dtype != RAD_I32 || len.dtype != RAD_I32)
|
||||
return RAD_E_SHAPE;
|
||||
for (int i = 0; i < 5; ++i)
|
||||
if (!a->t[i].data) return RAD_E_INVAL;
|
||||
AVX_PARALLEL_FOR_IF(q.shape[0] * h * d * bt.shape[1] * bs >= AVX_PAR_MIN)
|
||||
for (int64_t job = 0; job < q.shape[0] * h; ++job) {
|
||||
const int64_t r = job / h, head = job % h;
|
||||
const int64_t live = std::clamp(ld_int_dt(len.dtype, len.data, r * len.stride[0]),
|
||||
(int64_t)0, bt.shape[1] * bs);
|
||||
float *tmp = scratch_f32((size_t)(3 * d)), *query = tmp, *key = tmp + d,
|
||||
*value = tmp + 2 * d;
|
||||
for (int64_t c = 0; c < d; ++c) {
|
||||
query[c] = ldt(&q, r * q.stride[0] + head * q.stride[1] + c * q.stride[2]);
|
||||
value[c] = 0;
|
||||
}
|
||||
float max = -INFINITY, den = 0;
|
||||
for (int64_t j = 0; j < live; ++j) {
|
||||
const int64_t page =
|
||||
ld_int_dt(bt.dtype, bt.data, r * bt.stride[0] + (j / bs) * bt.stride[1]);
|
||||
if (page < 0 || page >= kv.shape[0]) continue;
|
||||
const int64_t base = page * kv.stride[0] + (j % bs) * kv.stride[2];
|
||||
for (int64_t c = 0; c < d; ++c) key[c] = ldt(&kv, base + c * kv.stride[3]);
|
||||
vf acc = vf_zero();
|
||||
int64_t c = 0;
|
||||
for (; c + VF_N <= d; c += VF_N)
|
||||
acc = vf_fma(vf_loadu(query + c), vf_loadu(key + c), acc);
|
||||
float score = vf_hsum(acc);
|
||||
for (; c < d; ++c) score += query[c] * key[c];
|
||||
score *= scale;
|
||||
const float next = std::max(max, score), old = std::exp(max - next),
|
||||
w = std::exp(score - next);
|
||||
den = den * old + w;
|
||||
max = next;
|
||||
const vf a = vf_set1(old), b = vf_set1(w);
|
||||
c = 0;
|
||||
for (; c + VF_N <= d; c += VF_N)
|
||||
vf_storeu(value + c, vf_fma(vf_loadu(key + c), b, vf_mul(vf_loadu(value + c), a)));
|
||||
for (; c < d; ++c) value[c] = value[c] * old + key[c] * w;
|
||||
}
|
||||
for (int64_t c = 0; c < d; ++c)
|
||||
stt(&out, r * out.stride[0] + head * out.stride[1] + c * out.stride[2],
|
||||
den > 0 ? value[c] / den : 0);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
+2
-2
@@ -1098,7 +1098,7 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) {
|
||||
if (jc > 0 || (ts && cb_joined(wse[e]))) return RAD_E_DTYPE;
|
||||
}
|
||||
mw[e] = as_mat(&we[e], k);
|
||||
SW[e] = make_scales(quant && ts ? &wse[e] : nullptr, n, k, false);
|
||||
SW[e] = make_scales(quant && ts ? &wse[e] : nullptr, n, k, we[e].dtype == RAD_FP4E2M1);
|
||||
/* An activation scale grid finer than an expert's cannot be hoisted out of the group. No
|
||||
* supported format has one, but libref answers it by scaling each element, so the panel
|
||||
* below is scaled as it is packed and the dot reads no activation scale (`SAg`). */
|
||||
@@ -1218,7 +1218,7 @@ AVX_KERNEL(moe_gemm_q_mod4) { return moe_gemm_impl(a, true, 4); }
|
||||
/* y[t] = sum over the token's slots of expert_w[t, j] * y_expert[position of (t, j)], summed in
|
||||
* ascending slot j (see the file header). The inverse permutation is built once per batch. */
|
||||
AVX_KERNEL(moe_gather) {
|
||||
if (!rad_args_have(a, 6)) return RAD_E_INVAL;
|
||||
if (!a || !a->t || a->n_t < 6 || !rad_args_have(a, 3) || !rad_arg_in(a, 5)) return RAD_E_INVAL;
|
||||
const RadTensor *ye = &a->t[0], *ew = &a->t[1], *sorted = &a->t[2], *Y = &a->t[5];
|
||||
/* Optional shared-expert fold: y = narrow(shared * act(gate)) + narrow(gathered). Both
|
||||
* operands or neither, as in libref. */
|
||||
|
||||
@@ -67,6 +67,26 @@ static const RadOperandSpec oHcRead[] = { OPD("h"), WGT("w"), WGT("mix_down"),
|
||||
WGT_O("inject_w"), OUT("x"), OUT_O("inj"), OUT_O("q"),
|
||||
OUT_O("scale"), OUT_O("rq"), OUT_O("rscale") };
|
||||
|
||||
static const RadParamSpec pMhcPre[] = { P_INT("M"), P_INT("n"), P_INT("hc"),
|
||||
P_INT("iterations"), P_F64("eps"), P_F64("hc_eps"), P_STR("dtype") };
|
||||
static const RadOperandSpec oMhcPre[] = { OPD("h"), WGT("fn"), WGT("scale"), WGT("base"),
|
||||
OUT("x"), OUT("post"), OUT("comb") };
|
||||
static const RadParamSpec pMhcPrePartial[] = { P_INT("M"), P_INT("n"), P_INT("hc"),
|
||||
P_INT("chunk"), P_INT("first"), P_INT("chunks"), P_STR("dtype") };
|
||||
static const RadOperandSpec oMhcPrePartial[] = { OPD("h"), WGT("fn"), OUT("part") };
|
||||
static const RadParamSpec pMhcPreFinish[] = { P_INT("M"), P_INT("n"), P_INT("hc"),
|
||||
P_INT("iterations"), P_F64("eps"), P_F64("hc_eps"), P_INT("chunk"), P_STR("dtype") };
|
||||
static const RadOperandSpec oMhcPreFinish[] = { OPD("part"), OPD("h"), WGT("scale"), WGT("base"),
|
||||
OUT("x"), OUT("post"), OUT("comb") };
|
||||
static const RadOperandSpec oMhcPost[] = { OPD("x"), OPD("h"), OPD("post"), OPD("comb"), OUT("out") };
|
||||
static const RadOperandSpec oMhcContract[] = { OPD("h"), OUT("x") };
|
||||
static const RadParamSpec pKdaUpdate[] = { P_INT("M"), P_INT("heads"), P_INT("head_k"),
|
||||
P_INT("head_v"), P_F64("lower_bound"), P_F64("scale"), P_F64("l2_eps"),
|
||||
P_STR("mode"), P_STR("dtype"), P_STRO("state_form") };
|
||||
static const RadOperandSpec oKdaUpdate[] = { OPD("q"), OPD("k"), OPD("v"), OPD("a"), OPD("b"),
|
||||
WGT("A_log"), WGT("dt_bias"), INOUT("state"), OPD("state_idx"), OPD("cu"),
|
||||
OPD_O("num_accepted"), OPD_O("has_init"), OUT("o") };
|
||||
|
||||
static const RadParamSpec pNgramIds[] = { P_INT("M"), P_INT("heads"), P_INT("ngram"),
|
||||
P_INT("eos") };
|
||||
static const RadOperandSpec oNgramIds[] = { OPD("tok"), INOUT("state"), OPD("cu"), WGT("mult"),
|
||||
@@ -110,6 +130,22 @@ static const RadOperandSpec oLayernorm[] = { OPD("x"), WGT("w"), WGT_O("b"), OUT
|
||||
static const RadParamSpec pGridEmbed[] = { P_INT("M"), P_INT("n"), P_INT("side"), P_STR("dtype") };
|
||||
static const RadOperandSpec oGridEmbed[] = { INOUT("x"), WGT("table"), OPD("coord") };
|
||||
|
||||
static const RadParamSpec pSwigluClamped[] = { P_INT("M"), P_INT("n"), P_F64("limit"), P_STR("dtype") };
|
||||
static const RadParamSpec pDsaPool[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), P_STR("dtype"), P_INTO("block_size") };
|
||||
static const RadParamSpec pMlaAttn[] = { P_INT("M"), P_INT("latent_dim"), P_INT("heads"),
|
||||
P_INT("blocks"), P_INT("block_size"), P_F64("scale"), P_STR("dtype") };
|
||||
static const RadParamSpec pMlaProject[] = { P_INT("M"), P_INT("heads"), P_INT("head_dim"),
|
||||
P_INT("latent_dim"), P_STR("mode"), P_STR("dtype") };
|
||||
static const RadOperandSpec oMlaAttn[] = { OPD("q"), OPD("kv"), OPD("bt"), OPD("length"), OUT("out") };
|
||||
static const RadParamSpec pDsaScore[] = { P_INT("M"), P_INT("n"), P_INT("heads"),
|
||||
P_INT("blocks"), P_INT("seqs"), P_STR("dtype") };
|
||||
static const RadOperandSpec oDsaScore[] = { OPD("q"), OPD("q_scale"), OPD("gate"), OPD("k"),
|
||||
OPD_O("k_scale"), OPD("bt"), OPD("cu"), OPD("nc"), OUT("score") };
|
||||
static const RadOperandSpec oDsaPool[] = { OPD("kg"), WGT("ape"), OUT("q"), OUT("scale"),
|
||||
OPD_O("page"), INOUT_O("cache") };
|
||||
static const RadParamSpec pRouterSigmoid[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"),
|
||||
P_INT("norm"), P_F64("route_scale"), P_STR("dtype") };
|
||||
static const RadOperandSpec oRouterSigmoid[] = { OPD("logits"), WGT("bias"), OUT("ids"), OUT("weights") };
|
||||
static const RadParamSpec pMnD[] = { P_INT("M"), P_INT("n"), P_STR("dtype") };
|
||||
/* `add`'s `div` divides the rounded sum (libref's pAdd). */
|
||||
static const RadParamSpec pAdd[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_F64O("div") };
|
||||
@@ -697,6 +733,14 @@ static const RadOpSchema kSchemas[] = {
|
||||
"f32 sum, the multiply from residual_out after narrowing, as libref." },
|
||||
{ "hc_enter", ARR(pHcWrite), ARR(oHcEnter),
|
||||
"h[s] = x for each of the hc streams -- the wide residual stream's first value." },
|
||||
{ "mhc_pre", ARR(pMhcPre), ARR(oMhcPre), "Whole-residual RMS projection, sigmoid gates and Sinkhorn mixing." },
|
||||
{ "mhc_pre_partial", ARR(pMhcPrePartial), ARR(oMhcPrePartial),
|
||||
"mhc_pre's projection over chunks [first, first+chunks) of `chunk` columns, zero-padded per chunk." },
|
||||
{ "mhc_pre_finish", ARR(pMhcPreFinish), ARR(oMhcPreFinish),
|
||||
"mhc_pre from every chunk's partials: chunk sums, gates, Sinkhorn mixing, collapse." },
|
||||
{ "mhc_post", ARR(pHcWrite), ARR(oMhcPost), "Source-to-destination manifold residual update." },
|
||||
{ "mhc_contract", ARR(pHcWrite), ARR(oMhcContract), "Mean over manifold residual streams." },
|
||||
{ "kda_update", ARR(pKdaUpdate), ARR(oKdaUpdate), "Bounded per-channel KDA with candidate-state rollback." },
|
||||
{ "hc_read", ARR(pHcRead), ARR(oHcRead),
|
||||
"The read half of a gated residual: grouped norm, low-rank gate, stream mix, and optionally the "
|
||||
"block-scaled fp8 form of x and its Hadamard-rotated twin. See docs/OPS.md for the three facts "
|
||||
@@ -737,6 +781,20 @@ static const RadOpSchema kSchemas[] = {
|
||||
"local attention with a relative-position term and a softcap (Gemma 4's audio)." },
|
||||
{ "pool_rows", ARR(pPoolRows), ARR(oUnary),
|
||||
"y[r] = the mean of x's rows [r*k, r*k + k), rounded to y's dtype, times mult, rounded again." },
|
||||
{ "mla_attn", ARR(pMlaAttn), ARR(oMlaAttn),
|
||||
"Softmax over selected latent vectors used as both key and value; per-query page tables and visible lengths." },
|
||||
{ "mla_project", ARR(pMlaProject), ARR(oGemm),
|
||||
"Per-head query absorption or value expansion through the shared [head,(K|V),latent] BF16 matrix." },
|
||||
{ "dsa_score", ARR(pDsaScore), ARR(oDsaScore),
|
||||
"Per-head ReLU of FP8 dot products, then signed head gates and scales; invalid history is -inf." },
|
||||
{ "gemm_nt_f32", ARR(pGemm), ARR(oGemm),
|
||||
"BF16 activations times F32 weights, F32 accumulation and output; preserves routing and index gate precision." },
|
||||
{ "dsa_query", ARR(pMnD), ARR(oQuantFp8),
|
||||
"Normalized Hadamard, BF16 boundary and power-of-two E4M3 quantization per query head." },
|
||||
{ "dsa_pool", ARR(pDsaPool), ARR(oDsaPool),
|
||||
"Channel-wise softmax pooling with learned position bias, BF16, normalized Hadamard, BF16, power-of-two FP8." },
|
||||
{ "swiglu_clamped", ARR(pSwigluClamped), ARR(oGateUp),
|
||||
"silu(min(gate,limit))*clamp(up,-limit,limit); gate is the first half." },
|
||||
{ "silu_mul", ARR(pMnD), ARR(oGateUp),
|
||||
"silu-gated product over a fused [M, 2n] gate_up: y = silu(gate) * up." },
|
||||
{ "gelu_mul", ARR(pMnD), ARR(oGateUp),
|
||||
@@ -848,6 +906,8 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "qk_norm_rope", ARR(pQkNormRope), ARR(oQkNormRope), "per-head QK norm then rotary embedding." },
|
||||
{ "scale_rows", ARR(pScaleRows), ARR(oScaleRows),
|
||||
"one scalar per row, optionally through an activation, broadcast across the row." },
|
||||
{ "router_sigmoid_topk", ARR(pRouterSigmoid), ARR(oRouterSigmoid),
|
||||
"Single-group sigmoid routing; correction bias selects experts, original scores weight them." },
|
||||
{ "router_topk", ARR(pRouter), ARR(oRouter), "softmax then exact top-k routing." },
|
||||
{ "moe_scatter", ARR(pScatter), ARR(oScatter),
|
||||
"stable counting sort of routing slots by expert." },
|
||||
@@ -1160,6 +1220,12 @@ SIMPLE("avx_rmsnorm_add", "rmsnorm_add", "norm", "residual add then RMS norm", D
|
||||
L(rmsnorm_add)),
|
||||
SIMPLE("avx_hc_enter", "hc_enter", "norm", "gated residual entry: hc copies of x", DT_FLOAT,
|
||||
L(hc_enter)),
|
||||
SIMPLE("avx_mhc_pre", "mhc_pre", "norm", "manifold gates and Sinkhorn mixing", DT_FLOAT, L(mhc_pre)),
|
||||
SIMPLE("avx_mhc_pre_partial", "mhc_pre_partial", "norm", "manifold projection partials", DT_FLOAT, L(mhc_pre_partial)),
|
||||
SIMPLE("avx_mhc_pre_finish", "mhc_pre_finish", "norm", "manifold gates from projection partials", DT_FLOAT, L(mhc_pre_finish)),
|
||||
SIMPLE("avx_mhc_post", "mhc_post", "norm", "manifold residual update", DT_FLOAT, L(mhc_post)),
|
||||
SIMPLE("avx_mhc_contract", "mhc_contract", "norm", "mean of residual streams", DT_FLOAT, L(mhc_contract)),
|
||||
SIMPLE("avx_kda_update", "kda_update", "gdn", "bounded KDA and candidate-state rollback", DT_FLOAT, L(kda_update)),
|
||||
ROWL("avx_hc_read", "hc_read", "norm",
|
||||
"gated residual read: grouped norm, low-rank gate, stream mix",
|
||||
DT_FLOAT ", or mixing matrices of E4M3 / int8 codes with a scale plane, joined", L(hc_read),
|
||||
@@ -1203,6 +1269,20 @@ SIMPLE("avx_seg_sinusoid", "seg_sinusoid", "elem",
|
||||
SIMPLE("avx_attn_local_rel", "attn_local_rel", "attn",
|
||||
"local attention with a relative-position term and a softcap", DT_FLOAT,
|
||||
L(attn_local_rel)),
|
||||
SIMPLE("avx_mla_attn", "mla_attn", "attn", "absorbed latent MQA attention", DT_FLOAT,
|
||||
L(mla_attn)),
|
||||
SIMPLE("avx_dsa_score", "dsa_score", "attn", "weighted FP8 index scoring", DT_FLOAT,
|
||||
L(dsa_score)),
|
||||
SIMPLE("avx_dsa_pool", "dsa_pool", "attn", "learned compressed FP8 index keys", DT_FLOAT,
|
||||
L(dsa_pool)),
|
||||
SIMPLE("avx_dsa_query", "dsa_query", "attn", "normalized FP8 index queries", DT_FLOAT,
|
||||
L(dsa_query)),
|
||||
SIMPLE("avx_gemm_nt_f32", "gemm_nt_f32", "gemm", "F32 routing projection", DT_FLOAT,
|
||||
L(gemm_nt_f32)),
|
||||
SIMPLE("avx_mla_project", "mla_project", "attn", "absorbed MLA projections", DT_FLOAT,
|
||||
L(mla_project)),
|
||||
SIMPLE("avx_swiglu_clamped", "swiglu_clamped", "elem", "asymmetrically clipped SwiGLU", DT_FLOAT,
|
||||
L(swiglu_clamped)),
|
||||
SIMPLE("avx_silu_mul", "silu_mul", "elem", "silu-gated product over a fused gate_up", DT_FLOAT,
|
||||
L(silu_mul)),
|
||||
SIMPLE("avx_gelu_mul", "gelu_mul", "elem", "gelu_tanh-gated product over a fused gate_up", DT_FLOAT,
|
||||
@@ -1325,6 +1405,8 @@ SIMPLE("avx_qsa_work", "qsa_work", "attn",
|
||||
|
||||
SIMPLE("avx_router_topk", "router_topk", "moe", "softmax then exact top-k routing", DT_FLOAT,
|
||||
L(router_topk)),
|
||||
SIMPLE("avx_router_sigmoid_topk", "router_sigmoid_topk", "moe", "sigmoid correction-bias routing", DT_FLOAT,
|
||||
L(router_sigmoid_topk)),
|
||||
SIMPLE("avx_moe_scatter", "moe_scatter", "moe", "stable counting sort of routing slots by expert",
|
||||
"i32 indices", L(moe_scatter)),
|
||||
SIMPLE("avx_moe_gemm", "moe_gemm", "moe", "grouped GEMM over the expert-sorted rows", DT_FLOAT,
|
||||
|
||||
Reference in new issue
Block a user