ops: attention sinks and LiLiCorr's correlator

For NVIDIA's LiLiCorr drafter:
- attn_paged_sink: attn_paged with a learned logit a query head beside the keys, in libref,
  libavx and libr4d (the windowed kernels at h128, gqa 8 and 16)
- sample_logprobs without params writes every row (a drafter's candidate logprobs)
- lili_cand, lili_attn, lili_factor, lili_walk: the correlator's candidates and features, its
  attention over the candidate lattice, the factor input and the greedy walk

ref_test, avx_check_hand and r4d_emu cases; docs/OPS.md.
This commit is contained in:
keptn42 committed 2026-11-04 22:08:52 +01:00
1 parent 44490c859a
commit 3b278dcec3
26 files changed
+1904 -55

No files matched your search

+1
View File
@@ -60,6 +60,7 @@ set(AVX_KERNEL_SRC
avx_ltx.cpp
avx_vsa.cpp
avx_audio.cpp
avx_lili.cpp
)
# The flag sets, written out because each states which instructions the object may contain.
+37 -9
View File
@@ -101,8 +101,23 @@ static inline void axpy(float* acc, const float* v, float w, int64_t n) {
* q-block) unit widens the context once into panels and runs its rows from them. Per-row math
* (ascending dots, the same rescale points) is the decode form's; the loads differ. q-blocks of 64
* keep enough units for the thread pool. Ragged (cus) inputs always take the decode form. */
static int attn_paged_prefill(const RadArgs* a, [[maybe_unused]] RadStream stream) {
const RadTensor *q = &a->t[0], *kv = &a->t[1], *bt = &a->t[2], *su = &a->t[3], *o = &a->t[7];
/* A sink (attn_paged_sink): one more logit in a row's softmax, with no value. Folded in after the
* keys: the maximum moves to it if it is larger, and the sum takes its weight. */
static inline void sink_fold(float sk, float* acc, int64_t head_dim, float* m, float* l) {
if (*m == -INFINITY) return; /* no visible key: the row stays zero */
if (sk > *m) {
const float r = sc_exp(*m - sk);
for (int64_t d = 0; d < head_dim; ++d) acc[d] *= r;
*l = *l * r + 1.0f;
*m = sk;
} else {
*l += sc_exp(sk - *m);
}
}
static int attn_paged_prefill(const RadArgs* a, [[maybe_unused]] RadStream stream,
const RadTensor* sinks, int oi) {
const RadTensor *q = &a->t[0], *kv = &a->t[1], *bt = &a->t[2], *su = &a->t[3], *o = &a->t[oi];
const RadTensor* kdes = rad_arg_in(a, 4);
const RadTensor* vdes = rad_arg_in(a, 5);
const int64_t head_dim = p_int(a, "head_dim", q->rank >= 3 ? q->shape[q->rank - 1] : 0);
@@ -225,6 +240,7 @@ static int attn_paged_prefill(const RadArgs* a, [[maybe_unused]] RadStream strea
if (++ntile == AVX_KV_TILE) flush();
}
flush();
if (sinks) sink_fold(ldt(sinks, h), acc, head_dim, &m, &l);
if (m == -INFINITY) {
for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, 0.0f);
continue;
@@ -246,6 +262,7 @@ static int attn_paged_prefill(const RadArgs* a, [[maybe_unused]] RadStream strea
return RAD_OK;
}
/* attn_paged, and attn_paged_sink with `sinks` (one logit a query head): out at operand `oi`. */
/* attn_paged_tree's ninth operand, `spec_parent` (rad_drafter_tree), is read here too, as libref
* reads it: -2 an ordinary causal row; else the row's parent's index within its sequence's rows
* (-1 for the block's first). Inside the block such a row sees itself and its ancestors only, and
@@ -253,14 +270,17 @@ static int attn_paged_prefill(const RadArgs* a, [[maybe_unused]] RadStream strea
/* `shared_anchor_window` (attn_paged_anchor_window): every row of a sequence measures its window,
* and a causal row its last visible key, from the sequence's first query position instead of its
* own, as libref does (ref_attn.cpp, ref_attn_paged_impl). */
static int attn_paged_impl(const RadArgs* a, RadStream stream, bool shared_anchor_window) {
if (a->n_t < 8) return RAD_E_INVAL;
const RadTensor *q = &a->t[0], *kv = &a->t[1], *bt = &a->t[2], *su = &a->t[3], *o = &a->t[7];
static int attn_paged_rows(const RadArgs* a, RadStream stream, const RadTensor* sinks, int oi,
bool shared_anchor_window = false) {
if (a->n_t < oi + 1) return RAD_E_INVAL;
const RadTensor *q = &a->t[0], *kv = &a->t[1], *bt = &a->t[2], *su = &a->t[3], *o = &a->t[oi];
const RadTensor* kdes = rad_arg_in(a, 4);
const RadTensor* vdes = rad_arg_in(a, 5);
const RadTensor* cus = rad_arg_in(a, 6);
const RadTensor* tpar = a->n_t > 8 ? rad_arg_in(a, 8) : nullptr;
/* The tree operand sits where attn_paged_sink keeps its output; a sinked call has none. */
const RadTensor* tpar = !sinks && a->n_t > 8 ? rad_arg_in(a, 8) : nullptr;
if (!q->data || !kv->data || !bt->data || !su->data || !o->data) return RAD_E_INVAL;
if (sinks && !sinks->data) return RAD_E_INVAL;
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);
@@ -277,6 +297,7 @@ static int attn_paged_impl(const RadArgs* a, RadStream stream, bool shared_ancho
if (kv_heads <= 0) return RAD_E_SHAPE;
const int64_t q_heads = gqa * kv_heads;
if (q->rank >= 3 && q->shape[q->rank - 2] != q_heads) return RAD_E_SHAPE;
if (sinks && numel(sinks) != q_heads) return RAD_E_SHAPE;
const int64_t n_seq = numel(su);
const int64_t rows = numel(q) / (q_heads * head_dim);
if (n_seq <= 0 || rows <= 0) return RAD_E_SHAPE;
@@ -303,7 +324,8 @@ static int attn_paged_impl(const RadArgs* a, RadStream stream, bool shared_ancho
const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim));
/* Uniform long queries take the panel form; ragged (cus) inputs stay here. */
if (!cus && q_len >= 32 && !tpar && !shared_anchor_window) return attn_paged_prefill(a, stream);
if (!cus && q_len >= 32 && !tpar && !shared_anchor_window)
return attn_paged_prefill(a, stream, sinks, oi);
/* Work units are (token, kv-head) groups: the gqa query rows of a group share every key and
* value row, so each is widened once for gqa dots/axpys. Per-row arithmetic is unchanged. */
const int64_t total = rows * kv_heads;
@@ -446,6 +468,7 @@ static int attn_paged_impl(const RadArgs* a, RadStream stream, bool shared_ancho
const int64_t h = kh * gqa + g;
const int64_t ob = tok * o_rs + h * o_hs;
float* ac = accs + g * head_dim;
if (sinks) sink_fold(ldt(sinks, h), ac, head_dim, &mm[g], &ll[g]);
if (mm[g] == -INFINITY) {
for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, 0.0f);
continue;
@@ -466,6 +489,11 @@ static int attn_paged_impl(const RadArgs* a, RadStream stream, bool shared_ancho
return RAD_OK;
}
AVX_KERNEL(attn_paged_sink) {
if (a->n_t < 9 || !a->t[7].data) return RAD_E_INVAL;
return attn_paged_rows(a, stream, &a->t[7], 8);
}
/* ------------------------------------------------------------------ attn_dense, bf16 blocks */
/* Encoder attention is all prefill. The per-query loop in attn_dense parallelises over
* (segment, head) only and re-widens every key row for every query (four million row conversions
@@ -752,13 +780,13 @@ AVX_BF16_TARGET static bool attn_dense_bf16(const RadTensor* q, const RadTensor*
}
#endif
AVX_KERNEL(attn_paged) { return attn_paged_impl(a, stream, false); }
AVX_KERNEL(attn_paged) { return attn_paged_rows(a, stream, nullptr, 7, false); }
/* attn_paged with one window anchor a sequence (DSpark's drafter); no tree operand. */
AVX_KERNEL(attn_paged_anchor_window) {
if (!a || a->n_t < 8) return RAD_E_INVAL;
if (a->n_t > 8 && rad_arg_in(a, 8)) return RAD_E_UNSUPPORTED;
return attn_paged_impl(a, stream, true);
return attn_paged_rows(a, stream, nullptr, 7, true);
}
/* attn_paged with its tree operand present, which attn_paged reads (see there). Refused without
+20
View File
@@ -390,6 +390,16 @@ std::vector<Case> build_cases() {
HI("block_size", 16), HI("causal", 1), HI("window", 8),
HS("q_dtype", dt), HS("kv_dtype", dt), HF("scale", 0.125),
HI("max_ctx", 128), HI("n_head", 8), HI("max_seqs", 2) });
/* The sink form: a block of 8 non-causal rows (LiLiCorr's query pass), a decode row and the
* prefill panel form, with and without a window. */
for (const char* dt : { "f32", "bf16" })
for (int qlen : { 1, 8, 64 })
for (int window : { 0, 16 })
add("attn_paged_sink", { HI("q_len", qlen), HI("head_dim", 64), HI("gqa", 4),
HI("block_size", 16), HI("causal", qlen == 8 ? 0 : 1),
HI("window", window), HS("q_dtype", dt),
HS("kv_dtype", dt), HF("scale", 0.125),
HI("max_ctx", 128), HI("n_head", 8), HI("max_seqs", 2) });
for (const char* dt : { "f32", "bf16" })
for (int causal : { 0, 1 })
add("attn_dense", { HI("M", 24), HI("head_dim", 64), HI("gqa", 2),
@@ -662,6 +672,16 @@ std::vector<Case> build_cases() {
add("grid_embed_aa", { HI("M", 40), HI("n", 72), HI("side", 4), HS("dtype", dt) });
}
/* LiLiCorr's lattice ops, at its geometry (7 positions of 8 candidates, 8 heads) narrowed in
* width; lili_cand's rows are no draw and are avx_check_hand.cpp's. */
for (const char* dt : { "f32", "bf16" }) {
add("lili_attn", { HI("M", 112), HI("steps", 7), HI("k", 8), HI("n_head", 8),
HI("head_dim", 16), HS("dtype", dt) });
add("lili_factor", { HI("M", 112), HI("L", 56), HI("n", 48), HS("dtype", dt) });
add("lili_walk", { HI("M", 3), HI("steps", 7), HI("k", 8), HI("n", 40), HS("dtype", dt),
HF("eps", 1e-4), HF("scale", 8.0) });
}
/* MoE. Both `a_order` spellings, since the two grouped GEMMs of a routed block use
* different ones. */
for (const char* dt : { "f32", "bf16" }) {
+31
View File
@@ -544,6 +544,37 @@ void shape_cases(std::vector<Hand>& hs) {
.pi("M", 6).pi("n", N).pi("side", 4).ps("dtype", "f32");
hs.push_back(std::move(ga));
/* LiLiCorr's candidates over two ranks' sample_logprobs rows: a merge that interleaves the
* ranks, an equal value on both (the lower id first), a rank with an unfilled slot. Rows
* of (max, sum, 4 (id, logit) pairs descending) a rank, k = 4, steps 3, n = 24. */
{
constexpr int64_t K = 4, W = 2, M = 3, NW = 24;
static const float kSt[M][W][2 + 2 * K] = {
{ { 2.0f, 7.5f, 10, 2.0f, 11, 1.5f, 40, 0.25f, 41, -1.0f },
{ 1.5f, 9.0f, 70, 1.5f, 77, 1.0f, 72, 0.5f, 73, 0.25f } },
{ { 0.5f, 3.0f, 5, 0.5f, 3, 0.25f, 9, 0.0f, 2, -3.0f },
{ 0.5f, 2.0f, 4, 0.5f, 8, 0.4f, -1, -INFINITY, -1, -INFINITY } },
{ { -1.0f, 12.0f, 100, -1.0f, 101, -1.25f, 102, -2.0f, 103, -2.5f },
{ 3.0f, 1.5f, 200, 3.0f, 201, -4.0f, 202, -5.0f, 203, -6.0f } },
};
Hand lc("two ranks merged, a tie and an unfilled slot", "lili_cand", 2e-5);
lc.dense(RAD_F32, { M, W * (2 + 2 * K) },
[](int64_t i) { return (&kSt[0][0][0])[i]; })
.dense(RAD_F32, { M, NW }, hfill(71))
.dense(RAD_F32, { 5 }, hfill(72))
.dense(RAD_F32, { 5 }, hfill(73))
.dense(RAD_F32, { NW, 5 }, hfill(74))
.dense(RAD_F32, { NW }, hfill(75))
.dense(RAD_F32, { 3, NW }, hfill(76))
.dense(RAD_F32, { K, NW }, hfill(77))
.dense(RAD_I32, { M, K }, [](int64_t) { return 0.0f; }, true)
.dense(RAD_F32, { M * K, NW }, [](int64_t) { return 0.0f; }, true)
.dense(RAD_F32, { M * K, NW }, [](int64_t) { return 0.0f; }, true)
.pi("M", M).pi("k", K).pi("world", W).pi("steps", 3).pi("n", NW).ps("dtype", "f32")
.pf("eps", 1e-5);
hs.push_back(std::move(lc));
}
Hand n("M = 64 over 5 rows, verifies of 3 and 2", "ngram_ids", 0.0);
n.idx({ 11, 12, 13, 21, 22 })
.dense(RAD_I32, { 2, 2 + 2 }, [](int64_t i) { return (float)(100 + i); }, true)
+2 -1
View File
@@ -85,6 +85,7 @@ int avx_par_force(int threads);
X(mla_attn) \
X(mla_attn_paged) \
X(add) X(grid_embed) X(grid_embed_aa) X(causal_conv1d) \
X(lili_cand) X(lili_attn) X(lili_factor) X(lili_walk) \
X(mul) X(silu_mul) X(gelu_mul) X(gelu) \
X(silu) X(sigmoid) X(logit_softcap) X(gather_rows) \
X(scatter_rows) X(ngram_ids) \
@@ -108,7 +109,7 @@ int avx_par_force(int threads);
X(gemm_nt_q_gated) X(embed_lookup) X(embed_lookup_q) X(logits_gemm) \
X(lora_shrink) X(lora_expand) X(lora_expand_mm) \
/* ---- attention */ \
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(kv_store_streamed) X(kv_resolve) X(rope) \
X(attn_paged) X(attn_paged_sink) X(attn_dense) X(attn_cross) X(attn_na3d) X(table_add) X(mix_rows) X(chan_stats) X(kv_store) X(kv_store_streamed) X(kv_resolve) 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) \
X(sam_attn) \
+244
View File
@@ -0,0 +1,244 @@
/* avx_lili.cpp -- LiLiCorr's candidate correlator, the contracts of libref/ref_lili.cpp: lili_cand,
* lili_attn, lili_factor and lili_walk. Small ops at a draft step's size (seven positions of eight
* candidates a sequence), so the arithmetic is libref's in its order, with the lattice's rows
* widened once into a panel and the rows or (sequence, head) units shared over the threads.
*/
#include "avx_vec.h"
#include "avx_common.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include <vector>
using namespace avx;
/* ------------------------------------------------------------------ lili_cand */
AVX_KERNEL(lili_cand) {
if (a->n_t < 11) return RAD_E_INVAL;
for (int i = 0; i < 11; ++i) if (!a->t[i].data) return RAD_E_INVAL;
const RadTensor *st = &a->t[0], *pas = &a->t[1], *lnw = &a->t[2], *lnb = &a->t[3];
const RadTensor *upw = &a->t[4], *upb = &a->t[5], *slot = &a->t[6], *rank = &a->t[7];
const RadTensor *cand = &a->t[8], *fo = &a->t[9], *bo = &a->t[10];
const int64_t k = p_int(a, "k", 0), world = p_int(a, "world", 1), steps = p_int(a, "steps", 0);
const int64_t n = p_int(a, "n", 0);
const float eps = p_f32(a, "eps", 1e-5f);
const int64_t rk = p_int(a, "row_k", k);
if (k < 2 || k > 64 || rk < k || world < 1 || world > 16 || steps < 1 || n <= 0)
return RAD_E_SHAPE;
const int64_t w = 2 + 2 * rk;
const int64_t M = rows_of(st, world * w);
if (M <= 0 || rows_of(pas, n) < M || numel(cand) < M * k || rows_of(fo, n) < M * k ||
rows_of(bo, n) < M * k)
return RAD_E_SHAPE;
if (numel(lnw) < 5 || numel(lnb) < 5 || numel(upw) < n * 5 || numel(upb) < n ||
rows_of(slot, n) < steps || rows_of(rank, n) < k)
return RAD_E_SHAPE;
if (cand->dtype != RAD_I32) return RAD_E_DTYPE;
/* The up projection widened once: [n, 5] and its bias. */
std::vector<float> uw((size_t)(n * 5)), ub((size_t)n);
for (int64_t i = 0; i < n * 5; ++i) uw[(size_t)i] = ldt(upw, i);
for (int64_t i = 0; i < n; ++i) ub[(size_t)i] = ldt(upb, i);
float lw[5], lb[5];
for (int i = 0; i < 5; ++i) { lw[i] = ldt(lnw, i); lb[i] = ldt(lnb, i); }
AVX_PARALLEL_FOR_IF(M >= 2)
for (int64_t m = 0; m < M; ++m) {
const int64_t sb = rowoff(st, m, world * w), ss = laststride(st);
auto S = [&](int64_t r, int64_t i) { return ldt(st, sb + (r * w + i) * ss); };
float mx = -INFINITY;
for (int64_t r = 0; r < world; ++r) mx = std::max(mx, S(r, 0));
double sum = 0.0;
for (int64_t r = 0; r < world; ++r)
if (S(r, 0) > -INFINITY) sum += (double)S(r, 1) * std::exp((double)S(r, 0) - mx);
const double lse = (double)mx + std::log(sum);
/* A world-way merge of lists sorted by value, ties to the lower id. */
float lp[64];
int64_t ids[64];
int64_t at[16] = {};
for (int64_t j = 0; j < k; ++j) {
int64_t br = -1;
float bv = 0.0f;
int64_t bid = 0;
for (int64_t r = 0; r < world; ++r) {
while (at[r] < k && (int64_t)S(r, 2 + 2 * at[r]) < 0) ++at[r];
if (at[r] >= k) continue;
const float v = S(r, 3 + 2 * at[r]);
const int64_t id = (int64_t)S(r, 2 + 2 * at[r]);
if (br < 0 || v > bv || (v == bv && id < bid)) { br = r; bv = v; bid = id; }
}
ids[j] = br < 0 ? 0 : bid;
lp[j] = br < 0 ? -1e4f : (float)((double)bv - lse);
if (br >= 0) ++at[br];
((int32_t*)cand->data)[rowoff(cand, m, k) + j * laststride(cand)] = (int32_t)ids[j];
}
const int64_t s = m % steps;
const int64_t pb = rowoff(pas, m, n), ps = laststride(pas);
const int64_t slb = rowoff(slot, s, n), sls = laststride(slot);
for (int64_t j = 0; j < k; ++j) {
const float f[5] = { lp[j], std::exp(lp[j]), lp[j] - lp[0],
(float)j / (float)(k - 1), j == 0 ? 1.0f : 0.0f };
float mean = 0.0f;
for (int i = 0; i < 5; ++i) mean += f[i];
mean /= 5.0f;
float var = 0.0f;
for (int i = 0; i < 5; ++i) var += (f[i] - mean) * (f[i] - mean);
var /= 5.0f;
const float rs = 1.0f / std::sqrt(var + eps);
float y[5];
for (int i = 0; i < 5; ++i) y[i] = (f[i] - mean) * rs * lw[i] + lb[i];
const int64_t row = m * k + j;
const int64_t fb = rowoff(fo, row, n), fs = laststride(fo);
const int64_t bb = rowoff(bo, row, n), bs = laststride(bo);
const int64_t rb = rowoff(rank, j, n), rks = laststride(rank);
for (int64_t c = 0; c < n; ++c) {
float u = ub[(size_t)c];
for (int i = 0; i < 5; ++i) u += uw[(size_t)(c * 5 + i)] * y[i];
stt(fo, fb + c * fs, u / (1.0f + std::exp(-u)));
stt(bo, bb + c * bs,
ldt(pas, pb + c * ps) + ldt(slot, slb + c * sls) + ldt(rank, rb + c * rks));
}
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ lili_attn */
AVX_KERNEL(lili_attn) {
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
const RadTensor *qkv = &a->t[0], *rel = &a->t[1], *same = &a->t[2], *o = &a->t[3];
const int64_t steps = p_int(a, "steps", 0), k = p_int(a, "k", 0);
const int64_t nh = p_int(a, "n_head", 0), hd = p_int(a, "head_dim", 0);
if (steps < 1 || k < 1 || nh < 1 || hd < 1) return RAD_E_SHAPE;
const int64_t L = steps * k, n = nh * hd;
const int64_t M = rows_of(qkv, 3 * n);
if (M <= 0 || M % L || rows_of(o, n) < M) return RAD_E_SHAPE;
const int64_t rw = rel->rank ? rel->shape[rel->rank - 1] : 0;
if (rw < 2 * steps - 1 || rows_of(rel, rw) < nh || numel(same) < nh) return RAD_E_SHAPE;
const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)hd));
const int64_t qs = laststride(qkv), os = laststride(o);
const int64_t units = (M / L) * nh;
AVX_PARALLEL_FOR_IF(units >= 2)
for (int64_t u = 0; u < units; ++u) {
const int64_t q0 = u / nh * L, h = u % nh;
/* The lattice's q, k and v of this head, widened once. */
float* pan = scratch_f32((size_t)(3 * L * hd + L) + 16);
float *Q = pan, *K = pan + L * hd, *V = pan + 2 * L * hd, *sc = pan + 3 * L * hd;
for (int64_t i = 0; i < L; ++i) {
const int64_t b = rowoff(qkv, q0 + i, 3 * n);
for (int64_t d = 0; d < hd; ++d) {
Q[i * hd + d] = ldt(qkv, b + (h * hd + d) * qs);
K[i * hd + d] = ldt(qkv, b + (n + h * hd + d) * qs);
V[i * hd + d] = ldt(qkv, b + (2 * n + h * hd + d) * qs);
}
}
const float sm = ldt(same, h);
const int64_t relb = rowoff(rel, h, rw), rels = laststride(rel);
for (int64_t i = 0; i < L; ++i) {
const int64_t si = i / k;
float mx = -INFINITY;
for (int64_t j = 0; j < L; ++j) {
float dot = 0.0f;
for (int64_t d = 0; d < hd; ++d) dot += Q[i * hd + d] * K[j * hd + d];
const int64_t sj = j / k;
float b = ldt(rel, relb + (si - sj + steps) * rels);
if (si == sj) b += sm;
sc[j] = dot * scale + b;
mx = std::max(mx, sc[j]);
}
float sum = 0.0f;
for (int64_t j = 0; j < L; ++j) { sc[j] = std::exp(sc[j] - mx); sum += sc[j]; }
const int64_t ob = rowoff(o, q0 + i, n) + h * hd * os;
for (int64_t d = 0; d < hd; ++d) {
float acc = 0.0f;
for (int64_t j = 0; j < L; ++j) acc += sc[j] * V[j * hd + d];
stt(o, ob + d * os, acc / sum);
}
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ lili_factor */
AVX_KERNEL(lili_factor) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *h = &a->t[0], *an = &a->t[1], *y = &a->t[2];
const int64_t L = p_int(a, "L", 0), n = p_int(a, "n", 0);
if (L < 1 || n < 1) return RAD_E_SHAPE;
const int64_t M = rows_of(h, n);
if (M <= 0 || M % L || rows_of(an, n) < M / L || rows_of(y, 3 * n) < M) return RAD_E_SHAPE;
AVX_PARALLEL_FOR_IF(M >= 8)
for (int64_t i = 0; i < M; ++i) {
const int64_t hb = rowoff(h, i, n), ab = rowoff(an, i / L, n), yb = rowoff(y, i, 3 * n);
const int64_t hs = laststride(h), as = laststride(an), ys = laststride(y);
for (int64_t c = 0; c < n; ++c) {
const float hv = ldt(h, hb + c * hs), av = ldt(an, ab + c * as);
stt(y, yb + c * ys, hv);
stt(y, yb + (n + c) * ys, av);
stt(y, yb + (2 * n + c) * ys, hv * av);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ lili_walk */
AVX_KERNEL(lili_walk) {
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
const RadTensor *ed = &a->t[0], *ao = &a->t[1], *cd = &a->t[2], *tk = &a->t[3];
const RadTensor* sco = a->n_t > 4 && a->t[4].data ? &a->t[4] : nullptr;
const int64_t steps = p_int(a, "steps", 0), k = p_int(a, "k", 0), n = p_int(a, "n", 0);
const float eps = p_f32(a, "eps", 1e-4f), scale = p_f32(a, "scale", 1.0f);
if (steps < 1 || k < 1 || n < 1) return RAD_E_SHAPE;
const int64_t M = rows_of(ao, n);
if (M <= 0 || rows_of(ed, 2 * n) < M * steps * k || numel(cd) < M * steps * k ||
numel(tk) < M * steps)
return RAD_E_SHAPE;
if (cd->dtype != RAD_I32 || tk->dtype != RAD_I32) return RAD_E_DTYPE;
if (sco && numel(sco) < M * steps * k * k) return RAD_E_SHAPE;
AVX_PARALLEL_FOR_IF(M >= 2)
for (int64_t m = 0; m < M; ++m) {
const int64_t R = steps * k;
float* pan = scratch_f32((size_t)((2 * R + 1) * n + R * k) + 16);
float *vo = pan, *vi = pan + R * n, *va = pan + 2 * R * n, *sc = pan + (2 * R + 1) * n;
auto vec = [&](const RadTensor* t, int64_t row, int64_t pitch, int64_t col0, float* v) {
const int64_t b = rowoff(t, row, pitch) + col0 * laststride(t), s = laststride(t);
double ss = 0.0;
for (int64_t c = 0; c < n; ++c) { v[c] = ldt(t, b + c * s); ss += (double)v[c] * v[c]; }
const float inv = 1.0f / std::max((float)std::sqrt(ss), eps);
for (int64_t c = 0; c < n; ++c) v[c] *= inv;
};
vec(ao, m, n, 0, va);
for (int64_t r = 0; r < R; ++r) {
vec(ed, m * R + r, 2 * n, 0, vo + r * n);
vec(ed, m * R + r, 2 * n, n, vi + r * n);
}
auto dot = [&](const float* x, const float* y) {
float s = 0.0f;
for (int64_t c = 0; c < n; ++c) s += x[c] * y[c];
return s * scale;
};
for (int64_t j = 0; j < k; ++j) {
const float v = dot(va, vi + j * n);
for (int64_t i = 0; i < k; ++i) sc[i * k + j] = v;
}
for (int64_t s = 1; s < steps; ++s)
for (int64_t i = 0; i < k; ++i)
for (int64_t j = 0; j < k; ++j)
sc[(s * k + i) * k + j] = dot(vo + ((s - 1) * k + i) * n, vi + (s * k + j) * n);
int64_t prev = 0;
for (int64_t s = 0; s < steps; ++s) {
int64_t best = 0;
for (int64_t j = 1; j < k; ++j)
if (sc[(s * k + prev) * k + j] > sc[(s * k + prev) * k + best]) best = j;
const int64_t id = ldi(cd, rowoff(cd, m * steps + s, k) + best * laststride(cd));
((int32_t*)tk->data)[rowoff(tk, m, steps) + s * laststride(tk)] = (int32_t)id;
prev = best;
}
if (sco)
for (int64_t e = 0; e < R * k; ++e) stt(sco, m * R * k + e, sc[e]);
}
return RAD_OK;
}
+48 -1
View File
@@ -134,6 +134,22 @@ static const RadParamSpec pLayernorm[] = { P_INT("M"), P_INT("n"), P_F64("eps"
static const RadOperandSpec oLayernorm[] = { OPD("x"), WGT("w"), WGT_O("b"), OUT("y") };
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") };
/* LiLiCorr's correlator (avx_lili.cpp; libref/ref_lili.cpp has the contracts). */
static const RadParamSpec pLiliCand[] = { P_INT("M"), P_INT("k"), P_INT("world"), P_INT("steps"),
P_INT("n"), P_STR("dtype"), P_F64O("eps"),
P_INTO("row_k") };
static const RadOperandSpec oLiliCand[] = { OPD("stats"), OPD("pas"), WGT("ln_w"), WGT("ln_b"),
WGT("up_w"), WGT("up_b"), WGT("slot"), WGT("rank"),
OUT("cand"), OUT("feat"), OUT("base") };
static const RadParamSpec pLiliAttn[] = { P_INT("M"), P_INT("steps"), P_INT("k"), P_INT("n_head"),
P_INT("head_dim"), P_STR("dtype"), P_F64O("scale") };
static const RadOperandSpec oLiliAttn[] = { OPD("qkv"), WGT("rel"), WGT("same"), OUT("out") };
static const RadParamSpec pLiliFactor[] = { P_INT("M"), P_INT("L"), P_INT("n"), P_STR("dtype") };
static const RadOperandSpec oLiliFactor[] = { OPD("h"), OPD("a"), OUT("y") };
static const RadParamSpec pLiliWalk[] = { P_INT("M"), P_INT("steps"), P_INT("k"), P_INT("n"),
P_STR("dtype"), P_F64O("eps"), P_F64O("scale") };
static const RadOperandSpec oLiliWalk[] = { OPD("edges"), OPD("aout"), OPD("cand"), OUT("tokens"),
OUT_O("scores") };
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") };
@@ -313,6 +329,12 @@ static const RadOperandSpec oAttnPagedTree[] = {
OPD("q"), OPD("kv_cache"), OPD("block_table"), OPD("seqused"),
OPD_O("k_descale"), OPD_O("v_descale"), OPD_O("cu_seqlens"), OUT("out"), OPD("spec_parent")
};
/* attn_paged with a learned sink logit a query head; a name of its own (libref's file comment). */
static const RadOperandSpec oAttnPagedSink[] = {
OPD("q"), OPD("kv_cache"), OPD("block_table"), OPD("seqused"),
OPD_O("k_descale"), OPD_O("v_descale"), OPD_O("cu_seqlens"), WGT("sinks"), OUT("out")
};
static const RadConstraint cPagedBlock[] = { RAD_CGE("block_size", 1) };
static const RadParamSpec pAttnDense[] = { P_INT("M"), P_INT("head_dim"), P_INT("gqa"),
@@ -899,7 +921,7 @@ static const RadOperandSpec oTopk[] = { OPD("logits"), OPD("params"),
static const RadOperandSpec oArgmax[] = { OPD("logits"), OPD("params"), OUT("token") };
static const RadParamSpec pLogprobs[] = { P_INT("M"), P_INT("n_vocab"), P_INT("k"),
P_INTO("vocab_off") };
static const RadOperandSpec oLogprobs[] = { OPD("logits"), OPD("params"), OUT("stats") };
static const RadOperandSpec oLogprobs[] = { OPD("logits"), OPD_O("params"), OUT("stats") };
static const RadOperandSpec oNarrow[] = { INOUT("cand_idx"), INOUT("cand_val"), OPD("params") };
static const RadOperandSpec oPick[] = { OPD("cand_idx"), OPD("cand_val"), OPD("params"),
OUT("token") };
@@ -973,6 +995,16 @@ static const RadOpSchema kSchemas[] = {
"x += a side x side position table resampled bilinearly to the row's grid." },
{ "grid_embed_aa", ARR(pGridEmbed), ARR(oGridEmbed),
"x += the table resampled as torch's antialiased half-pixel bilinear, SigLIP2's." },
{ "lili_cand", ARR(pLiliCand), ARR(oLiliCand),
"LiLiCorr's candidates from the ranks' sample_logprobs rows, their rank features through "
"layernorm, the up projection and silu, and the lattice rows' additive part." },
{ "lili_attn", ARR(pLiliAttn), ARR(oLiliAttn),
"attention over each sequence's candidate lattice with a learned bias on slot distance and the "
"same slot." },
{ "lili_factor", ARR(pLiliFactor), ARR(oLiliFactor),
"[h | a | h * a] a lattice row, a its sequence's anchor." },
{ "lili_walk", ARR(pLiliWalk), ARR(oLiliWalk),
"LiLiCorr's normalised edge scores and their greedy walk." },
{ "add", ARR(pAdd), ARR(oBinary),
"y = a + b; a `b` of exactly n elements against a taller output broadcasts along rows. With "
"`div`, y = rd(rd(a + b) / div), bit for bit libref's." },
@@ -1124,6 +1156,9 @@ static const RadOpSchema kSchemas[] = {
"else the row's parent's index within its sequence's rows (-1 for the block's first). Inside the "
"block such a row sees itself and its ancestors only; its window is measured from the block's "
"first position plus its depth." },
{ "attn_paged_sink", ARR(pAttnPaged), ARR(oAttnPagedSink),
"attn_paged with `sinks` [n_head] f32, one logit a query head beside the keys in the softmax's "
"maximum and denominator, with no value." },
{ "attn_dense", ARR(pAttnDense), ARR(oAttnDense),
"dense varlen attention over cu_seqlens; a non-causal window may reach further right "
"(`window_right`)." },
@@ -1631,6 +1666,14 @@ SIMPLE("avx_grid_embed", "grid_embed", "elem",
SIMPLE("avx_grid_embed_aa", "grid_embed_aa", "elem",
"antialiased half-pixel bilinear resample of a position grid, added in", DT_FLOAT,
L(grid_embed_aa)),
SIMPLE("avx_lili_cand", "lili_cand", "draft", "LiLiCorr candidates and their features", DT_FLOAT,
L(lili_cand)),
SIMPLE("avx_lili_attn", "lili_attn", "draft", "LiLiCorr lattice attention with slot biases",
DT_FLOAT, L(lili_attn)),
SIMPLE("avx_lili_factor", "lili_factor", "draft", "LiLiCorr factor input [h | a | h * a]",
DT_FLOAT, L(lili_factor)),
SIMPLE("avx_lili_walk", "lili_walk", "draft", "LiLiCorr edge scores and greedy walk", DT_FLOAT,
L(lili_walk)),
SIMPLE("avx_add", "add", "elem", "elementwise sum", DT_FLOAT, L(add)),
SIMPLE("avx_mul", "mul", "elem", "elementwise product, broadcasting b", DT_FLOAT, L(mul)),
SIMPLE("avx_act_mul", "act_mul", "elem", "act(a) * b over two operands", DT_FLOAT, L(act_mul)),
@@ -1793,6 +1836,10 @@ ROW("avx_attn_paged_tree", "attn_paged_tree", "attn",
"paged causal / sliding-window attention with a tree verify block (spec_parent)",
"any q and out dtype; bf16 or fp8 kv cache with optional per-(seq,head) descales; i32 parents",
cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])), L(attn_paged_tree)),
ROW("avx_attn_paged_sink", "attn_paged_sink", "attn",
"paged causal / sliding-window attention with a sink logit a head, any query length",
"any q and out dtype; bf16 or fp8 kv cache with optional per-(seq,head) descales; f32 sinks",
cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])), L(attn_paged_sink)),
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",
+4 -4
View File
@@ -685,9 +685,9 @@ AVX_KERNEL(sample_argmax) {
* pass the test after the first few thousand columns.
*
* The sum is f32 in four accumulators. Its terms are in (0, 1] and a logprob carries only its
* relative error, so f32 suffices (libref uses double). */
* relative error, so f32 suffices (libref uses double). Without `params` every row is written. */
AVX_KERNEL(sample_logprobs) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
if (a->n_t < 3 || !a->t[0].data || !a->t[2].data) return RAD_E_INVAL;
const RadTensor *lg = &a->t[0], *pr = &a->t[1], *st = &a->t[2];
const int64_t n_vocab = p_int(a, "n_vocab", lg->rank >= 2 ? lg->shape[lg->rank - 1] : 0);
const int64_t k = p_int(a, "k", 0);
@@ -697,11 +697,11 @@ AVX_KERNEL(sample_logprobs) {
const int64_t w = 2 + 2 * k;
if (M <= 0 || numel(st) < M * w) return RAD_E_SHAPE;
Rows R;
AVX_TRY(rows_of_params(pr, M, &R));
if (pr->data) AVX_TRY(rows_of_params(pr, M, &R));
AVX_PARALLEL_FOR_IF(M * n_vocab >= AVX_PAR_MIN)
for (int64_t m = 0; m < M; ++m) {
if (!(R.p[m].flags & RAD_SP_LOGPROBS)) continue;
if (pr->data && !(R.p[m].flags & RAD_SP_LOGPROBS)) continue;
float* buf = scratch_f32((size_t)n_vocab + 2 * (size_t)k);
const float* v = in_row(lg, rowoff(lg, m, n_vocab), n_vocab, buf);
float* tv = buf + n_vocab; /* the set's values, descending */