Archived
merge origin/main: the upstream LoRA-runtime refactor beneath the ref2va port
Merges upstream 1.10.0 (152 commits: the LoRA acquire/runtime refactor, the
form-1 LTX-2 scheduler family, guidance terms + negative prompts, decoder
selection, input_reference, new architectures) into the ref2va port branch.
Resolution rule throughout: keep BOTH feature sets; ABI numbering follows
upstream (RAD_ABI_VERSION 26, RAD_FORMAT_VER 2), with the port's video fields
unioned into RadVideoGenBatch/RadVideoGenDecl and abi_layout_table.h
regenerated from the live table.
Notable reconciliations:
* videos.cpp: the task grammars are disjoint by capability -- keyframe tasks
(i2va/l2va/flash-attn l2va/fl2va) are recognized only when decl.encodes,
so upstream models keep refusing them as unknown tasks; input_reference,
the LoRA tag/field pipeline, and the guidance/negative_prompt rendering
coexist with refs/ref2va; the prompt put() helper hoisted to block scope
for the media branch.
* video_schedule(): upstream's (steps, video_tokens, refine) keeps its
positional slots; the port's shift_video/shift_audio overrides move to the
tail so upstream's schedule tests call unchanged.
* r4d_selftest conv3d cases: the port's sp/st/causal/down/refl geometry and
upstream's tpad/tpre fold into one reference (ft = causal ? 2 : tpad==2 ?
2+tpre : 1); rms_mod rows keep the port's i8/fp8 quant modes alongside
upstream's wadd/norm_once/norm parameters.
* tests/oot_plugins.sh: the per-plugin cmake --install gains a --prefix
staging dir -- plugin .so files still land in the absolute
RAD_PLUGIN_INSTALL_HOME, but libr4d now also installs r4d_selftest to a
relative bin/, which needs no root.
Host ctest: 112/113 (mm_test's webp gap pre-exists this merge); r4d_selftest,
engine_e2e, oot_plugins, abi_layout, all LoRA tests green.
Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
commit
a1a75da7e9
415 files changed
+78837
-5310
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
|
||||
@@ -51,6 +54,7 @@ set(AVX_KERNEL_SRC
|
||||
avx_gen.cpp
|
||||
avx_gen_attn.cpp
|
||||
avx_video.cpp
|
||||
avx_ltx.cpp
|
||||
avx_vsa.cpp
|
||||
avx_audio.cpp
|
||||
)
|
||||
|
||||
+5
-5
@@ -78,7 +78,7 @@ Every `RAD_E_UNSUPPORTED` a libavx kernel returns, beside libref's answer to the
|
||||
| `rope` | YaRN with `axial` or a position scale | the same |
|
||||
| `rope` | Llama 3 scaling beside YaRN, with `axial`, or over multi-component positions | the same |
|
||||
| `rope` | a rotary half-width over 1024 | the same |
|
||||
| `had_quant_act_i8`, `had_quant_act_fp8`, `rmsnorm_had_quant_i8`, `gated_had_quant_i8`, `hc_read` | a Hadamard group over 4096 | the same (`REF_HAD_MAX`) |
|
||||
| `had_quant_act_i8`, `had_quant_act_fp8`, `had_quant_act_i8g`, `rmsnorm_had_quant_i8`, `gated_had_quant_i8`, `hc_read` | a Hadamard group over 4096 | the same (`REF_HAD_MAX`) |
|
||||
| `gdn_conv_prep`, `gdn_conv_update` | a convolution history over 16 | the same |
|
||||
| `gdn_recurrent_update` | a `state_form` other than `per_candidate` or `anchor` | the same |
|
||||
| `ple_conv`, `causal_conv1d` | a history over 64 | the same |
|
||||
@@ -123,11 +123,11 @@ engine would load. It checks, in order: schema agreement (a copy of the loader's
|
||||
before any arithmetic, because the loader refuses the whole plugin on one disagreement), coverage,
|
||||
the numbers, and every ISA level. Each level prints:
|
||||
|
||||
522 checked, 522 passed, 0 failed, 0 declined, 0 skipped, 0 missing. worst rel_l2 = 3.556e-04
|
||||
924 checked, 924 passed, 0 failed, 0 declined, 0 skipped, 0 missing. worst rel_l2 = 3.556e-04
|
||||
worst case: rmsnorm M=3 n=645 eps=1e-05 dtype=bf16 wadd=1
|
||||
522 rerun on 4 threads, byte for byte
|
||||
hand-built: 198 checked, 0 failed
|
||||
zero rows: 116 ops checked, 0 failed
|
||||
924 rerun on 4 threads, byte for byte
|
||||
hand-built: 449 checked, 0 failed
|
||||
zero rows: 188 ops checked, 0 failed, 2 not reducible to zero rows
|
||||
|
||||
against `rad-kbench`'s tolerance table, ids (i32, u32, i64 outputs) exactly; the worst case differs
|
||||
per level. Every conversion is also checked exhaustively: all 256 or 65536 bit patterns of each
|
||||
|
||||
@@ -1646,3 +1646,181 @@ AVX_KERNEL(qsa_block_key) {
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ attn_cross */
|
||||
/* attn_dense with each entry's keys a run of their own (`cu_k`), libref's attn_cross: causal
|
||||
* counts from each run's start, and a query that sees no key is zero. The same tiled online
|
||||
* softmax as attn_dense's portable path. */
|
||||
AVX_KERNEL(attn_cross) {
|
||||
if (!rad_args_have(a, 6)) return RAD_E_INVAL;
|
||||
const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *cu = &a->t[3], *cuk = &a->t[4];
|
||||
const RadTensor *o = &a->t[5];
|
||||
const int64_t head_dim = p_int(a, "head_dim", q->rank >= 3 ? q->shape[q->rank - 1] : 0);
|
||||
const int64_t gqa = p_int(a, "gqa", 1);
|
||||
const int causal = (int)p_int(a, "causal", 0);
|
||||
if (head_dim <= 0 || gqa <= 0) return RAD_E_SHAPE;
|
||||
if (head_dim > AVX_HD_MAX) return RAD_E_UNSUPPORTED;
|
||||
const int64_t q_heads = q->rank >= 3 ? q->shape[q->rank - 2]
|
||||
: (q->rank == 2 ? q->shape[1] / head_dim : 1);
|
||||
const int64_t kv_heads = q_heads / gqa;
|
||||
if (kv_heads <= 0 || q_heads % gqa != 0) return RAD_E_SHAPE;
|
||||
const int64_t n_seq = numel(cu) - 1;
|
||||
if (n_seq <= 0 || numel(cuk) < n_seq + 1) return RAD_E_SHAPE;
|
||||
const int64_t total_q = numel(q) / (q_heads * head_dim);
|
||||
const int64_t total_k = numel(k) / (kv_heads * head_dim);
|
||||
if (total_q <= 0 || ldi(cu, offlin(cu, n_seq)) <= ldi(cu, offlin(cu, 0))) return RAD_E_SHAPE; /* zero rows */
|
||||
if (numel(o) < total_q * q_heads * head_dim) return RAD_E_SHAPE;
|
||||
for (int64_t s = 0; s < n_seq; ++s)
|
||||
if (ldi(cu, offlin(cu, s + 1)) < ldi(cu, offlin(cu, s)) ||
|
||||
ldi(cuk, offlin(cuk, s + 1)) < ldi(cuk, offlin(cuk, s)) ||
|
||||
ldi(cu, offlin(cu, s + 1)) > total_q || ldi(cuk, offlin(cuk, s + 1)) > total_k)
|
||||
return RAD_E_SHAPE;
|
||||
|
||||
const int64_t q_ds = q->rank >= 2 ? q->stride[q->rank - 1] : 1;
|
||||
const int64_t q_hs = q->rank >= 3 ? q->stride[q->rank - 2] : head_dim * q_ds;
|
||||
const int64_t q_rs = row_stride(q, q_heads * head_dim);
|
||||
const int64_t k_ds = k->rank >= 2 ? k->stride[k->rank - 1] : 1;
|
||||
const int64_t k_hs = k->rank >= 3 ? k->stride[k->rank - 2] : head_dim * k_ds;
|
||||
const int64_t k_rs = row_stride(k, kv_heads * head_dim);
|
||||
const int64_t v_ds = v->rank >= 2 ? v->stride[v->rank - 1] : 1;
|
||||
const int64_t v_hs = v->rank >= 3 ? v->stride[v->rank - 2] : head_dim * v_ds;
|
||||
const int64_t v_rs = row_stride(v, kv_heads * head_dim);
|
||||
const int64_t o_ds = o->rank >= 2 ? o->stride[o->rank - 1] : 1;
|
||||
const int64_t o_hs = o->rank >= 3 ? o->stride[o->rank - 2] : head_dim * o_ds;
|
||||
const int64_t o_rs = row_stride(o, q_heads * head_dim);
|
||||
const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim));
|
||||
|
||||
AVX_PARALLEL_FOR_IF(n_seq * q_heads >= 2)
|
||||
for (int64_t sh = 0; sh < n_seq * q_heads; ++sh) {
|
||||
const int64_t s = sh / q_heads, h = sh % q_heads, kh = h / gqa;
|
||||
const int64_t b0 = ldi(cu, offlin(cu, s)), b1 = ldi(cu, offlin(cu, s + 1));
|
||||
const int64_t k0 = ldi(cuk, offlin(cuk, s)), k1 = ldi(cuk, offlin(cuk, s + 1));
|
||||
float* frame = (float*)scratch_f32((size_t)(4 * head_dim + AVX_KV_TILE) + 16);
|
||||
float* qbuf = frame;
|
||||
float* kbuf = frame + head_dim;
|
||||
float* vbuf = frame + 2 * head_dim;
|
||||
float* acc = frame + 3 * head_dim;
|
||||
float* sbuf = frame + 4 * head_dim;
|
||||
int64_t vbase[AVX_KV_TILE];
|
||||
for (int64_t i = b0; i < b1; ++i) {
|
||||
const int64_t qb = i * q_rs + h * q_hs, ob = i * o_rs + h * o_hs;
|
||||
const int64_t jend = causal ? std::min<int64_t>(k1, k0 + (i - b0) + 1) : k1;
|
||||
const float* qv = head_f32(q, qb, q_ds, head_dim, 1.0f, qbuf);
|
||||
for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f;
|
||||
float m = -INFINITY, l = 0.0f;
|
||||
int ntile = 0;
|
||||
auto flush = [&]() {
|
||||
if (ntile == 0) return;
|
||||
float tmax = sbuf[0];
|
||||
for (int t = 1; t < ntile; ++t) if (sbuf[t] > tmax) tmax = sbuf[t];
|
||||
if (tmax > m) {
|
||||
const float r = (m == -INFINITY) ? 0.0f : sc_exp(m - tmax);
|
||||
if (r != 1.0f) {
|
||||
for (int64_t d = 0; d < head_dim; ++d) acc[d] *= r;
|
||||
l *= r;
|
||||
}
|
||||
m = tmax;
|
||||
}
|
||||
for (int t = 0; t < ntile; ++t) sbuf[t] = sc_exp(sbuf[t] - m);
|
||||
for (int t = 0; t < ntile; ++t) {
|
||||
const float w = sbuf[t];
|
||||
l += w;
|
||||
axpy(acc, head_f32(v, vbase[t], v_ds, head_dim, 1.0f, vbuf), w, head_dim);
|
||||
}
|
||||
ntile = 0;
|
||||
};
|
||||
for (int64_t j = k0; j < jend; ++j) {
|
||||
const float* kvr = head_f32(k, j * k_rs + kh * k_hs, k_ds, head_dim, 1.0f, kbuf);
|
||||
sbuf[ntile] = dotf(qv, kvr, head_dim) * scale;
|
||||
vbase[ntile] = j * v_rs + kh * v_hs;
|
||||
if (++ntile == AVX_KV_TILE) flush();
|
||||
}
|
||||
flush();
|
||||
if (m == -INFINITY) {
|
||||
for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, 0.0f);
|
||||
continue;
|
||||
}
|
||||
const float inv = l > 0.0f ? 1.0f / l : 0.0f;
|
||||
for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, acc[d] * inv);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* attn_na3d: libref's neighborhood attention (libref/ref_attn.cpp), the window's keys through
|
||||
* attn_cross's online softmax. */
|
||||
AVX_KERNEL(attn_na3d) {
|
||||
if (!rad_args_have(a, 5)) return RAD_E_INVAL;
|
||||
const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *G = &a->t[3], *o = &a->t[4];
|
||||
const int64_t head_dim = p_int(a, "head_dim", 0);
|
||||
const int64_t kt = p_int(a, "kt", 0), kh = p_int(a, "kh", 0), kw = p_int(a, "kw", 0);
|
||||
if (head_dim <= 0 || kt <= 0 || kh <= 0 || kw <= 0 || numel(G) < 3 || q->rank != 2)
|
||||
return RAD_E_SHAPE;
|
||||
if (head_dim > AVX_HD_MAX) return RAD_E_UNSUPPORTED;
|
||||
const int64_t heads = q->shape[1] / head_dim;
|
||||
const int64_t T = ldi(G, offlin(G, 0)), H = ldi(G, offlin(G, 1)), W = ldi(G, offlin(G, 2));
|
||||
if (heads <= 0 || q->shape[1] % head_dim || T <= 0 || H <= 0 || W <= 0) return RAD_E_SHAPE;
|
||||
const int64_t N = std::min(q->shape[0], T * H * W);
|
||||
if (N <= 0 || numel(k) < N * heads * head_dim || numel(v) < N * heads * head_dim ||
|
||||
numel(o) < N * heads * head_dim)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t nt = std::min(kt, T), nh = std::min(kh, H), nw = std::min(kw, W);
|
||||
const int64_t q_ds = q->stride[1], q_rs = row_stride(q, heads * head_dim);
|
||||
const int64_t k_ds = k->rank >= 2 ? k->stride[k->rank - 1] : 1, k_rs = row_stride(k, heads * head_dim);
|
||||
const int64_t v_ds = v->rank >= 2 ? v->stride[v->rank - 1] : 1, v_rs = row_stride(v, heads * head_dim);
|
||||
const int64_t o_ds = o->rank >= 2 ? o->stride[o->rank - 1] : 1, o_rs = row_stride(o, heads * head_dim);
|
||||
const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim));
|
||||
auto start = [](int64_t c, int64_t n, int64_t L) {
|
||||
return std::min(std::max<int64_t>(c - n / 2, 0), L - n);
|
||||
};
|
||||
AVX_PARALLEL_FOR_IF(N * heads >= 2)
|
||||
for (int64_t rh = 0; rh < N * heads; ++rh) {
|
||||
const int64_t r = rh / heads, h = rh % heads;
|
||||
const int64_t t = r / (H * W), i = (r / W) % H, j = r % W;
|
||||
const int64_t t0 = start(t, nt, T), i0 = start(i, nh, H), j0 = start(j, nw, W);
|
||||
float* frame = (float*)scratch_f32((size_t)(4 * head_dim + AVX_KV_TILE) + 16);
|
||||
float* qbuf = frame;
|
||||
float* kbuf = frame + head_dim;
|
||||
float* vbuf = frame + 2 * head_dim;
|
||||
float* acc = frame + 3 * head_dim;
|
||||
float* sbuf = frame + 4 * head_dim;
|
||||
int64_t vbase[AVX_KV_TILE];
|
||||
const int64_t ob = r * o_rs + h * head_dim * o_ds;
|
||||
const float* qv = head_f32(q, r * q_rs + h * head_dim * q_ds, q_ds, head_dim, 1.0f, qbuf);
|
||||
for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f;
|
||||
float m = -INFINITY, l = 0.0f;
|
||||
int ntile = 0;
|
||||
auto flush = [&]() {
|
||||
if (ntile == 0) return;
|
||||
float tmax = sbuf[0];
|
||||
for (int u = 1; u < ntile; ++u) if (sbuf[u] > tmax) tmax = sbuf[u];
|
||||
if (tmax > m) {
|
||||
const float rr = (m == -INFINITY) ? 0.0f : sc_exp(m - tmax);
|
||||
if (rr != 1.0f) {
|
||||
for (int64_t d = 0; d < head_dim; ++d) acc[d] *= rr;
|
||||
l *= rr;
|
||||
}
|
||||
m = tmax;
|
||||
}
|
||||
for (int u = 0; u < ntile; ++u) sbuf[u] = sc_exp(sbuf[u] - m);
|
||||
for (int u = 0; u < ntile; ++u) {
|
||||
l += sbuf[u];
|
||||
axpy(acc, head_f32(v, vbase[u], v_ds, head_dim, 1.0f, vbuf), sbuf[u], head_dim);
|
||||
}
|
||||
ntile = 0;
|
||||
};
|
||||
for (int64_t a1 = t0; a1 < t0 + nt; ++a1)
|
||||
for (int64_t b1 = i0; b1 < i0 + nh; ++b1)
|
||||
for (int64_t c1 = j0; c1 < j0 + nw; ++c1) {
|
||||
const int64_t key = (a1 * H + b1) * W + c1;
|
||||
const float* kr = head_f32(k, key * k_rs + h * head_dim * k_ds, k_ds, head_dim, 1.0f, kbuf);
|
||||
sbuf[ntile] = dotf(qv, kr, head_dim) * scale;
|
||||
vbase[ntile] = key * v_rs + h * head_dim * v_ds;
|
||||
if (++ntile == AVX_KV_TILE) flush();
|
||||
}
|
||||
flush();
|
||||
const float inv = l > 0.0f ? 1.0f / l : 0.0f;
|
||||
for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, acc[d] * inv);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -1108,6 +1108,37 @@ AVX_KERNEL(iota) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ int_affine */
|
||||
/* y[j] = (src[j] < 0 ? 0 : x[src[j]]) * mul[j] + add[j] over three integer lists. */
|
||||
static int avx_parse_ints(const char* s, int64_t* v, int cap) {
|
||||
int n = 0;
|
||||
while (s && *s) {
|
||||
char* e = nullptr;
|
||||
const long long x = std::strtoll(s, &e, 10);
|
||||
if (e == s) break;
|
||||
if (n == cap) return -1;
|
||||
v[n++] = x;
|
||||
s = e;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
AVX_KERNEL(int_affine) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *Y = &a->t[1];
|
||||
int64_t src[16], mul[16], add[16];
|
||||
const int n = avx_parse_ints(p_str(a, "src", ""), src, 16);
|
||||
if (n <= 0 || avx_parse_ints(p_str(a, "mul", ""), mul, 16) != n ||
|
||||
avx_parse_ints(p_str(a, "add", ""), add, 16) != n || numel(Y) < n)
|
||||
return RAD_E_SHAPE;
|
||||
for (int j = 0; j < n; ++j) {
|
||||
if (src[j] >= numel(X)) return RAD_E_SHAPE;
|
||||
const int64_t v = src[j] < 0 ? 0 : at(X, src[j]);
|
||||
st_int_dt(Y->dtype, Y->data, offlin(Y, j), v * mul[j] + add[j]);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ cu_repeat */
|
||||
/* y[j] = j * len[0] * mult over y's elements: the bounds of equal sequences. */
|
||||
AVX_KERNEL(cu_repeat) {
|
||||
|
||||
+144
-6
@@ -117,7 +117,47 @@ 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_project",{ HI("M", 5), HI("n", 128), HI("hc", 4), HF("scale", 1.0),
|
||||
HS("dtype", dt) });
|
||||
/* The model's own width: Qwen3.8-Flash-Next's stream is 2560 wide with hc 4, and a decode
|
||||
* step is one row per sequence (with speculation, up to 1 + depth). One case at that
|
||||
* geometry is what says whether 41 of these a step is affordable. */
|
||||
add("hc_project",{ HI("M", 4), HI("n", 2560), HI("hc", 4), HF("scale", 1.0),
|
||||
HS("dtype", "bf16") });
|
||||
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),
|
||||
HI("group", 0) });
|
||||
@@ -138,6 +178,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));
|
||||
@@ -157,6 +201,8 @@ std::vector<Case> build_cases() {
|
||||
HS("dtype", "bf16") }, EB(5, 256, 2, 1.5));
|
||||
add("had_quant_act_fp8", { HI("M", 5), HI("n", 256), HI("group", group),
|
||||
HS("dtype", "bf16") });
|
||||
add("had_quant_act_i8g", { HI("M", 5), HI("n", 256), HI("group", group),
|
||||
HS("dtype", "bf16") });
|
||||
add("had_quant_act_i8", { HI("M", 5), HI("n", 256), HI("group", group),
|
||||
HS("dtype", "bf16") });
|
||||
add("dequant", { HI("M", 5), HI("n", 256), HI("group", group),
|
||||
@@ -216,7 +262,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),
|
||||
@@ -225,11 +271,14 @@ std::vector<Case> build_cases() {
|
||||
add("gemm_nt_q_bias", { HI("M", M), HI("N", 96), HI("K", 256), HI("group", 128),
|
||||
HS("dtype", dt) }, 0, fl);
|
||||
}
|
||||
/* The int8 trunk (row-major codes, a scale per row per 128 of K on both sides) and OCP-MXFP4
|
||||
* (e2m1 codes with an E8M0 exponent per 32 of K against the E4M3 activation). */
|
||||
/* The int8 trunk (row-major codes, a scale per row per 128 of K on both sides; i8a8h is the
|
||||
* same operands over a rotated weight) and OCP-MXFP4 (e2m1 codes with an E8M0 exponent per 32
|
||||
* of K against the E4M3 activation). */
|
||||
for (int M : { 1, 65 }) {
|
||||
add("gemm_nt_q", { HI("M", M), HI("N", 96), HI("K", 256), HI("group", 128),
|
||||
HS("dtype", "i8a8") }, 0, 2.0 * M * 96 * 256);
|
||||
add("gemm_nt_q", { HI("M", M), HI("N", 96), HI("K", 256), HI("group", 128),
|
||||
HS("dtype", "i8a8h") }, 0, 2.0 * M * 96 * 256);
|
||||
add("gemm_nt_q", { HI("M", M), HI("N", 96), HI("K", 256), HI("group", 32),
|
||||
HS("dtype", "mxfp4a8") }, 0, 2.0 * M * 96 * 256);
|
||||
}
|
||||
@@ -276,8 +325,9 @@ std::vector<Case> build_cases() {
|
||||
add("lora_shrink", { HI("M", M), HI("K", K), HI("R", 48), HI("S", 4),
|
||||
HI("group", 128), HS("dtype", dt) }, 0, 2.0 * M * 48 * K);
|
||||
for (const char* dt : { "f32", "bf16", "f16" })
|
||||
add("lora_expand", { HI("M", M), HI("N", 645), HI("R", 48), HI("S", 4),
|
||||
HS("dtype", dt) }, 0, 2.0 * M * 645 * 48);
|
||||
for (const char* op : { "lora_expand", "lora_expand_mm" })
|
||||
add(op, { HI("M", M), HI("N", 645), HI("R", 48), HI("S", 4), HS("dtype", dt) }, 0,
|
||||
2.0 * M * 645 * 48);
|
||||
}
|
||||
for (const char* dt : { "f32", "bf16" }) {
|
||||
add("embed_lookup", { HI("M", 9), HI("n_embd", 128), HI("n_vocab", 64), HS("dtype", dt),
|
||||
@@ -326,6 +376,17 @@ std::vector<Case> build_cases() {
|
||||
add("attn_dense", { HI("M", 24), HI("head_dim", 256), HI("gqa", 1), HI("causal", 1),
|
||||
HS("dtype", dt), HF("scale", 0.125), HI("max_seqlen", 24),
|
||||
HI("window", 8) });
|
||||
/* Cross attention: each entry's keys a run of their own, both sides of `causal`. */
|
||||
for (const char* dt : { "f32", "bf16" })
|
||||
for (int causal : { 0, 1 })
|
||||
add("attn_cross", { HI("M", 24), HI("head_dim", 64), HI("gqa", 2),
|
||||
HI("causal", causal), HS("dtype", dt), HF("scale", 0.125) });
|
||||
/* Neighborhood attention: a 4 x 4 x 4 volume (the description's), windows narrower and as wide
|
||||
* as its axes. */
|
||||
for (const char* dt : { "f32", "bf16" })
|
||||
for (int kw : { 3, 4 })
|
||||
add("attn_na3d", { HI("M", 64), HI("head_dim", 64), HI("kt", 3), HI("kh", 3),
|
||||
HI("kw", kw), HS("dtype", dt) });
|
||||
for (const char* dt : { "f32", "bf16" })
|
||||
add("seg_sinusoid", { HI("M", 30), HI("n", 64), HI("period", 13), HS("dtype", dt) });
|
||||
/* Gemma 4's audio attention: left 12, over segments longer than the window. */
|
||||
@@ -443,6 +504,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),
|
||||
@@ -527,6 +592,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
|
||||
@@ -658,10 +726,16 @@ std::vector<Case> build_cases() {
|
||||
EB(7, 645, dt[0] == 'f' ? 4 : 2, 3));
|
||||
add("gate_add", { HI("M", 7), HI("n", 645), HS("dtype", dt), HS("act", "none") },
|
||||
EB(7, 645, dt[0] == 'f' ? 4 : 2, 3));
|
||||
add("table_add", { HI("M", 3), HI("n", 645), HI("L", 5), HS("dtype", dt) });
|
||||
add("mix_rows", { HI("M", 7), HI("n", 645), HI("k", 12), HS("dtype", dt) });
|
||||
for (const char* mode : { "denorm", "norm" })
|
||||
for (int var : { 0, 1 })
|
||||
add("chan_stats", { HI("M", 7), HI("n", 645), HS("mode", mode), HI("var", var),
|
||||
HF("eps", 1e-4), HS("dtype", dt) });
|
||||
for (int gated : { 1, 0 })
|
||||
add("ln_mod_quant_fp8", { HI("M", 5), HI("n", 256), HF("eps", 1e-6), HI("group", 128),
|
||||
HI("gated", gated), HS("dtype", dt) });
|
||||
for (int round : { 1, 0 })
|
||||
for (int round : { 3, 2, 1, 0 })
|
||||
add("timestep_embed", { HI("M", 3), HI("n", 256), HF("scale", 1000.0),
|
||||
HF("max_period", 10000.0), HI("round", round),
|
||||
HS("dtype", dt) });
|
||||
@@ -673,6 +747,10 @@ std::vector<Case> build_cases() {
|
||||
add("randn_lanes", { HI("M", 24), HI("n", 64), HI("stride", 16), HI("n_seq", 2),
|
||||
HS("dtype", dt) });
|
||||
add("flow_euler", { HI("M", 24), HI("n", 64), HI("stride", 16), HS("dtype", dt) });
|
||||
add("kd_input", { HI("M", 24), HI("n", 4), HI("stride", 16), HS("dtype", dt) });
|
||||
for (const char* pred : { "eps", "v" })
|
||||
add("kd_step", { HI("M", 24), HI("n", 4), HI("stride", 16), HS("pred", pred),
|
||||
HS("dtype", dt) });
|
||||
for (const char* mode : { "fma", "inv" })
|
||||
for (int round : { 1, 0 })
|
||||
add("chan_affine", { HI("M", 9), HI("n", 67), HS("mul", kMul.c_str()),
|
||||
@@ -682,6 +760,7 @@ std::vector<Case> build_cases() {
|
||||
add("l2norm_chan", { HI("M", 9), HI("n", 645), HS("act", act), HS("dtype", dt) });
|
||||
add("to_rgba8", { HI("M", 9), HI("n", 4), HS("dtype", dt) });
|
||||
add("gelu_tanh", { HI("M", 6), HI("n", 645), HS("dtype", dt) });
|
||||
add("gelu_quick", { HI("M", 6), HI("n", 645), HS("dtype", dt) });
|
||||
add("scatter_add_rows", { HI("M", 6), HI("n", 645), HS("dtype", dt) });
|
||||
struct Conv { int M, cin, cout, k, stride, up; const char* pad; };
|
||||
static const Conv kConv[] = {
|
||||
@@ -696,6 +775,17 @@ std::vector<Case> build_cases() {
|
||||
HI("stride", v.stride), HS("pad", v.pad), HI("up", v.up),
|
||||
HS("dtype", dt) },
|
||||
0, 2.0 * v.M * v.cout * v.cin * v.k * v.k);
|
||||
/* The convolutions' geometries once each: cout is not a parameter of the unfold. */
|
||||
for (const Conv& v : kConv) {
|
||||
bool seen = false;
|
||||
for (const Conv* u = kConv; u != &v; ++u)
|
||||
seen = seen || (u->M == v.M && u->cin == v.cin && u->k == v.k &&
|
||||
u->stride == v.stride && u->up == v.up && u->pad == v.pad);
|
||||
if (seen) continue;
|
||||
add("im2col_nhwc", { HI("M", v.M), HI("cin", v.cin), HI("k", v.k),
|
||||
HI("stride", v.stride), HS("pad", v.pad), HI("up", v.up),
|
||||
HS("dtype", dt) });
|
||||
}
|
||||
for (int ft : { 1, 2 }) {
|
||||
add("d2s_add", { HI("M", 64), HI("cin", 24), HI("cout", 24), HI("ft", ft),
|
||||
HS("dtype", dt) });
|
||||
@@ -738,6 +828,17 @@ std::vector<Case> build_cases() {
|
||||
HS("dtype", dt) });
|
||||
add("rms_mod_quant_fp8", { HI("M", 5), HI("n", 256), HF("eps", 1e-5), HI("group", 128),
|
||||
HI("gated", gated), HS("dtype", dt) });
|
||||
/* A zero-centred gain (1 + w), the norm and gain rounded once (Krea 2's). */
|
||||
add("rms_mod", { HI("M", 7), HI("n", 645), HF("eps", 1e-5), HI("gated", gated),
|
||||
HS("dtype", dt), HF("wadd", 1.0), HI("norm_once", 1) });
|
||||
add("rms_mod_quant_fp8", { HI("M", 5), HI("n", 256), HF("eps", 1e-5), HI("group", 128),
|
||||
HI("gated", gated), HS("dtype", dt), HF("wadd", 1.0),
|
||||
HI("norm_once", 1) });
|
||||
/* A LayerNorm without a gain (FLUX's). */
|
||||
add("rms_mod", { HI("M", 7), HI("n", 645), HF("eps", 1e-6), HI("gated", gated),
|
||||
HS("dtype", dt), HS("norm", "layer") });
|
||||
add("rms_mod_quant_fp8", { HI("M", 5), HI("n", 256), HF("eps", 1e-6), HI("group", 128),
|
||||
HI("gated", gated), HS("dtype", dt), HS("norm", "layer") });
|
||||
}
|
||||
add("flow_x0_step", { HI("M", 9), HI("n", 645), HS("dtype", dt) });
|
||||
for (int pt : { 1, 4 })
|
||||
@@ -798,6 +899,37 @@ std::vector<Case> build_cases() {
|
||||
add("flow_renoise", { HI("M", 9), HI("n", 96), HI("stream", 1), HS("dtype", "f32") });
|
||||
add("flow_renoise", { HI("M", 5), HI("n", 645), HI("stream", 7), HS("dtype", "f32") });
|
||||
|
||||
/* LTX-2: the video's 3-axis rotary (two padded pairs, a rank's second head), the cross
|
||||
* attentions' 1-axis one, the per-head gate and the guided step. */
|
||||
for (const char* dt : { "f32", "bf16" }) {
|
||||
add("rope_split", { HI("M", 7), HI("n_head", 3), HI("head_dim", 128), HI("dim", 4096),
|
||||
HI("n_dims", 3), HF("theta", 10000.0), HS("max", "20 2048 2048"),
|
||||
HI("head0", 1), HS("dtype", dt) });
|
||||
add("rope_split", { HI("M", 5), HI("n_head", 4), HI("head_dim", 64), HI("dim", 256),
|
||||
HI("n_dims", 1), HF("theta", 10000.0), HS("max", "20"),
|
||||
HS("dtype", dt) });
|
||||
add("head_gate", { HI("M", 7), HI("n_head", 5), HI("head_dim", 64), HS("dtype", dt) });
|
||||
add("ltx_guide", { HI("M", 9), HI("n", 128), HS("dtype", dt) });
|
||||
add("pixel_norm", { HI("M", 26), HI("n", 96), HF("eps", 1e-6), HS("form", "rsqrt"),
|
||||
HI("ileave", 13), HF("mult", 3.7), HS("dtype", dt) });
|
||||
add("pixel_norm", { HI("M", 7), HI("n", 256), HF("eps", 1e-8), HS("form", "div"),
|
||||
HS("act", "silu"), HS("dtype", dt) });
|
||||
add("d2s3d", { HI("M", 27), HI("C", 5), HI("st", 2), HI("sh", 2), HI("sw", 2),
|
||||
HS("dtype", dt) });
|
||||
add("s2d3d", { HI("M", 27), HI("C", 4), HI("st", 2), HI("sh", 1), HI("sw", 1),
|
||||
HI("tpre", 1), HS("mode", "copy"), HS("dtype", dt) });
|
||||
add("s2d3d", { HI("M", 64), HI("C", 6), HI("st", 2), HI("sh", 2), HI("sw", 2),
|
||||
HI("group", 4), HS("mode", "mean"), HI("add", 1), HS("dtype", dt) });
|
||||
add("pix_patch", { HI("M", 12), HI("p", 4), HI("C", 3), HS("dtype", dt) });
|
||||
add("patch_pix8", { HI("M", 12), HI("p", 4), HI("C", 3), HS("dtype", dt) });
|
||||
add("stft_logmel", { HI("M", 6), HI("hop", 80), HI("nfft", 512), HI("n_mel", 64),
|
||||
HI("ch", 2), HS("dtype", dt) });
|
||||
add("bwe_up", { HI("M", 600), HI("ratio", 3), HI("ch", 2), HS("dtype", dt) });
|
||||
add("tile_crop", { HI("M", 125), HI("C", 7), HS("dtype", dt) });
|
||||
add("tile_stitch", { HI("M", 4000), HI("tile", 4), HI("stride", 3), HI("scale", 2),
|
||||
HI("p", 4), HI("C", 3), HS("dtype", dt) });
|
||||
}
|
||||
|
||||
/* Video sparse attention over the cubes libref describes: a 3 x 3 x 3 grid in boxes of 2
|
||||
* after two dense segments of as many rows (P 8, V 8; sparsity 0.8 keeps 2), with and without
|
||||
* the coarse operands; and MiniMax-H3's boxes of 4 at patch 2 over a 10 x 5 x 5 grid after
|
||||
@@ -939,9 +1071,13 @@ std::vector<Case> build_cases() {
|
||||
add("frame_store", { HI("M", 4), HI("n_codes", 3), HI("stride", 5), HI("rep", 1),
|
||||
HI("skip", 1) });
|
||||
add("iota", { HI("M", 645), HI("start", 3), HI("step", 2) });
|
||||
add("tile_grid", { HI("M", 9), HI("tile", 16), HI("stride", 14) });
|
||||
add("vol_index", { HI("M", 125) });
|
||||
add("iota", { HI("M", 7), HI("start", -5), HI("step", 1) });
|
||||
add("cu_repeat", { HI("M", 5), HI("mult", 3) });
|
||||
add("cu_repeat", { HI("M", 9), HI("mult", 1) });
|
||||
add("int_affine", { HI("M", 4), HS("src", "0 -1 2 1"), HS("mul", "2 0 8 4"),
|
||||
HS("add", "-1 7 -7 -3") });
|
||||
|
||||
/* ================================================================== speed-only, at model size
|
||||
*
|
||||
@@ -982,6 +1118,8 @@ std::vector<Case> build_cases() {
|
||||
HS("dtype", "bf16") }, (double)M * 2048 * 3, 0);
|
||||
speed("quant_act_i8g", { HI("M", M), HI("n", 2048), HI("group", 128),
|
||||
HS("dtype", "bf16") }, (double)M * 2048 * 3, 0);
|
||||
speed("had_quant_act_i8g", { HI("M", M), HI("n", 2048), HI("group", 128),
|
||||
HS("dtype", "bf16") }, (double)M * 2048 * 3, 0);
|
||||
speed("had_quant_act_i8", { HI("M", M), HI("n", 2048), HI("group", 128),
|
||||
HS("dtype", "bf16") }, (double)M * 2048 * 3, 0);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
@@ -1793,6 +1913,51 @@ void gen_cases(std::vector<Hand>& hs) {
|
||||
.pi("M", 17).pi("n", n).pi("stride", 6).ps("dtype", dn);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
{
|
||||
/* The k-diffusion input: entry 0 a first step guided against entry 1 (pair -2, which
|
||||
* only its positive entry writes), entry 2 a later step, unguided, in lane 3. */
|
||||
static const uint32_t kSeeds[6] = { 11u, 0u, 0u, 0u, 0xfeedbeefu, 3u };
|
||||
Hand h(("first, parked, later, n 4" + sfx).c_str(), "kd_input", 0.0);
|
||||
h.dense(RAD_F32, { 3 }, [](int64_t i) { return 14.6f - 6.0f * (float)i; })
|
||||
.idx({ 1, -2, -1 })
|
||||
.idx({ 0, 1, 3 })
|
||||
.idx({ 1, 0, 0 })
|
||||
.raw(RAD_U32, { 6 }, kSeeds)
|
||||
.idx({ 0, 5, 10, 13 })
|
||||
.dense(RAD_F32, { 24, 4 }, hfill(227), true)
|
||||
.dense(dt, { 13, 4 }, zero, true)
|
||||
.pi("M", 13).pi("n", 4).pi("stride", 6).ps("dtype", dn);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
for (const char* pred : { "eps", "v" }) {
|
||||
/* Every sampler: entry 0 Euler guided against entry 1 with a preview, entry 2 Euler
|
||||
* ancestral at step 7, entry 3 DPM++ 2M past its first step, entry 4 DPM++ 2M's first
|
||||
* step, entry 5 Euler ancestral to sigma 0, entry 6 DPM++ 2M to sigma 0. */
|
||||
static const uint32_t kSeeds[14] = { 3u, 0u, 4u, 0u, 5u, 9u, 6u, 1u, 7u, 0u, 8u, 0u,
|
||||
9u, 2u };
|
||||
Hand h(("seven entries, every sampler, " + std::string(pred) + sfx).c_str(), "kd_step",
|
||||
0.0);
|
||||
static const float kS[7] = { 6.0f, 6.0f, 3.5f, 1.25f, 9.0f, 0.4f, 0.3f };
|
||||
static const float kSn[7] = { 4.5f, 4.5f, 2.0f, 0.7f, 6.5f, 0.0f, 0.0f };
|
||||
static const float kSp[7] = { 0.0f, 0.0f, 5.0f, 2.0f, 0.0f, 0.9f, 0.6f };
|
||||
h.dense(dt, { 21, 5 }, hfill(228))
|
||||
.dense(RAD_F32, { 7 }, [](int64_t i) { return kS[i]; })
|
||||
.dense(RAD_F32, { 7 }, [](int64_t i) { return kSn[i]; })
|
||||
.dense(RAD_F32, { 7 }, [](int64_t i) { return kSp[i]; })
|
||||
.dense(RAD_F32, { 7 }, [](int64_t) { return 6.5f; })
|
||||
.idx({ 1, -2, -1, -1, -1, -1, -1 })
|
||||
.idx({ 0, 1, 2, 3, 4, 5, 6 })
|
||||
.idx({ 4, 0, 0, 0, 1, 0, 0 })
|
||||
.raw(RAD_U32, { 14 }, kSeeds)
|
||||
.idx({ 0, 0, 1, 2, 2, 1, 2 })
|
||||
.idx({ 0, 0, 7, 4, 0, 20, 21 })
|
||||
.idx({ 0, 3, 6, 9, 12, 15, 18, 21 })
|
||||
.dense(RAD_F32, { 28, 5 }, hfill(229, 3.0f), true)
|
||||
.dense(RAD_F32, { 28, 5 }, hfill(230), true)
|
||||
.dense(RAD_F32, { 28, 5 }, zero, true)
|
||||
.pi("M", 21).pi("n", 5).pi("stride", 4).ps("pred", pred).ps("dtype", dn);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
{
|
||||
Hand h(("a mask column into three lanes" + sfx).c_str(), "lane_store", 0.0);
|
||||
h.dense(dt, { 9, 1 }, hfill(225))
|
||||
@@ -2825,6 +2990,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,215 @@
|
||||
#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 RadTensor* cu_part = rad_arg_in(a, 9);
|
||||
const int64_t n = p_int(a, "n", 0), h = p_int(a, "heads", 0);
|
||||
const int64_t part = p_int(a, "row_part", -1);
|
||||
if (h > 0 && q.rank == 2 && qs.rank == 2 && qs.shape[1] == 1 && g.rank == 2 &&
|
||||
q.shape[0] == g.shape[0] * h && qs.shape[0] == q.shape[0]) {
|
||||
q.rank = 3;
|
||||
q.shape[0] = g.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] = g.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 ||
|
||||
(part < 0 ? out.shape[0] != q.shape[0]
|
||||
: out.shape[0] < 1 || q.shape[0] < (part + 1) * out.shape[0]) ||
|
||||
out.shape[1] > bt.shape[1])
|
||||
return RAD_E_SHAPE;
|
||||
if (cu_part && (part < 0 || cu_part->rank != 1 || cu_part->shape[0] != cu.shape[0]))
|
||||
return part < 0 ? RAD_E_INVAL : RAD_E_SHAPE;
|
||||
if (cu_part && cu_part->dtype != RAD_I32) return RAD_E_DTYPE;
|
||||
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));
|
||||
/* A part scores out's rows from step row part * rows; the query operands span the step. */
|
||||
const int64_t row0 = part > 0 ? part * out.shape[0] : 0;
|
||||
if (cu_part)
|
||||
for (int64_t s = 0; s < cu.shape[0]; ++s)
|
||||
st_int_dt(RAD_I32, cu_part->data, s * cu_part->stride[0],
|
||||
ld_int_dt(cu.dtype, cu.data, s * cu.stride[0]) - row0);
|
||||
AVX_PARALLEL_FOR_IF(q.shape[0] * out.shape[1] * h * n >= AVX_PAR_MIN)
|
||||
for (int64_t o = 0; o < out.shape[0]; ++o) {
|
||||
const int64_t r = row0 + o;
|
||||
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, o * 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;
|
||||
}
|
||||
+396
-16
@@ -325,21 +325,27 @@ AVX_KERNEL(ln_mod_quant_fp8) {
|
||||
/* Both forms: with `gated` the branch added through the gate row (no tanh) and the residual stored
|
||||
* in x's dtype; then n1 = rd(x rsqrt(mean(x^2) + eps)), n2 = rd(n1 w), m = rd(n2 rd(1 + scale)),
|
||||
* z = rd(m + shift), rd the norm chain's dtype (z's for rms_mod, bf16 for the quantised form,
|
||||
* libref's rule). The sum of squares is the vector reduction, held to the tolerance table; every
|
||||
* libref's rule); `norm` none takes n2 = x. The sum of squares is the vector reduction, held to the tolerance table; every
|
||||
* rounding is a pass through the stored dtype, so the rest is libref's arithmetic. The per-entry
|
||||
* rows (1 + scale rounded, the shift and the gate) and the gain are built once a launch. */
|
||||
static int rms_mod_run(const RadArgs* a, bool quant) {
|
||||
if (a->n_t < (quant ? 9 : 7)) return RAD_E_INVAL;
|
||||
const RadTensor *Yv = rad_arg_in(a, 0), *G = rad_arg_in(a, 1), *S = &a->t[2], *W = &a->t[3];
|
||||
const RadTensor *Yv = rad_arg_in(a, 0), *G = rad_arg_in(a, 1), *S = &a->t[2];
|
||||
const RadTensor* W = rad_arg_in(a, 3);
|
||||
const RadTensor *cu = &a->t[4], *X = &a->t[5];
|
||||
const RadTensor *Q = quant ? &a->t[6] : nullptr, *SC = quant ? &a->t[7] : nullptr;
|
||||
const RadTensor* Z = quant ? rad_arg_in(a, 8) : &a->t[6];
|
||||
const int64_t n = p_int(a, "n", 0), grp = quant ? p_int(a, "group", 0) : 1;
|
||||
const bool gated = p_int(a, "gated", 0) != 0;
|
||||
const float eps = p_f32(a, "eps", 1e-6f);
|
||||
const float wadd = p_f32(a, "wadd", 0.0f);
|
||||
const bool once = p_int(a, "norm_once", 0) != 0;
|
||||
const char* nk = p_str(a, "norm", "rms");
|
||||
const bool layer = std::strcmp(nk, "layer") == 0, none = std::strcmp(nk, "none") == 0;
|
||||
if ((!layer && !none && std::strcmp(nk, "rms") != 0) || (none && W)) return RAD_E_INVAL;
|
||||
if (n <= 0 || grp <= 0 || n % grp || (gated && (!Yv || !G))) return RAD_E_SHAPE;
|
||||
const int64_t rows = rows_of(quant ? Q : Z, n), n_seq = numel(cu) - 1, ngrp = n / grp;
|
||||
if (rows <= 0 || n_seq <= 0 || rows_of(X, n) < rows || numel(W) < n ||
|
||||
if (rows <= 0 || n_seq <= 0 || rows_of(X, n) < rows || (W && numel(W) < n) ||
|
||||
numel(S) < n_seq * 2 * n)
|
||||
return RAD_E_SHAPE;
|
||||
if (gated && (rows_of(Yv, n) < rows || numel(G) < n_seq * n)) return RAD_E_SHAPE;
|
||||
@@ -359,7 +365,8 @@ static int rms_mod_run(const RadArgs* a, bool quant) {
|
||||
row[n + i] = ldt(S, e * s_rs + i * s_cs);
|
||||
if (gated) row[2 * n + i] = ldt(G, e * g_rs + i * g_cs);
|
||||
}
|
||||
for (int64_t i = 0; i < n; ++i) tabs[n_seq * tw + i] = ldt(W, i * laststride(W));
|
||||
for (int64_t i = 0; i < n; ++i)
|
||||
tabs[n_seq * tw + i] = W ? ldt(W, i * laststride(W)) + wadd : 1.0f;
|
||||
}
|
||||
const float* wrow = tabs + n_seq * tw;
|
||||
|
||||
@@ -380,13 +387,23 @@ static int rms_mod_run(const RadArgs* a, bool quant) {
|
||||
} else {
|
||||
std::memcpy(v, xv, (size_t)n * sizeof(float));
|
||||
}
|
||||
const float rs = 1.0f / std::sqrt(row_sumsq(v, n) / (float)n + eps);
|
||||
if (layer) {
|
||||
/* Centred first, the mean an f32 sum in ascending order (libref's). */
|
||||
float mu = 0.0f;
|
||||
for (int64_t k = 0; k < n; ++k) mu += v[k];
|
||||
mu /= (float)n;
|
||||
for (int64_t k = 0; k < n; ++k) v[k] -= mu;
|
||||
}
|
||||
/* `none`: no norm, the residual as it is (libref's n2 = x). */
|
||||
const float rs = none ? 1.0f : 1.0f / std::sqrt(row_sumsq(v, n) / (float)n + eps);
|
||||
const vf vr = vf_set1(rs);
|
||||
int64_t i = 0;
|
||||
for (; i + VF_N <= n; i += VF_N) vf_storeu(o + i, vf_mul(vf_loadu(v + i), vr));
|
||||
for (; i < n; ++i) o[i] = v[i] * rs;
|
||||
narrow_row(dt, o, n, tmp);
|
||||
mul_rows(o, wrow, n);
|
||||
if (W) {
|
||||
if (!once) narrow_row(dt, o, n, tmp);
|
||||
mul_rows(o, wrow, n);
|
||||
}
|
||||
narrow_row(dt, o, n, tmp);
|
||||
mul_rows(o, ent, n);
|
||||
narrow_row(dt, o, n, tmp);
|
||||
@@ -452,7 +469,9 @@ AVX_KERNEL(timestep_embed) {
|
||||
for (int64_t i = 0; i < h; ++i) f[i] = sc_exp(coef * (float)i / (float)h);
|
||||
for (int64_t m = 0; m < rows; ++m) {
|
||||
const float tv = std::fmax(ldt(T, offlin(T, m)), clamp); /* ref pins are floors */
|
||||
const float tt = round ? scale * narrow1(RAD_BF16, narrow1(RAD_BF16, tv * scale) / scale)
|
||||
const float tt = round == 3 ? narrow1(RAD_BF16, scale * narrow1(RAD_BF16, tv))
|
||||
: round == 2 ? scale * narrow1(RAD_BF16, tv)
|
||||
: round ? scale * narrow1(RAD_BF16, narrow1(RAD_BF16, tv * scale) / scale)
|
||||
: scale * tv;
|
||||
for (int64_t i = 0; i < h; ++i) {
|
||||
const float arg = tt * f[i];
|
||||
@@ -581,14 +600,15 @@ AVX_KERNEL(randn_lanes) {
|
||||
* x' = bf16(x + bf16(bf16(sigma_next - sigma) * v'))
|
||||
*
|
||||
* flag 4 writes x - sigma v' to the lane's preview, and flag 2 restores the kept region,
|
||||
* x' = bf16(m x' + (1 - m)((1 - sigma_next) src + sigma_next noise)). libref requires every
|
||||
* operand, the optional three included. Every entry is checked before any lane is written. */
|
||||
* x' = bf16(m x' + (1 - m)((1 - sigma_next) src + sigma_next noise)). inp, mask and preview are
|
||||
* optional, as in libref: an entry whose flags need one that is absent is refused. Every entry is
|
||||
* checked before any lane is written. */
|
||||
AVX_KERNEL(flow_euler) {
|
||||
if (!rad_args_have(a, 13)) return RAD_E_INVAL;
|
||||
if (!rad_args_have(a, 9) || !rad_arg_in(a, 11)) return RAD_E_INVAL;
|
||||
const RadTensor *V = &a->t[0], *sg = &a->t[1], *sgn = &a->t[2], *cfg = &a->t[3];
|
||||
const RadTensor *pair = &a->t[4], *lane = &a->t[5], *fl = &a->t[6], *seed = &a->t[7];
|
||||
const RadTensor *cu = &a->t[8], *inp = &a->t[9], *mask = &a->t[10], *st = &a->t[11];
|
||||
const RadTensor* pv = &a->t[12];
|
||||
const RadTensor *cu = &a->t[8], *inp = rad_arg_in(a, 9), *mask = rad_arg_in(a, 10);
|
||||
const RadTensor *st = &a->t[11], *pv = rad_arg_in(a, 12);
|
||||
const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0);
|
||||
if (n <= 0 || stride <= 0) return RAD_E_SHAPE;
|
||||
const int64_t n_seq = numel(cu) - 1, st_rows = rows_of(st, n), v_rows = rows_of(V, n);
|
||||
@@ -604,6 +624,8 @@ AVX_KERNEL(flow_euler) {
|
||||
if (len > 0 && (b0 < 0 || b0 + len > v_rows)) return RAD_E_SHAPE;
|
||||
if (pr >= 0 && len > 0 && (cu_at(cu, pr) < 0 || cu_at(cu, pr) + len > v_rows))
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t f = ldi(fl, offlin(fl, e));
|
||||
if (((f & kInpaint) && (!inp || !mask)) || ((f & kPreview) && !pv)) return RAD_E_INVAL;
|
||||
}
|
||||
const uint32_t dt = st->dtype;
|
||||
for (int64_t e = 0; e < n_seq; ++e) {
|
||||
@@ -683,6 +705,203 @@ AVX_KERNEL(flow_euler) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ kd_input, kd_step */
|
||||
/* The k-diffusion sampler over a discrete-time denoiser (libref/ref_gen.cpp): libref's f32 steps
|
||||
* bit for bit, element by element, `kd_keep` holding every product to its own rounding before the
|
||||
* sum that follows it. The lanes are a few thousand rows of four channels, so a scalar loop costs
|
||||
* nothing next to the denoiser. */
|
||||
namespace {
|
||||
|
||||
enum { kSamplerEuler = 0, kSamplerEulerAncestral = 1, kSamplerDpmpp2m = 2 };
|
||||
|
||||
/* A product the compiler may not fuse into the next add (any ISA level: a scalar in an xmm). */
|
||||
inline float kd_keep(float x) { __asm__("" : "+x"(x)); return x; }
|
||||
|
||||
struct KdEntry {
|
||||
float s = 0, sn = 0, w = 0;
|
||||
float cskip = 0, cout = 0;
|
||||
float sup = 0, sdown = 0;
|
||||
float ratio = 0, em = 0;
|
||||
float c1 = 0, c2 = 0;
|
||||
bool second = false;
|
||||
};
|
||||
|
||||
KdEntry kd_entry(float s, float sn, float sp, float w, int64_t sampler, bool first) {
|
||||
KdEntry k;
|
||||
k.s = s;
|
||||
k.sn = sn;
|
||||
k.w = w;
|
||||
const float s2p = kd_keep(s * s) + 1.0f;
|
||||
k.cskip = 1.0f / s2p;
|
||||
k.cout = s / std::sqrt(s2p);
|
||||
if (sampler == kSamplerEulerAncestral) {
|
||||
const float s2 = kd_keep(s * s), sn2 = kd_keep(sn * sn);
|
||||
const float up2 = kd_keep(sn2 * (s2 - sn2)) / s2;
|
||||
float sup = std::sqrt(up2);
|
||||
if (!(sup < sn)) sup = sn;
|
||||
const float dn2 = sn2 - kd_keep(sup * sup);
|
||||
k.sup = sup;
|
||||
k.sdown = std::sqrt(dn2 > 0.0f ? dn2 : 0.0f);
|
||||
} else if (sampler == kSamplerDpmpp2m && sn > 0.0f) {
|
||||
const float t = -std::log(s), tn = -std::log(sn);
|
||||
const float h = tn - t;
|
||||
k.ratio = sn / s;
|
||||
k.em = std::expm1(-h);
|
||||
if (!first) {
|
||||
const float hl = t - (-std::log(sp));
|
||||
const float r = hl / h;
|
||||
k.c2 = 1.0f / kd_keep(2.0f * r);
|
||||
k.c1 = 1.0f + k.c2;
|
||||
k.second = true;
|
||||
}
|
||||
}
|
||||
return k;
|
||||
}
|
||||
|
||||
inline float kd_denoised(const KdEntry& k, bool v_pred, float x, float o) {
|
||||
return v_pred ? kd_keep(x * k.cskip) - kd_keep(o * k.cout) : x - kd_keep(k.s * o);
|
||||
}
|
||||
|
||||
inline float kd_next(const KdEntry& k, int64_t sampler, float x, float D, float hist, float nz) {
|
||||
if (sampler == kSamplerEuler) {
|
||||
const float d = (x - D) / k.s;
|
||||
return x + kd_keep((k.sn - k.s) * d);
|
||||
}
|
||||
if (sampler == kSamplerEulerAncestral) {
|
||||
const float d = (x - D) / k.s;
|
||||
float xn = x + kd_keep(d * (k.sdown - k.s));
|
||||
if (k.sn > 0.0f) xn = xn + kd_keep(nz * k.sup);
|
||||
return xn;
|
||||
}
|
||||
if (k.sn == 0.0f) return D;
|
||||
const float Dd = k.second ? kd_keep(k.c1 * D) - kd_keep(k.c2 * hist) : D;
|
||||
return kd_keep(k.ratio * x) - kd_keep(k.em * Dd);
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* The model's input per entry that moves a lane: a first step's noise times sqrt(1 + sigma^2)
|
||||
* into the lane, then rd(x / sqrt(sigma^2 + 1)) at the entry's rows and its pair's. Every entry is
|
||||
* checked before any is written. */
|
||||
AVX_KERNEL(kd_input) {
|
||||
if (!rad_args_have(a, 8)) return RAD_E_INVAL;
|
||||
const RadTensor *sg = &a->t[0], *pair = &a->t[1], *lane = &a->t[2], *fl = &a->t[3];
|
||||
const RadTensor *seed = &a->t[4], *cu = &a->t[5], *st = &a->t[6], *Y = &a->t[7];
|
||||
const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0);
|
||||
if (n <= 0 || stride <= 0) return RAD_E_SHAPE;
|
||||
const int64_t n_seq = numel(cu) - 1, st_rows = rows_of(st, n), y_rows = rows_of(Y, n);
|
||||
if (n_seq <= 0 || cu_at(cu, n_seq) <= cu_at(cu, 0)) return RAD_E_SHAPE;
|
||||
if (numel(sg) < n_seq || numel(pair) < n_seq || numel(lane) < n_seq || numel(fl) < n_seq ||
|
||||
numel(seed) < 2 * n_seq)
|
||||
return RAD_E_SHAPE;
|
||||
for (int64_t e = 0; e < n_seq; ++e) {
|
||||
const int64_t pr = ldi(pair, offlin(pair, e));
|
||||
if (pr == -2) continue;
|
||||
const int64_t L = ldi(lane, offlin(lane, e));
|
||||
const int64_t b0 = cu_at(cu, e), len = cu_at(cu, e + 1) - b0;
|
||||
if (L < 0 || len > stride || (L + 1) * stride > st_rows || b0 < 0 || b0 + len > y_rows)
|
||||
return RAD_E_SHAPE;
|
||||
if (pr >= n_seq || (pr >= 0 && (cu_at(cu, pr + 1) - cu_at(cu, pr) != len ||
|
||||
cu_at(cu, pr) < 0 || cu_at(cu, pr) + len > y_rows)))
|
||||
return RAD_E_SHAPE;
|
||||
if (ldi(fl, offlin(fl, e)) & kInpaint) return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
for (int64_t e = 0; e < n_seq; ++e) {
|
||||
const int64_t pr = ldi(pair, offlin(pair, e));
|
||||
if (pr == -2) continue;
|
||||
const int64_t L = ldi(lane, offlin(lane, e));
|
||||
const int64_t b0 = cu_at(cu, e), len = cu_at(cu, e + 1) - b0;
|
||||
const int64_t p0 = pr >= 0 ? cu_at(cu, pr) : 0;
|
||||
const float s = ldt(sg, offlin(sg, e));
|
||||
const float init = std::sqrt(1.0f + kd_keep(s * s));
|
||||
const float cin = 1.0f / std::sqrt(kd_keep(s * s) + 1.0f);
|
||||
const bool first = (ldi(fl, offlin(fl, e)) & kFirst) != 0;
|
||||
const uint64_t sd = seed_of(seed, e);
|
||||
AVX_PARALLEL_FOR_IF(len * n * 8 >= AVX_PAR_MIN)
|
||||
for (int64_t k = 0; k < len; ++k) {
|
||||
const int64_t sb = rowoff(st, L * stride + k, n), ss = laststride(st);
|
||||
const int64_t yb = rowoff(Y, b0 + k, n), ys = laststride(Y);
|
||||
const int64_t pb = pr >= 0 ? rowoff(Y, p0 + k, n) : 0;
|
||||
for (int64_t c = 0; c < n; ++c) {
|
||||
if (first) stt(st, sb + c * ss, rad_philox_normal(sd, (uint64_t)(k * n + c)) * init);
|
||||
const float v = ldt(st, sb + c * ss) * cin;
|
||||
stt(Y, yb + c * ys, v);
|
||||
if (pr >= 0) stt(Y, pb + c * ys, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* One sampler step per entry that moves a lane, libref's arithmetic (docs/OPS.md, kd_step). */
|
||||
AVX_KERNEL(kd_step) {
|
||||
if (!rad_args_have(a, 14)) return RAD_E_INVAL;
|
||||
const RadTensor *O = &a->t[0], *sg = &a->t[1], *sgn = &a->t[2], *sgp = &a->t[3];
|
||||
const RadTensor *cfg = &a->t[4], *pair = &a->t[5], *lane = &a->t[6], *fl = &a->t[7];
|
||||
const RadTensor *seed = &a->t[8], *smp = &a->t[9], *stp = &a->t[10], *cu = &a->t[11];
|
||||
const RadTensor *st = &a->t[12], *hs = &a->t[13], *pv = rad_arg_in(a, 14);
|
||||
const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0);
|
||||
const char* pred = p_str(a, "pred", "eps");
|
||||
const bool v_pred = pred && !std::strcmp(pred, "v");
|
||||
if (!v_pred && (!pred || std::strcmp(pred, "eps"))) return RAD_E_INVAL;
|
||||
if (n <= 0 || stride <= 0) return RAD_E_SHAPE;
|
||||
const int64_t n_seq = numel(cu) - 1, st_rows = rows_of(st, n), o_rows = rows_of(O, n);
|
||||
if (n_seq <= 0 || cu_at(cu, n_seq) <= cu_at(cu, 0)) return RAD_E_SHAPE;
|
||||
for (const RadTensor* t : { sg, sgn, sgp, cfg, pair, lane, fl, smp, stp })
|
||||
if (numel(t) < n_seq) return RAD_E_SHAPE;
|
||||
if (numel(seed) < 2 * n_seq || rows_of(hs, n) < st_rows || (pv && rows_of(pv, n) < st_rows))
|
||||
return RAD_E_SHAPE;
|
||||
for (int64_t e = 0; e < n_seq; ++e) {
|
||||
const int64_t pr = ldi(pair, offlin(pair, e));
|
||||
if (pr == -2) continue;
|
||||
const int64_t L = ldi(lane, offlin(lane, e));
|
||||
const int64_t b0 = cu_at(cu, e), len = cu_at(cu, e + 1) - b0;
|
||||
if (L < 0 || len > stride || (L + 1) * stride > st_rows || b0 < 0 || b0 + len > o_rows)
|
||||
return RAD_E_SHAPE;
|
||||
if (pr >= n_seq || (pr >= 0 && (cu_at(cu, pr + 1) - cu_at(cu, pr) != len ||
|
||||
cu_at(cu, pr) < 0 || cu_at(cu, pr) + len > o_rows)))
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t f = ldi(fl, offlin(fl, e)), sm = ldi(smp, offlin(smp, e));
|
||||
if ((f & kInpaint) || sm < kSamplerEuler || sm > kSamplerDpmpp2m) return RAD_E_UNSUPPORTED;
|
||||
if ((f & kPreview) && !pv) return RAD_E_INVAL;
|
||||
}
|
||||
for (int64_t e = 0; e < n_seq; ++e) {
|
||||
const int64_t pr = ldi(pair, offlin(pair, e));
|
||||
if (pr == -2) continue;
|
||||
const int64_t L = ldi(lane, offlin(lane, e));
|
||||
const int64_t b0 = cu_at(cu, e), len = cu_at(cu, e + 1) - b0;
|
||||
const int64_t p0 = pr >= 0 ? cu_at(cu, pr) : 0;
|
||||
const int64_t f = ldi(fl, offlin(fl, e)), sm = ldi(smp, offlin(smp, e));
|
||||
const uint64_t stream = (uint64_t)(uint32_t)(1 + ldi(stp, offlin(stp, e)));
|
||||
const KdEntry K = kd_entry(ldt(sg, offlin(sg, e)), ldt(sgn, offlin(sgn, e)),
|
||||
ldt(sgp, offlin(sgp, e)), ldt(cfg, offlin(cfg, e)), sm,
|
||||
(f & kFirst) != 0);
|
||||
const uint64_t sd = seed_of(seed, e);
|
||||
AVX_PARALLEL_FOR_IF(len * n * 8 >= AVX_PAR_MIN)
|
||||
for (int64_t k = 0; k < len; ++k) {
|
||||
const int64_t ob = rowoff(O, b0 + k, n), os = laststride(O);
|
||||
const int64_t ub = pr >= 0 ? rowoff(O, p0 + k, n) : 0;
|
||||
const int64_t sb = rowoff(st, L * stride + k, n), ss = laststride(st);
|
||||
const int64_t hb = rowoff(hs, L * stride + k, n), hss = laststride(hs);
|
||||
for (int64_t c = 0; c < n; ++c) {
|
||||
const float x = ldt(st, sb + c * ss);
|
||||
float D = kd_denoised(K, v_pred, x, ldt(O, ob + c * os));
|
||||
if (pr >= 0) {
|
||||
const float Du = kd_denoised(K, v_pred, x, ldt(O, ub + c * os));
|
||||
D = Du + kd_keep(K.w * (D - Du));
|
||||
}
|
||||
if (f & kPreview)
|
||||
stt(pv, rowoff(pv, L * stride + k, n) + c * laststride(pv), D);
|
||||
const float nz = sm == kSamplerEulerAncestral && K.sn > 0.0f
|
||||
? rad_philox_normal_s(sd, stream, (uint64_t)(k * n + c)) : 0.0f;
|
||||
stt(st, sb + c * ss, kd_next(K, sm, x, D, ldt(hs, hb + c * hss), nz));
|
||||
stt(hs, hb + c * hss, D);
|
||||
}
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ flow_x0_step */
|
||||
/* x' = f32(f32(r x) + f32(f32(1 - r) d)) with d = f32(x + f32((1 - t) v)) and
|
||||
* r = sigma_next / sigma: libref's f32 steps bit for bit, `keep` holding each product to its own
|
||||
@@ -825,6 +1044,56 @@ AVX_KERNEL(chan_affine) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ im2col_nhwc */
|
||||
/* conv2d_nhwc's receptive fields as rows (libref's definition): y [Ho * Wo, cin * k * k], column
|
||||
* (ci k + i) k + j of row oy * Wo + ox the input at that tap, 0 in the padding. Each output row is
|
||||
* filled tap by tap from the input pixel's channel run; bf16 into bf16 copies the bits. Parallel
|
||||
* over output image rows. */
|
||||
AVX_KERNEL(im2col_nhwc) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *Y = &a->t[1];
|
||||
const int64_t cin = p_int(a, "cin", 0), k = p_int(a, "k", 0);
|
||||
const int64_t stride = p_int(a, "stride", 1), up = p_int(a, "up", 1);
|
||||
const char* pad = p_str(a, "pad", "same");
|
||||
const bool down = pad && !std::strcmp(pad, "down");
|
||||
const bool causal = pad && !std::strcmp(pad, "causal");
|
||||
if (cin <= 0 || k <= 0 || stride <= 0 || up <= 0) return RAD_E_SHAPE;
|
||||
if (X->rank != 2 || X->shape[1] % cin) return RAD_E_SHAPE;
|
||||
const int64_t Hin = X->shape[0], Win = X->shape[1] / cin, kk = cin * k * k;
|
||||
if (Hin <= 0 || Win <= 0) return RAD_E_SHAPE;
|
||||
const int64_t Hv = Hin * up, Wv = Win * up;
|
||||
const int64_t pt = down ? 0 : causal ? k - 1 : k / 2, pb = down ? 1 : causal ? 0 : k / 2;
|
||||
const int64_t pl = down ? 0 : k / 2, pr = down ? 1 : k / 2;
|
||||
const int64_t Ho = (Hv + pt + pb - k) / stride + 1, Wo = (Wv + pl + pr - k) / stride + 1;
|
||||
if (Ho <= 0 || Wo <= 0 || rows_of(Y, kk) != Ho * Wo) return RAD_E_SHAPE;
|
||||
const int64_t xr = X->stride[0], xs = laststride(X), ys = laststride(Y);
|
||||
const bool bits = X->dtype == RAD_BF16 && Y->dtype == RAD_BF16;
|
||||
AVX_PARALLEL_FOR_IF(Ho * Wo * kk >= AVX_PAR_MIN)
|
||||
for (int64_t oy = 0; oy < Ho; ++oy)
|
||||
for (int64_t ox = 0; ox < Wo; ++ox) {
|
||||
const int64_t yb = rowoff(Y, oy * Wo + ox, kk);
|
||||
for (int64_t i = 0; i < k; ++i) {
|
||||
const int64_t iy = oy * stride + i - pt;
|
||||
for (int64_t j = 0; j < k; ++j) {
|
||||
const int64_t ix = ox * stride + j - pl;
|
||||
const bool in = iy >= 0 && iy < Hv && ix >= 0 && ix < Wv;
|
||||
const int64_t xb = in ? (iy / up) * xr + (ix / up) * cin * xs : 0;
|
||||
const int64_t yt = yb + (i * k + j) * ys;
|
||||
for (int64_t ci = 0; ci < cin; ++ci) {
|
||||
const int64_t yo = yt + ci * k * k * ys;
|
||||
if (bits) {
|
||||
((uint16_t*)Y->data)[yo] =
|
||||
in ? ((const uint16_t*)X->data)[xb + ci * xs] : (uint16_t)0;
|
||||
} else {
|
||||
stt(Y, yo, in ? ldt(X, xb + ci * xs) : 0.0f);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ conv2d_nhwc */
|
||||
/* An image convolution as GEMMs over patch rows. x [Hin, Win * cin] and y [Ho, Wo * cout] are
|
||||
* images whose sizes come from the operands, rows at their own pitch and channels contiguous, as
|
||||
@@ -855,8 +1124,11 @@ AVX_KERNEL(conv2d_nhwc) {
|
||||
const int64_t Ho = Y->shape[0], Wo = Y->shape[1] / cout;
|
||||
if (Hin <= 0 || Win <= 0 || Ho <= 0 || Wo <= 0) return RAD_E_SHAPE;
|
||||
const int64_t Hv = Hin * up, Wv = Win * up;
|
||||
const int64_t pt = down ? 0 : k / 2, pb = down ? 1 : k / 2;
|
||||
if ((Hv + pt + pb - k) / stride + 1 != Ho || (Wv + pt + pb - k) / stride + 1 != Wo)
|
||||
/* `causal` pads k - 1 rows above and none below (libref's). */
|
||||
const bool causal = pad && !std::strcmp(pad, "causal");
|
||||
const int64_t pt = down ? 0 : causal ? k - 1 : k / 2, pb = down ? 1 : causal ? 0 : k / 2;
|
||||
const int64_t pl = down ? 0 : k / 2, pr = down ? 1 : k / 2;
|
||||
if ((Hv + pt + pb - k) / stride + 1 != Ho || (Wv + pl + pr - k) / stride + 1 != Wo)
|
||||
return RAD_E_SHAPE;
|
||||
if (numel(W) < cout * cin * k * k || numel(B) < cout) return RAD_E_SHAPE;
|
||||
const int64_t xr = X->stride[0], yr = Y->stride[0];
|
||||
@@ -934,7 +1206,7 @@ AVX_KERNEL(conv2d_nhwc) {
|
||||
for (int64_t kh = 0; kh < k; ++kh) {
|
||||
const int64_t iy = oy * stride + kh - pt;
|
||||
for (int64_t kw = 0; kw < k; ++kw) {
|
||||
const int64_t ix = ox * stride + kw - pt;
|
||||
const int64_t ix = ox * stride + kw - pl;
|
||||
char* d = dst + (size_t)((kh * k + kw) * cin) * ael;
|
||||
if (iy < 0 || iy >= Hv || ix < 0 || ix >= Wv) {
|
||||
std::memset(d, 0, (size_t)cin * ael);
|
||||
@@ -1223,6 +1495,32 @@ AVX_KERNEL(gelu_tanh) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ gelu_quick */
|
||||
/* CLIP's quick_gelu in libref's three roundings: a = rd(1.702 x), s = rd(sigmoid(a)),
|
||||
* y = rd(x s), libm's exp, element by element: a text encoder's feed-forward, small beside its
|
||||
* GEMMs. */
|
||||
AVX_KERNEL(gelu_quick) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *Y = &a->t[1];
|
||||
const int64_t n = p_int(a, "n", 0);
|
||||
if (n <= 0) return RAD_E_SHAPE;
|
||||
const int64_t rows = rows_of(Y, n);
|
||||
if (rows <= 0 || rows_of(X, n) < rows) return RAD_E_SHAPE;
|
||||
const uint32_t dt = Y->dtype;
|
||||
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
const int64_t xb = rowoff(X, r, n), xs = laststride(X);
|
||||
const int64_t yb = rowoff(Y, r, n), ys = laststride(Y);
|
||||
for (int64_t c = 0; c < n; ++c) {
|
||||
const float v = ldt(X, xb + c * xs);
|
||||
const float t = narrow1(dt, 1.702f * v);
|
||||
const float s = narrow1(dt, 1.0f / (1.0f + std::exp(-t)));
|
||||
stt(Y, yb + c * ys, v * s);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ scatter_add_rows */
|
||||
/* x[idx[i]] = x[idx[i]] + v[i], rounded to x's dtype; a negative index adds nothing. Every index
|
||||
* is checked before the first write. Rows run in parallel only when no destination repeats: a
|
||||
@@ -1265,3 +1563,85 @@ AVX_KERNEL(scatter_add_rows) {
|
||||
for (int64_t m = 0; m < M; ++m) add_row(m);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ table_add */
|
||||
/* libref's table_add: y[r, l n + c] = x[r, c] + t[l, c], f32 sum rounded once to y's dtype. */
|
||||
AVX_KERNEL(table_add) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *T = &a->t[1], *Y = &a->t[2];
|
||||
const int64_t n = p_int(a, "n", 0), L = p_int(a, "L", 0);
|
||||
if (n <= 0 || L <= 0 || numel(T) < L * n) return RAD_E_SHAPE;
|
||||
const int64_t rows = rows_of(Y, L * n);
|
||||
if (rows <= 0 || rows_of(X, n) < rows) return RAD_E_SHAPE;
|
||||
AVX_PARALLEL_FOR_IF(rows * L * n >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
float* buf = scratch_f32((size_t)(3 * n + 64));
|
||||
float *xs = buf, *ts = buf + n + 16, *p = ts + n + 16;
|
||||
const float* xv = in_row(X, rowoff(X, r, n), n, xs);
|
||||
for (int64_t l = 0; l < L; ++l) {
|
||||
const float* tv = in_row(T, l * n * laststride(T), n, ts);
|
||||
for (int64_t c = 0; c < n; ++c) p[c] = xv[c] + tv[c];
|
||||
out_row(Y, rowoff(Y, r, L * n) + l * n * laststride(Y), n, p);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ mix_rows */
|
||||
/* libref's mix_rows: y[r, c] = sum_i w[i] x[r k + i, c], f32 in ascending i, rounded once. */
|
||||
AVX_KERNEL(mix_rows) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *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 <= 0 || k <= 0 || numel(W) < k) return RAD_E_SHAPE;
|
||||
const int64_t rows = rows_of(Y, n);
|
||||
if (rows <= 0 || rows_of(X, n) < rows * k) return RAD_E_SHAPE;
|
||||
std::vector<float> w((size_t)k);
|
||||
for (int64_t i = 0; i < k; ++i) w[(size_t)i] = ldt(W, i * laststride(W));
|
||||
AVX_PARALLEL_FOR_IF(rows * n * k >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
float* buf = scratch_f32((size_t)(2 * n + 64));
|
||||
float *xs = buf, *acc = buf + n + 16;
|
||||
for (int64_t c = 0; c < n; ++c) acc[c] = 0.0f;
|
||||
for (int64_t i = 0; i < k; ++i) {
|
||||
const float* xv = in_row(X, rowoff(X, r * k + i, n), n, xs);
|
||||
for (int64_t c = 0; c < n; ++c) acc[c] += w[(size_t)i] * xv[c];
|
||||
}
|
||||
out_row(Y, rowoff(Y, r, n), n, acc);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ chan_stats */
|
||||
/* libref's chan_stats: per-channel statistics held as weights, every step rounded as libref. */
|
||||
AVX_KERNEL(chan_stats) {
|
||||
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *Mn = &a->t[1], *Sd = &a->t[2], *Y = &a->t[3];
|
||||
const int64_t n = p_int(a, "n", 0);
|
||||
const bool var = p_int(a, "var", 0) != 0;
|
||||
const float eps = p_f32(a, "eps", 0.0f);
|
||||
const char* mode = p_str(a, "mode", "denorm");
|
||||
const bool norm = std::strcmp(mode, "norm") == 0;
|
||||
if (!norm && std::strcmp(mode, "denorm") != 0) return RAD_E_INVAL;
|
||||
if (n <= 0 || numel(Mn) < n || numel(Sd) < n) return RAD_E_SHAPE;
|
||||
const int64_t rows = rows_of(Y, n);
|
||||
if (rows <= 0 || rows_of(X, n) < rows) return RAD_E_SHAPE;
|
||||
const uint32_t dt = Y->dtype;
|
||||
std::vector<float> mu((size_t)n), sd((size_t)n);
|
||||
for (int64_t c = 0; c < n; ++c) {
|
||||
mu[(size_t)c] = narrow1(dt, ldt(Mn, c * laststride(Mn)));
|
||||
const float v = ldt(Sd, c * laststride(Sd));
|
||||
sd[(size_t)c] = narrow1(dt, var ? std::sqrt(v + eps) : v);
|
||||
}
|
||||
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
float* buf = scratch_f32((size_t)(2 * n + 32));
|
||||
float *xs = buf, *o = buf + n + 16;
|
||||
const float* xv = in_row(X, rowoff(X, r, n), n, xs);
|
||||
for (int64_t c = 0; c < n; ++c)
|
||||
o[c] = norm ? narrow1(dt, narrow1(dt, xv[c] - mu[(size_t)c]) / sd[(size_t)c])
|
||||
: narrow1(dt, narrow1(dt, xv[c] * sd[(size_t)c]) + mu[(size_t)c]);
|
||||
out_row(Y, rowoff(Y, r, n), n, o);
|
||||
}
|
||||
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;
|
||||
}
|
||||
@@ -331,6 +331,64 @@ AVX_KERNEL(hc_write) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ hc_project */
|
||||
/* The control vector's projection (core/cvec.h): h[s] -= scale * (h[s] . v) * v for each of the
|
||||
* hc streams of a row whose switch is on. v is f32, the stream may be bf16/f16/f32; a row with a
|
||||
* zero switch is skipped without a read, so an unprojected request is byte-identical to one on a
|
||||
* deployment with no vector. */
|
||||
AVX_KERNEL(hc_project) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor* h = &a->t[0];
|
||||
const RadTensor* v = &a->t[1];
|
||||
const RadTensor* on = &a->t[2];
|
||||
|
||||
const int64_t n = p_int(a, "n", 0);
|
||||
const int64_t hc = p_int(a, "hc", 0);
|
||||
const float sc = p_f32(a, "scale", 1.0f);
|
||||
if (n <= 0 || hc <= 1 || numel(v) < n) return RAD_E_SHAPE;
|
||||
const int64_t hn = hc * n;
|
||||
const int64_t rows = numel(h) / hn;
|
||||
if (rows <= 0 || numel(on) < rows) return RAD_E_SHAPE;
|
||||
|
||||
const int64_t vb = rowoff(v, 0, n);
|
||||
float* vbuf = scratch_f32_c((size_t) n);
|
||||
const float* vec = in_row(v, vb, n, vbuf);
|
||||
|
||||
AVX_PARALLEL_FOR_IF(rows * hn >= AVX_PAR_MIN)
|
||||
for (int64_t k = 0; k < rows * hc; ++k) {
|
||||
const int64_t r = k / hc, c = k % hc;
|
||||
if (ldi(on, offlin(on, r)) == 0) continue;
|
||||
const int64_t hb = rowoff(h, r, hn), hs = laststride(h);
|
||||
const int64_t base = hb + c * n;
|
||||
float* hv = scratch_f32((size_t) n);
|
||||
const float* row = in_row(h, base, n, hv);
|
||||
if (hs != 1) {
|
||||
float dot = 0.0f;
|
||||
for (int64_t i = 0; i < n; ++i) dot += row[i] * vec[i];
|
||||
const float g = dot * sc;
|
||||
for (int64_t i = 0; i < n; ++i)
|
||||
stt(h, base + i * hs, row[i] - g * vec[i]);
|
||||
continue;
|
||||
}
|
||||
if (row != hv) std::memcpy(hv, row, (size_t) n * sizeof(float));
|
||||
/* The dot reads the row and the direction; the update then rewrites the same elements, so
|
||||
* the direction's own copy is not needed (it is never written). */
|
||||
vf acc = vf_zero();
|
||||
int64_t i = 0;
|
||||
for (; i + VF_N <= n; i += VF_N)
|
||||
acc = vf_fma(vf_loadu(hv + i), vf_loadu(vec + i), acc);
|
||||
float dot = vf_hsum(acc);
|
||||
for (; i < n; ++i) dot += hv[i] * vec[i];
|
||||
const vf vg = vf_set1(dot * sc);
|
||||
i = 0;
|
||||
for (; i + VF_N <= n; i += VF_N)
|
||||
vf_storeu(hv + i, vf_sub(vf_loadu(hv + i), vf_mul(vg, vf_loadu(vec + i))));
|
||||
for (; i < n; ++i) hv[i] -= (dot * sc) * vec[i];
|
||||
out_row(h, base, n, hv);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ================================================================== mtp_enter
|
||||
*
|
||||
* Entry of the multi-token-prediction head for a model with an `hc`-wide residual stream.
|
||||
|
||||
+22
-6
@@ -70,7 +70,17 @@ int avx_par_force(int threads);
|
||||
#define AVX_OP_LIST(X) \
|
||||
/* ---- 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(hc_read) X(hc_write) X(hc_project) 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) \
|
||||
@@ -84,14 +94,14 @@ int avx_par_force(int threads);
|
||||
/* ---- quantisation and rotation */ \
|
||||
X(quant_act_i8) X(quant_act_i8g) X(had_quant_act_i8) X(quant_act_fp8) \
|
||||
X(had_quant_act_fp8) X(gram_accum) X(rmsnorm_had_quant_i8) X(gated_had_quant_i8) \
|
||||
X(dequant) X(quant_cols_fp8) \
|
||||
X(dequant) X(quant_cols_fp8) X(had_quant_act_i8g) \
|
||||
X(rmsnorm_quant_fp8) X(gated_quant_fp8) X(givens_rotate) X(givens_dense_quant) \
|
||||
/* ---- gemm and the vocabulary edges */ \
|
||||
X(gemm_nt) X(gemm_nt_bias) X(gemm_nt_q) X(gemm_nt_q_bias) \
|
||||
X(gemm_nt_q_gated) X(embed_lookup) X(embed_lookup_q) X(logits_gemm) \
|
||||
X(lora_shrink) X(lora_expand) \
|
||||
X(lora_shrink) X(lora_expand) X(lora_expand_mm) \
|
||||
/* ---- attention */ \
|
||||
X(attn_paged) X(attn_dense) X(kv_store) X(rope) \
|
||||
X(attn_paged) X(attn_dense) X(attn_cross) X(attn_na3d) X(table_add) X(mix_rows) X(chan_stats) X(kv_store) X(rope) \
|
||||
X(rope_table) X(qk_norm_rope) X(qsa_block_key) X(attn_local_rel) \
|
||||
X(qsa_score) X(qsa_select) X(qsa_tail_store) X(qsa_work) \
|
||||
/* ---- mixture of experts */ \
|
||||
@@ -108,19 +118,25 @@ int avx_par_force(int threads);
|
||||
X(gather_rows2) X(lane_gather) X(lane_store) X(randn_lanes) \
|
||||
X(flow_euler) X(chan_affine) X(conv2d_nhwc) X(l2norm_chan) \
|
||||
X(d2s_add) X(s2d_avg_add) X(to_rgba8) X(gelu_tanh) \
|
||||
X(scatter_add_rows) X(attn_prefix_self) \
|
||||
X(scatter_add_rows) X(attn_prefix_self) X(kd_input) X(kd_step) \
|
||||
X(gelu_quick) X(im2col_nhwc) \
|
||||
/* ---- video generation */ \
|
||||
X(rms_mod) X(rms_mod_quant_fp8) X(flow_x0_step) X(patch_unfold) \
|
||||
X(flow_res_multistep) \
|
||||
X(vtile_gather) X(vtile_stitch) X(grid_pos3) X(vsa_select) \
|
||||
X(attn_vsa) X(conv3d_ndhwc) X(group_norm) X(tconv_dw) \
|
||||
X(resize_bilinear) X(patch_fold) X(flow_renoise) \
|
||||
/* ---- LTX-2 */ \
|
||||
X(rope_split) X(head_gate) X(ltx_guide) X(pixel_norm) \
|
||||
X(d2s3d) X(s2d3d) X(pix_patch) X(patch_pix8) \
|
||||
X(stft_logmel) X(bwe_up) X(tile_grid) X(tile_crop) \
|
||||
X(tile_stitch) X(vol_index) \
|
||||
/* ---- audio generation */ \
|
||||
X(conv1d) X(conv_t1d) X(snake) X(cfg_topk_sample) \
|
||||
X(rvq_embed) X(frame_mix_store) X(end_status) X(frame_store) \
|
||||
X(resample_nearest) X(fourier_embed) X(win_input) X(win_prep) \
|
||||
X(win_finish) X(chan_split) X(interleave2) X(iota) \
|
||||
X(cu_repeat) X(snake_aa) \
|
||||
X(cu_repeat) X(snake_aa) X(int_affine) \
|
||||
/* ---- sampling, and the drafter's token walk */ \
|
||||
X(sample_penalties) X(sample_dry) X(sample_temp) X(sample_topk) \
|
||||
X(sample_topp) X(sample_minp) X(sample_typical) X(sample_xtc) \
|
||||
|
||||
+13
-2
@@ -150,8 +150,8 @@ AVX_KERNEL(lora_shrink) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* operands: t, slot, lora_b, scale, y (inout) */
|
||||
AVX_KERNEL(lora_expand) {
|
||||
/* operands: t, slot, lora_b, scale, y (inout). `bf16_t`: lora_expand_mm, t rounded to bf16. */
|
||||
static int expand_impl(const RadArgs* a, bool bf16_t) {
|
||||
if (!rad_args_have(a, 5)) return RAD_E_INVAL;
|
||||
const RadTensor *T = &a->t[0], *SL = &a->t[1], *LB = &a->t[2], *SC = &a->t[3], *Y = &a->t[4];
|
||||
const int64_t N = p_int(a, "N", 0), R = p_int(a, "R", 0), S = p_int(a, "S", 0);
|
||||
@@ -176,6 +176,12 @@ AVX_KERNEL(lora_expand) {
|
||||
const int64_t s = row_slot(SL, m, S);
|
||||
if (s < 0) continue; /* a base row: not read, not written */
|
||||
const float* tv = in_row(T, m * mt.rs, R, scratch_f32((size_t)R));
|
||||
if (bf16_t) {
|
||||
float* tr = scratch_f32((size_t)R);
|
||||
if (tr != tv) for (int64_t j = 0; j < R; ++j) tr[j] = tv[j];
|
||||
for (int64_t j = 0; j < R; ++j) tr[j] = rad_bf16_to_f32(rad_f32_to_bf16(tr[j]));
|
||||
tv = tr;
|
||||
}
|
||||
const float* bv = in_row(LB, s * pb.s0 + n * pb.s1, R, scratch_f32_b((size_t)R));
|
||||
const float d = scd[s * sc_r + n * sc_c] * dotf(tv, bv, R);
|
||||
const int64_t o = m * ys_r + n * ys_c;
|
||||
@@ -183,3 +189,8 @@ AVX_KERNEL(lora_expand) {
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
AVX_KERNEL(lora_expand) { return expand_impl(a, false); }
|
||||
|
||||
/* lora_expand with t rounded to bf16 (docs/OPS.md). */
|
||||
AVX_KERNEL(lora_expand_mm) { return expand_impl(a, true); }
|
||||
@@ -0,0 +1,604 @@
|
||||
/* avx_ltx.cpp -- LTX-2's ops (docs/OPS.md, "LTX-2"): its rotary over fractional coordinates, the
|
||||
* per-head attention gate, the guided sampler step, its VAE's norm, resampling and patches, and its
|
||||
* vocoder's spectrogram and resampler. libref's arithmetic, element by element
|
||||
* (libref/ref_ltx.cpp states the roundings): LTX-2 is a GPU model, and these run on the CPU only
|
||||
* where a whole model does, so they are written for agreement rather than speed.
|
||||
*/
|
||||
#include "avx_vec.h"
|
||||
#include "avx_common.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
using namespace avx;
|
||||
|
||||
namespace {
|
||||
|
||||
/* A product the compiler may not fuse into the add after it (libavx builds with
|
||||
* -ffp-contract=fast; libref rounds the product first). */
|
||||
inline float keep(float x) { __asm__("" : "+x"(x)); return x; }
|
||||
|
||||
double linspace01(int64_t i, int64_t steps) {
|
||||
if (steps <= 1) return 0.0;
|
||||
const double step = 1.0 / (double)(steps - 1);
|
||||
return i < steps / 2 ? step * (double)i : 1.0 - step * (double)(steps - 1 - i);
|
||||
}
|
||||
|
||||
int parse_floats(const char* s, std::vector<float>* out) {
|
||||
out->clear();
|
||||
while (s && *s) {
|
||||
char* end = nullptr;
|
||||
const double v = std::strtod(s, &end);
|
||||
if (end == s) break;
|
||||
out->push_back((float)v);
|
||||
s = end;
|
||||
}
|
||||
return (int)out->size();
|
||||
}
|
||||
|
||||
inline int64_t at_i(const RadTensor* t, int64_t i) {
|
||||
return (int64_t)ld_elem(t->data, t->dtype, i * laststride(t));
|
||||
}
|
||||
|
||||
float pos_at(const RadTensor* p, int64_t d, int64_t r) {
|
||||
const int64_t off = p->rank >= 2 ? d * p->stride[0] + r * p->stride[1] : r * laststride(p);
|
||||
return ldt(p, off);
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* ------------------------------------------------------------------ rope_split */
|
||||
AVX_KERNEL(rope_split) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *P = &a->t[1];
|
||||
const int64_t nh = p_int(a, "n_head", 0), hd = p_int(a, "head_dim", 0);
|
||||
const int64_t dim = p_int(a, "dim", 0), nd = p_int(a, "n_dims", 0), h0 = p_int(a, "head0", 0);
|
||||
const double theta = (double)p_f32(a, "theta", 10000.0f);
|
||||
std::vector<float> mx;
|
||||
if (nh <= 0 || hd <= 0 || (hd & 1) || nd <= 0 || dim < (h0 + nh) * hd ||
|
||||
parse_floats(p_str(a, "max", ""), &mx) != (int)nd)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t P2 = dim / 2, steps = P2 / nd, pad = P2 - steps * nd, half = hd / 2;
|
||||
const int64_t rows = rows_of(X, nh * hd);
|
||||
if (rows <= 0 || P->rank < 1) return RAD_E_SHAPE;
|
||||
std::vector<float> freq((size_t)steps);
|
||||
for (int64_t k = 0; k < steps; ++k)
|
||||
freq[(size_t)k] = (float)(std::pow(theta, linspace01(k, steps)) * M_PI / 2.0);
|
||||
const int64_t xs = laststride(X);
|
||||
AVX_PARALLEL_FOR_IF(rows * nh * hd >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
const int64_t xb = rowoff(X, r, nh * hd);
|
||||
for (int64_t h = 0; h < nh; ++h)
|
||||
for (int64_t i = 0; i < half; ++i) {
|
||||
const int64_t p = (h0 + h) * half + i;
|
||||
if (p < pad) continue;
|
||||
const int64_t j = p - pad, d = j % nd, k = j / nd;
|
||||
const float g = pos_at(P, d, r) / mx[(size_t)d];
|
||||
const float ang = (2.0f * g - 1.0f) * freq[(size_t)k];
|
||||
const float c = (float)std::cos((double)ang), s = (float)std::sin((double)ang);
|
||||
const int64_t o1 = xb + (h * hd + i) * xs, o2 = xb + (h * hd + half + i) * xs;
|
||||
const float x1 = ldt(X, o1), x2 = ldt(X, o2);
|
||||
st_elem(X->data, X->dtype, o1, keep(x1 * c) - keep(x2 * s));
|
||||
st_elem(X->data, X->dtype, o2, keep(x2 * c) + keep(x1 * s));
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ head_gate */
|
||||
AVX_KERNEL(head_gate) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *G = &a->t[0], *X = &a->t[1];
|
||||
const int64_t nh = p_int(a, "n_head", 0), hd = p_int(a, "head_dim", 0);
|
||||
if (nh <= 0 || hd <= 0) return RAD_E_SHAPE;
|
||||
const int64_t rows = rows_of(X, nh * hd);
|
||||
if (rows <= 0 || rows_of(G, nh) < rows) return RAD_E_SHAPE;
|
||||
const int64_t xs = laststride(X), gs = laststride(G);
|
||||
AVX_PARALLEL_FOR_IF(rows * nh * hd >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
const int64_t xb = rowoff(X, r, nh * hd), gb = rowoff(G, r, nh);
|
||||
for (int64_t h = 0; h < nh; ++h) {
|
||||
const float lg = ldt(G, gb + h * gs);
|
||||
const float sg = narrow1(G->dtype, 1.0f / (1.0f + std::exp(-lg)));
|
||||
const float gate = narrow1(X->dtype, 2.0f * sg);
|
||||
for (int64_t i = 0; i < hd; ++i) {
|
||||
const int64_t o = xb + (h * hd + i) * xs;
|
||||
st_elem(X->data, X->dtype, o, ldt(X, o) * gate);
|
||||
}
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ ltx_guide */
|
||||
AVX_KERNEL(ltx_guide) {
|
||||
if (a->n_t < 8) return RAD_E_INVAL;
|
||||
const RadTensor *Vc = &a->t[0], *Vu = rad_arg_in(a, 1), *Vs = rad_arg_in(a, 2);
|
||||
const RadTensor *Vm = rad_arg_in(a, 3), *Sc = &a->t[4], *Sh = &a->t[5], *X = &a->t[7];
|
||||
const int64_t n = p_int(a, "n", 0);
|
||||
if (n <= 0 || numel(Sc) < 4 || numel(Sh) < 2) return RAD_E_SHAPE;
|
||||
const int64_t rows = rows_of(X, n);
|
||||
if (rows <= 0 || rows_of(Vc, n) < rows || (Vu && rows_of(Vu, n) < rows) ||
|
||||
(Vs && rows_of(Vs, n) < rows) || (Vm && rows_of(Vm, n) < rows))
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t ss = laststride(Sc);
|
||||
const float gs = ldt(Sc, 0), stg = ldt(Sc, ss), ms = ldt(Sc, 2 * ss), rr = ldt(Sc, 3 * ss);
|
||||
const float sig = ldt(Sh, 0), sig_n = ldt(Sh, laststride(Sh));
|
||||
const bool use_u = Vu && gs != 1.0f, use_s = Vs && stg != 0.0f, use_m = Vm && ms != 1.0f;
|
||||
const float cu = gs - 1.0f, cm = ms - 1.0f;
|
||||
const int64_t N = rows * n;
|
||||
std::vector<float> x0c((size_t)N), g((size_t)N);
|
||||
auto x0 = [&](const RadTensor* V, int64_t r, int64_t c, float x) {
|
||||
return x - keep(ldt(V, rowoff(V, r, n) + c * laststride(V)) * sig);
|
||||
};
|
||||
AVX_PARALLEL_FOR_IF(N >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r)
|
||||
for (int64_t c = 0; c < n; ++c) {
|
||||
const float x = ldt(X, rowoff(X, r, n) + c * laststride(X));
|
||||
const float xc = x0(Vc, r, c, x);
|
||||
float v = xc;
|
||||
if (use_u) v = v + keep(cu * (xc - x0(Vu, r, c, x)));
|
||||
if (use_s) v = v + keep(stg * (xc - x0(Vs, r, c, x)));
|
||||
if (use_m) v = v + keep(cm * (xc - x0(Vm, r, c, x)));
|
||||
x0c[(size_t)(r * n + c)] = xc;
|
||||
g[(size_t)(r * n + c)] = v;
|
||||
}
|
||||
float fac = 1.0f, kept = 1.0f;
|
||||
if (rr > 0.0f) {
|
||||
auto stdev = [&](const std::vector<float>& v) {
|
||||
double m = 0.0;
|
||||
for (float e : v) m += e;
|
||||
m /= (double)N;
|
||||
double sq = 0.0;
|
||||
for (float e : v) sq += ((double)e - m) * ((double)e - m);
|
||||
return (float)std::sqrt(sq / (double)(N > 1 ? N - 1 : 1));
|
||||
};
|
||||
fac = stdev(x0c) / stdev(g);
|
||||
kept = (float)(1.0 - (double)rr);
|
||||
}
|
||||
const float dt = sig_n - sig;
|
||||
AVX_PARALLEL_FOR_IF(N >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r)
|
||||
for (int64_t c = 0; c < n; ++c) {
|
||||
float v = g[(size_t)(r * n + c)];
|
||||
if (rr > 0.0f) v = keep(rr * keep(v * fac)) + keep(kept * v);
|
||||
const int64_t o = rowoff(X, r, n) + c * laststride(X);
|
||||
const float x = ldt(X, o);
|
||||
const float vel = (x - v) / sig;
|
||||
st_elem(X->data, X->dtype, o, x + keep(dt * vel));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ pixel_norm */
|
||||
AVX_KERNEL(pixel_norm) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *Y = &a->t[1];
|
||||
const int64_t n = p_int(a, "n", 0), L = p_int(a, "ileave", 1);
|
||||
const float eps = p_f32(a, "eps", 1e-6f), mult = p_f32(a, "mult", 1.0f);
|
||||
const char* fs = p_str(a, "form", "rsqrt");
|
||||
const char* as = p_str(a, "act", "none");
|
||||
const int form = !std::strcmp(fs, "rsqrt") ? 0 : !std::strcmp(fs, "div") ? 1 : -1;
|
||||
const int act = !std::strcmp(as, "none") ? 0 : !std::strcmp(as, "silu") ? 1 : -1;
|
||||
if (form < 0 || act < 0 || n <= 0 || L <= 0) return RAD_E_INVAL;
|
||||
const int64_t rows = rows_of(Y, n * L) * L;
|
||||
if (rows <= 0 || rows_of(X, n) < rows) return RAD_E_SHAPE;
|
||||
const uint32_t dt = Y->dtype;
|
||||
const int64_t xs = laststride(X), ys = laststride(Y);
|
||||
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
const int64_t xb = rowoff(X, r, n), yb = rowoff(Y, r / L, n * L), l = r % L;
|
||||
float ss = 0.0f;
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const float v = ldt(X, xb + i * xs);
|
||||
ss += narrow1(dt, v * v);
|
||||
}
|
||||
const float v = narrow1(dt, narrow1(dt, ss / (float)n) + eps);
|
||||
const float sc = form == 0 ? narrow1(dt, 1.0f / std::sqrt(v)) : narrow1(dt, std::sqrt(v));
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const float x = ldt(X, xb + i * xs);
|
||||
float z = narrow1(dt, form == 0 ? x * sc : x / sc);
|
||||
if (act == 1) z = narrow1(dt, z / (1.0f + std::exp(-z)));
|
||||
if (mult != 1.0f) z = narrow1(dt, z * mult);
|
||||
st_elem(Y->data, dt, yb + (i * L + l) * ys, z);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ d2s3d */
|
||||
AVX_KERNEL(d2s3d) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *G = &a->t[1], *Y = &a->t[2];
|
||||
const int64_t C = p_int(a, "C", 0), st = p_int(a, "st", 1), sh = p_int(a, "sh", 1);
|
||||
const int64_t sw = p_int(a, "sw", 1), drop = p_int(a, "drop", st - 1);
|
||||
if (C <= 0 || st <= 0 || sh <= 0 || sw <= 0 || drop < 0 || drop >= st || numel(G) < 3)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t T = at_i(G, 0), H = at_i(G, 1), W = at_i(G, 2), P = st * sh * sw;
|
||||
const int64_t To = T * st - drop, Ho = H * sh, Wo = W * sw;
|
||||
if (T <= 0 || H <= 0 || W <= 0 || rows_of(X, C * P) < T * H * W ||
|
||||
rows_of(Y, C) < To * Ho * Wo)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t xs = laststride(X), ys = laststride(Y);
|
||||
AVX_PARALLEL_FOR_IF(To * Ho * Wo * C >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < To * Ho * Wo; ++r) {
|
||||
const int64_t tt = r / (Ho * Wo) + drop, ii = (r / Wo) % Ho, jj = r % Wo;
|
||||
const int64_t t = tt / st, aa = tt % st, i = ii / sh, b = ii % sh, j = jj / sw, d = jj % sw;
|
||||
const int64_t xb = rowoff(X, (t * H + i) * W + j, C * P), yb = rowoff(Y, r, C);
|
||||
for (int64_t c = 0; c < C; ++c)
|
||||
st_elem(Y->data, Y->dtype, yb + c * ys,
|
||||
ldt(X, xb + (((c * st + aa) * sh + b) * sw + d) * xs));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ s2d3d */
|
||||
AVX_KERNEL(s2d3d) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *G = &a->t[1], *Y = &a->t[2];
|
||||
const int64_t C = p_int(a, "C", 0), st = p_int(a, "st", 1), sh = p_int(a, "sh", 1);
|
||||
const int64_t sw = p_int(a, "sw", 1), tpre = p_int(a, "tpre", 0), grp = p_int(a, "group", 1);
|
||||
const bool add = p_int(a, "add", 0) != 0;
|
||||
const char* ms = p_str(a, "mode", "copy");
|
||||
const int mode = !std::strcmp(ms, "copy") ? 0 : !std::strcmp(ms, "mean") ? 1 : -1;
|
||||
if (mode < 0) return RAD_E_INVAL;
|
||||
if (C <= 0 || st <= 0 || sh <= 0 || sw <= 0 || tpre < 0 || grp <= 0 || numel(G) < 3)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t T = at_i(G, 0), H = at_i(G, 1), W = at_i(G, 2), P = C * st * sh * sw;
|
||||
const int64_t Tv = T + tpre;
|
||||
if (T <= 0 || Tv % st || H % sh || W % sw || (mode == 1 && P % grp)) return RAD_E_SHAPE;
|
||||
const int64_t To = Tv / st, Ho = H / sh, Wo = W / sw, Co = mode == 1 ? P / grp : P;
|
||||
if (rows_of(X, C) < T * H * W || rows_of(Y, Co) < To * Ho * Wo) return RAD_E_SHAPE;
|
||||
const int64_t xs = laststride(X), ys = laststride(Y);
|
||||
const uint32_t dt = Y->dtype;
|
||||
AVX_PARALLEL_FOR_IF(To * Ho * Wo * P >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < To * Ho * Wo; ++r) {
|
||||
const int64_t t = r / (Ho * Wo), i = (r / Wo) % Ho, j = r % Wo;
|
||||
const int64_t yb = rowoff(Y, r, Co);
|
||||
auto val = [&](int64_t q) {
|
||||
const int64_t d = q % sw, b = (q / sw) % sh, aa = (q / (sw * sh)) % st;
|
||||
const int64_t c = q / (sw * sh * st);
|
||||
const int64_t v = t * st + aa, tr = v < tpre ? v : v - tpre;
|
||||
return ldt(X, rowoff(X, (tr * H + i * sh + b) * W + j * sw + d, C) + c * xs);
|
||||
};
|
||||
for (int64_t o = 0; o < Co; ++o) {
|
||||
float v;
|
||||
if (mode == 0) {
|
||||
v = val(o);
|
||||
} else {
|
||||
float s = 0.0f;
|
||||
for (int64_t q = o * grp; q < (o + 1) * grp; ++q) s += val(q);
|
||||
v = narrow1(dt, s / (float)grp);
|
||||
}
|
||||
const int64_t oy = yb + o * ys;
|
||||
st_elem(Y->data, dt, oy, add ? narrow1(dt, ldt(Y, oy)) + narrow1(dt, v) : v);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ pix_patch / patch_pix8 */
|
||||
static inline int64_t patch_col(int64_t c, int64_t ph, int64_t pw, int64_t p, bool wh) {
|
||||
return c * p * p + (wh ? pw * p + ph : ph * p + pw);
|
||||
}
|
||||
|
||||
AVX_KERNEL(pix_patch) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *Y = &a->t[1];
|
||||
const int64_t p = p_int(a, "p", 0), C = p_int(a, "C", 0);
|
||||
const bool wh = std::strcmp(p_str(a, "order", "wh"), "hw") != 0;
|
||||
if (p <= 0 || C <= 0 || X->rank != 2 || Y->rank != 2 || X->shape[1] % C) return RAD_E_SHAPE;
|
||||
const int64_t H = X->shape[0], W = X->shape[1] / C;
|
||||
if (H <= 0 || W <= 0 || H % p || W % p || Y->shape[0] != H / p ||
|
||||
Y->shape[1] != (W / p) * C * p * p)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t xr = X->stride[0], yr = Y->stride[0];
|
||||
AVX_PARALLEL_FOR_IF(H * W * C >= AVX_PAR_MIN)
|
||||
for (int64_t y = 0; y < H; ++y)
|
||||
for (int64_t x = 0; x < W; ++x)
|
||||
for (int64_t c = 0; c < C; ++c)
|
||||
st_elem(Y->data, Y->dtype,
|
||||
(y / p) * yr + (x / p) * C * p * p + patch_col(c, y % p, x % p, p, wh),
|
||||
ldt(X, y * xr + x * C + c));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
AVX_KERNEL(patch_pix8) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *Y = &a->t[1];
|
||||
const int64_t p = p_int(a, "p", 0), C = p_int(a, "C", 0);
|
||||
const bool wh = std::strcmp(p_str(a, "order", "wh"), "hw") != 0;
|
||||
if (p <= 0 || C <= 0 || X->rank != 2 || Y->rank != 2 || Y->dtype != RAD_U8 ||
|
||||
X->shape[1] % (C * p * p))
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t R = X->shape[0], w = X->shape[1] / (C * p * p);
|
||||
if (R <= 0 || w <= 0 || Y->shape[0] != R * p || Y->shape[1] != w * p * C) return RAD_E_SHAPE;
|
||||
const int64_t xr = X->stride[0], yr = Y->stride[0];
|
||||
const uint32_t dt = X->dtype;
|
||||
uint8_t* yb = (uint8_t*)Y->data;
|
||||
AVX_PARALLEL_FOR_IF(R * p * w * p * C >= AVX_PAR_MIN)
|
||||
for (int64_t y = 0; y < R * p; ++y)
|
||||
for (int64_t x = 0; x < w * p; ++x)
|
||||
for (int64_t c = 0; c < C; ++c) {
|
||||
const float v = ldt(X, (y / p) * xr + (x / p) * C * p * p +
|
||||
patch_col(c, y % p, x % p, p, wh));
|
||||
const float cl = std::min(std::max(v, -1.0f), 1.0f);
|
||||
float u = narrow1(dt, narrow1(dt, cl / 2.0f) + 0.5f);
|
||||
u = std::min(std::max(u, 0.0f), 1.0f);
|
||||
yb[y * yr + x * C + c] = (uint8_t)std::nearbyint(u * 255.0f);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ vol_index */
|
||||
AVX_KERNEL(vol_index) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *G = &a->t[0], *Y = &a->t[1];
|
||||
if (numel(G) < 3 || Y->rank != 2 || Y->shape[0] != 3) return RAD_E_SHAPE;
|
||||
const int64_t T = at_i(G, 0), H = at_i(G, 1), W = at_i(G, 2), n = Y->shape[1];
|
||||
if (T <= 0 || H <= 0 || W <= 0 || n <= 0) return RAD_E_SHAPE;
|
||||
const int64_t m1 = std::min(n, T * H * W);
|
||||
for (int64_t m = 0; m < m1; ++m) {
|
||||
const int64_t v[3] = { m / (H * W), (m / W) % H, m % W };
|
||||
for (int64_t c = 0; c < 3; ++c)
|
||||
st_int_dt(Y->dtype, Y->data, c * Y->stride[0] + m * Y->stride[1], v[c]);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ tile_grid / tile_crop / tile_stitch */
|
||||
/* diffusers' tiled decodes: libref/ref_ltx.cpp states the cuts and the blends. */
|
||||
namespace {
|
||||
struct TileCut {
|
||||
int64_t tile = 1, stride = 1, min = 1;
|
||||
bool intervals = false;
|
||||
int64_t count(int64_t L) const {
|
||||
if (intervals && L <= tile) return 1;
|
||||
int64_t n = (L + stride - 1) / stride;
|
||||
while (intervals && n > 1 && L - (n - 1) * stride < min) --n;
|
||||
return n;
|
||||
}
|
||||
int64_t len(int64_t L, int64_t k) const {
|
||||
return k == count(L) - 1 ? L - k * stride : std::min(tile, L - k * stride);
|
||||
}
|
||||
};
|
||||
|
||||
bool tile_cuts(const RadArgs* a, TileCut* s, TileCut* t) {
|
||||
static const char* const kRules[] = { "stride", "intervals" };
|
||||
const int rule = p_enum(a, "rule", kRules, 2, 0);
|
||||
s->tile = p_int(a, "tile", 0);
|
||||
s->stride = p_int(a, "stride", 0);
|
||||
s->min = p_int(a, "min", 1);
|
||||
s->intervals = rule == 1;
|
||||
t->tile = p_int(a, "tile_t", 1 << 30);
|
||||
t->stride = p_int(a, "stride_t", 1 << 30);
|
||||
t->min = p_int(a, "min_t", 1);
|
||||
t->intervals = rule == 1;
|
||||
return rule >= 0 && s->tile > 0 && s->stride > 0 && s->stride <= s->tile && s->min > 0 &&
|
||||
t->tile > 0 && t->stride > 0 && t->stride <= t->tile && t->min > 0;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
AVX_KERNEL(tile_grid) {
|
||||
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
|
||||
const RadTensor *G = &a->t[0], *Y = &a->t[1];
|
||||
TileCut cs, ct;
|
||||
const int64_t n = numel(Y) / 8, tail = p_int(a, "tail", 0);
|
||||
if (!tile_cuts(a, &cs, &ct) || tail < 0 || n <= 0 || numel(G) < 3) return RAD_E_SHAPE;
|
||||
const int64_t T = at_i(G, 0), H = at_i(G, 1), W = at_i(G, 2);
|
||||
if (T <= 0 || H <= 0 || W <= 0) return RAD_E_SHAPE;
|
||||
const int64_t nt = ct.count(T), ni = cs.count(H), nj = cs.count(W), count = nt * ni * nj;
|
||||
for (int64_t k = 0; k < n; ++k) {
|
||||
int64_t row[8] = {};
|
||||
if (k < count) {
|
||||
const int64_t kt = k / (ni * nj), i = (k / nj) % ni, j = k % nj;
|
||||
const int64_t v[8] = { ct.len(T, kt) + (kt == nt - 1 ? tail : 0), cs.len(H, i),
|
||||
cs.len(W, j), kt * ct.stride, i * cs.stride, j * cs.stride, k,
|
||||
count };
|
||||
std::memcpy(row, v, sizeof row);
|
||||
}
|
||||
for (int64_t e = 0; e < 8; ++e) st_int_dt(Y->dtype, Y->data, offlin(Y, k * 8 + e), row[e]);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
AVX_KERNEL(tile_crop) {
|
||||
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *G = &a->t[1], *B = &a->t[2], *Y = &a->t[3];
|
||||
const int64_t C = p_int(a, "C", 0);
|
||||
if (C <= 0 || numel(G) < 3 || numel(B) < 6) return RAD_E_SHAPE;
|
||||
const int64_t T = at_i(G, 0), H = at_i(G, 1), W = at_i(G, 2);
|
||||
const int64_t t = at_i(B, 0), h = at_i(B, 1), w = at_i(B, 2);
|
||||
const int64_t t0 = at_i(B, 3), y0 = at_i(B, 4), x0 = at_i(B, 5);
|
||||
if (t <= 0 || h <= 0 || w <= 0 || t0 < 0 || y0 < 0 || x0 < 0 || t0 + t > T || y0 + h > H ||
|
||||
x0 + w > W || rows_of(X, C) < T * H * W || rows_of(Y, C) < t * h * w)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t xs = laststride(X), ys = laststride(Y);
|
||||
AVX_PARALLEL_FOR_IF(t * h * w * C >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < t * h * w; ++r) {
|
||||
const int64_t f = r / (h * w), i = (r / w) % h, j = r % w;
|
||||
const int64_t xb = rowoff(X, ((t0 + f) * H + y0 + i) * W + x0 + j, C), yb = rowoff(Y, r, C);
|
||||
for (int64_t c = 0; c < C; ++c) st_elem(Y->data, Y->dtype, yb + c * ys, ldt(X, xb + c * xs));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
namespace {
|
||||
struct TileStore {
|
||||
TileCut cs, ct;
|
||||
int64_t T, H, W, sc, st, nt, ni, nj, hsum, wsum;
|
||||
TileStore(const TileCut& s, const TileCut& t, int64_t T_, int64_t H_, int64_t W_, int64_t sc_,
|
||||
int64_t st_)
|
||||
: cs(s), ct(t), T(T_), H(H_), W(W_), sc(sc_), st(st_), nt(t.count(T_)), ni(s.count(H_)),
|
||||
nj(s.count(W_)), hsum(0), wsum(0) {
|
||||
for (int64_t i = 0; i < ni; ++i) hsum += cs.len(H, i);
|
||||
for (int64_t j = 0; j < nj; ++j) wsum += cs.len(W, j);
|
||||
}
|
||||
int64_t frames(int64_t kt) const {
|
||||
return st * ct.len(T, kt) - (kt == 0 ? st - 1 : 0);
|
||||
}
|
||||
int64_t offset(int64_t kt, int64_t i, int64_t j) const {
|
||||
int64_t before = 0;
|
||||
for (int64_t q = 0; q < kt; ++q) before += frames(q);
|
||||
int64_t left = 0, above = 0;
|
||||
for (int64_t q = 0; q < j; ++q) left += cs.len(W, q);
|
||||
for (int64_t q = 0; q < i; ++q) above += cs.len(H, q);
|
||||
return sc * sc * (before * hsum * wsum + frames(kt) * (above * wsum + cs.len(H, i) * left));
|
||||
}
|
||||
int64_t rows() const { return offset(nt, 0, 0); }
|
||||
};
|
||||
} /* namespace */
|
||||
|
||||
AVX_KERNEL(tile_stitch) {
|
||||
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *G = &a->t[1], *Fst = &a->t[2], *Y = &a->t[3];
|
||||
TileCut cs, ct;
|
||||
const int64_t sc = p_int(a, "scale", 0), st = p_int(a, "scale_t", 1);
|
||||
const int64_t p = p_int(a, "p", 0), C = p_int(a, "C", 0);
|
||||
const bool wh = std::strcmp(p_str(a, "order", "wh"), "hw") != 0;
|
||||
if (!tile_cuts(a, &cs, &ct) || sc <= 0 || st <= 0 || p <= 0 || C <= 0 || numel(G) < 3 ||
|
||||
numel(Fst) < 1 || Y->dtype != RAD_U8 || Y->rank != 2)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t T = at_i(G, 0), H = at_i(G, 1), W = at_i(G, 2), f0 = at_i(Fst, 0);
|
||||
const int64_t Hpx = H * sc * p, Wpx = W * sc * p, P = C * p * p;
|
||||
if (T <= 0 || H <= 0 || W <= 0 || Y->shape[1] != Wpx * C || Y->shape[0] % Hpx) return RAD_E_SHAPE;
|
||||
const int64_t nf = Y->shape[0] / Hpx;
|
||||
const TileStore ts(cs, ct, T, H, W, sc, st);
|
||||
if (nf <= 0 || f0 < 0 || f0 + nf > st * T - (st - 1) || rows_of(X, P) < ts.rows())
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t s = cs.stride * sc * p, E = (cs.tile - cs.stride) * sc * p;
|
||||
const int64_t Et = (ct.tile - ct.stride) * st, xs = laststride(X);
|
||||
const uint32_t dt = X->dtype;
|
||||
auto R = [&](int64_t kt, int64_t i, int64_t j, int64_t f, int64_t yy, int64_t xx, int64_t c) {
|
||||
const int64_t wp = cs.len(W, j) * sc, hp = cs.len(H, i) * sc;
|
||||
const int64_t row = ts.offset(kt, i, j) + (f * hp + yy / p) * wp + xx / p;
|
||||
return ldt(X, rowoff(X, row, P) + patch_col(c, yy % p, xx % p, p, wh) * xs);
|
||||
};
|
||||
auto mix = [&](float va, float vb, int64_t k, int64_t e) {
|
||||
const float wa = (float)(1.0 - (double)k / (double)e), wb = (float)((double)k / (double)e);
|
||||
return narrow1(dt, narrow1(dt, keep(va * wa)) + narrow1(dt, keep(vb * wb)));
|
||||
};
|
||||
auto S = [&](int64_t kt, int64_t f, int64_t Yp, int64_t Xp, int64_t c) {
|
||||
const int64_t i = std::min(Yp / s, ts.ni - 1), ly = Yp - i * s;
|
||||
const int64_t j = std::min(Xp / s, ts.nj - 1), lx = Xp - j * s;
|
||||
const int64_t ha = i > 0 ? cs.len(H, i - 1) * sc * p : 0;
|
||||
const int64_t ev = i > 0 ? std::min(std::min(ha, cs.len(H, i) * sc * p), E) : 0;
|
||||
const int64_t wl = j > 0 ? cs.len(W, j - 1) * sc * p : 0;
|
||||
const int64_t eh = j > 0 ? std::min(std::min(wl, cs.len(W, j) * sc * p), E) : 0;
|
||||
const bool vb = i > 0 && ly < ev, hb = j > 0 && lx < eh;
|
||||
float V = R(kt, i, j, f, ly, lx, c);
|
||||
if (vb) {
|
||||
const int64_t ya = ha - ev + ly;
|
||||
float A = R(kt, i - 1, j, f, ya, lx, c);
|
||||
if (hb) A = mix(R(kt, i - 1, j - 1, f, ya, wl - eh + lx, c), A, lx, eh);
|
||||
V = mix(A, V, ly, ev);
|
||||
}
|
||||
if (hb) {
|
||||
float L = R(kt, i, j - 1, f, ly, wl - eh + lx, c);
|
||||
if (vb) L = mix(R(kt, i - 1, j - 1, f, ha - ev + ly, wl - eh + lx, c), L, ly, ev);
|
||||
V = mix(L, V, lx, eh);
|
||||
}
|
||||
return V;
|
||||
};
|
||||
uint8_t* yb = (uint8_t*)Y->data;
|
||||
const int64_t yr = Y->stride[0], band = ct.stride * st;
|
||||
AVX_PARALLEL_FOR_IF(nf * Hpx * Wpx * C >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < nf * Hpx; ++r) {
|
||||
const int64_t n = f0 + r / Hpx, Yp = r % Hpx;
|
||||
const int64_t kt = std::min((n + st - 1) / band, ts.nt - 1);
|
||||
const int64_t f = n - (kt == 0 ? 0 : kt * band - (st - 1));
|
||||
const int64_t et = kt > 0 ? std::min(std::min(ts.frames(kt - 1), ts.frames(kt)), Et) : 0;
|
||||
for (int64_t Xp = 0; Xp < Wpx; ++Xp)
|
||||
for (int64_t c = 0; c < C; ++c) {
|
||||
float v = S(kt, f, Yp, Xp, c);
|
||||
if (kt > 0 && f < et) v = mix(S(kt - 1, ts.frames(kt - 1) - et + f, Yp, Xp, c), v, f, et);
|
||||
const float cl = std::min(std::max(v, -1.0f), 1.0f);
|
||||
float u = narrow1(dt, narrow1(dt, cl / 2.0f) + 0.5f);
|
||||
u = std::min(std::max(u, 0.0f), 1.0f);
|
||||
yb[r * yr + Xp * C + c] = (uint8_t)std::nearbyint(u * 255.0f);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ stft_logmel */
|
||||
AVX_KERNEL(stft_logmel) {
|
||||
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *B = &a->t[1], *Mb = &a->t[2], *Y = &a->t[3];
|
||||
const int64_t hop = p_int(a, "hop", 0), nfft = p_int(a, "nfft", 0), nm = p_int(a, "n_mel", 0);
|
||||
const int64_t ch = p_int(a, "ch", 0);
|
||||
if (hop <= 0 || nfft < hop || nm <= 0 || ch <= 0) return RAD_E_SHAPE;
|
||||
const int64_t F = nfft / 2 + 1, S = rows_of(X, ch), frames = rows_of(Y, ch * nm);
|
||||
if (S <= 0 || frames <= 0 || frames * hop > S || numel(B) < 2 * F * nfft || numel(Mb) < nm * F)
|
||||
return RAD_E_SHAPE;
|
||||
const uint32_t dt = Y->dtype;
|
||||
const int64_t pad = nfft - hop, xs = laststride(X), ys = laststride(Y);
|
||||
const float floor_v = narrow1(dt, 1e-5f);
|
||||
AVX_PARALLEL_FOR_IF(frames * ch * F * nfft >= AVX_PAR_MIN)
|
||||
for (int64_t t = 0; t < frames; ++t)
|
||||
for (int64_t h = 0; h < ch; ++h) {
|
||||
std::vector<float> mag((size_t)F);
|
||||
for (int64_t k = 0; k < F; ++k) {
|
||||
float re = 0.0f, im = 0.0f;
|
||||
for (int64_t j = 0; j < nfft; ++j) {
|
||||
const int64_t s = t * hop + j - pad;
|
||||
if (s < 0) continue;
|
||||
const float v = ldt(X, rowoff(X, s, ch) + h * xs);
|
||||
re += keep(ldt(B, k * nfft + j) * v);
|
||||
im += keep(ldt(B, (F + k) * nfft + j) * v);
|
||||
}
|
||||
re = narrow1(dt, re);
|
||||
im = narrow1(dt, im);
|
||||
mag[(size_t)k] = narrow1(dt, std::sqrt(narrow1(dt, narrow1(dt, re * re) +
|
||||
narrow1(dt, im * im))));
|
||||
}
|
||||
const int64_t yb = rowoff(Y, t, ch * nm);
|
||||
for (int64_t m = 0; m < nm; ++m) {
|
||||
float s = 0.0f;
|
||||
for (int64_t k = 0; k < F; ++k) s += keep(ldt(Mb, m * F + k) * mag[(size_t)k]);
|
||||
const float mel = std::max(narrow1(dt, s), floor_v);
|
||||
st_elem(Y->data, dt, yb + (h * nm + m) * ys, std::log(mel));
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ bwe_up */
|
||||
AVX_KERNEL(bwe_up) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *Rz = &a->t[1], *Y = &a->t[2];
|
||||
const int64_t r = p_int(a, "ratio", 0), ch = p_int(a, "ch", 0);
|
||||
if (r <= 0 || ch <= 0) return RAD_E_SHAPE;
|
||||
const int64_t S = rows_of(X, ch), O = rows_of(Y, ch);
|
||||
if (S <= 0 || O <= 0 || O > S * r || rows_of(Rz, ch) < O) return RAD_E_SHAPE;
|
||||
const uint32_t dt = X->dtype;
|
||||
const int64_t w = (int64_t)std::ceil(6.0 / 0.99), K = 2 * w * r + 1, off = 2 * w * r;
|
||||
std::vector<float> f((size_t)K);
|
||||
for (int64_t n = 0; n < K; ++n) {
|
||||
const float u = keep(keep((float)n / (float)r - (float)w) * 0.99f);
|
||||
const float uc = std::min(std::max(u, -6.0f), 6.0f);
|
||||
const float cw = std::cos(keep(keep(uc * (float)M_PI) / 6.0f) / 2.0f);
|
||||
const float pu = keep((float)M_PI * u);
|
||||
const float sinc = u == 0.0f ? 1.0f : std::sin(pu) / pu;
|
||||
f[(size_t)n] = narrow1(dt, keep(keep(sinc * keep(cw * cw)) * 0.99f) / (float)r);
|
||||
}
|
||||
const int64_t xs = laststride(X), rs = laststride(Rz), ys = laststride(Y);
|
||||
AVX_PARALLEL_FOR_IF(O * ch * K >= AVX_PAR_MIN)
|
||||
for (int64_t o = 0; o < O; ++o)
|
||||
for (int64_t h = 0; h < ch; ++h) {
|
||||
const int64_t u = o + off;
|
||||
float acc = 0.0f;
|
||||
for (int64_t k = u % r; k < K; k += r) {
|
||||
const int64_t i = (u - k) / r;
|
||||
const int64_t s = std::min(std::max<int64_t>(i - w, 0), S - 1);
|
||||
acc += keep(f[(size_t)k] * ldt(X, rowoff(X, s, ch) + h * xs));
|
||||
}
|
||||
const float up = narrow1(dt, (float)r * narrow1(dt, acc));
|
||||
const float v = narrow1(dt, ldt(Rz, rowoff(Rz, o, ch) + h * rs) + up);
|
||||
st_elem(Y->data, Y->dtype, rowoff(Y, o, ch) + h * ys, std::min(std::max(v, -1.0f), 1.0f));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -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. */
|
||||
|
||||
+45
-22
@@ -12,9 +12,10 @@
|
||||
* The keys are read once per tile, which at decode is once per sequence. The dots
|
||||
* sum in vector order (libref's order at the scalar level); the heads in order.
|
||||
* qsa_select Linear time per row: an order key per block (the bits of max(score, 0) plus one,
|
||||
* 0 for a dead block), a histogram of the keys' top bits, an exact select among the
|
||||
* keys in the bin that holds the topk-th largest, and one emitting pass in block
|
||||
* order. The ids match libref's byte for byte.
|
||||
* 0 for a dead block; with `signed` the float's total order over all 32 bits), a
|
||||
* histogram of the keys' top bits, an exact select among the keys in the bin that
|
||||
* holds the topk-th largest, and one emitting pass in block order. The ids match
|
||||
* libref's byte for byte.
|
||||
* qsa_tail_store, qsa_work Row copies through f32, as libref copies, so every value lands
|
||||
* with the bits libref's would.
|
||||
* dflash_conv Channels across lanes, in blocks of columns that walk their rows, so a block's base
|
||||
@@ -290,25 +291,29 @@ AVX_KERNEL(qsa_score) {
|
||||
/* ================================================================== qsa_select */
|
||||
namespace {
|
||||
|
||||
/* Bins of the first selection pass: the top 10 bits of a key, which is below 2^31. */
|
||||
enum { kBins = 1024, kBinShift = 21 };
|
||||
/* Bins of the first selection pass: the top 10 bits of a key, which is below 2^31 (a signed
|
||||
* key uses all 32 bits, so its bins sit one bit higher). */
|
||||
enum { kBins = 1024, kBinShift = 21, kBinShiftSigned = 22 };
|
||||
|
||||
struct SelJob {
|
||||
const RadTensor *sc, *bt, *nc, *po, *se, *ns, *su;
|
||||
const int64_t* seq;
|
||||
int64_t nb, topk, ratio;
|
||||
int64_t s_rs, s_cs, bt_rs, bt_cs, o_rs, o_cs;
|
||||
bool sgn; /* the `signed` order */
|
||||
};
|
||||
|
||||
/* The order key of each of the row's first `n` blocks: bits(max(score, 0)) + 1 for a live block
|
||||
* (page id >= 0 and score > -1e30), 0 for a dead one. Non-negative floats order as their bits, so
|
||||
* keys order as libref's values; max(score, 0) maps -0 to +0 as libref's `v > 0 ? v : 0` does.
|
||||
* Returns the live count. */
|
||||
* The signed order makes a block with a finite score live and keys it by the float's total order
|
||||
* (sign bit flipped for a positive value, every bit for a negative one), -0 keyed as +0, so keys
|
||||
* order as libref's signed values; no finite score keys to 0. Returns the live count. */
|
||||
static int64_t order_keys(const SelJob& j, int64_t m, int64_t s, int64_t n, uint32_t* key) {
|
||||
const int64_t sb = m * j.s_rs, bb = s * j.bt_rs;
|
||||
int64_t live = 0, b = 0;
|
||||
#if AVX_LEVEL >= 2
|
||||
if (j.sc->dtype == RAD_F32 && j.s_cs == 1 && j.bt->dtype == RAD_I32 && j.bt_cs == 1) {
|
||||
if (!j.sgn && j.sc->dtype == RAD_F32 && j.s_cs == 1 && j.bt->dtype == RAD_I32 && j.bt_cs == 1) {
|
||||
const float* v = (const float*)j.sc->data + sb;
|
||||
const int32_t* p = (const int32_t*)j.bt->data + bb;
|
||||
#if AVX_LEVEL == 3
|
||||
@@ -341,6 +346,17 @@ static int64_t order_keys(const SelJob& j, int64_t m, int64_t s, int64_t n, uint
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
if (j.sgn) {
|
||||
for (; b < n; ++b) {
|
||||
const float v = ldt(j.sc, sb + b * j.s_cs);
|
||||
if (ldi(j.bt, bb + b * j.bt_cs) < 0 || !std::isfinite(v)) { key[b] = 0; continue; }
|
||||
uint32_t u = 0;
|
||||
if (v != 0.0f) std::memcpy(&u, &v, 4);
|
||||
key[b] = (u & 0x80000000u) ? ~u : (u ^ 0x80000000u);
|
||||
++live;
|
||||
}
|
||||
return live;
|
||||
}
|
||||
for (; b < n; ++b) {
|
||||
const float v = ldt(j.sc, sb + b * j.s_cs);
|
||||
if (ldi(j.bt, bb + b * j.bt_cs) < 0 || !(v > -1e30f)) { key[b] = 0; continue; }
|
||||
@@ -355,19 +371,21 @@ static int64_t order_keys(const SelJob& j, int64_t m, int64_t s, int64_t n, uint
|
||||
|
||||
/* The topk-th largest key of a row with more than `topk` live keys, and how many keys are above
|
||||
* it. A histogram of the top bits finds the bin holding it; the keys in that bin are gathered and
|
||||
* the exact value taken among them. `cand` holds up to n keys. */
|
||||
static uint32_t threshold(const uint32_t* key, int64_t n, int64_t topk, uint32_t* hist,
|
||||
* the exact value taken among them. `cand` holds up to n keys. `sgn`: the keys are signed-order
|
||||
* keys, which use all 32 bits. */
|
||||
static uint32_t threshold(const uint32_t* key, int64_t n, int64_t topk, bool sgn, uint32_t* hist,
|
||||
uint32_t* cand, int64_t* above_out) {
|
||||
const int shift = sgn ? (int)kBinShiftSigned : (int)kBinShift;
|
||||
/* Four interleaved histograms, so runs of keys in one bin do not serialise on one counter. */
|
||||
std::memset(hist, 0, 4 * kBins * sizeof(uint32_t));
|
||||
int64_t b = 0;
|
||||
for (; b + 4 <= n; b += 4) {
|
||||
++hist[0 * kBins + (key[b] >> kBinShift)];
|
||||
++hist[1 * kBins + (key[b + 1] >> kBinShift)];
|
||||
++hist[2 * kBins + (key[b + 2] >> kBinShift)];
|
||||
++hist[3 * kBins + (key[b + 3] >> kBinShift)];
|
||||
++hist[0 * kBins + (key[b] >> shift)];
|
||||
++hist[1 * kBins + (key[b + 1] >> shift)];
|
||||
++hist[2 * kBins + (key[b + 2] >> shift)];
|
||||
++hist[3 * kBins + (key[b + 3] >> shift)];
|
||||
}
|
||||
for (; b < n; ++b) ++hist[key[b] >> kBinShift];
|
||||
for (; b < n; ++b) ++hist[key[b] >> shift];
|
||||
for (int i = 0; i < kBins; ++i)
|
||||
hist[i] += hist[kBins + i] + hist[2 * kBins + i] + hist[3 * kBins + i];
|
||||
/* Bin 0 is never counted: it is the last one left, and holds the dead keys (0) beside the
|
||||
@@ -380,8 +398,8 @@ static uint32_t threshold(const uint32_t* key, int64_t n, int64_t topk, uint32_t
|
||||
}
|
||||
/* The keys of the bin, i.e. in [lo, hi], with key 0 (dead) left out of bin 0. Few keys fall in
|
||||
* one bin, so the vector forms test a vector and walk only its hits. */
|
||||
const uint32_t lo = std::max<uint32_t>((uint32_t)bin << kBinShift, 1u);
|
||||
const uint32_t hi = (((uint32_t)bin + 1u) << kBinShift) - 1u;
|
||||
const uint32_t lo = std::max<uint32_t>((uint32_t)bin << shift, 1u);
|
||||
const uint32_t hi = (((uint32_t)bin + 1u) << shift) - 1u;
|
||||
int64_t nc = 0;
|
||||
b = 0;
|
||||
#if AVX_LEVEL == 3
|
||||
@@ -393,9 +411,10 @@ static uint32_t threshold(const uint32_t* key, int64_t n, int64_t topk, uint32_t
|
||||
nc += __builtin_popcount((unsigned)in);
|
||||
}
|
||||
#elif AVX_LEVEL == 2
|
||||
/* Keys are below 2^31, so the signed compares order them. */
|
||||
/* Keys are below 2^31, so the signed compares order them; signed-order keys take the scalar
|
||||
* loop. */
|
||||
const __m256i vlo = _mm256_set1_epi32((int)lo - 1), vhi = _mm256_set1_epi32((int)hi + 1);
|
||||
for (; b + 8 <= n; b += 8) {
|
||||
for (; !sgn && b + 8 <= n; b += 8) {
|
||||
const __m256i k = _mm256_loadu_si256((const __m256i*)(key + b));
|
||||
const __m256i in = _mm256_and_si256(_mm256_cmpgt_epi32(k, vlo), _mm256_cmpgt_epi32(vhi, k));
|
||||
unsigned hit = (unsigned)_mm256_movemask_ps(_mm256_castsi256_ps(in));
|
||||
@@ -439,9 +458,10 @@ static void emit(const SelJob& j, const uint32_t* key, int64_t n, int64_t s, uin
|
||||
}
|
||||
}
|
||||
#elif AVX_LEVEL == 2
|
||||
/* Keys are below 2^31, so the signed compare orders them. */
|
||||
/* Keys are below 2^31, so the signed compare orders them; signed-order keys take the scalar
|
||||
* loop. */
|
||||
const __m256i vt = _mm256_set1_epi32((int)thr - 1);
|
||||
for (; b + 8 <= n && (og < gt || ot < ties); b += 8) {
|
||||
for (; !j.sgn && b + 8 <= n && (og < gt || ot < ties); b += 8) {
|
||||
const __m256i k = _mm256_loadu_si256((const __m256i*)(key + b));
|
||||
unsigned hit = (unsigned)_mm256_movemask_ps(_mm256_castsi256_ps(_mm256_cmpgt_epi32(k, vt)));
|
||||
while (hit) {
|
||||
@@ -470,7 +490,7 @@ static void select_row(const SelJob& j, int64_t m) {
|
||||
} else {
|
||||
uint32_t* cand = (uint32_t*)scratch_f32_c((size_t)n);
|
||||
int64_t gt = 0;
|
||||
const uint32_t thr = threshold(key, n, topk, hist, cand, >);
|
||||
const uint32_t thr = threshold(key, n, topk, j.sgn, hist, cand, >);
|
||||
emit(j, key, n, s, thr, gt, topk - gt, row);
|
||||
out = topk;
|
||||
}
|
||||
@@ -496,7 +516,7 @@ static void select_row(const SelJob& j, int64_t m) {
|
||||
/* ------------------------------------------------------------------ qsa_select */
|
||||
/* The page-id table the sparse attention reads (docs/OPS.md): over the query's complete blocks
|
||||
* n = min(nc[seq], (pos + 1) / ratio, width), the live ones (page id >= 0, score > -1e30) ranked
|
||||
* by max(score, 0). All of them when `topk` or fewer are live, else every block above the topk-th
|
||||
* by max(score, 0), or with `signed` 1 those with a finite score, ranked by it. All of them when `topk` or fewer are live, else every block above the topk-th
|
||||
* largest value in block order, then the blocks equal to it in block order until topk are taken.
|
||||
* The partial page bt[n] follows when (pos + 1) % ratio != 0 and n < width, and -1 pads the row
|
||||
* to topk + 1. A row no sequence holds reads sequence 0, as libref's and libr4d's do. */
|
||||
@@ -505,7 +525,9 @@ AVX_KERNEL(qsa_select) {
|
||||
const RadTensor *sc = &a->t[0], *bt = &a->t[1], *nc = &a->t[2], *po = &a->t[3];
|
||||
const RadTensor *cu = &a->t[4], *se = &a->t[5], *ns = &a->t[6], *su = &a->t[7];
|
||||
const int64_t topk = p_int(a, "topk", 0), ratio = p_int(a, "ratio", 0);
|
||||
const int64_t sgn = p_int(a, "signed", 0);
|
||||
if (topk <= 0 || ratio <= 0) return RAD_E_SHAPE;
|
||||
if (sgn != 0 && sgn != 1) return RAD_E_INVAL;
|
||||
if (sc->rank != 2 || bt->rank != 2 || se->rank != 2) return RAD_E_SHAPE;
|
||||
const int64_t M = sc->shape[0], nb = std::min(bt->shape[1], sc->shape[1]);
|
||||
const int64_t n_seq = numel(cu) - 1;
|
||||
@@ -526,6 +548,7 @@ AVX_KERNEL(qsa_select) {
|
||||
j.s_rs = sc->stride[0]; j.s_cs = sc->stride[1];
|
||||
j.bt_rs = bt->stride[0]; j.bt_cs = bt->stride[1];
|
||||
j.o_rs = se->stride[0]; j.o_cs = se->stride[1];
|
||||
j.sgn = sgn != 0;
|
||||
AVX_PARALLEL_FOR_IF(M * nb >= AVX_PAR_MIN && M > 1)
|
||||
for (int64_t m = 0; m < M; ++m) select_row(j, m);
|
||||
return RAD_OK;
|
||||
|
||||
+13
-3
@@ -537,8 +537,10 @@ AVX_KERNEL(gated_quant_fp8) {
|
||||
* is scaled by.
|
||||
*
|
||||
* Unlike had_quant_act_i8, 1/sqrt(g) is not applied here. <Hw, Ha> = g <w, a>, and the whole g is
|
||||
* divided out of the weight scale instead, where dividing a bf16 by a power of two is exact. */
|
||||
AVX_KERNEL(had_quant_act_fp8) {
|
||||
* divided out of the weight scale instead, where dividing a bf16 by a power of two is exact.
|
||||
*
|
||||
* had_quant_act_i8g is the same at int8 codes (`top` 127), for the i8a8h weight. */
|
||||
static int had_quant_q8(const RadArgs* a, float top) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *x = &a->t[0], *q = &a->t[1], *s = &a->t[2];
|
||||
const int64_t n = p_int(a, "n", 0);
|
||||
@@ -561,7 +563,7 @@ AVX_KERNEL(had_quant_act_fp8) {
|
||||
fwht_row(buf, n, g);
|
||||
for (int64_t gi = 0; gi < ngrp; ++gi) {
|
||||
float sc;
|
||||
fp8_group(buf, out, gi * g, gi * g + g, &sc);
|
||||
fp8_group(buf, out, gi * g, gi * g + g, &sc, top);
|
||||
stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc);
|
||||
}
|
||||
out_row(q, rowoff(q, r, n), n, out);
|
||||
@@ -569,6 +571,14 @@ AVX_KERNEL(had_quant_act_fp8) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
AVX_KERNEL(had_quant_act_fp8) {
|
||||
return had_quant_q8(a, 448.0f);
|
||||
}
|
||||
|
||||
AVX_KERNEL(had_quant_act_i8g) {
|
||||
return had_quant_q8(a, 127.0f);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- givens_rotate */
|
||||
/* ParoQuant's activation side for a 16-bit GEMM: each row is divided by its channel scales and
|
||||
* rotated by `stages` rounds of disjoint Givens pairs, once per part, parts side by side in y.
|
||||
|
||||
+281
-7
@@ -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"),
|
||||
@@ -94,6 +114,10 @@ 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") };
|
||||
/* The control vector's projection: one unit direction per layer (f32) and an int32 per-row switch. */
|
||||
static const RadParamSpec pHcProject[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_F64("scale"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oHcProject[] = { INOUT("h"), OPD("v"), OPD("on") };
|
||||
|
||||
static const RadParamSpec pMtpEnter[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_F64("eps"),
|
||||
P_STR("dtype"), P_F64O("wadd"), P_INTO("ngroup"),
|
||||
@@ -110,6 +134,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"), P_INTO("row_part") };
|
||||
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"), OUT_O("cu_part") };
|
||||
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") };
|
||||
@@ -218,8 +258,10 @@ static const RadParamSpec pGemmBias[] = { P_INT("M"), P_INT("N"), P_INT("K"),
|
||||
static const RadOperandSpec oGemmBias[] = { OPD("a"), WGT("b"), WGT("bias"), OPD_O("res"),
|
||||
OUT("y") };
|
||||
|
||||
/* `split_n` is libr4d's (docs/OPS.md); accepted and ignored here. */
|
||||
static const RadParamSpec pGemmQ[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"),
|
||||
P_STR("dtype"), P_INTO("pb1"), P_INTO("pb2") };
|
||||
P_STR("dtype"), P_INTO("pb1"), P_INTO("pb2"),
|
||||
P_INTO("split_n") };
|
||||
static const RadParamSpec pGemmQBias[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oGemmQ[] = { OPD("a"), OPD_O("a_scale"), WGT("b"), WGT("b_scale"),
|
||||
@@ -261,6 +303,13 @@ static const RadParamSpec pAttnDense[] = { P_INT("M"), P_INT("head_dim"), P_IN
|
||||
P_INTO("window_right") };
|
||||
static const RadOperandSpec oAttnDense[] = { OPD("q"), OPD("k"), OPD("v"), OPD("cu_seqlens"),
|
||||
OUT("out") };
|
||||
static const RadParamSpec pAttnCross[] = { P_INT("M"), P_INT("head_dim"), P_INT("gqa"),
|
||||
P_INT("causal"), P_STR("dtype"), P_F64O("scale") };
|
||||
static const RadOperandSpec oAttnCross[] = { OPD("q"), OPD("k"), OPD("v"), OPD("cu_seqlens"),
|
||||
OPD("cu_k"), OUT("out") };
|
||||
static const RadParamSpec pAttnNa3d[] = { P_INT("M"), P_INT("head_dim"), P_INT("kt"), P_INT("kh"),
|
||||
P_INT("kw"), P_STR("dtype"), P_F64O("scale") };
|
||||
static const RadOperandSpec oAttnNa3d[] = { OPD("q"), OPD("k"), OPD("v"), OPD("geom"), OUT("out") };
|
||||
|
||||
static const RadParamSpec pKvStore[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head_kv"),
|
||||
P_INT("block_size"), P_STR("kv_dtype"),
|
||||
@@ -305,7 +354,7 @@ static const RadParamSpec pQsaScore[] = { P_INT("M"), P_INT("n"), P_INT("heads")
|
||||
static const RadOperandSpec oQsaScore[] = { OPD("q"), OPD("bk"), OPD("bt"), OPD("cu"), OPD("nc"),
|
||||
OUT("score") };
|
||||
static const RadParamSpec pQsaSelect[] = { P_INT("M"), P_INT("blocks"), P_INT("topk"),
|
||||
P_INT("ratio"), P_INT("seqs") };
|
||||
P_INT("ratio"), P_INT("seqs"), P_INTO("signed") };
|
||||
static const RadOperandSpec oQsaSelect[] = { OPD("score"), OPD("bt"), OPD("nc"), OPD("pos"),
|
||||
OPD("cu"), OUT("sel"), OUT("nsel"), OUT("seqused") };
|
||||
static const RadParamSpec pQsaTailStore[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), P_INT("ring"),
|
||||
@@ -468,6 +517,13 @@ static const RadOperandSpec oAllGather[] = { OPD("x"), OUT("y") };
|
||||
/* ---- image generation --------------------------------------------------------------------- */
|
||||
static const RadParamSpec pLnMod[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype") };
|
||||
static const RadOperandSpec oLnMod[] = { OPD("x"), OPD("s"), OPD("cu_seqlens"), OUT("y") };
|
||||
static const RadParamSpec pTableAdd[] = { P_INT("M"), P_INT("n"), P_INT("L"), P_STR("dtype") };
|
||||
static const RadOperandSpec oTableAdd[] = { OPD("x"), WGT("t"), OUT("y") };
|
||||
static const RadParamSpec pMixRows[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_STR("dtype") };
|
||||
static const RadParamSpec pChanStats[] = { P_INT("M"), P_INT("n"), P_STR("mode"), P_INTO("var"),
|
||||
P_F64O("eps"), P_STR("dtype") };
|
||||
static const RadOperandSpec oChanStats[] = { OPD("x"), WGT("mean"), WGT("s"), OUT("y") };
|
||||
static const RadOperandSpec oMixRows[] = { OPD("x"), WGT("w"), OUT("y") };
|
||||
static const RadParamSpec pGateAdd[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_STRO("act") };
|
||||
static const RadOperandSpec oGateAdd[] = { OPD("y"), OPD("g"), OPD("cu_seqlens"), INOUT("x") };
|
||||
static const RadParamSpec pLnModQ[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"),
|
||||
@@ -475,12 +531,14 @@ static const RadParamSpec pLnModQ[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P
|
||||
static const RadOperandSpec oLnModQ[] = { OPD_O("y"), OPD_O("g"), OPD("s"), OPD("cu_seqlens"),
|
||||
INOUT("x"), OUT("q"), OUT("scale"), OUT_O("z") };
|
||||
static const RadParamSpec pRmsMod[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INTO("gated"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oRmsMod[] = { OPD_O("y"), OPD_O("g"), OPD("s"), WGT("w"),
|
||||
P_STR("dtype"), P_F64O("wadd"),
|
||||
P_INTO("norm_once"), P_STRO("norm") };
|
||||
static const RadOperandSpec oRmsMod[] = { OPD_O("y"), OPD_O("g"), OPD("s"), WGT_O("w"),
|
||||
OPD("cu_seqlens"), INOUT("x"), OUT("z") };
|
||||
static const RadParamSpec pRmsModQ[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"),
|
||||
P_INT("gated"), P_STR("dtype") };
|
||||
static const RadOperandSpec oRmsModQ[] = { OPD_O("y"), OPD_O("g"), OPD("s"), WGT("w"),
|
||||
P_INT("gated"), P_STR("dtype"), P_F64O("wadd"),
|
||||
P_INTO("norm_once"), P_STRO("norm") };
|
||||
static const RadOperandSpec oRmsModQ[] = { OPD_O("y"), OPD_O("g"), OPD("s"), WGT_O("w"),
|
||||
OPD("cu_seqlens"), INOUT("x"), OUT("q"), OUT("scale"),
|
||||
OUT_O("z") };
|
||||
static const RadOperandSpec oFlowX0[] = { OPD("v"), OPD("t"), OPD("sigma"), OPD("sigma_next"),
|
||||
@@ -501,11 +559,24 @@ static const RadOperandSpec oFlowEuler[] = { OPD("v"), OPD("sigma"), OPD("sigma
|
||||
OPD("pair"), OPD("lane"), OPD("flags"), OPD("seed"),
|
||||
OPD("cu_seqlens"), OPD_O("inp_lat"), OPD_O("inp_mask"),
|
||||
INOUT("state"), INOUT_O("preview") };
|
||||
/* The k-diffusion sampler's input and step: `pred` "eps" or "v", the lanes f32. */
|
||||
static const RadParamSpec pKdStep[] = { P_INT("M"), P_INT("n"), P_INT("stride"), P_STR("pred"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oKdInput[] = { OPD("sigma"), OPD("pair"), OPD("lane"), OPD("flags"),
|
||||
OPD("seed"), OPD("cu_seqlens"), INOUT("state"),
|
||||
OUT("y") };
|
||||
static const RadOperandSpec oKdStep[] = { OPD("out"), OPD("sigma"), OPD("sigma_next"),
|
||||
OPD("sigma_prev"), OPD("cfg"), OPD("pair"), OPD("lane"),
|
||||
OPD("flags"), OPD("seed"), OPD("sampler"), OPD("step"),
|
||||
OPD("cu_seqlens"), INOUT("state"), INOUT("hist"),
|
||||
INOUT_O("preview") };
|
||||
static const RadParamSpec pChanAffine[] = { P_INT("M"), P_INT("n"), P_STR("mul"), P_STR("add"),
|
||||
P_STR("mode"), P_STR("dtype"), P_INTO("round") };
|
||||
static const RadParamSpec pConvNhwc[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
|
||||
P_INT("stride"), P_STR("pad"), P_INT("up"), P_STR("dtype") };
|
||||
static const RadOperandSpec oConvNhwc[] = { OPD("x"), WGT("w"), WGT("b"), OUT("y") };
|
||||
static const RadParamSpec pIm2col[] = { P_INT("M"), P_INT("cin"), P_INT("k"), P_INT("stride"),
|
||||
P_STR("pad"), P_INT("up"), P_STR("dtype") };
|
||||
static const RadParamSpec pL2Norm[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_STR("dtype") };
|
||||
static const RadOperandSpec oL2Norm[] = { OPD("x"), WGT("gamma"), OUT("y") };
|
||||
static const RadParamSpec pSpaceDepth[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("ft"),
|
||||
@@ -559,7 +630,7 @@ static const RadOperandSpec oAttnVsa[] = { OPD("q"), OPD("k"), OPD("v"), OPD("se
|
||||
static const RadParamSpec pConv3d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
|
||||
P_INT("kt"), P_STR("dtype"), P_INTO("stride"),
|
||||
P_INTO("stride_t"), P_INTO("causal"), P_STRO("pad"),
|
||||
P_INTO("reflect") };
|
||||
P_INTO("reflect"), P_STRO("tpad"), P_INTO("tpre") };
|
||||
static const RadOperandSpec oConv3d[] = { OPD("x"), WGT("w"), WGT("b"), OPD("geom"),
|
||||
OPD_O("res"), OUT("y") };
|
||||
static const RadParamSpec pGroupNorm[] = { P_INT("M"), P_INT("n"), P_INT("groups"), P_F64("eps"),
|
||||
@@ -573,6 +644,52 @@ static const RadParamSpec pFlowRenoise[] = { P_INT("M"), P_INT("n"), P_INT("stre
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oFlowRenoise[] = { OPD("sigma"), OPD("seed"), INOUT("x") };
|
||||
|
||||
/* ---- LTX-2 (avx_ltx.cpp) */
|
||||
static const RadParamSpec pRopeSplit[] = { P_INT("M"), P_INT("n_head"), P_INT("head_dim"),
|
||||
P_INT("dim"), P_INT("n_dims"), P_F64("theta"),
|
||||
P_STR("max"), P_INTO("head0"), P_STR("dtype") };
|
||||
static const RadOperandSpec oRopeSplit[] = { INOUT("x"), OPD("positions") };
|
||||
static const RadParamSpec pHeadGate[] = { P_INT("M"), P_INT("n_head"), P_INT("head_dim"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oHeadGate[] = { OPD("g"), INOUT("x") };
|
||||
static const RadParamSpec pLtxGuide[] = { P_INT("M"), P_INT("n"), P_STR("dtype") };
|
||||
static const RadOperandSpec oLtxGuide[] = { OPD("vc"), OPD_O("vu"), OPD_O("vs"), OPD_O("vm"),
|
||||
OPD("scales"), OPD("sched"), INOUT("stats"),
|
||||
INOUT("x") };
|
||||
static const RadParamSpec pPixelNorm[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("form"),
|
||||
P_STRO("act"), P_INTO("ileave"), P_STR("dtype"),
|
||||
P_F64O("mult") };
|
||||
static const RadOperandSpec oPixelNorm[] = { OPD("x"), OUT("y") };
|
||||
static const RadParamSpec pD2s3d[] = { P_INT("M"), P_INT("C"), P_INT("st"), P_INT("sh"), P_INT("sw"),
|
||||
P_INTO("drop"), P_STR("dtype") };
|
||||
static const RadOperandSpec oD2s3d[] = { OPD("x"), OPD("geom"), OUT("y") };
|
||||
static const RadParamSpec pS2d3d[] = { P_INT("M"), P_INT("C"), P_INT("st"), P_INT("sh"), P_INT("sw"),
|
||||
P_INTO("tpre"), P_INTO("group"), P_STR("mode"),
|
||||
P_INTO("add"), P_STR("dtype") };
|
||||
static const RadOperandSpec oS2d3d[] = { OPD("x"), OPD("geom"), INOUT("y") };
|
||||
static const RadParamSpec pPixPatch[] = { P_INT("M"), P_INT("p"), P_INT("C"), P_STRO("order"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oPixPatch[] = { OPD("x"), OUT("y") };
|
||||
static const RadParamSpec pVolIndex[] = { P_INT("M") };
|
||||
static const RadOperandSpec oVolIndex[] = { OPD("geom"), OUT("y") };
|
||||
static const RadParamSpec pTileGrid[] = { P_INT("M"), P_INT("tile"), P_INT("stride"), P_STRO("rule"),
|
||||
P_INTO("min"), P_INTO("tile_t"), P_INTO("stride_t"),
|
||||
P_INTO("min_t"), P_INTO("tail") };
|
||||
static const RadOperandSpec oTileGrid[] = { OPD("geom"), OUT("y") };
|
||||
static const RadParamSpec pTileCrop[] = { P_INT("M"), P_INT("C"), P_STR("dtype") };
|
||||
static const RadOperandSpec oTileCrop[] = { OPD("x"), OPD("geom"), OPD("box"), OUT("y") };
|
||||
static const RadParamSpec pTileStitch[] = { P_INT("M"), P_INT("tile"), P_INT("stride"),
|
||||
P_STRO("rule"), P_INTO("min"), P_INTO("tile_t"),
|
||||
P_INTO("stride_t"), P_INTO("min_t"), P_INT("scale"),
|
||||
P_INTO("scale_t"), P_INT("p"), P_INT("C"),
|
||||
P_STRO("order"), P_STR("dtype") };
|
||||
static const RadOperandSpec oTileStitch[] = { OPD("x"), OPD("geom"), OPD("first"), OUT("y") };
|
||||
static const RadParamSpec pStftMel[] = { P_INT("M"), P_INT("hop"), P_INT("nfft"), P_INT("n_mel"),
|
||||
P_INT("ch"), P_STR("dtype") };
|
||||
static const RadOperandSpec oStftMel[] = { OPD("x"), WGT("basis"), WGT("mel"), OUT("y") };
|
||||
static const RadParamSpec pBweUp[] = { P_INT("M"), P_INT("ratio"), P_INT("ch"), P_STR("dtype") };
|
||||
static const RadOperandSpec oBweUp[] = { OPD("x"), OPD("res"), OUT("y") };
|
||||
|
||||
/* ---- audio generation (avx_audio.cpp), as libref declares it ------------------------------ */
|
||||
static const RadParamSpec pConv1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
|
||||
P_INT("dil"), P_STRO("act"), P_STR("dtype"),
|
||||
@@ -633,6 +750,8 @@ static const RadParamSpec pIota[] = { P_INT("M"), P_INT("start"), P_INT("step"),
|
||||
static const RadOperandSpec oIota[] = { OUT("y") };
|
||||
static const RadParamSpec pCuRepeat[] = { P_INT("M"), P_INT("mult") };
|
||||
static const RadOperandSpec oCuRepeat[] = { OPD("len"), OUT("y") };
|
||||
static const RadParamSpec pIntAffine[] = { P_INT("M"), P_STR("src"), P_STR("mul"), P_STR("add") };
|
||||
static const RadOperandSpec oIntAffine[] = { OPD("x"), OUT("y") };
|
||||
|
||||
/* ---- vocabulary edges --------------------------------------------------------------------- */
|
||||
static const RadParamSpec pEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_vocab"),
|
||||
@@ -702,6 +821,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 "
|
||||
@@ -709,6 +836,9 @@ static const RadOpSchema kSchemas[] = {
|
||||
"gate argument, and hc_write adds into the UNNORMED h). `mix` names the matrices' stored "
|
||||
"format; a host kernel reads them as the dense tensors it is handed." },
|
||||
{ "hc_write", ARR(pHcWrite), ARR(oHcWrite), "h[s] += inj[s] * y, into the unnormed stream." },
|
||||
{ "hc_project", ARR(pHcProject), ARR(oHcProject),
|
||||
"The control vector's projection (llama.cpp's `--cvec-mode project`): h[s] -= scale * "
|
||||
"(h[s] . v) * v for each of the hc streams of a row whose flag is on. A zero flag is not read." },
|
||||
{ "mtp_enter", ARR(pMtpEnter), ARR(oMtpEnter),
|
||||
"MTP head entry: two norms, a per-sub-stream fc and a broadcast fc. `fc` names the two "
|
||||
"matrices' stored format; a host kernel reads them as the dense tensors it is handed." },
|
||||
@@ -745,6 +875,20 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "pool_cols", ARR(pPoolRows), ARR(oUnary),
|
||||
"y[m][c] = the mean of x[m]'s columns [c*k, c*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),
|
||||
@@ -780,6 +924,9 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "had_quant_act_fp8", ARR(pQuant), ARR(oQuantFp8),
|
||||
"width-`group` Hadamard, then the same symmetric block-scaled E4M3 quantiser. No normalisation: "
|
||||
"the 1/group is folded into the stored weight scale at convert (docs/OPS.md)." },
|
||||
{ "had_quant_act_i8g", ARR(pQuant), ARR(oQuantFp8),
|
||||
"width-`group` Hadamard, then quant_act_i8g's symmetric int8 per group. No normalisation: the "
|
||||
"1/group is the i8a8h weight's stored scale (docs/OPS.md)." },
|
||||
{ "gram_accum", ARR(pQuant), ARR(oGram),
|
||||
"h += x^T x over a dequantised E4M3 activation. `h` is [n, n] and INOUT." },
|
||||
{ "givens_dense_quant", ARR(pGivensDense), ARR(oGivensDense),
|
||||
@@ -819,6 +966,9 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "lora_expand", ARR(pLoraExpand), ARR(oLoraExpand),
|
||||
"y[m, n] += scale[slot[m], n] * sum_j t[m, j] * lora_b[slot[m], n, j]; a base row is neither "
|
||||
"read nor written." },
|
||||
{ "lora_expand_mm", ARR(pLoraExpand), ARR(oLoraExpand),
|
||||
"lora_expand with t rounded to bf16, the sum over j in any order; a base row is neither read nor "
|
||||
"written." },
|
||||
{ "gemm_nt_q_gated", ARR(pGemmQGated), ARR(oGemmQGated),
|
||||
"gemm_nt_q over a [N, K] gate_up plane with gated_quant_fp8's pass in the epilogue, byte for "
|
||||
"byte the pair. `N` is the weight's rows, twice the fused width; the output is [M, N/2]." },
|
||||
@@ -828,6 +978,11 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "attn_dense", ARR(pAttnDense), ARR(oAttnDense),
|
||||
"dense varlen attention over cu_seqlens; a non-causal window may reach further right "
|
||||
"(`window_right`)." },
|
||||
{ "attn_cross", ARR(pAttnCross), ARR(oAttnCross),
|
||||
"attn_dense with each entry's keys a run of their own (cu_k); causal counts from each run's "
|
||||
"start." },
|
||||
{ "attn_na3d", ARR(pAttnNa3d), ARR(oAttnNa3d),
|
||||
"3-D neighborhood attention over a volume, libref's window and arithmetic." },
|
||||
{ "kv_store", ARR(pKvStore), ARR(oKvStore), "scatter k and v into the paged cache." },
|
||||
{ "rope_table", ARR(pRopeTable), ARR(oRopeTable), "cos/sin at each position's own row." },
|
||||
{ "qsa_block_key", ARR(pQsaBlockKey), ARR(oQsaBlockKey),
|
||||
@@ -853,6 +1008,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." },
|
||||
@@ -894,6 +1051,13 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "ln_mod", ARR(pLnMod), ARR(oLnMod),
|
||||
"y = bf16(bf16(LN(x)) * bf16(1 + s[seq])): a gainless layer norm and the row's entry's "
|
||||
"modulation row of `s` ([n_seq, >= n] at its own pitch)." },
|
||||
{ "table_add", ARR(pTableAdd), ARR(oTableAdd),
|
||||
"y[r, l n + c] = x[r, c] + t[l, c], f32 sum rounded once." },
|
||||
{ "chan_stats", ARR(pChanStats), ARR(oChanStats),
|
||||
"per-channel statistics held as weights: denorm rd(rd(x std) + mean), norm rd(rd(x - mean) / "
|
||||
"std)." },
|
||||
{ "mix_rows", ARR(pMixRows), ARR(oMixRows),
|
||||
"y[r, c] = sum_i w[i] x[r k + i, c], f32 in ascending i, rounded once." },
|
||||
{ "gate_add", ARR(pGateAdd), ARR(oGateAdd),
|
||||
"x = bf16(x + bf16(bf16(tanh(g[seq])) * y)), or with `act` none the gate g itself, bit for bit "
|
||||
"libref's." },
|
||||
@@ -912,12 +1076,22 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "flow_euler", ARR(pLane), ARR(oFlowEuler),
|
||||
"one flow-matching Euler step per entry that moves a lane, with guidance, the preview and the "
|
||||
"repaint's kept region; libref's roundings bit for bit." },
|
||||
{ "kd_input", ARR(pLane), ARR(oKdInput),
|
||||
"a k-diffusion sampler's model input per entry that moves a lane: a first step's noise times "
|
||||
"sqrt(1 + sigma^2) into the lane, then rd(x / sqrt(sigma^2 + 1)) at the entry's and its pair's "
|
||||
"rows; libref's arithmetic bit for bit." },
|
||||
{ "kd_step", ARR(pKdStep), ARR(oKdStep),
|
||||
"one k-diffusion sampler step per entry that moves a lane: the guided clean estimate from an "
|
||||
"eps or v output, then Euler, Euler ancestral or DPM++ 2M; libref's arithmetic bit for bit." },
|
||||
{ "chan_affine", ARR(pChanAffine), ARR(oUnary),
|
||||
"a per-channel affine from two lists of n bf16 values, `fma` or `inv`; `round` 0 keeps the "
|
||||
"lists and the arithmetic in f32, rounded once." },
|
||||
{ "conv2d_nhwc", ARR(pConvNhwc), ARR(oConvNhwc),
|
||||
"an image convolution, channels innermost, as GEMMs over bands of patch rows; `up` 2 reads the "
|
||||
"input upsampled nearest-neighbour, `pad` same or down." },
|
||||
{ "im2col_nhwc", ARR(pIm2col), ARR(oUnary),
|
||||
"conv2d_nhwc's receptive fields as rows, y [Hout * Wout, cin * k * k], column (ci * k + i) * k "
|
||||
"+ j the value conv2d_nhwc multiplies weight[o, ci, i, j] by; libref's copies bit for bit." },
|
||||
{ "l2norm_chan", ARR(pL2Norm), ARR(oL2Norm),
|
||||
"each pixel's channels to unit L2, times sqrt(n), times gamma (three roundings), then `act`." },
|
||||
{ "d2s_add", ARR(pSpaceDepth), ARR(oSpaceDepth),
|
||||
@@ -928,6 +1102,8 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "to_rgba8", ARR(pMnD), ARR(oUnary),
|
||||
"decoded pixels in [-1, 1] to bytes as diffusers' postprocess makes them, u8 out." },
|
||||
{ "gelu_tanh", ARR(pMnD), ARR(oUnary), "the tanh approximation of gelu." },
|
||||
{ "gelu_quick", ARR(pMnD), ARR(oUnary),
|
||||
"CLIP's quick_gelu, three roundings: a = rd(1.702 x), s = rd(sigmoid(a)), y = rd(x s)." },
|
||||
{ "scatter_add_rows", ARR(pMnD), ARR(oScatterRows),
|
||||
"x[idx[i]] += v[i], rounded to x's dtype; a negative index adds nothing." },
|
||||
{ "attn_prefix_self", ARR(pAttnPS), ARR(oAttnPS),
|
||||
@@ -983,6 +1159,29 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "flow_renoise", ARR(pFlowRenoise), ARR(oFlowRenoise),
|
||||
"x = f32(f32(1 - s) x) + f32(s z), z the (seed, stream) normal stream at k n + c, bit for bit "
|
||||
"libref's." },
|
||||
{ "rope_split", ARR(pRopeSplit), ARR(oRopeSplit),
|
||||
"LTX-2's split rotary over fractional coordinates, libref's arithmetic element by element." },
|
||||
{ "head_gate", ARR(pHeadGate), ARR(oHeadGate),
|
||||
"x = rd(x rd(2 rd(sigmoid(g)))) per head, libref's." },
|
||||
{ "ltx_guide", ARR(pLtxGuide), ARR(oLtxGuide),
|
||||
"LTX-2's guided sampler step in f32, libref's arithmetic with the deviations in f64." },
|
||||
{ "pixel_norm", ARR(pPixelNorm), ARR(oPixelNorm),
|
||||
"an RMS norm over each row as bf16 tensors compute it, every step rounded; rsqrt or div form, "
|
||||
"optionally silu, `ileave` interleaving the output; libref's." },
|
||||
{ "d2s3d", ARR(pD2s3d), ARR(oD2s3d), "depth to space over voxel rows, libref's copy." },
|
||||
{ "s2d3d", ARR(pS2d3d), ARR(oS2d3d),
|
||||
"space to depth over voxel rows, a copy or the mean of each group, libref's." },
|
||||
{ "pix_patch", ARR(pPixPatch), ARR(oPixPatch), "an image to patch rows, libref's copy." },
|
||||
{ "patch_pix8", ARR(pPixPatch), ARR(oPixPatch), "patch rows to RGB bytes, libref's rule." },
|
||||
{ "vol_index", ARR(pVolIndex), ARR(oVolIndex), "a volume's voxel coordinates, libref's." },
|
||||
{ "tile_grid", ARR(pTileGrid), ARR(oTileGrid), "a tiled decode's boxes, libref's cut." },
|
||||
{ "tile_crop", ARR(pTileCrop), ARR(oTileCrop), "a tile out of a volume, libref's copy." },
|
||||
{ "tile_stitch", ARR(pTileStitch), ARR(oTileStitch),
|
||||
"decoded tiles blended to RGB bytes, libref's blends and rounding." },
|
||||
{ "stft_logmel", ARR(pStftMel), ARR(oStftMel),
|
||||
"each channel's causal log-mel spectrogram, libref's roundings." },
|
||||
{ "bwe_up", ARR(pBweUp), ARR(oBweUp),
|
||||
"a Hann-windowed sinc resampler plus a residual, clamped, libref's roundings." },
|
||||
{ "conv1d", ARR(pConv1d), ARR(oConv1d),
|
||||
"a 1-D convolution over the sequences `cu_seqlens` bounds, channels innermost, PyTorch's "
|
||||
"[cout, cin, k] weight, dilation `dil`, centred or (`causal`) all on the left, zeros outside "
|
||||
@@ -1024,6 +1223,8 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "interleave2", ARR(pInterleave), ARR(oInterleave2), "two streams interleaved, y [rows, 2]." },
|
||||
{ "iota", ARR(pIota), ARR(oIota), "y[i] = start + i * step." },
|
||||
{ "cu_repeat", ARR(pCuRepeat), ARR(oCuRepeat), "y[j] = j * len[0] * mult." },
|
||||
{ "int_affine", ARR(pIntAffine), ARR(oIntAffine),
|
||||
"y[j] = (src[j] < 0 ? 0 : x[src[j]]) * mul[j] + add[j] over three integer lists." },
|
||||
{ "embed_lookup", ARR(pEmbedM), ARR(oEmbed),
|
||||
"embedding gather, vocab-parallel with an offset; `mult` multiplies every row (rounded once)." },
|
||||
{ "embed_lookup_q", ARR(pEmbed), ARR(oEmbedQ),
|
||||
@@ -1171,12 +1372,21 @@ 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),
|
||||
avx_layout_hc),
|
||||
SIMPLE("avx_hc_write", "hc_write", "norm", "gated residual write: h[s] += inj[s] * y", DT_FLOAT,
|
||||
L(hc_write)),
|
||||
SIMPLE("avx_hc_project", "hc_project", "norm",
|
||||
"control vector: h[s] -= scale * (h[s] . v) * v where the row's flag is on", DT_FLOAT,
|
||||
L(hc_project)),
|
||||
ROWL("avx_mtp_enter", "mtp_enter", "norm",
|
||||
"MTP head entry: two norms, a per-sub-stream fc and a broadcast fc",
|
||||
DT_FLOAT ", or fc matrices of E4M3 / int8 codes with a scale plane, joined", L(mtp_enter),
|
||||
@@ -1216,6 +1426,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,
|
||||
@@ -1260,6 +1484,10 @@ SIMPLE("avx_had_quant_act_fp8", "had_quant_act_fp8", "quant",
|
||||
"width-`group` Hadamard, then the same symmetric block-scaled E4M3 quantiser",
|
||||
"float in, fp8_e4m3 out, f32 scale per group; n a multiple of group",
|
||||
L(had_quant_act_fp8)),
|
||||
SIMPLE("avx_had_quant_act_i8g", "had_quant_act_i8g", "quant",
|
||||
"width-`group` Hadamard, then the symmetric int8 quantiser, one scale per group",
|
||||
"float in, i8 out, f32 scale per group; n a multiple of group",
|
||||
L(had_quant_act_i8g)),
|
||||
SIMPLE("avx_givens_rotate", "givens_rotate", "quant",
|
||||
"channel scale and Givens rotations per part, in the output's dtype",
|
||||
"float in, float out; int32 pairs, f32 angles and channel scales", L(givens_rotate)),
|
||||
@@ -1300,6 +1528,9 @@ SIMPLE("avx_lora_shrink", "lora_shrink", "gemm", "t = x A[slot]^T per row, base
|
||||
SIMPLE("avx_lora_expand", "lora_expand", "gemm",
|
||||
"y += scale * (t B[slot]^T) per row, base rows untouched",
|
||||
"f32 t and scale; bf16 lora_b; i32 slot; bf16 / f16 / f32 y", L(lora_expand)),
|
||||
SIMPLE("avx_lora_expand_mm", "lora_expand_mm", "gemm",
|
||||
"y += scale * (bf16(t) B[slot]^T) per row, base rows untouched",
|
||||
"f32 t and scale; bf16 lora_b; i32 slot; bf16 / f16 / f32 y", L(lora_expand_mm)),
|
||||
SIMPLE("avx_gemm_nt_q_gated", "gemm_nt_q_gated", "gemm",
|
||||
"gemm_nt_q over a gate_up plane with the gated E4M3 quantiser in the epilogue",
|
||||
"i8 / fp8 / float A; w4, w2, mxfp4, i8 or float B; fp8_e4m3 out, f32 scale",
|
||||
@@ -1311,6 +1542,11 @@ ROW("avx_attn_paged", "attn_paged", "attn",
|
||||
cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])), L(attn_paged)),
|
||||
SIMPLE("avx_attn_dense", "attn_dense", "attn", "dense varlen attention over cu_seqlens", DT_FLOAT,
|
||||
L(attn_dense)),
|
||||
SIMPLE("avx_attn_cross", "attn_cross", "attn",
|
||||
"dense varlen attention, keys bounded apart from the queries (cu_k)", DT_FLOAT,
|
||||
L(attn_cross)),
|
||||
SIMPLE("avx_attn_na3d", "attn_na3d", "attn", "3-D neighborhood attention over a volume", DT_FLOAT,
|
||||
L(attn_na3d)),
|
||||
ROW("avx_kv_store", "kv_store", "attn", "scatter k and v into the paged cache", DT_ANY,
|
||||
cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])), L(kv_store)),
|
||||
SIMPLE("avx_rope", "rope", "attn", "rotary embedding in place", DT_FLOAT, L(rope)),
|
||||
@@ -1334,6 +1570,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,
|
||||
@@ -1385,6 +1623,12 @@ SIMPLE("avx_ln_mod", "ln_mod", "norm", "gainless layer norm times (1 + an entry'
|
||||
DT_FLOAT, L(ln_mod)),
|
||||
SIMPLE("avx_gate_add", "gate_add", "elem", "x += act(gate row) * y, act tanh or none", DT_FLOAT,
|
||||
L(gate_add)),
|
||||
SIMPLE("avx_table_add", "table_add", "elem", "a row plus each of L table rows", DT_FLOAT,
|
||||
L(table_add)),
|
||||
SIMPLE("avx_mix_rows", "mix_rows", "elem", "a weighted sum of k consecutive rows", DT_FLOAT,
|
||||
L(mix_rows)),
|
||||
SIMPLE("avx_chan_stats", "chan_stats", "elem", "per-channel statistics held as weights",
|
||||
DT_FLOAT, L(chan_stats)),
|
||||
SIMPLE("avx_ln_mod_quant_fp8", "ln_mod_quant_fp8", "norm",
|
||||
"gated residual, adaptive norm and the E4M3 quantiser in one pass",
|
||||
"float in, fp8_e4m3 out, f32 scale, bf16 z", L(ln_mod_quant_fp8)),
|
||||
@@ -1400,11 +1644,17 @@ SIMPLE("avx_randn_lanes", "randn_lanes", "elem", "a lane's rows from its seed's
|
||||
DT_FLOAT, L(randn_lanes)),
|
||||
SIMPLE("avx_flow_euler", "flow_euler", "elem", "a flow-matching Euler step with guidance",
|
||||
DT_FLOAT, L(flow_euler)),
|
||||
SIMPLE("avx_kd_input", "kd_input", "elem", "a k-diffusion sampler's model input", DT_FLOAT,
|
||||
L(kd_input)),
|
||||
SIMPLE("avx_kd_step", "kd_step", "elem", "a k-diffusion sampler step with guidance", DT_FLOAT,
|
||||
L(kd_step)),
|
||||
SIMPLE("avx_chan_affine", "chan_affine", "elem", "a per-channel affine from parameter lists",
|
||||
DT_FLOAT, L(chan_affine)),
|
||||
SIMPLE("avx_conv2d_nhwc", "conv2d_nhwc", "conv",
|
||||
"an image convolution, channels innermost, as GEMMs over patch rows", DT_FLOAT,
|
||||
L(conv2d_nhwc)),
|
||||
SIMPLE("avx_im2col_nhwc", "im2col_nhwc", "elem", "a convolution's receptive fields as rows",
|
||||
DT_FLOAT, L(im2col_nhwc)),
|
||||
SIMPLE("avx_l2norm_chan", "l2norm_chan", "norm", "unit-L2 channel norm, scaled, optional silu",
|
||||
DT_FLOAT, L(l2norm_chan)),
|
||||
SIMPLE("avx_d2s_add", "d2s_add", "elem", "an upsampling shortcut added in", DT_FLOAT, L(d2s_add)),
|
||||
@@ -1412,6 +1662,7 @@ SIMPLE("avx_s2d_avg_add", "s2d_avg_add", "elem", "a downsampling shortcut added
|
||||
L(s2d_avg_add)),
|
||||
SIMPLE("avx_to_rgba8", "to_rgba8", "elem", "decoded pixels to bytes", DT_FLOAT, L(to_rgba8)),
|
||||
SIMPLE("avx_gelu_tanh", "gelu_tanh", "elem", "tanh gelu", DT_FLOAT, L(gelu_tanh)),
|
||||
SIMPLE("avx_gelu_quick", "gelu_quick", "elem", "quick gelu", DT_FLOAT, L(gelu_quick)),
|
||||
SIMPLE("avx_scatter_add_rows", "scatter_add_rows", "elem", "x[idx[i]] += v[i]", DT_FLOAT,
|
||||
L(scatter_add_rows)),
|
||||
SIMPLE("avx_attn_prefix_self", "attn_prefix_self", "attn",
|
||||
@@ -1455,6 +1706,27 @@ SIMPLE("avx_patch_fold", "patch_fold", "elem", "voxel rows to normalised patch r
|
||||
L(patch_fold)),
|
||||
SIMPLE("avx_flow_renoise", "flow_renoise", "elem", "a clean latent re-noised to a sigma",
|
||||
DT_FLOAT, L(flow_renoise)),
|
||||
SIMPLE("avx_rope_split", "rope_split", "elem", "LTX-2's split rotary over coordinates", DT_FLOAT,
|
||||
L(rope_split)),
|
||||
SIMPLE("avx_head_gate", "head_gate", "elem", "each head times 2 sigmoid of its logit", DT_FLOAT,
|
||||
L(head_gate)),
|
||||
SIMPLE("avx_ltx_guide", "ltx_guide", "elem", "LTX-2's guided sampler step", DT_FLOAT,
|
||||
L(ltx_guide)),
|
||||
SIMPLE("avx_pixel_norm", "pixel_norm", "norm", "an RMS norm as bf16 tensors compute it", DT_FLOAT,
|
||||
L(pixel_norm)),
|
||||
SIMPLE("avx_d2s3d", "d2s3d", "elem", "depth to space over voxel rows", DT_FLOAT, L(d2s3d)),
|
||||
SIMPLE("avx_s2d3d", "s2d3d", "elem", "space to depth over voxel rows", DT_FLOAT, L(s2d3d)),
|
||||
SIMPLE("avx_pix_patch", "pix_patch", "elem", "an image to patch rows", DT_FLOAT, L(pix_patch)),
|
||||
SIMPLE("avx_patch_pix8", "patch_pix8", "elem", "patch rows to RGB bytes", DT_FLOAT, L(patch_pix8)),
|
||||
SIMPLE("avx_vol_index", "vol_index", "elem", "a volume's voxel coordinates", DT_ANY, L(vol_index)),
|
||||
SIMPLE("avx_tile_grid", "tile_grid", "elem", "a tiled decode's boxes", DT_ANY, L(tile_grid)),
|
||||
SIMPLE("avx_tile_crop", "tile_crop", "elem", "a tile out of a volume", DT_FLOAT, L(tile_crop)),
|
||||
SIMPLE("avx_tile_stitch", "tile_stitch", "elem", "decoded tiles blended to RGB bytes", DT_FLOAT,
|
||||
L(tile_stitch)),
|
||||
SIMPLE("avx_stft_logmel", "stft_logmel", "elem", "a causal log-mel spectrogram", DT_FLOAT,
|
||||
L(stft_logmel)),
|
||||
SIMPLE("avx_bwe_up", "bwe_up", "elem", "a sinc-resampled waveform plus a residual, clamped",
|
||||
DT_FLOAT, L(bwe_up)),
|
||||
|
||||
SIMPLE("avx_conv1d", "conv1d", "conv", "a 1-D convolution over sequences, as GEMMs over patch rows",
|
||||
DT_FLOAT, L(conv1d)),
|
||||
@@ -1489,6 +1761,8 @@ SIMPLE("avx_interleave2", "interleave2", "elem", "two streams interleaved", DT_A
|
||||
L(interleave2)),
|
||||
SIMPLE("avx_iota", "iota", "elem", "an arithmetic index sequence", DT_ANY, L(iota)),
|
||||
SIMPLE("avx_cu_repeat", "cu_repeat", "elem", "bounds of equal sequences", DT_ANY, L(cu_repeat)),
|
||||
SIMPLE("avx_int_affine", "int_affine", "elem", "integers derived from device geometry", DT_ANY,
|
||||
L(int_affine)),
|
||||
|
||||
SIMPLE("avx_embed_lookup", "embed_lookup", "vocab", "embedding gather", DT_FLOAT, L(embed_lookup)),
|
||||
/* Its layout hook only validates: the table is read as stored and other encodings are refused
|
||||
|
||||
+18
-4
@@ -468,21 +468,33 @@ AVX_KERNEL(conv3d_ndhwc) {
|
||||
const RadTensor *X = &a->t[0], *W = &a->t[1], *B = &a->t[2], *G = &a->t[3];
|
||||
const RadTensor *R = rad_arg_in(a, 4), *Y = &a->t[5];
|
||||
const int64_t cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0);
|
||||
const int64_t k = p_int(a, "k", 0), kt = p_int(a, "kt", 0);
|
||||
if (cin <= 0 || cout <= 0 || k <= 0 || kt <= 0 || !(k & 1) || !(kt & 1) || numel(G) < 3)
|
||||
const int64_t k = p_int(a, "k", 0), kt = p_int(a, "kt", 0), tpre = p_int(a, "tpre", 0);
|
||||
/* The frames' padding (libref's): zero, the edge frame repeated, or causal with `tpre` more
|
||||
* copies of the first frame in front (T + tpre frames out). */
|
||||
const char* tps = p_str(a, "tpad", "zero");
|
||||
const int tpad = !std::strcmp(tps, "zero") ? 0 : !std::strcmp(tps, "replicate") ? 1
|
||||
: !std::strcmp(tps, "causal") ? 2 : -1;
|
||||
if (tpad < 0 || (tpre && tpad != 2)) return RAD_E_INVAL;
|
||||
if (cin <= 0 || cout <= 0 || k <= 0 || kt <= 0 || !(k & 1) || !(kt & 1) || tpre < 0 ||
|
||||
numel(G) < 3)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t sp = p_int(a, "stride", 1), st = p_int(a, "stride_t", 1);
|
||||
const int64_t causal = p_int(a, "causal", 0), reflect = p_int(a, "reflect", 0);
|
||||
const char* pads = p_str(a, "pad", "same");
|
||||
const bool down = pads && !std::strcmp(pads, "down");
|
||||
if (sp <= 0 || st <= 0 || (causal && causal != 1) || (reflect && reflect != 1) ||
|
||||
(causal && tpad) /* zero-causal and replicated-causal contradict */ ||
|
||||
!(!pads || !std::strcmp(pads, "same") || down))
|
||||
return RAD_E_SHAPE;
|
||||
const bool gen = sp != 1 || st != 1 || causal || down || reflect;
|
||||
if (gen && (k != 3 || kt != 3)) return RAD_E_SHAPE;
|
||||
const int64_t T = at(G, 0), H = at(G, 1), Wd = at(G, 2);
|
||||
if (T <= 0 || H <= 0 || Wd <= 0) return RAD_E_SHAPE;
|
||||
const int64_t ft = causal ? kt - 1 : kt / 2, bk = causal ? 0 : kt / 2;
|
||||
/* `tpad` folds into the front pad: replicate centres as `zero` does and clamps the reads to
|
||||
* the volume; causal-`tpre` front-pads kt - 1 + `tpre` replicated first frames, which is
|
||||
* T + `tpre` frames out -- libref's form, the same grid math as `causal`. */
|
||||
const int64_t ft = causal ? kt - 1 : tpad == 2 ? kt - 1 + tpre : kt / 2;
|
||||
const int64_t bk = (causal || tpad == 2) ? 0 : kt / 2;
|
||||
const int64_t pt = down ? 0 : k / 2, pb = down ? 1 : k / 2;
|
||||
const int64_t pl = down ? 0 : k / 2, pr = down ? 1 : k / 2;
|
||||
if (reflect && (std::max(pt, pb) >= H || std::max(pl, pr) >= Wd)) return RAD_E_SHAPE;
|
||||
@@ -531,7 +543,9 @@ AVX_KERNEL(conv3d_ndhwc) {
|
||||
for (int64_t dz = 0; dz < kt; ++dz)
|
||||
for (int64_t kh = 0; kh < k; ++kh)
|
||||
for (int64_t kw = 0; kw < k; ++kw, d += (size_t)cin * ael) {
|
||||
const int64_t tz = t * st + dz - ft;
|
||||
int64_t tz = t * st + dz - ft;
|
||||
if (tpad) /* replicate and causal-tpre clamp; `zero`/`causal` pad */
|
||||
tz = std::min<int64_t>(std::max<int64_t>(tz, 0), T - 1);
|
||||
int64_t iy = i * sp + kh - pt;
|
||||
int64_t ix = j * sp + kw - pl;
|
||||
if (reflect) { /* torch's mirror, no repeated edge, then the bounds */
|
||||
|
||||
Reference in new issue
Block a user