diff --git a/docs/OPS.md b/docs/OPS.md index dad4df74..95c64a25 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -950,6 +950,7 @@ as the weight's GEMM stored them and claims no form. It changes no value. |---|---|---| | `attn_paged` | `q_len`(range) `head_dim` `gqa` `block_size`/der `causal` `window` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt `prefill_fp8`/opt | `q`, `kv_cache`, `block_table`, `seqused`, `k_descale`?, `v_descale`?, `cu_seqlens`? → `out` | | `attn_paged_anchor_window` | same parameters as `attn_paged` | same operands as `attn_paged` → `out` | +| `attn_paged_sink` | `q_len`(range) `head_dim` `gqa` `block_size`/der `causal` `window` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt `prefill_fp8`/opt | `q`, `kv_cache`, `block_table`, `seqused`, `k_descale`?, `v_descale`?, `cu_seqlens`?, `sinks`w → `out` | | `attn_dense` | `M`(range) `head_dim` `gqa` `causal` `dtype` `scale`:f64/opt `max_seqlen`/opt `window`/opt `cu_div`/opt `block`/opt `window_right`/opt | `q`, `k`, `v`, `cu_seqlens` → `out` | | `attn_cross` | `M`(range) `head_dim` `gqa` `causal` `dtype` `scale`:f64/opt | `q`, `k`, `v`, `cu_seqlens`, `cu_k` → `out` | | `attn_na3d` | `M`(range) `head_dim` `kt` `kh` `kw` `dtype` `scale`:f64/opt | `q`, `k`, `v`, `geom` → `out` | @@ -968,6 +969,12 @@ as the weight's GEMM stored them and claims no form. It changes no value. | `qkv_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `ladder`/opt `wadd`:f64/opt `v_from_k`/opt `v_norm`/opt `dtype` | `q`:inout, `k`:inout, `v`:inout, `positions`, `q_w`w, `k_w`w | | `qkv_norm_rope_kv_store` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `ladder`/opt `wadd`:f64/opt `v_from_k`/opt `dtype` `v_norm`/opt `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `q`:inout, `k`:inout, `v`:inout, `positions`, `q_w`w, `k_w`w, `slot_mapping`, `kv_cache`:inout | +**`attn_paged_sink`** is `attn_paged` with a learned logit a query head beside the keys: `sinks` +`[n_head]` f32, in the scaled-score domain, joins each row's softmax maximum and denominator and +carries no value, so `out = Σ_j p_j v_j` with `p_j = exp(s_j) / (Σ_k exp(s_k) + exp(sink))`. A row +with no visible key stays zero. It has its own name so that no `attn_paged` kernel which does not +know the operand can be chosen for it (LiLiCorr's drafter, and gpt-oss's sinks have the same form). + **`attn_paged`**'s band is `q_len`, not `M`: one query row at decode, `1 + n_spec` at a speculative verify, thousands in a prefill chunk, and libr4d has a different kernel for each band. `attn_paged_anchor_window` has the same layout but different visibility: the first query position @@ -2849,7 +2856,7 @@ resolutions of one op. The one exception is `sample_chain` (below). | `sample_pick` | `M`(range) `n_cand` | `cand_idx`, `cand_val`, `params` → `token` | | `sample_argmax` | `M`(range) `n_vocab` | `logits`, `params` → `token` | | `sample_merge_topk` | `M`(range) `n_cand` | `gathered`, `params` → `cand_idx`, `cand_val` | -| `sample_logprobs` | `M`(range) `n_vocab` `k` `vocab_off`/opt | `logits`, `params` → `stats` | +| `sample_logprobs` | `M`(range) `n_vocab` `k` `vocab_off`/opt | `logits`, `params`? → `stats` | | `mtp_couple_propose` | `M`(range) `n_vocab` `round` `max_rounds` | `idx`:inout, `val`, `seq_ids`, `draw` → `state`:inout | | `mtp_couple_verify` | `M`(range) `n_cand` `n_vocab` | `cand_idx`, `cand_val`, `params`, `state` → `token`:inout | | `dflash_couple_propose` | `M`(range) `steps` `top_k` `rank` `n_vocab` `anchor_stride` `max_rounds` `q_temp`:f64/opt | `cand`, `unary`, `hp`?, `anchor`, `pred`w, `succ`w, `seq_ids`, `draw`, `tokens`:inout → `state`:inout | @@ -2907,7 +2914,8 @@ llama.cpp's: 0 turns the stage off for the row, and a negative value takes the w `sample_logprobs` serves an OpenAI `logprobs` field or llama-server's `n_probs`. It runs on the raw logits, before any stage has touched them, and only for a row whose flags carry `RAD_SP_LOGPROBS`; -other rows are not written. `stats` is `[M, 2 + 2k]` f32: the row's maximum, the sum of +other rows are not written. Without `params` every row is written (a drafter's candidate logprobs, +`lili_cand`). `stats` is `[M, 2 + 2k]` f32: the row's maximum, the sum of `exp(l - max)` over it, and its `k` largest as (id, logit) pairs, descending, ties to the lower id, the id written as a float (exact below 2^24) and global under a split vocabulary (`vocab_off` added). A slot past the vocabulary is id -1, logit -infinity. `k` is geometry, the one width every @@ -3450,6 +3458,42 @@ inside one workgroup. Written literally it is `steps` full-vocabulary `[rank, n_ products; through this operand it is a codebook gather. The only approximation is the top-K candidate set, which can cost acceptance and nothing else. +### LiLiCorr + +| op | params | operands | +|---|---|---| +| `lili_cand` | `M`(range) `k` `world` `steps` `n` `dtype` `eps`:f64/opt `row_k`/opt | `stats`, `pas`, `ln_w`w, `ln_b`w, `up_w`w, `up_b`w, `slot`w, `rank`w → `cand`, `feat`, `base` | +| `lili_attn` | `M`(range) `steps` `k` `n_head` `head_dim` `dtype` `scale`:f64/opt | `qkv`, `rel`w, `same`w → `out` | +| `lili_factor` | `M`(range) `L` `n` `dtype` | `h`, `a` → `y` | +| `lili_walk` | `M`(range) `steps` `k` `n` `dtype` `eps`:f64/opt `scale`:f64/opt | `edges`, `aout`, `cand` → `tokens`, `scores`? | + +LiLiCorr (Nemotron-3.5-Bolt's drafter) is a DFlash2 backbone whose head is a candidate correlator: +each draft position keeps the target head's top-k, and a small transformer over all positions' +candidates scores the edges between consecutive positions. A sequence's lattice is `steps` positions +of `k` candidates, row `s * k + j`, the sequences one after another. + +**`lili_cand`** reads `stats` `[M, world * (2 + 2 row_k)]` f32, each rank's `sample_logprobs` row +row-interleaved (`row_k` >= `k` pairs, by default `k`: a caller widens a rank's row to whole 16-byte +words for the all-gather, 9 pairs where it keeps 8), and merges them as one row would be read: the log-normaliser from the maxima and +the rescaled sums, the `k` largest pairs by value, ties to the lower id. `cand` `[M, k]` i32 holds +those ids. With `lp_j = logit_j - lse`, row `m * k + j` of `feat` is +`silu(up_w · layernorm([lp_j, exp lp_j, lp_j - lp_0, j/(k-1), j == 0]; ln_w, ln_b, eps) + up_b)` +and of `base` `pas[m] + slot[m % steps] + rank[j]`: the lattice row's additive part, to which the +token and feature projections are added by their GEMMs' residual operand. + +**`lili_attn`** is attention within each lattice, every row seeing every row: `qkv` is +`[M, 3 * n_head * head_dim]` as q | k | v, and the score is +`q_i · k_j * scale + rel[h][s_i - s_j + steps] + (s_i == s_j ? same[h] : 0)` with `s_i = i / k`. + +**`lili_factor`** writes `[h_i | a_s | h_i * a_s]`, `s = i / L`: a lattice row beside its sequence's +anchor and their product, the input of the factor projection `W [x, a, x * a] + b`. + +**`lili_walk`** normalises each candidate's outgoing and incoming vector (`edges`, `[out | in]`) and +the anchor's outgoing one (`aout`) as `v / max(|v|, eps)`, scores `start[j] = scale * aout · in[0][j]` +and `pair[s][i][j] = scale * out[s][i] · in[s + 1][j]`, and walks greedily from the start, the first +index winning a tie: `tokens[m][s] = cand[m * steps + s][p_s]`. `scores` `[M, steps, k, k]` is the +score tensor vLLM builds (row 0 the start for every `i`), for checking. + ### `mtp_enter` | op | params | operands | diff --git a/libavx/CMakeLists.txt b/libavx/CMakeLists.txt index cda34e89..531567ec 100644 --- a/libavx/CMakeLists.txt +++ b/libavx/CMakeLists.txt @@ -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. diff --git a/libavx/avx_attn.cpp b/libavx/avx_attn.cpp index 13d6e64b..e334c59e 100644 --- a/libavx/avx_attn.cpp +++ b/libavx/avx_attn.cpp @@ -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 diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index 51ac3f3e..cd49faf4 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -390,6 +390,16 @@ std::vector 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 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" }) { diff --git a/libavx/avx_check_hand.cpp b/libavx/avx_check_hand.cpp index fb8015a2..f3c5c55f 100644 --- a/libavx/avx_check_hand.cpp +++ b/libavx/avx_check_hand.cpp @@ -544,6 +544,37 @@ void shape_cases(std::vector& 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) diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index 209f79c1..c722a820 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -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) \ diff --git a/libavx/avx_lili.cpp b/libavx/avx_lili.cpp new file mode 100644 index 00000000..d1a37768 --- /dev/null +++ b/libavx/avx_lili.cpp @@ -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 +#include +#include +#include + +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 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; +} diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 94b16f5e..aa3ff906 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -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", diff --git a/libavx/avx_sample.cpp b/libavx/avx_sample.cpp index 2b69fe2a..f1228462 100644 --- a/libavx/avx_sample.cpp +++ b/libavx/avx_sample.cpp @@ -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 */ diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index 84f1d42c..931a7020 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -196,6 +196,8 @@ set(R4D_UNITS "r4d_rowtopk_bf16|" # The vocab-sharded draft head's cross-rank top-1, one id a row. "r4d_pair_argmax_f32|" + # LiLiCorr's correlator: candidates, lattice attention, factor input, walk. + "r4d_lili|" # Gemma 4's sandwich-norm joins (norm_add_norm, norm_add_norm_route, join_add_scale) and # expert_scale, each one kernel for a chain of small ones. "r4d_norm_join_bf16|" diff --git a/libr4d/r4d_attn_paged_window.hip b/libr4d/r4d_attn_paged_window.hip index 3e97e629..990ae017 100644 --- a/libr4d/r4d_attn_paged_window.hip +++ b/libr4d/r4d_attn_paged_window.hip @@ -28,6 +28,10 @@ * a block-table entry < 0 is a missing block: its keys are not visible * no visible key at all -> a zero row * k_descale / v_descale per (sequence, kv head), absent = 1 + * attn_paged_sink: `sinks` [query heads] f32, one logit a head in the scaled-score domain, in + * the softmax's maximum and denominator and with no value (LiLiCorr's drafter). Folded in where + * a row is normalised: the unsplit kernel's store and the merge. The WMMA kernel takes none, + * so a sink launch stays scalar. * * Paged layout: kv_cache[n_blocks, kv_heads, 16, 2*head_dim], K then V per slot, so one block of * one KV head is a contiguous run of 16 * 2 * head_dim elements; a key tile is one or two runs, @@ -194,6 +198,7 @@ struct AttnArgs { const float* vdes; uint16_t* out; long long o_rs, o_hs; float* part; /* split-KV partials, or null */ + const float* sinks; /* [query heads] or null */ int* tinfo; /* [tile] = (first row, positions) */ float qscale; /* softmax scale * log2(e) */ int max_blocks, n_seq, q_len, tps, kv_heads, causal, window, n_split; @@ -484,6 +489,21 @@ __device__ __forceinline__ void attn_body(AttnArgs A) { if (!val[i]) continue; const int r = wave * RW + i, p = r / GQA, g = r - p * GQA; if (A.n_split == 1) { + /* A sink joins the row's max and sum with no value (log2 domain, as m and l). */ + if (A.sinks && m[i] != -__builtin_inff()) { + const float s2 = A.sinks[kh * GQA + g] * 1.4426950408889634f; + if (s2 > m[i]) { + const float corr = ex2(m[i] - s2); +#pragma unroll + for (int c = 0; c < NC; ++c) +#pragma unroll + for (int e = 0; e < 4; ++e) o[i][c][e] *= corr; + l[i] = l[i] * corr + 1.0f; + m[i] = s2; + } else { + l[i] += ex2(s2 - m[i]); + } + } const float inv = l[i] > 0.0f ? vds / l[i] : 0.0f; uint16_t* op = A.out + (long long)(tok0 + p) * A.o_rs + (long long)(kh * GQA + g) * A.o_hs; #pragma unroll @@ -922,8 +942,11 @@ __device__ __forceinline__ void merge_body(AttnArgs A) { for (int c = 0; c < NC; ++c) *(uint2*)(op + c * 128 + lane * 4) = make_uint2(0u, 0u); continue; } - const float w0 = ex2(m0 - mt), w1 = ex2(m1 - mt); /* an empty split: ex2(-inf) = 0 */ - const float lt = wave_sum(__builtin_fmaf(l0, w0, l1 * w1)); + /* A sink joins the max and the sum with no value (log2 domain). */ + const float s2 = A.sinks ? A.sinks[kh * GQA + g] * 1.4426950408889634f : ninf; + const float ms = __builtin_fmaxf(mt, s2); + const float w0 = ex2(m0 - ms), w1 = ex2(m1 - ms); /* an empty split: ex2(-inf) = 0 */ + const float lt = wave_sum(__builtin_fmaf(l0, w0, l1 * w1)) + (A.sinks ? ex2(s2 - ms) : 0.0f); const float inv = lt > 0.0f ? 1.0f / lt : 0.0f; float acc[NC][4]; #pragma unroll @@ -1051,9 +1074,11 @@ __global__ __launch_bounds__(kThreads) void r4dchain_merge_window(AttnArgs A) { } template -static int launch_attn(const RadArgs* a, RadStream stream) { +static int launch_attn(const RadArgs* a, RadStream stream, bool sink = false) { constexpr int R = Geo::R, BK = Geo::BK, BQ = R / GQA, ESZ = KV8 ? 1 : 2; - if (!a || a->n_t < (TREE ? 9 : 8)) return RAD_E_INVAL; + if (!a || a->n_t < (TREE || sink ? 9 : 8)) return RAD_E_INVAL; + /* attn_paged_sink keeps its output where the tree operand would be: never both. */ + if (TREE && sink) return RAD_E_INVAL; /* attn_paged_qrow_tree's ninth operand: one int32 a query row (docs/OPS.md). Causal only. */ const RadTensor* tp = TREE ? rad_arg_in(a, 8) : nullptr; if (TREE && (!tp || !tp->data)) return RAD_E_INVAL; @@ -1066,8 +1091,9 @@ static int launch_attn(const RadArgs* a, RadStream stream) { const RadTensor* kd = rad_arg_in(a, 4); const RadTensor* vd = rad_arg_in(a, 5); const RadTensor* cu = rad_arg_in(a, 6); - const RadTensor* o = rad_arg_in(a, 7); - if (!q || !kv || !bt || !su || !o) return RAD_E_INVAL; + const RadTensor* sk = sink ? rad_arg_in(a, 7) : nullptr; + const RadTensor* o = rad_arg_in(a, sink ? 8 : 7); + if (!q || !kv || !bt || !su || !o || (sink && !sk)) return RAD_E_INVAL; if (rad_args_geti_or(a, "head_dim", HD) != HD || rad_args_geti_or(a, "gqa", GQA) != GQA || rad_args_geti_or(a, "block_size", 16) != 16) @@ -1083,6 +1109,7 @@ static int launch_attn(const RadArgs* a, RadStream stream) { if (kv->dtype != (uint32_t)(KV8 ? RAD_F8E4M3 : RAD_BF16)) return RAD_E_DTYPE; if (bt->dtype != RAD_I32 || su->dtype != RAD_I32 || (cu && cu->dtype != RAD_I32)) return RAD_E_DTYPE; if ((kd && kd->dtype != RAD_F32) || (vd && vd->dtype != RAD_F32)) return RAD_E_DTYPE; + if (sk && sk->dtype != RAD_F32) return RAD_E_DTYPE; /* the cache: [n_blocks, kv_heads, 16, 2 * head_dim], slots dense */ if (kv->rank != 4 || kv->shape[2] != 16 || kv->shape[3] != 2 * HD) return RAD_E_SHAPE; @@ -1090,6 +1117,7 @@ static int launch_attn(const RadArgs* a, RadStream stream) { const int64_t kvh = kv->shape[1]; if (kvh <= 0 || kvh > 65535) return RAD_E_SHAPE; const int64_t qh = kvh * GQA; + if (sk && rad_tensor_numel(sk) != qh) return RAD_E_SHAPE; int64_t rows = 0, q_rs = 0, q_hs = 0, orows = 0, o_rs = 0, o_hs = 0; if (!head_view(q, qh, HD, &rows, &q_rs, &q_hs) || !head_view(o, qh, HD, &orows, &o_rs, &o_hs)) @@ -1154,7 +1182,7 @@ static int launch_attn(const RadArgs* a, RadStream stream) { rows >= n_seq * (kWmmaMinQ / 2); const bool aligned = rad_ptr_aligned(q->data, 16) && rad_ptr_aligned(o->data, 16) && (q_rs | q_hs | o_rs | o_hs) % 8 == 0; - if (shaped && aligned) { + if (shaped && aligned && !sk) { constexpr int BQW = WGeo::R / GQA; int64_t ntw = 0, tpsw = 0; if (!cu) { @@ -1220,6 +1248,7 @@ static int launch_attn(const RadArgs* a, RadStream stream) { A.vdes = vd ? (const float*)vd->data : nullptr; A.out = (uint16_t*)o->data; A.o_rs = o_rs; A.o_hs = o_hs; A.part = ns > 1 ? (float*)a->scratch : nullptr; + A.sinks = sk ? (const float*)sk->data : nullptr; A.tinfo = ns > 1 ? (int*)((char*)a->scratch + part_bytes()) : nullptr; const double scale = rad_args_getf_or(a, "scale", 1.0 / __builtin_sqrt((double)HD)); A.qscale = (float)(scale * 1.4426950408889634); @@ -1311,6 +1340,19 @@ R4D_WIN_ANCHOR_DEF(256, 1) R4D_WIN_ANCHOR_DEF(256, 2) R4D_WIN_ANCHOR_DEF(256, 4) R4D_WIN_ANCHOR_DEF(512, 1) R4D_WIN_ANCHOR_DEF(512, 2) R4D_WIN_ANCHOR_DEF(512, 4) R4D_WIN_ANCHOR_DEF(512, 8) #undef R4D_WIN_ANCHOR_DEF +/* attn_paged_sink: LiLiCorr's drafter, 32 query heads over 2 KV heads at head_dim 128 (16 over 1 + * at TP 2: gqa 16 either way; 8 over its replicated head at TP 4: gqa 8), non-causal over its + * block, a 1024-token window. */ +#define R4D_WINSINK_DEF(HD, G) \ + int r4d_rad_attn_window_sink_h##HD##_gqa##G##_bf16(const RadArgs* a, RadStream s) { \ + return r4d_win::launch_attn(a, s, true); \ + } \ + int r4d_rad_attn_window_sink_h##HD##_gqa##G##_fp8(const RadArgs* a, RadStream s) { \ + return r4d_win::launch_attn(a, s, true); \ + } +R4D_WINSINK_DEF(128, 8) R4D_WINSINK_DEF(128, 16) +#undef R4D_WINSINK_DEF + /* Called at declare with no tensors. Partials are capped at kPartBudget (tile, head, split) * triples for any batch, so the size is a constant. */ int64_t r4d_rad_attn_window_h128_scratch(const RadArgs*) { return r4d_win::scratch_need<128>(); } diff --git a/libr4d/r4d_lili.hip b/libr4d/r4d_lili.hip new file mode 100644 index 00000000..d5ae822b --- /dev/null +++ b/libr4d/r4d_lili.hip @@ -0,0 +1,421 @@ +/* r4d_lili.hip -- LiLiCorr's candidate correlator (libref/ref_lili.cpp has the contracts): + * lili_cand, lili_attn, lili_factor and lili_walk, at a draft step's size (seven positions of eight + * candidates a sequence, a 1024-wide lattice). Each is a few microseconds of a draft step, so the + * kernels are plain: one workgroup a row (lili_cand, lili_factor), a (sequence, head) pair + * (lili_attn) or a sequence (lili_walk), shared memory and serial loops where a step is short, f32 + * arithmetic in libref's order and one rounding to bf16 at each store. + * + * Activations are bf16; lili_cand's statistics, LayerNorm and up projection are f32 and its slot and + * rank tables bf16; lili_attn's biases f32. Rows may have their own pitch, the last axis dense. + * Nothing here allocates or synchronises (docs/PLUGIN.md §5). + */ +#include + +#include +#include + +#include "r4d_plugin.h" +#include "r4d_launch.h" +#include "rad_plugin.h" + +namespace r4d_lili { + +constexpr int kThr = 256; +constexpr int kMaxK = 64; /* candidates a position (lili_cand, lili_walk) */ +constexpr int kMaxW = 16; /* ranks (lili_cand) */ +constexpr int kMaxL = 64; /* lattice rows a sequence (lili_attn) */ +constexpr int kMaxHd = 128; /* head width (lili_attn) */ +constexpr int kMaxWalk = 512; /* steps * k * k scores a sequence (lili_walk) */ + +__device__ __forceinline__ float bf(uint16_t v) { return __uint_as_float((uint32_t)v << 16); } +__device__ __forceinline__ uint16_t tobf(float f) { + uint32_t u = __float_as_uint(f); + if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t)((u >> 16) | 0x40u); /* NaN stays NaN */ + u += 0x7fffu + ((u >> 16) & 1u); + return (uint16_t)(u >> 16); +} + +/* ------------------------------------------------------------------ lili_cand */ +struct CandArgs { + const float* st; long long st_rs; + const uint16_t* pas; long long pas_rs; + const float *lnw, *lnb, *upw, *upb; + const uint16_t *slot, *rank; + int* cand; long long cand_rs; + uint16_t* feat; long long feat_rs; + uint16_t* base; long long base_rs; + int k, row_k, world, steps, n; + float eps; +}; + +__global__ __launch_bounds__(kThr) void cand_kernel(CandArgs A) { + __shared__ float s_y[kMaxK][5]; + const long long m = blockIdx.x; + const int k = A.k, w = 2 + 2 * A.row_k; + if (threadIdx.x == 0) { + const float* row = A.st + m * A.st_rs; + float mx = -__builtin_inff(); + for (int r = 0; r < A.world; ++r) mx = __builtin_fmaxf(mx, row[r * w]); + float sum = 0.0f; + for (int r = 0; r < A.world; ++r) + if (row[r * w] > -__builtin_inff()) sum += row[r * w + 1] * expf(row[r * w] - mx); + const float lse = mx + logf(sum); + /* A world-way merge of lists sorted by value, ties to the lower id. */ + int at[kMaxW]; + for (int r = 0; r < A.world; ++r) at[r] = 0; + float lp[kMaxK]; + for (int j = 0; j < k; ++j) { + int br = -1, bid = 0; + float bv = 0.0f; + for (int r = 0; r < A.world; ++r) { + while (at[r] < k && (int)row[r * w + 2 + 2 * at[r]] < 0) ++at[r]; + if (at[r] >= k) continue; + const float v = row[r * w + 3 + 2 * at[r]]; + const int id = (int)row[r * w + 2 + 2 * at[r]]; + if (br < 0 || v > bv || (v == bv && id < bid)) { br = r; bv = v; bid = id; } + } + lp[j] = br < 0 ? -1e4f : bv - lse; + if (br >= 0) ++at[br]; + A.cand[m * A.cand_rs + j] = br < 0 ? 0 : bid; + } + for (int j = 0; j < k; ++j) { + const float f[5] = { lp[j], expf(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 / __builtin_sqrtf(var + A.eps); + for (int i = 0; i < 5; ++i) s_y[j][i] = (f[i] - mean) * rs * A.lnw[i] + A.lnb[i]; + } + } + __syncthreads(); + const int s = (int)(m % A.steps); + for (int c = (int)threadIdx.x; c < A.n; c += kThr) { + const float pv = bf(A.pas[m * A.pas_rs + c]) + bf(A.slot[(long long)s * A.n + c]); + float uw[5]; + for (int i = 0; i < 5; ++i) uw[i] = A.upw[(long long)c * 5 + i]; + const float ub = A.upb[c]; + for (int j = 0; j < k; ++j) { + float u = ub; + for (int i = 0; i < 5; ++i) u += uw[i] * s_y[j][i]; + const long long row = m * k + j; + A.feat[row * A.feat_rs + c] = tobf(u / (1.0f + expf(-u))); + A.base[row * A.base_rs + c] = tobf(pv + bf(A.rank[(long long)j * A.n + c])); + } + } +} + +/* ------------------------------------------------------------------ lili_attn */ +struct AttnArgs { + const uint16_t* qkv; long long q_rs; + const float *rel, *same; int rel_w; + uint16_t* out; long long o_rs; + int steps, k, nh, hd; + float scale; +}; + +__global__ __launch_bounds__(kThr) void attn_kernel(AttnArgs A) { + __shared__ uint16_t s_k[kMaxL][kMaxHd], s_v[kMaxL][kMaxHd]; + __shared__ float s_q[kMaxHd], s_sc[kMaxL], s_sum; + const int L = A.steps * A.k, hd = A.hd, n = A.nh * hd, h = (int)blockIdx.y; + const long long r0 = (long long)blockIdx.x * L; + const int tid = (int)threadIdx.x; + for (int e = tid; e < L * hd; e += kThr) { + const int j = e / hd, d = e - j * hd; + const uint16_t* row = A.qkv + (r0 + j) * A.q_rs; + s_k[j][d] = row[n + h * hd + d]; + s_v[j][d] = row[2 * n + h * hd + d]; + } + const float sm = A.same[h]; + for (int i = 0; i < L; ++i) { + __syncthreads(); + if (tid < hd) s_q[tid] = bf(A.qkv[(r0 + i) * A.q_rs + h * hd + tid]); + __syncthreads(); + const int si = i / A.k; + if (tid < L) { + float dot = 0.0f; + for (int d = 0; d < hd; ++d) dot += s_q[d] * bf(s_k[tid][d]); + const int sj = tid / A.k; + float b = A.rel[(long long)h * A.rel_w + (si - sj + A.steps)]; + if (si == sj) b += sm; + s_sc[tid] = dot * A.scale + b; + } + __syncthreads(); + if (tid == 0) { + float mx = s_sc[0]; + for (int j = 1; j < L; ++j) mx = __builtin_fmaxf(mx, s_sc[j]); + float sum = 0.0f; + for (int j = 0; j < L; ++j) { s_sc[j] = expf(s_sc[j] - mx); sum += s_sc[j]; } + s_sum = sum; + } + __syncthreads(); + if (tid < hd) { + float acc = 0.0f; + for (int j = 0; j < L; ++j) acc += s_sc[j] * bf(s_v[j][tid]); + A.out[(r0 + i) * A.o_rs + h * hd + tid] = tobf(acc / s_sum); + } + } +} + +/* ------------------------------------------------------------------ lili_factor */ +struct FactorArgs { + const uint16_t* h; long long h_rs; + const uint16_t* a; long long a_rs; + uint16_t* y; long long y_rs; + int L, n; +}; + +__global__ __launch_bounds__(kThr) void factor_kernel(FactorArgs A) { + const long long i = blockIdx.x; + const uint16_t* hr = A.h + i * A.h_rs; + const uint16_t* ar = A.a + (i / A.L) * A.a_rs; + uint16_t* yr = A.y + i * A.y_rs; + for (int c = (int)threadIdx.x; c < A.n; c += kThr) { + const float hv = bf(hr[c]), av = bf(ar[c]); + yr[c] = hr[c]; + yr[A.n + c] = ar[c]; + yr[2 * A.n + c] = tobf(hv * av); + } +} + +/* ------------------------------------------------------------------ lili_walk */ +struct WalkArgs { + const uint16_t* ed; long long e_rs; + const uint16_t* ao; long long a_rs; + const int* cand; long long c_rs; + int* tok; long long t_rs; + float* scores; /* [M, steps, k, k] dense, or null */ + int steps, k, n; + float eps, scale; +}; + +__global__ __launch_bounds__(kThr) void walk_kernel(WalkArgs A) { + /* norms: [0, R) outgoing, [R, 2R) incoming, 2R the anchor's */ + __shared__ float s_nrm[2 * kMaxK * 8 + 1]; + __shared__ float s_sc[kMaxWalk]; + const long long m = blockIdx.x; + const int k = A.k, R = A.steps * k, n = A.n, tid = (int)threadIdx.x; + const uint16_t* E = A.ed + m * R * A.e_rs; + const uint16_t* an = A.ao + m * A.a_rs; + for (int v = tid; v < 2 * R + 1; v += kThr) { + const uint16_t* p = v < 2 * R ? E + (long long)(v % R) * A.e_rs + (v < R ? 0 : n) : an; + float ss = 0.0f; + for (int c = 0; c < n; ++c) { const float x = bf(p[c]); ss += x * x; } + s_nrm[v] = __builtin_fmaxf(__builtin_sqrtf(ss), A.eps); + } + __syncthreads(); + /* start (k entries, shared by every i) and the pairs: dots of the raw vectors over their norms */ + const int npair = (A.steps - 1) * k * k; + for (int e = tid; e < k + npair; e += kThr) { + const uint16_t *x, *y; + float nx, ny; + if (e < k) { + x = an; nx = s_nrm[2 * R]; + y = E + (long long)e * A.e_rs + n; ny = s_nrm[R + e]; + } else { + const int q = e - k, s = q / (k * k) + 1, i = (q / k) % k, j = q % k; + x = E + (long long)((s - 1) * k + i) * A.e_rs; nx = s_nrm[(s - 1) * k + i]; + y = E + (long long)(s * k + j) * A.e_rs + n; ny = s_nrm[R + s * k + j]; + } + float d = 0.0f; + for (int c = 0; c < n; ++c) d += bf(x[c]) * bf(y[c]); + const float v = A.scale * (d / nx / ny); + if (e < k) { + for (int i = 0; i < k; ++i) s_sc[i * k + e] = v; + } else { + s_sc[k * k + (e - k)] = v; + } + } + __syncthreads(); + if (tid == 0) { + int prev = 0; + for (int s = 0; s < A.steps; ++s) { + const float* row = s_sc + (s * k + prev) * k; + int best = 0; + for (int j = 1; j < k; ++j) if (row[j] > row[best]) best = j; + A.tok[m * A.t_rs + s] = A.cand[(m * A.steps + s) * A.c_rs + best]; + prev = best; + } + } + if (A.scores) + for (int e = tid; e < R * k; e += kThr) A.scores[m * R * k + e] = s_sc[e]; +} + +/* A tensor read as [rows, cols] with a row pitch, last axis dense: the pitch, and the rows in *M. */ +static long long pitch_of(const RadTensor* t, long long cols, long long* M) { + if (!t || cols <= 0) return -1; + if (t->rank == 1) { + if (t->stride[0] != 1 || t->shape[0] % cols) return -1; + *M = t->shape[0] / cols; + return cols; + } + const uint32_t r = t->rank; + if (r < 2 || t->stride[r - 1] != 1) return -1; + long long rows = 1; + for (uint32_t i = 0; i + 1 < r; ++i) rows *= t->shape[i]; + if (t->shape[r - 1] == cols) { + for (uint32_t i = 0; i + 2 < r; ++i) + if (t->shape[i] > 1 && t->stride[i] != t->stride[i + 1] * t->shape[i + 1]) return -1; + *M = rows; + return t->stride[r - 2]; + } + /* A flat [rows, a * cols] read at a narrower width is not a pitch. */ + if (r == 2 && t->stride[0] == t->shape[1] && t->shape[1] % cols == 0) { + *M = rows * (t->shape[1] / cols); + return cols; + } + return -1; +} + +static bool dense(const RadTensor* t) { + int64_t s = 1; + for (int i = (int)t->rank - 1; i >= 0; --i) { + if (t->shape[i] != 1 && t->stride[i] != s) return false; + s *= t->shape[i]; + } + return true; +} + +} /* namespace r4d_lili */ + +using namespace r4d_lili; + +extern "C" { + +int r4d_rad_lili_cand(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 11) return RAD_E_INVAL; + const RadTensor* t[11]; + for (int i = 0; i < 11; ++i) if (!(t[i] = rad_arg_in(a, i))) return RAD_E_INVAL; + const long long k = rad_args_geti_or(a, "k", 0), world = rad_args_geti_or(a, "world", 1); + const long long steps = rad_args_geti_or(a, "steps", 0), n = rad_args_geti_or(a, "n", 0); + const long long rk = rad_args_geti_or(a, "row_k", k); + if (k < 2 || k > kMaxK || rk < k || world < 1 || world > kMaxW || steps < 1 || n <= 0) + return RAD_E_SHAPE; + if (t[0]->dtype != RAD_F32 || t[1]->dtype != RAD_BF16 || t[8]->dtype != RAD_I32 || + t[9]->dtype != RAD_BF16 || t[10]->dtype != RAD_BF16 || t[6]->dtype != RAD_BF16 || + t[7]->dtype != RAD_BF16) + return RAD_E_DTYPE; + for (int i = 2; i <= 5; ++i) if (t[i]->dtype != RAD_F32) return RAD_E_DTYPE; + for (int i = 2; i <= 7; ++i) if (!dense(t[i])) return RAD_E_STRIDE; + if (rad_tensor_numel(t[2]) < 5 || rad_tensor_numel(t[3]) < 5 || rad_tensor_numel(t[4]) < n * 5 || + rad_tensor_numel(t[5]) < n || rad_tensor_numel(t[6]) < steps * n || + rad_tensor_numel(t[7]) < k * n) + return RAD_E_SHAPE; + long long M = 0, Mp = 0, Mc = 0, Mf = 0, Mb = 0; + CandArgs A{}; + A.st_rs = pitch_of(t[0], world * (2 + 2 * rk), &M); + A.pas_rs = pitch_of(t[1], n, &Mp); + A.cand_rs = pitch_of(t[8], k, &Mc); + A.feat_rs = pitch_of(t[9], n, &Mf); + A.base_rs = pitch_of(t[10], n, &Mb); + if (A.st_rs < 0 || A.pas_rs < 0 || A.cand_rs < 0 || A.feat_rs < 0 || A.base_rs < 0) + return RAD_E_STRIDE; + if (M <= 0 || Mp < M || Mc < M || Mf < M * k || Mb < M * k) return RAD_E_SHAPE; + A.st = (const float*)t[0]->data; A.pas = (const uint16_t*)t[1]->data; + A.lnw = (const float*)t[2]->data; A.lnb = (const float*)t[3]->data; + A.upw = (const float*)t[4]->data; A.upb = (const float*)t[5]->data; + A.slot = (const uint16_t*)t[6]->data; A.rank = (const uint16_t*)t[7]->data; + A.cand = (int*)t[8]->data; A.feat = (uint16_t*)t[9]->data; + A.base = (uint16_t*)t[10]->data; + A.k = (int)k; A.row_k = (int)rk; A.world = (int)world; A.steps = (int)steps; A.n = (int)n; + A.eps = (float)rad_args_getf_or(a, "eps", 1e-5); + R4D_KLAUNCH(R4D_KNAME(cand_kernel), dim3((unsigned)M), dim3(kThr), (hipStream_t)stream, A); + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; +} + +int r4d_rad_lili_attn(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 4) return RAD_E_INVAL; + const RadTensor* q = rad_arg_in(a, 0); + const RadTensor* rel = rad_arg_in(a, 1); + const RadTensor* same = rad_arg_in(a, 2); + const RadTensor* o = rad_arg_in(a, 3); + if (!q || !rel || !same || !o) return RAD_E_INVAL; + const long long steps = rad_args_geti_or(a, "steps", 0), k = rad_args_geti_or(a, "k", 0); + const long long nh = rad_args_geti_or(a, "n_head", 0), hd = rad_args_geti_or(a, "head_dim", 0); + if (steps < 1 || k < 1 || nh < 1 || hd < 1 || hd > kMaxHd || steps * k > kMaxL) + return RAD_E_SHAPE; + if (q->dtype != RAD_BF16 || o->dtype != RAD_BF16 || rel->dtype != RAD_F32 || + same->dtype != RAD_F32) + return RAD_E_DTYPE; + if (!dense(rel) || !dense(same)) return RAD_E_STRIDE; + const long long rw = rel->rank ? rel->shape[rel->rank - 1] : 0; + if (rw < 2 * steps - 1 || rad_tensor_numel(rel) < nh * rw || rad_tensor_numel(same) < nh) + return RAD_E_SHAPE; + const long long L = steps * k, n = nh * hd; + long long M = 0, Mo = 0; + AttnArgs A{}; + A.q_rs = pitch_of(q, 3 * n, &M); + A.o_rs = pitch_of(o, n, &Mo); + if (A.q_rs < 0 || A.o_rs < 0) return RAD_E_STRIDE; + if (M <= 0 || M % L || Mo < M) return RAD_E_SHAPE; + A.qkv = (const uint16_t*)q->data; A.out = (uint16_t*)o->data; + A.rel = (const float*)rel->data; A.same = (const float*)same->data; A.rel_w = (int)rw; + A.steps = (int)steps; A.k = (int)k; A.nh = (int)nh; A.hd = (int)hd; + A.scale = (float)rad_args_getf_or(a, "scale", 1.0 / __builtin_sqrt((double)hd)); + R4D_KLAUNCH(R4D_KNAME(attn_kernel), dim3((unsigned)(M / L), (unsigned)nh), dim3(kThr), + (hipStream_t)stream, A); + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; +} + +int r4d_rad_lili_factor(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 3) return RAD_E_INVAL; + const RadTensor* h = rad_arg_in(a, 0); + const RadTensor* an = rad_arg_in(a, 1); + const RadTensor* y = rad_arg_in(a, 2); + if (!h || !an || !y) return RAD_E_INVAL; + if (h->dtype != RAD_BF16 || an->dtype != RAD_BF16 || y->dtype != RAD_BF16) return RAD_E_DTYPE; + const long long L = rad_args_geti_or(a, "L", 0), n = rad_args_geti_or(a, "n", 0); + if (L < 1 || n < 1) return RAD_E_SHAPE; + long long M = 0, Ma = 0, My = 0; + FactorArgs A{}; + A.h_rs = pitch_of(h, n, &M); + A.a_rs = pitch_of(an, n, &Ma); + A.y_rs = pitch_of(y, 3 * n, &My); + if (A.h_rs < 0 || A.a_rs < 0 || A.y_rs < 0) return RAD_E_STRIDE; + if (M <= 0 || M % L || Ma < M / L || My < M) return RAD_E_SHAPE; + A.h = (const uint16_t*)h->data; A.a = (const uint16_t*)an->data; A.y = (uint16_t*)y->data; + A.L = (int)L; A.n = (int)n; + R4D_KLAUNCH(R4D_KNAME(factor_kernel), dim3((unsigned)M), dim3(kThr), (hipStream_t)stream, A); + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; +} + +int r4d_rad_lili_walk(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 4) return RAD_E_INVAL; + const RadTensor* ed = rad_arg_in(a, 0); + const RadTensor* ao = rad_arg_in(a, 1); + const RadTensor* cd = rad_arg_in(a, 2); + const RadTensor* tk = rad_arg_in(a, 3); + const RadTensor* sc = a->n_t > 4 ? rad_arg_in(a, 4) : nullptr; + if (!ed || !ao || !cd || !tk) return RAD_E_INVAL; + const long long steps = rad_args_geti_or(a, "steps", 0), k = rad_args_geti_or(a, "k", 0); + const long long n = rad_args_geti_or(a, "n", 0); + if (steps < 1 || k < 1 || k > kMaxK || n < 1 || steps * k * k > kMaxWalk || + steps * k > kMaxK * 8) + return RAD_E_SHAPE; + if (ed->dtype != RAD_BF16 || ao->dtype != RAD_BF16 || cd->dtype != RAD_I32 || + tk->dtype != RAD_I32 || (sc && sc->dtype != RAD_F32)) + return RAD_E_DTYPE; + if (sc && !dense(sc)) return RAD_E_STRIDE; + long long M = 0, Me = 0, Mc = 0, Mt = 0; + WalkArgs A{}; + A.a_rs = pitch_of(ao, n, &M); + A.e_rs = pitch_of(ed, 2 * n, &Me); + A.c_rs = pitch_of(cd, k, &Mc); + A.t_rs = pitch_of(tk, steps, &Mt); + if (A.a_rs < 0 || A.e_rs < 0 || A.c_rs < 0 || A.t_rs < 0) return RAD_E_STRIDE; + if (M <= 0 || Me < M * steps * k || Mc < M * steps || Mt < M) return RAD_E_SHAPE; + if (sc && rad_tensor_numel(sc) < M * steps * k * k) return RAD_E_SHAPE; + A.ed = (const uint16_t*)ed->data; A.ao = (const uint16_t*)ao->data; + A.cand = (const int*)cd->data; A.tok = (int*)tk->data; + A.scores = sc ? (float*)sc->data : nullptr; + A.steps = (int)steps; A.k = (int)k; A.n = (int)n; + A.eps = (float)rad_args_getf_or(a, "eps", 1e-4); + A.scale = (float)rad_args_getf_or(a, "scale", 1.0); + R4D_KLAUNCH(R4D_KNAME(walk_kernel), dim3((unsigned)M), dim3(kThr), (hipStream_t)stream, A); + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; +} + +} /* extern "C" */ diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 67c44a93..f2d37ccc 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -169,6 +169,11 @@ int64_t r4d_rad_attn_qrow_h128_gqa8_scratch(const RadArgs*); * row pitch, so they serve both attn_paged and attn_paged_qrow. */ int r4d_rad_attn_window_h128_gqa1_bf16(const RadArgs*, RadStream); int r4d_rad_attn_window_h128_gqa1_fp8 (const RadArgs*, RadStream); +/* The same kernels under attn_paged_sink (a sink logit a query head). */ +int r4d_rad_attn_window_sink_h128_gqa8_bf16 (const RadArgs*, RadStream); +int r4d_rad_attn_window_sink_h128_gqa8_fp8 (const RadArgs*, RadStream); +int r4d_rad_attn_window_sink_h128_gqa16_bf16(const RadArgs*, RadStream); +int r4d_rad_attn_window_sink_h128_gqa16_fp8 (const RadArgs*, RadStream); int r4d_rad_attn_window_h256_gqa1_bf16(const RadArgs*, RadStream); int r4d_rad_attn_window_h256_gqa1_fp8 (const RadArgs*, RadStream); int r4d_rad_attn_window_h256_gqa2_bf16(const RadArgs*, RadStream); @@ -223,6 +228,11 @@ int r4d_rad_dflash_tree(const RadArgs*, RadStream); /* The top-1 of a row of all-gathered (id, value) pairs, written one id a row: the vocab-sharded * draft head's merge (r4d_pair_argmax_f32.hip). */ int r4d_rad_pair_argmax_f32(const RadArgs*, RadStream); +/* LiLiCorr's correlator (r4d_lili.hip). */ +int r4d_rad_lili_cand (const RadArgs*, RadStream); +int r4d_rad_lili_attn (const RadArgs*, RadStream); +int r4d_rad_lili_factor(const RadArgs*, RadStream); +int r4d_rad_lili_walk (const RadArgs*, RadStream); /* Gemma 4's two sandwich-norm joins, each one kernel for a chain of rmsnorm / add / mul_weight * launches (r4d_norm_join_bf16.hip), and expert_scale, the embed_lookup + mul pair that scales * each routing weight by its expert's scale (r4d_expert_scale_bf16.hip). */ @@ -977,6 +987,7 @@ int r4d_shape_sample_pick (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_sample_chain (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_attn_paged (const RadParam*, int, int operand, RadOpdDesc*); +int r4d_shape_attn_paged_sink (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_attn_paged_gate_quant(const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_qk_norm_rope_gate (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_qk_norm_rope_gate_kv_store(const RadParam*, int, int operand, RadOpdDesc*); @@ -1013,6 +1024,10 @@ int r4d_shape_scale_rows (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_scale (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_row_topk_merge (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_pair_argmax (const RadParam*, int, int operand, RadOpdDesc*); +int r4d_shape_lili_cand (const RadParam*, int, int operand, RadOpdDesc*); +int r4d_shape_lili_attn (const RadParam*, int, int operand, RadOpdDesc*); +int r4d_shape_lili_factor (const RadParam*, int, int operand, RadOpdDesc*); +int r4d_shape_lili_walk (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_quant_act_i8 (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_had_quant_act_i8 (const RadParam*, int, int operand, RadOpdDesc*); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index bea221e4..38407e54 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -137,6 +137,19 @@ static const RadOperandSpec oAttnPagedTree[] = { { "spec_parent", RAD_OPD_IN, 0 }, }; +/* attn_paged with a sink logit a query head, its own name so no kernel ignorant of it is chosen. */ +static const RadOperandSpec oAttnPagedSink[] = { + { "q", RAD_OPD_IN, 0 }, + { "kv_cache", RAD_OPD_IN, 0 }, + { "block_table", RAD_OPD_IN, 0 }, + { "seqused", RAD_OPD_IN, 0 }, + { "k_descale", RAD_OPD_IN, 1 }, + { "v_descale", RAD_OPD_IN, 1 }, + { "cu_seqlens", RAD_OPD_IN, 1 }, + { "sinks", RAD_OPD_WEIGHT, 0 }, /* [n_head] f32 */ + { "out", RAD_OPD_OUT, 0 }, +}; + /* attn_paged with gate_quant_fp8 folded into its merge: attn_paged's parameters plus the two of * gate_quant_fp8's that are not implied (its `n` is `head_dim`, its rows attn_paged's (token, * head) pairs), then attn_paged's operands, the gate, the codes and the scales. `out` holds the @@ -2477,7 +2490,7 @@ static const RadParamSpec pLogprobs[] = { }; static const RadOperandSpec oLogprobs[] = { { "logits", RAD_OPD_IN, 0 }, - { "params", RAD_OPD_IN, 0 }, + { "params", RAD_OPD_IN, 1 }, /* absent: every row */ { "stats", RAD_OPD_OUT, 0 }, }; static const RadOperandSpec oNarrow[] = { @@ -2514,6 +2527,38 @@ static const RadOperandSpec oPairArgmax[] = { { "idx", RAD_OPD_OUT, 0 }, { "val", RAD_OPD_OUT, 1 }, }; +/* LiLiCorr's correlator (r4d_lili.hip; 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[] = { + { "stats", RAD_OPD_IN, 0 }, { "pas", RAD_OPD_IN, 0 }, + { "ln_w", RAD_OPD_WEIGHT, 0 }, { "ln_b", RAD_OPD_WEIGHT, 0 }, + { "up_w", RAD_OPD_WEIGHT, 0 }, { "up_b", RAD_OPD_WEIGHT, 0 }, + { "slot", RAD_OPD_WEIGHT, 0 }, { "rank", RAD_OPD_WEIGHT, 0 }, + { "cand", RAD_OPD_OUT, 0 }, { "feat", RAD_OPD_OUT, 0 }, { "base", RAD_OPD_OUT, 0 }, +}; +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[] = { + { "qkv", RAD_OPD_IN, 0 }, { "rel", RAD_OPD_WEIGHT, 0 }, { "same", RAD_OPD_WEIGHT, 0 }, + { "out", RAD_OPD_OUT, 0 }, +}; +static const RadParamSpec pLiliFactor[] = { P_INT("M"), P_INT("L"), P_INT("n"), P_STR("dtype") }; +static const RadOperandSpec oLiliFactor[] = { + { "h", RAD_OPD_IN, 0 }, { "a", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 }, +}; +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[] = { + { "edges", RAD_OPD_IN, 0 }, { "aout", RAD_OPD_IN, 0 }, { "cand", RAD_OPD_IN, 0 }, + { "tokens", RAD_OPD_OUT, 0 }, { "scores", RAD_OPD_OUT, 1 }, +}; static const RadParamSpec pNormJoin[] = { P_INT("M"), P_INT("n"), @@ -3345,6 +3390,9 @@ static const RadOpSchema kSchemas[] = { * attn_paged kernels read q dense and refuse a slice (RAD_E_STRIDE). Under this name the op * resolves to a kernel that takes the slice or to nothing, and in the latter case the * architecture lifts q into a dense block for attn_paged. */ + SCHEMA("attn_paged_sink", pAttnPaged, oAttnPagedSink, + "attn_paged with `sinks` [n_head] f32: one logit a query head in the scaled-score " + "domain, in the softmax's maximum and denominator, with no value."), SCHEMA("attn_paged_qrow", pAttnPaged, oAttnPaged, "attn_paged, parameter for parameter and value for value, with q read at its own row " "pitch: a column slice of a wider row -- the q part of a fused [q|k|v] projection -- read " @@ -3819,6 +3867,16 @@ static const RadOpSchema kSchemas[] = { "token order (with the shared arm folded when present) ARE the all-reduce's message, " "and the gated residual's write follows the reduction. Both wires at two ranks, the " "exact one at four."), + SCHEMA("lili_cand", pLiliCand, 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."), + SCHEMA("lili_attn", pLiliAttn, oLiliAttn, + "attention over each sequence's candidate lattice with a learned bias on slot distance " + "and the same slot."), + SCHEMA("lili_factor", pLiliFactor, oLiliFactor, + "[h | a | h * a] a lattice row, a its sequence's anchor."), + SCHEMA("lili_walk", pLiliWalk, oLiliWalk, + "LiLiCorr's normalised edge scores and their greedy walk."), SCHEMA("pair_argmax", pPairArgmax, oPairArgmax, "idx[m] = the id of the largest value among pairs[m, 0..n), each pair an int32 id in " "the first f32 slot and its value in the second (row_topk's `pairs`, all-gathered): ties " @@ -4304,6 +4362,8 @@ static const RadConstraint cAttnPrefillH64G4Bf16[] = { C_GE("window", WMIN), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", KV), \ }; R4D_WIN_C(cWinH128G1Bf16, 128, 1, "bf16", 0) R4D_WIN_C(cWinH128G1Fp8, 128, 1, "fp8_e4m3", 0) +R4D_WIN_C(cWinH128G8Bf16, 128, 8, "bf16", 0) R4D_WIN_C(cWinH128G8Fp8, 128, 8, "fp8_e4m3", 0) +R4D_WIN_C(cWinH128G16Bf16, 128, 16, "bf16", 0) R4D_WIN_C(cWinH128G16Fp8, 128, 16, "fp8_e4m3", 0) R4D_WIN_C(cWinH256G1Bf16, 256, 1, "bf16", 0) R4D_WIN_C(cWinH256G1Fp8, 256, 1, "fp8_e4m3", 0) R4D_WIN_C(cWinH256G2Bf16, 256, 2, "bf16", 0) R4D_WIN_C(cWinH256G2Fp8, 256, 2, "fp8_e4m3", 0) R4D_WIN_C(cWinH256G4Bf16, 256, 4, "bf16", 1) R4D_WIN_C(cWinH256G4Fp8, 256, 4, "fp8_e4m3", 1) @@ -4786,6 +4846,14 @@ static const RadConstraint cNormJoinRoute[] = { static const RadConstraint cPairArgmax[] = { C_GE("n", 1), C_IN("dtype", "f32 fp32"), }; +static const RadConstraint cLiliCand[] = { + C_GE("k", 2), C_LE("k", 64), C_GE("world", 1), C_LE("world", 16), C_IN("dtype", "bf16"), +}; +static const RadConstraint cLiliAttn[] = { + C_GE("head_dim", 1), C_LE("head_dim", 128), C_IN("dtype", "bf16"), +}; +static const RadConstraint cLiliFactor[] = { C_IN("dtype", "bf16") }; +static const RadConstraint cLiliWalk[] = { C_GE("k", 1), C_LE("k", 64), C_IN("dtype", "bf16") }; static const RadConstraint cExpertScale[] = { C_GE("top_k", 1), C_LE("top_k", 64), C_GE("n_expert", 1), C_IN("dtype", "bf16"), }; @@ -7371,6 +7439,24 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, R4D_WIN_PAIR(512, 16) #undef R4D_WIN_PAIR #undef R4D_WIN_ROW +/* attn_paged_sink: the windowed kernels with the sink folded in (LiLiCorr's drafter, h128 at gqa 16 + * to TP 2, gqa 8 at TP 4). */ +#define R4D_WINSINK_ROW(HD, G, KVN, KVS, C, KVDOC) \ +{ "attn_window_sink_h" #HD "_gqa" #G "_" #KVN, "attn_paged_sink", "attn", \ + "paged attention with a sink logit a head, any window, causal or not; split-KV with a merge", \ + "head_dim " #HD ", " #G " queries per kv head, paged block 16, any q_len, varlen", \ + "bf16 query, " KVDOC " kv cache, f32 sinks, bf16 out, f32 partials", \ + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, \ + ROW(C), NOTUNE, \ + nullptr, nullptr, r4d_rad_attn_window_sink_h##HD##_gqa##G##_##KVS, \ + r4d_rad_attn_window_h##HD##_scratch, \ + nullptr, nullptr, \ + r4d_shape_attn_paged_sink }, +R4D_WINSINK_ROW(128, 8, bf16kv, bf16, cWinH128G8Bf16, "bf16") +R4D_WINSINK_ROW(128, 8, fp8kv, fp8, cWinH128G8Fp8, "fp8-e4m3 (per-(seq,head) descales)") +R4D_WINSINK_ROW(128, 16, bf16kv, bf16, cWinH128G16Bf16, "bf16") +R4D_WINSINK_ROW(128, 16, fp8kv, fp8, cWinH128G16Fp8, "fp8-e4m3 (per-(seq,head) descales)") +#undef R4D_WINSINK_ROW /* DSpark's shared-anchor mask is intentionally a distinct op/kernel family, not an accepted * `window` variation of attn_paged's per-query visibility. Its base/upper key bounds are tied to @@ -9886,6 +9972,41 @@ R4D_WIN_TREE_PAIR(512, 4) R4D_WIN_TREE_PAIR(512, 8) /* pair_argmax, the sandwich-norm joins and expert_scale. The joins and expert_scale have no * opd_shape: libref has no row for them, and tests/r4d_emu holds their source to the replaced chain * bit for bit on the host. pair_argmax is described as libref describes it. */ +/* LiLiCorr's correlator: a few microseconds of a draft step each (r4d_lili.hip). */ +{ "lili_cand_bf16", "lili_cand", "draft", + "LiLiCorr candidates: the ranks' logprob rows merged, five rank features through layernorm, " + "the up projection and silu, and the lattice rows' additive part", + "k <= 64, world <= 16; one workgroup a draft position", + "f32 stats, layernorm and up projection; bf16 activations, slot and rank tables; i32 cand", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cLiliCand), NOTUNE, + nullptr, nullptr, r4d_rad_lili_cand, nullptr, nullptr, nullptr, + r4d_shape_lili_cand }, +{ "lili_attn_bf16", "lili_attn", "draft", + "LiLiCorr lattice attention with learned slot biases, no mask", + "steps * k <= 64, head_dim <= 128; one workgroup a (sequence, head)", + "bf16 qkv and out, f32 biases", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cLiliAttn), NOTUNE, + nullptr, nullptr, r4d_rad_lili_attn, nullptr, nullptr, nullptr, + r4d_shape_lili_attn }, +{ "lili_factor_bf16", "lili_factor", "draft", + "LiLiCorr factor input [h | a | h * a]", + "any M and n; one workgroup a row", + "bf16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cLiliFactor), NOTUNE, + nullptr, nullptr, r4d_rad_lili_factor, nullptr, nullptr, nullptr, + r4d_shape_lili_factor }, +{ "lili_walk_bf16", "lili_walk", "draft", + "LiLiCorr normalised edge scores and their greedy walk", + "k <= 64, steps * k * k <= 512; one workgroup a sequence", + "bf16 edges and anchor, i32 cand and tokens, f32 scores", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cLiliWalk), NOTUNE, + nullptr, nullptr, r4d_rad_lili_walk, nullptr, nullptr, nullptr, + r4d_shape_lili_walk }, + { "pair_argmax_f32", "pair_argmax", "select", "the top-1 of a row of (id, value) pairs, ties to the lower id, negative ids skipped", "any M and n; one wave a row; the outputs one element a row at their own pitch", diff --git a/libr4d/r4d_sample_stages_f32.hip b/libr4d/r4d_sample_stages_f32.hip index a7bdd464..fe138f11 100644 --- a/libr4d/r4d_sample_stages_f32.hip +++ b/libr4d/r4d_sample_stages_f32.hip @@ -687,7 +687,7 @@ __global__ __launch_bounds__(kTopkThreads) void logprobs_kernel( __shared__ float red[kTopkWaves]; const uint32_t m = blockIdx.x; - if (!(sp[m].flags & SP_LOGPROBS)) return; + if (sp && !(sp[m].flags & SP_LOGPROBS)) return; /* no params: every row */ const float* __restrict__ row = lg + (size_t)m * lg_ld; float* __restrict__ out = st + (size_t)m * st_ld; const uint32_t kk = k < n_vocab ? k : n_vocab; @@ -1165,7 +1165,7 @@ static int r4d_sample_argmax_f32(long lg, long tok, int M, int n_vocab, int lg_l static int r4d_sample_logprobs_f32(long lg, long params, long stats, int M, int n_vocab, int k, int lg_ld, int st_ld, int vocab_off, long stream) { - if (!lg || !params || !stats) return R4D_NO(RAD_E_INVAL); + if (!lg || !stats) return R4D_NO(RAD_E_INVAL); if (M <= 0 || n_vocab <= 0 || k <= 0) return R4D_NO(RAD_E_SHAPE); if ((uint32_t)k > kMaxLogprobs) return R4D_NO(RAD_E_SHAPE); if (!lg_ld) lg_ld = n_vocab; @@ -1389,8 +1389,9 @@ extern "C" int r4d_rad_sample_logprobs(const RadArgs* a, RadStream s) { const RadTensor* lg; long long M = 0, nv = 0, ld = 0; R4D_NEED(logits_of(a, &lg, &M, &nv, &ld)); + /* Absent params: every row (a drafter's candidate logprobs). */ const RadTensor* pr = r4d_opt(a, V_PARAMS); - R4D_NEED(params_ok(pr, M)); + if (pr) R4D_NEED(params_ok(pr, M)); const RadTensor* st = r4d_opt(a, 2); if (!st) return R4D_NO(RAD_E_INVAL); R4D_NEED(dt_f32(st)); diff --git a/libr4d/r4d_shapes.cpp b/libr4d/r4d_shapes.cpp index 4d2e111b..fb140501 100644 --- a/libr4d/r4d_shapes.cpp +++ b/libr4d/r4d_shapes.cpp @@ -1062,6 +1062,20 @@ extern "C" int r4d_shape_attn_paged(const RadParam* p, int n_p, int operand, R4D_PICK(l); } +/* attn_paged_sink -- attn_paged's operands with `sinks` [n_head] f32 before `out`. */ +extern "C" int r4d_shape_attn_paged_sink(const RadParam* p, int n_p, int operand, + RadOpdDesc* out) { + if (operand < 7) return r4d_shape_attn_paged(p, n_p, operand, out); + if (operand == 8) return r4d_shape_attn_paged(p, n_p, 7, out); + const int64_t nh = pi(p, n_p, "n_head"); + if (nh <= 0) return RAD_E_UNSUPPORTED; + const RadOpdDesc l[] = { + opd_none(), opd_none(), opd_none(), opd_none(), opd_none(), opd_none(), opd_none(), + opd((uint32_t)RAD_F32, nh), + }; + R4D_PICK(l); +} + /* attn_paged_gate_quant -- attn_paged's operands, then gate_quant_fp8's gate, codes and scales, * flat as gate_quant_fp8 describes them: one row per (token, head) pair, `head_dim` columns. */ extern "C" int r4d_shape_attn_paged_gate_quant(const RadParam* p, int n_p, int operand, @@ -1757,6 +1771,49 @@ extern "C" int r4d_shape_pair_argmax(const RadParam* p, int n_p, int operand, Ra R4D_PICK(l); } +/* LiLiCorr's ops, described as libref describes them; lili_cand declines (its stats rows are no + * draw; avx_check_hand.cpp and tests/r4d_emu build them). */ +extern "C" int r4d_shape_lili_cand(const RadParam*, int, int, RadOpdDesc*) { + return RAD_E_UNSUPPORTED; +} +extern "C" int r4d_shape_lili_attn(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), S = pi(p, n_p, "steps"), k = pi(p, n_p, "k"); + const int64_t nh = pi(p, n_p, "n_head"), hd = pi(p, n_p, "head_dim"); + if (M <= 0 || S <= 0 || k <= 0 || nh <= 0 || hd <= 0) return RAD_E_UNSUPPORTED; + const int64_t rows = (M + S * k - 1) / (S * k) * (S * k); + const RadOpdDesc l[] = { + opd((uint32_t)RAD_BF16, rows, 3 * nh * hd), + opd((uint32_t)RAD_F32, nh, 2 * S + 1), + opd((uint32_t)RAD_F32, nh), + opd((uint32_t)RAD_BF16, rows, nh * hd), + }; + R4D_PICK(l); +} +extern "C" int r4d_shape_lili_factor(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), L = pi(p, n_p, "L"), n = pi(p, n_p, "n"); + if (M <= 0 || L <= 0 || n <= 0) return RAD_E_UNSUPPORTED; + const int64_t rows = (M + L - 1) / L * L; + const RadOpdDesc l[] = { + opd((uint32_t)RAD_BF16, rows, n), + opd((uint32_t)RAD_BF16, rows / L, n), + opd((uint32_t)RAD_BF16, rows, 3 * n), + }; + R4D_PICK(l); +} +extern "C" int r4d_shape_lili_walk(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), S = pi(p, n_p, "steps"), k = pi(p, n_p, "k"); + const int64_t n = pi(p, n_p, "n"); + if (M <= 0 || S <= 0 || k <= 0 || n <= 0) return RAD_E_UNSUPPORTED; + const RadOpdDesc l[] = { + opd((uint32_t)RAD_BF16, M * S * k, 2 * n), + opd((uint32_t)RAD_BF16, M, n), + opd_idx(M * S, k, 1000), + opd((uint32_t)RAD_I32, M, S), + opd((uint32_t)RAD_F32, M, S, k, k), + }; + R4D_PICK(l); +} + /* ========================================================================================== * Quantisation, the norms and the fusions (shims beside their kernels). * diff --git a/libref/ref_attn.cpp b/libref/ref_attn.cpp index 31bf2431..c7658bba 100644 --- a/libref/ref_attn.cpp +++ b/libref/ref_attn.cpp @@ -75,20 +75,24 @@ struct KvDyn { } /* namespace */ /* ------------------------------------------------------------------ attn_paged */ +/* attn_paged, and attn_paged_sink with `sinks` (one logit a query head, beside the keys in the + * softmax's denominator and nowhere else): out at operand `oi`. */ /* attn_paged_tree's ninth operand, `spec_parent` (RadBatch::spec_parent, rad_drafter_tree), is * read here too: a row whose entry is -2 is an ordinary causal row; any other row is a node of its * sequence's verify block, whose entry is its parent's row within the sequence's rows (-1 for the * root, the block's first row). Inside the block such a row sees itself and its ancestors only, * and its window is measured from the block's first position plus its depth -- the position its * token has if its path is committed -- rather than from its row. */ -static int ref_attn_paged_impl(const RadArgs* a, RadStream, 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_impl(const RadArgs* a, const RadTensor* sinks, int oi, bool shared_anchor_window) { + 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 = t_in(a, 4); const RadTensor* vdes = t_in(a, 5); const RadTensor* cus = t_in(a, 6); - const RadTensor* tpar = a->n_t > 8 ? t_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 ? t_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); @@ -107,6 +111,7 @@ static int ref_attn_paged_impl(const RadArgs* a, RadStream, bool shared_anchor_w /* gqa and the cache's head count fix the query head count; a rank-3 query that disagrees would * stride through the wrong rows. */ 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; @@ -255,6 +260,11 @@ static int ref_attn_paged_impl(const RadArgs* a, RadStream, bool shared_anchor_w return; } + /* A sink is one more logit in the softmax with no value: the maximum takes it, + * the sum adds it last, and the output stays the keys' weighted values. */ + const float sk = sinks ? ldt(sinks, h) : -INFINITY; + if (sinks && sk > mx) mx = sk; + /* Pass two: exponentiate and accumulate in ascending key order. */ float acc[REF_HD_MAX]; for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f; @@ -268,6 +278,7 @@ static int ref_attn_paged_impl(const RadArgs* a, RadStream, bool shared_anchor_w for (int64_t d = 0; d < head_dim; ++d) acc[d] += w * (kl(kv->data, vb + d * kvv.sd) * vds); } + if (sinks) sum += ref_exp(sk - mx); const float inv = sum > 0.0f ? 1.0f / sum : 0.0f; for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, acc[d] * inv); }; @@ -282,14 +293,17 @@ static int ref_attn_paged_impl(const RadArgs* a, RadStream, bool shared_anchor_w return RAD_OK; } -int ref_attn_paged(const RadArgs* a, RadStream s) { - return ref_attn_paged_impl(a, s, false); -} +int ref_attn_paged(const RadArgs* a, RadStream) { return attn_paged_impl(a, nullptr, 7, false); } -int ref_attn_paged_anchor_window(const RadArgs* a, RadStream s) { +int ref_attn_paged_anchor_window(const RadArgs* a, RadStream) { if (!a || a->n_t < 8) return RAD_E_INVAL; if (a->n_t > 8 && t_in(a, 8)) return RAD_E_UNSUPPORTED; - return ref_attn_paged_impl(a, s, true); + return attn_paged_impl(a, nullptr, 7, true); +} + +int ref_attn_paged_sink(const RadArgs* a, RadStream) { + if (a->n_t < 9 || !a->t[7].data) return RAD_E_INVAL; + return attn_paged_impl(a, &a->t[7], 8, false); } /* attn_paged with its tree operand present: ref_attn_paged reads it (see there). Refused without diff --git a/libref/ref_lili.cpp b/libref/ref_lili.cpp new file mode 100644 index 00000000..a57996d7 --- /dev/null +++ b/libref/ref_lili.cpp @@ -0,0 +1,260 @@ +/* ref_lili.cpp -- LiLiCorr's candidate correlator (NVIDIA's Nemotron-3.5-Bolt drafter; vLLM's + * model_executor/models/lilicorr.py), the four ops a block drafter's query pass ends in: + * + * lili_cand the candidates of every draft position from the target head's top-k, their five + * rank features through LayerNorm, the up projection and SiLU, and the lattice row's + * additive part: the position's own state plus a slot and a rank embedding + * lili_attn attention over each sequence's lattice of steps x k rows, with a learned bias per + * head on the slot distance and on the same slot + * lili_factor [h | a | h * a] a row, a = its sequence's anchor + * lili_walk the factored edge scores and the greedy walk over them + * + * A sequence's lattice is `steps` draft positions of `k` candidates, row s * k + j for position s's + * j-th candidate, the sequences one after another. Everything runs in f32 and rounds once to the + * output's dtype. + */ +#include "ref_common.h" +#include "ref_ops.h" + +#include +#include +#include + +using namespace ref; + +/* ------------------------------------------------------------------ lili_cand */ +/* stats [M, world * (2 + 2 row_k)] f32: each rank's sample_logprobs row (max, sum of exp(l - max), + * row_k >= k (id, logit) pairs descending), all-gathered row-interleaved; row_k defaults to k (a + * caller widens it so a row is whole 16-byte words for the all-gather). The ranks merge as one row would: + * the maximum and the rescaled sum give the log-normaliser, the pairs the k largest by value, ties + * to the lower id. For candidate j of row m, with lp_j = logit_j - lse: + * + * feat = [lp_j, exp(lp_j), lp_j - lp_0, j / (k - 1), j == 0] + * f = silu(up_w . layernorm(feat; ln_w, ln_b, eps) + up_b) -> feat out, row m*k+j + * base = pas[m] + slot[m % steps] + rank[j] -> base out, row m*k+j + * cand = id_j -> cand [M, k] i32 + */ +int ref_lili_cand(const RadArgs* a, RadStream) { + 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 || 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; + + REF_PAR_FOR(M * k * n * 8) + 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); }; + /* The log-normaliser over every rank's shard. */ + 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); + /* The k largest pairs of the world * k, by value, ties to the lower id. */ + std::vector> all; + all.reserve((size_t)(world * k)); + for (int64_t r = 0; r < world; ++r) + for (int64_t j = 0; j < k; ++j) { + const int64_t id = (int64_t)S(r, 2 + 2 * j); + if (id >= 0) all.push_back({ S(r, 3 + 2 * j), id }); + } + std::sort(all.begin(), all.end(), [](const auto& x, const auto& y) { + return x.first > y.first || (x.first == y.first && x.second < y.second); + }); + float lp[64]; + int64_t ids[64]; + for (int64_t j = 0; j < k; ++j) { + const bool have_j = j < (int64_t)all.size(); + ids[j] = have_j ? all[(size_t)j].second : 0; + lp[j] = have_j ? (float)((double)all[(size_t)j].first - lse) : -1e4f; + ((int32_t*)cand->data)[rowoff(cand, m, k) + j * laststride(cand)] = (int32_t)ids[j]; + } + const int64_t s = m % steps; + 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 * ldt(lnw, i) + ldt(lnb, 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); + for (int64_t c = 0; c < n; ++c) { + float u = ldt(upb, c); + for (int i = 0; i < 5; ++i) u += ldt(upw, c * 5 + i) * y[i]; + stt(fo, fb + c * fs, u / (1.0f + std::exp(-u))); + const float b = ldt(pas, rowoff(pas, m, n) + c * laststride(pas)) + + ldt(slot, rowoff(slot, s, n) + c * laststride(slot)) + + ldt(rank, rowoff(rank, j, n) + c * laststride(rank)); + stt(bo, bb + c * bs, b); + } + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ lili_attn */ +/* qkv [M, 3 * n_head * head_dim] (q | k | v, heads contiguous within each), M = sequences * L with + * L = steps * k. Row i of a lattice sits at slot s_i = i / k. Per sequence and head: + * + * score(i, j) = q_i . k_j * scale + rel[h][s_i - s_j + steps] + (s_i == s_j ? same[h] : 0) + * out_i = softmax_j(score(i, .)) . v + * + * Every row sees every row of its lattice: the bias is a preference, not a mask. */ +int ref_lili_attn(const RadArgs* a, RadStream) { + if (!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); + + REF_PAR_FOR(M * nh * L * hd * 2) + for (int64_t u = 0; u < M * nh; ++u) { + const int64_t i = u / nh, h = u % nh; + const int64_t q0 = i / L * L, si = (i - q0) / k; + const int64_t qb = rowoff(qkv, i, 3 * n) + h * hd * qs; + std::vector sc((size_t)L); + float mx = -INFINITY; + for (int64_t j = 0; j < L; ++j) { + const int64_t kb = rowoff(qkv, q0 + j, 3 * n) + (n + h * hd) * qs; + float dot = 0.0f; + for (int64_t d = 0; d < hd; ++d) dot += ldt(qkv, qb + d * qs) * ldt(qkv, kb + d * qs); + const int64_t sj = j / k; + float b = ldt(rel, rowoff(rel, h, rw) + (si - sj + steps) * laststride(rel)); + if (si == sj) b += ldt(same, h); + sc[(size_t)j] = dot * scale + b; + mx = std::max(mx, sc[(size_t)j]); + } + float sum = 0.0f; + for (int64_t j = 0; j < L; ++j) { sc[(size_t)j] = std::exp(sc[(size_t)j] - mx); sum += sc[(size_t)j]; } + const int64_t ob = rowoff(o, 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[(size_t)j] * ldt(qkv, rowoff(qkv, q0 + j, 3 * n) + (2 * n + h * hd + d) * qs); + stt(o, ob + d * os, acc / sum); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ lili_factor */ +/* y[i] = [h_i | a_s | h_i * a_s] with s = i / L, the factor projection's input. */ +int ref_lili_factor(const RadArgs* a, RadStream) { + if (!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; + REF_PAR_FOR(M * n * 3) + 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 */ +/* edges [M * steps * k, 2n]: each candidate's outgoing | incoming vector, aout [M, n] the anchor's + * outgoing one, cand [M * steps, k] i32. Vectors are normalised as F.normalize (v / max(|v|, eps)). + * + * start[j] = scale * aout . in[0][j] + * pair[s][i][j] = scale * out[s][i] . in[s + 1][j] + * walk p_0 = argmax start, p_s = argmax pair[s - 1][p_{s-1}] (first index on ties) + * tokens[m][s] = cand[m * steps + s][p_s] + * + * `scores` [M, steps, k, k], when present, is vLLM's tensor: row 0 is start for every i. */ +int ref_lili_walk(const RadArgs* a, RadStream) { + if (!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; + + REF_PAR_FOR(M * steps * k * k * n) + for (int64_t m = 0; m < M; ++m) { + 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); + double ss = 0.0; + for (int64_t c = 0; c < n; ++c) { v[c] = ldt(t, b + c * laststride(t)); 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; + }; + std::vector va((size_t)n), vo((size_t)(steps * k * n)), vi((size_t)(steps * k * n)); + vec(ao, m, n, 0, va.data()); + for (int64_t r = 0; r < steps * k; ++r) { + vec(ed, m * steps * k + r, 2 * n, 0, &vo[(size_t)(r * n)]); + vec(ed, m * steps * k + r, 2 * n, n, &vi[(size_t)(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; + }; + std::vector sc((size_t)(steps * k * k)); + for (int64_t j = 0; j < k; ++j) { + const float v = dot(va.data(), &vi[(size_t)(j * n)]); + for (int64_t i = 0; i < k; ++i) sc[(size_t)(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[(size_t)((s * k + i) * k + j)] = + dot(&vo[(size_t)(((s - 1) * k + i) * n)], &vi[(size_t)((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[(size_t)((s * k + prev) * k + j)] > sc[(size_t)((s * k + prev) * k + best)]) best = j; + const int64_t id = ld_int(cd->dtype, cd->data, 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 < steps * k * k; ++e) stt(sco, m * steps * k * k + e, sc[(size_t)e]); + } + return RAD_OK; +} diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 0c98eac3..b63f168d 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -72,6 +72,10 @@ int ref_mtp_enter (const RadArgs*, RadStream); int ref_layernorm (const RadArgs*, RadStream); int ref_grid_embed (const RadArgs*, RadStream); int ref_grid_embed_aa (const RadArgs*, RadStream); +int ref_lili_cand (const RadArgs*, RadStream); +int ref_lili_attn (const RadArgs*, RadStream); +int ref_lili_factor (const RadArgs*, RadStream); +int ref_lili_walk (const RadArgs*, RadStream); int ref_add (const RadArgs*, RadStream); int ref_mul (const RadArgs*, RadStream); int ref_silu_mul (const RadArgs*, RadStream); @@ -157,6 +161,7 @@ int ref_logits_gemm (const RadArgs*, RadStream); int ref_attn_paged (const RadArgs*, RadStream); int ref_attn_paged_anchor_window(const RadArgs*, RadStream); int ref_attn_paged_tree (const RadArgs*, RadStream); +int ref_attn_paged_sink (const RadArgs*, RadStream); int ref_attn_dense (const RadArgs*, RadStream); int ref_attn_cross (const RadArgs*, RadStream); int ref_table_add (const RadArgs*, RadStream); @@ -356,6 +361,10 @@ REF_SHAPE_FN(ref_mtp_enter); REF_SHAPE_FN(ref_layernorm); REF_SHAPE_FN(ref_grid_embed); REF_SHAPE_FN(ref_grid_embed_aa); +REF_SHAPE_FN(ref_lili_cand); +REF_SHAPE_FN(ref_lili_attn); +REF_SHAPE_FN(ref_lili_factor); +REF_SHAPE_FN(ref_lili_walk); REF_SHAPE_FN(ref_add); REF_SHAPE_FN(ref_mul); REF_SHAPE_FN(ref_silu_mul); @@ -437,6 +446,7 @@ REF_SHAPE_FN(ref_logits_gemm); REF_SHAPE_FN(ref_attn_paged); REF_SHAPE_FN(ref_attn_paged_anchor_window); REF_SHAPE_FN(ref_attn_paged_tree); +REF_SHAPE_FN(ref_attn_paged_sink); REF_SHAPE_FN(ref_attn_dense); REF_SHAPE_FN(ref_attn_cross); REF_SHAPE_FN(ref_table_add); diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index 860a6c06..8436cdcf 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -162,6 +162,22 @@ static const RadOperandSpec oLayernorm[] = { OPD("x"), WGT("w"), WGT_O("b"), OUT /* A learned position table resampled to each row's grid and added in (a vision tower's). */ 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 (ref_lili.cpp). */ +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") }; @@ -399,6 +415,13 @@ 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 (gpt-oss, LiLiCorr's drafter). A name of its + * own, so no attn_paged kernel that does not know the operand can be chosen for it. */ +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") +}; /* Effective on kv_store, where `block_size` is RAD_REQUIRED: admits every value and refuses only a * query that omits it. On attn_paged the key is RAD_DERIVED and the constraint is skipped * (core/plugin/select.cpp). See the file header for the spec §7.2 consequence. */ @@ -803,7 +826,7 @@ static const RadOperandSpec oArgmax[] = { OPD("logits"), OPD("params"), OUT(" * sample_topk. */ 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") }; @@ -1178,6 +1201,26 @@ static const RadOpSchema kSchemas[] = { "antialias=True) resamples it to the row's grid -- SigLIP2's position embedding: per axis a " "triangle filter on half-pixel centres, widened by the scale when shrinking, its in-table taps " "normalised. Separable, f32, rounded once before the add; coordinates clamp into their grid." }, +{ "lili_cand", ARR(pLiliCand), ARR(oLiliCand), + "LiLiCorr's candidates. `stats` [M, world * (2 + 2k)] f32 is each rank's sample_logprobs row, " + "row-interleaved; the ranks merge to the log-normaliser and the k largest pairs by value, ties to " + "the lower id. cand [M, k] i32 = those ids. For candidate j, lp_j = logit_j - lse: feat row m*k+j " + "= silu(up_w . layernorm([lp_j, exp lp_j, lp_j - lp_0, j/(k-1), j == 0]; ln_w, ln_b, eps) + " + "up_b); base row m*k+j = pas[m] + slot[m % steps] + rank[j]. f32, rounded once to the outputs." }, +{ "lili_attn", ARR(pLiliAttn), ARR(oLiliAttn), + "Attention over each sequence's lattice of L = steps * k rows (row i at slot i / k): qkv [M, 3 * " + "n_head * head_dim] as q | k | v; score(i, j) = q_i . k_j * scale + rel[h][s_i - s_j + steps] + " + "(s_i == s_j ? same[h] : 0), softmax over the lattice's rows, out [M, n_head * head_dim]. No " + "mask." }, +{ "lili_factor", ARR(pLiliFactor), ARR(oLiliFactor), + "y [M, 3n] = [h_i | a_s | h_i * a_s] with s = i / L: each lattice row beside its sequence's anchor " + "and their product, the factor projection's input." }, +{ "lili_walk", ARR(pLiliWalk), ARR(oLiliWalk), + "LiLiCorr's walk. edges [M * steps * k, 2n] each candidate's outgoing | incoming vector, aout " + "[M, n] the anchor's; each normalised as v / max(|v|, eps). start[j] = scale * aout . in[0][j], " + "pair[s][i][j] = scale * out[s][i] . in[s+1][j]; greedy p_0 = argmax start, p_s = argmax " + "pair[s-1][p_{s-1}], first index on ties; tokens [M, steps] i32 = cand[m * steps + s][p_s]. " + "`scores` [M, steps, k, k], when passed: row 0 start for every i, row s pair[s - 1]." }, { "add", ARR(pAdd), ARR(oBinary), "y = a + b. An operand carrying exactly n elements against a taller output broadcasts along " "rows; nothing else broadcasts. With `div`, y = rd(rd(a + b) / div), rd y's dtype: the last " @@ -1489,6 +1532,10 @@ static const RadOpSchema kSchemas[] = { "causal row, else the row's parent's index within its sequence's rows (-1 for the block's " "first row). Inside the block such a row sees itself and its ancestors only, and 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 in the scaled-score domain: it " + "joins the softmax's maximum and denominator, contributes no value, and so only shrinks the " + "keys' weights (out = sum_j p_j v_j with p_j = exp(s_j) / (sum_k exp(s_k) + exp(sink)))." }, { "attn_dense", ARR(pAttnDense), ARR(oAttnDense), "Dense varlen attention over cu_seqlens segments (rows cu/cu_div). Nothing paged. `window` is " "attn_paged's rule over a segment's positions: causal, i - j < window; non-causal, |i - j| < " @@ -2290,6 +2337,14 @@ SIMPLE("ref_grid_embed", "grid_embed", "elem", SIMPLE("ref_grid_embed_aa", "grid_embed_aa", "elem", "antialiased half-pixel bilinear resample of a position grid, added in", DT_FLOAT, ref_grid_embed_aa), +SIMPLE("ref_lili_cand", "lili_cand", "draft", "LiLiCorr candidates and their features", + DT_FLOAT, ref_lili_cand), +SIMPLE("ref_lili_attn", "lili_attn", "draft", "LiLiCorr lattice attention with slot biases", + DT_FLOAT, ref_lili_attn), +SIMPLE("ref_lili_factor", "lili_factor", "draft", "LiLiCorr factor input [h | a | h * a]", + DT_FLOAT, ref_lili_factor), +SIMPLE("ref_lili_walk", "lili_walk", "draft", "LiLiCorr edge scores and greedy walk", DT_FLOAT, + ref_lili_walk), SIMPLE("ref_add", "add", "elem", "elementwise sum", DT_FLOAT, ref_add), SIMPLE("ref_mul", "mul", "elem", "elementwise product", DT_FLOAT, ref_mul), SIMPLE("ref_mla_attn", "mla_attn", "attn", "absorbed latent MQA attention", DT_FLOAT, @@ -2476,6 +2531,11 @@ ROW("ref_attn_paged_tree", "attn_paged_tree", "attn", "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])), nullptr, nullptr, ref_attn_paged_tree, nullptr), +ROW("ref_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])), + nullptr, nullptr, ref_attn_paged_sink, nullptr), SIMPLE("ref_attn_dense", "attn_dense", "attn", "dense varlen attention over cu_seqlens", DT_FLOAT, ref_attn_dense), SIMPLE("ref_attn_cross", "attn_cross", "attn", diff --git a/libref/ref_sample.cpp b/libref/ref_sample.cpp index 697e4573..8d0c43ba 100644 --- a/libref/ref_sample.cpp +++ b/libref/ref_sample.cpp @@ -674,9 +674,9 @@ int ref_sample_argmax(const RadArgs* a, RadStream) { * floats (exact below 2^24). Read before any sampling stage, as OpenAI's and llama-server's * logprobs report. Rows without the flag are not written. Under a split vocabulary ids are global * (+ `vocab_off`) and the host merges ranks; an unfilled slot is id -1, logit -infinity. The sum is - * in double. */ + * in double. Without `params` every row is written (a drafter's candidate logprobs). */ int ref_sample_logprobs(const RadArgs* a, RadStream) { - if (!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); @@ -686,11 +686,11 @@ int ref_sample_logprobs(const RadArgs* a, RadStream) { const int64_t w = 2 + 2 * k; if (M <= 0 || numel(st) < M * w) return RAD_E_SHAPE; Rows R; - RAD_REF_TRY(param_rows(pr, M, &R)); + if (pr->data) RAD_REF_TRY(param_rows(pr, M, &R)); REF_PAR_FOR(M * n_vocab * (k + 2)) 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; const int64_t lb = rowoff(lg, m, n_vocab), ls = laststride(lg); const int64_t sb = rowoff(st, m, w), ss = laststride(st); float mx = -INFINITY; diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index e7260f89..ea5a76a6 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -488,6 +488,50 @@ int ref_grid_embed_aa_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* return o.finish("grid_embed_aa", operand, out); } +/* LiLiCorr's ops. lili_cand declines: its stats rows (sample_logprobs' sorted pairs and positive + * sums) are no draw; avx_check_hand.cpp builds them. The others draw freely. */ +int ref_lili_cand_shape(const RadParam*, int, int, RadOpdDesc*) { return RAD_E_UNSUPPORTED; } + +int ref_lili_attn_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), S = gi(p, n_p, "steps", 0), k = gi(p, n_p, "k", 0); + const int64_t nh = gi(p, n_p, "n_head", 0), hd = gi(p, n_p, "head_dim", 0); + if (M <= 0 || S <= 0 || k <= 0 || nh <= 0 || hd <= 0) return RAD_E_UNSUPPORTED; + const int64_t rows = (M + S * k - 1) / (S * k) * (S * k); /* whole lattices */ + Opd o; + o.t(D, { rows, 3 * nh * hd }); /* qkv */ + o.t((uint32_t)RAD_F32, { nh, 2 * S + 1 }); /* rel */ + o.t((uint32_t)RAD_F32, { nh }); /* same */ + o.t(D, { rows, nh * hd }); /* out */ + return o.finish("lili_attn", operand, out); +} + +int ref_lili_factor_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), L = gi(p, n_p, "L", 0), n = gi(p, n_p, "n", 0); + if (M <= 0 || L <= 0 || n <= 0) return RAD_E_UNSUPPORTED; + const int64_t rows = (M + L - 1) / L * L; + Opd o; + o.t(D, { rows, n }); /* h */ + o.t(D, { rows / L, n }); /* a */ + o.t(D, { rows, 3 * n }); /* y */ + return o.finish("lili_factor", operand, out); +} + +int ref_lili_walk_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), S = gi(p, n_p, "steps", 0), k = gi(p, n_p, "k", 0); + const int64_t n = gi(p, n_p, "n", 0); + if (M <= 0 || S <= 0 || k <= 0 || n <= 0) return RAD_E_UNSUPPORTED; + Opd o; + o.t(D, { M * S * k, 2 * n }); /* edges */ + o.t(D, { M, n }); /* aout */ + o.t_idx({ M * S, k }, 1000, -1, 0); /* cand: ids, copied */ + o.t((uint32_t)RAD_I32, { M, S }); /* tokens */ + o.t((uint32_t)RAD_F32, { M, S, k, k }); /* scores */ + return o.finish("lili_walk", operand, out); +} + int ref_layernorm_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); @@ -1467,6 +1511,24 @@ int ref_attn_paged_tree_shape(const RadParam* p, int n_p, int operand, RadOpdDes return o.finish("attn_paged_tree", operand, out); } +/* attn_paged's operands with the sinks before `out`: a learned logit a query head. */ +int ref_attn_paged_sink_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int nbase = 8; + if (operand < 7) return ref_attn_paged_shape(p, n_p, operand, out); + if (operand == 8) return ref_attn_paged_shape(p, n_p, nbase - 1, out); + if (operand != 7 || !out) return RAD_E_SHAPE; + const int64_t gqa = gi(p, n_p, "gqa", 1); + const int64_t nh = gi(p, n_p, "n_head", gqa); + if (nh <= 0) return RAD_E_UNSUPPORTED; + std::memset(out, 0, sizeof *out); + out->fill = (uint32_t)RAD_FILL_NORMAL; + out->idx_const = -1; + out->dtype = (uint32_t)RAD_F32; + out->rank = 1; + out->shape[0] = nh; + return RAD_OK; +} + int ref_attn_dense_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0); const int64_t hd = gi(p, n_p, "head_dim", 0); diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index f2d4bec2..e167c1b7 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -539,11 +539,12 @@ set(R4D_EMU_HIP ${R4D_DIR}/r4d_attn_paged_window.hip ${R4D_DIR}/r4d_pair_argmax_ ${R4D_DIR}/r4d_mhc.hip ${R4D_DIR}/r4d_fp8_f32scale.hip ${R4D_DIR}/r4d_kda.hip ${R4D_DIR}/r4d_moe_mxfp4.hip ${R4D_DIR}/r4d_mla.hip ${R4D_DIR}/r4d_quant_act_fp8.hip ${R4D_DIR}/r4d_kv_resolve.hip ${R4D_DIR}/r4d_dsa.hip - ${R4D_DIR}/r4d_gemm_m2xfp4a8_decode.hip ${R4D_DIR}/r4d_gemm_m2xfp4a8_tiled.hip) + ${R4D_DIR}/r4d_gemm_m2xfp4a8_decode.hip ${R4D_DIR}/r4d_gemm_m2xfp4a8_tiled.hip + ${R4D_DIR}/r4d_lili.hip) # The M2XFP4 units' plugin entries call two cfg readers that r4d_rows.cpp defines, which is not in # this build: cfg_stub.cpp defines them at their axis defaults, in both arms below. set(R4D_EMU_TESTS attn pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse kvres - dsa m2xfp4) + dsa m2xfp4 lili) set(R4D_EMU_BUILT OFF) if(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64)$") # No fiber switch for this ISA. @@ -584,7 +585,8 @@ else() ${R4D_EMU}/test_f32.cpp ${R4D_EMU}/test_mhc.cpp ${R4D_EMU}/test_fp8f32.cpp ${R4D_EMU}/test_kda.cpp ${R4D_EMU}/test_moemx.cpp ${R4D_EMU}/test_mla.cpp ${R4D_EMU}/test_moefuse.cpp ${R4D_EMU}/test_kvres.cpp - ${R4D_EMU}/test_dsa.cpp ${R4D_EMU}/test_m2xfp4.cpp ${R4D_EMU}/cfg_stub.cpp) + ${R4D_EMU}/test_dsa.cpp ${R4D_EMU}/test_m2xfp4.cpp ${R4D_EMU}/test_lili.cpp + ${R4D_EMU}/cfg_stub.cpp) get_filename_component(stem ${src} NAME_WE) set(lang "") if(src MATCHES "\\.hip$") @@ -621,7 +623,7 @@ else() endif() endif() if(R4D_EMU_BUILT) - foreach(t pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse kvres dsa m2xfp4) + foreach(t pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse kvres dsa m2xfp4 lili) add_test(NAME r4d_emu_${t} COMMAND ${CMAKE_BINARY_DIR}/tests/r4d_emu_${t}) endforeach() # The attention cases take about 11 s, 7 of them in the two long prefills on the WMMA kernel, @@ -632,7 +634,7 @@ if(R4D_EMU_BUILT) endforeach() set_tests_properties(r4d_emu_attn_shard0 r4d_emu_attn_shard1 r4d_emu_attn_shard2 r4d_emu_pick r4d_emu_norm r4d_emu_escale r4d_emu_qsa r4d_emu_lora r4d_emu_mla r4d_emu_moefuse - r4d_emu_dsa r4d_emu_m2xfp4 + r4d_emu_dsa r4d_emu_m2xfp4 r4d_emu_lili PROPERTIES LABELS "r4d_emu" TIMEOUT ${RAD_TEST_TIMEOUT}) # The LoRA pair has a libref oracle, and the test holds the emulated kernels to it when it can # load one -- expand bit for bit, shrink to its bound. kda_update is held to libref's within diff --git a/tests/r4d_emu/test_attn.cpp b/tests/r4d_emu/test_attn.cpp index 756b5a6f..e480898e 100644 --- a/tests/r4d_emu/test_attn.cpp +++ b/tests/r4d_emu/test_attn.cpp @@ -1,6 +1,7 @@ /* Drives libr4d's windowed attn_paged entry points (r4d_attn_paged_window.hip) through the SIMT * emulator and checks every output element against a port of libref's ref_attn_paged (same mask - * predicates, f64 accumulation). */ + * predicates, f64 accumulation). The attn_paged_sink entries too: a sink logit a query head joins + * the reference's maximum and sum. */ #include "rad_abi.h" #include "rad_plugin.h" #include "r4d_plugin.h" @@ -38,6 +39,7 @@ struct Case { int qpitch_extra = 0; /* q as a column slice of a wider buffer */ int expect_wmma = -1; /* 1: must take the WMMA kernel, 0: must not, -1: either */ bool ahead = false; /* non-causal, the window bounds the keys behind only */ + bool sink = false; /* attn_paged_sink: a sink logit a query head */ }; using Fn = int (*)(const RadArgs*, RadStream); @@ -54,6 +56,13 @@ static Fn pick(int hd, int gqa, bool fp8, bool ahead) { #undef P return nullptr; } +static Fn pick_sink(int hd, int gqa, bool fp8) { + if (hd == 128 && gqa == 8) + return fp8 ? r4d_rad_attn_window_sink_h128_gqa8_fp8 : r4d_rad_attn_window_sink_h128_gqa8_bf16; + if (hd == 128 && gqa == 16) + return fp8 ? r4d_rad_attn_window_sink_h128_gqa16_fp8 : r4d_rad_attn_window_sink_h128_gqa16_bf16; + return nullptr; +} static int run(const Case& c) { const int n_seq = (int)c.qlen.size(), HD = c.hd, kvh = c.kvh, qh = kvh * c.gqa; @@ -101,7 +110,11 @@ static int run(const Case& c) { std::vector scratch(c.scratch + 64); char* sp = scratch.data() + ((16 - ((uintptr_t)scratch.data() & 15)) & 15); - RadTensor t[8]; + /* Sinks spread around the scores' scale, a few far above them (the sink takes the maximum) and + * one far below (it vanishes). */ + std::vector sinks(qh); + for (int h = 0; h < qh; ++h) sinks[h] = h % 5 == 3 ? 6.f + nrm() : h % 7 == 6 ? -40.f : 1.5f * nrm(); + RadTensor t[9]; t[0] = tens(qb.data(), RAD_BF16, {rows, qh * HD}); t[0].stride[0] = qcols; t[1] = tens(c.fp8 ? (void*)kv8.data() : (void*)kvb.data(), c.fp8 ? RAD_F8E4M3 : RAD_BF16, {nblocks, kvh, 16, slot}); t[2] = tens(bt.data(), RAD_I32, {n_seq, maxb}); @@ -110,6 +123,7 @@ static int run(const Case& c) { t[5] = c.descale ? tens(vd.data(), RAD_F32, {n_seq, kvh}) : RadTensor{}; t[6] = c.ragged ? tens(cu.data(), RAD_I32, {n_seq + 1}) : RadTensor{}; t[7] = tens(out.data(), RAD_BF16, {rows, qh, HD}); + if (c.sink) { t[8] = t[7]; t[7] = tens(sinks.data(), RAD_F32, {qh}); } int qmax = 0; for (int q : c.qlen) qmax = std::max(qmax, q); std::vector p; auto pi = [&](const char* k, long long v) { RadParam x{}; x.key = k; x.kind = RAD_P_INT; x.ival = v; p.push_back(x); }; @@ -121,9 +135,10 @@ static int run(const Case& c) { const double scale = 1.0 / std::sqrt((double)HD) * 1.3; /* not the default: the param must be read */ pf("scale", scale); pi("n_head", qh); pi("max_seqs", n_seq); if (c.max_ctx) pi("max_ctx", c.max_ctx); - RadArgs a{}; a.t = t; a.n_t = 8; a.p = p.data(); a.n_p = (int)p.size(); + RadArgs a{}; a.t = t; a.n_t = c.sink ? 9 : 8; a.p = p.data(); a.n_p = (int)p.size(); a.scratch = c.scratch ? sp : nullptr; a.scratch_bytes = c.scratch; - Fn fn = pick(HD, c.gqa, c.fp8, c.ahead); + Fn fn = c.sink ? pick_sink(HD, c.gqa, c.fp8) : pick(HD, c.gqa, c.fp8, c.ahead); + if (!fn) { std::printf("%-44s no entry point for this geometry\n", c.name.c_str()); return 1; } const int g0 = emu_grids; const int rc = fn(&a, nullptr); const int launches = emu_grids - g0; @@ -146,13 +161,16 @@ static int run(const Case& c) { sc[j] = dot * scale; mx = std::max(mx, sc[j]); } std::vector acc(HD, 0.0); double sum = 0; - if (mx > -INFINITY) + const bool any = mx > -INFINITY; + if (c.sink && any) mx = std::max(mx, (double)sinks[h]); + if (any) for (int j = 0; j < c.ctx[s]; ++j) { if (sc[j] == -INFINITY) continue; const double w = std::exp(sc[j] - mx); sum += w; const int64_t kb = (((int64_t)bt[s * maxb + j / 16] * kvh + kh) * 16 + j % 16) * slot; for (int d = 0; d < HD; ++d) acc[d] += w * kvf[kb + HD + d] * vd[s * kvh + kh]; } + if (c.sink && any) sum += std::exp((double)sinks[h] - mx); for (int d = 0; d < HD; ++d) { const double ref = sum > 0 ? acc[d] / sum : 0.0; const float got = rad_bf16_to_f32(out[((size_t)tok * qh + h) * HD + d]); @@ -244,6 +262,28 @@ int main(int argc, char** argv) { {"h256 gqa4 ahead w20 split", 256, 4, 1, false, false, false, false, 20, {5}, {300}, -1, 4096, s256, 0, 0, true}, {"wmma h256 gqa2 ahead w20 picture 100 of 100", 256, 2, 2, false, false, false, false, 20, {100}, {100}, -1, 0, 0, 0, 1, true}, {"wmma h256 gqa2 ahead w20 picture 90 of 300 fp8", 256, 2, 2, true, false, false, true, 20, {90}, {300}, -1, 0, 0, 0, 1, true}, + /* LiLiCorr's drafter (attn_paged_sink): 32 query heads over 2 KV heads at h128 (16 over 1 at + * TP 2), a block of 8 non-causal rows past the context, a 1024-token window; one sequence + * and a batch, unsplit and split, a bf16 and an fp8 cache */ + {"sink h128 gqa16 kvh2 block8 w1024", 128, 16, 2, false, false, false, false, 1024, {8}, {1500}, + -1, 0, 0, 0, -1, false, true}, + {"sink h128 gqa16 kvh1 block8 x3 split", 128, 16, 1, false, false, true, false, 1024, {8, 8, 8}, + {900, 40, 2100}, -1, 262144, s128, 0, -1, false, true}, + {"sink h128 gqa16 kvh2 fp8+descale split", 128, 16, 2, true, false, false, true, 1024, {8}, {1300}, + -1, 262144, s128, 0, -1, false, true}, + {"sink h128 gqa16 prefill-shaped stays scalar", 128, 16, 1, false, false, false, false, 1024, {96}, + {400}, -1, 0, 0, 0, 0, false, true}, + {"sink h128 gqa16 missing-block", 128, 16, 1, false, false, false, false, 1024, {8}, {70}, 1, + 0, 0, 0, -1, false, true}, + /* and at TP 4, 8 query heads over the rank's replicated KV head */ + {"sink h128 gqa8 kvh1 block8 w1024", 128, 8, 1, false, false, false, false, 1024, {8}, {1500}, + -1, 0, 0, 0, -1, false, true}, + {"sink h128 gqa8 kvh1 block8 x3 split", 128, 8, 1, false, false, true, false, 1024, {8, 8, 8}, + {900, 40, 2100}, -1, 262144, s128, 0, -1, false, true}, + {"sink h128 gqa8 kvh1 fp8+descale split", 128, 8, 1, true, false, false, true, 1024, {8}, {1300}, + -1, 262144, s128, 0, -1, false, true}, + {"sink h128 gqa8 prefill-shaped stays scalar", 128, 8, 1, false, false, false, false, 1024, {96}, + {400}, -1, 0, 0, 0, 0, false, true}, /* and what must stay scalar: a verify batch, many sequences, a few rows each */ {"scalar: 8 x verify16, ragged", 512, 4, 1, false, true, true, false, 0, {16, 16, 16, 16, 16, 16, 16, 16}, {40, 50, 60, 70, 80, 90, 100, 110}, -1, 262144, s512, 0, 0}, diff --git a/tests/r4d_emu/test_lili.cpp b/tests/r4d_emu/test_lili.cpp new file mode 100644 index 00000000..7ab970d7 --- /dev/null +++ b/tests/r4d_emu/test_lili.cpp @@ -0,0 +1,267 @@ +/* LiLiCorr's correlator (r4d_lili.hip) through the SIMT emulator, at the drafter's geometry: seven + * positions of eight candidates, eight heads of 128, a 1024-wide lattice. Each kernel against a host + * port of libref's ref_lili.cpp in double: lili_cand over two ranks' disjoint vocabulary halves (ids + * exact, features and the additive part to bf16), lili_attn and lili_factor to bf16, lili_walk's + * scores to f32 rounding and its tokens exactly wherever the winning margin is not a near-tie. */ +#include "rad_abi.h" +#include "rad_plugin.h" +#include "r4d_plugin.h" + +#include +#include +#include +#include +#include +#include +#include + +static std::mt19937 rng(77); +static float nrm() { static std::normal_distribution d(0.f, 1.f); return d(rng); } + +static RadTensor tens(void* p, uint32_t dt, std::vector shape) { + RadTensor t{}; t.data = p; t.dtype = dt; t.rank = (uint32_t)shape.size(); + int64_t st = 1; + for (int i = (int)shape.size() - 1; i >= 0; --i) { t.shape[i] = shape[i]; t.stride[i] = st; st *= shape[i]; } + return t; +} +static std::vector bfv(size_t n, float sc, std::vector* f) { + std::vector b(n); + f->resize(n); + for (size_t i = 0; i < n; ++i) { b[i] = rad_f32_to_bf16(nrm() * sc); (*f)[i] = rad_bf16_to_f32(b[i]); } + return b; +} +struct Params { + std::vector p; + std::vector s; + void i(const char* k, long long v) { RadParam x{}; x.key = k; x.kind = RAD_P_INT; x.ival = v; p.push_back(x); } + void f(const char* k, double v) { RadParam x{}; x.key = k; x.kind = RAD_P_F64; x.dval = v; p.push_back(x); } + void str(const char* k, const char* v) { RadParam x{}; x.key = k; x.kind = RAD_P_STR; x.sval = v; p.push_back(x); } +}; +/* rel_l2 and the worst element relative to the reference's scale */ +static bool close(const char* what, const std::vector& ref, const std::vector& got, double tol) { + double se = 0, sr = 0, worst = 0, scale = 1e-30; + long nan = 0; + for (double r : ref) scale = std::max(scale, std::fabs(r)); + for (size_t i = 0; i < ref.size(); ++i) { + if (std::isnan(got[i])) { ++nan; continue; } + const double e = std::fabs(got[i] - ref[i]); + se += e * e; sr += ref[i] * ref[i]; + worst = std::max(worst, e / scale); + } + const double rel = std::sqrt(se / std::max(sr, 1e-30)); + const bool ok = nan == 0 && rel < tol && worst < 8 * tol; + std::printf(" %-34s rel_l2 %.2e worst %.2e nan %ld %s\n", what, rel, worst, nan, ok ? "PASS" : "FAIL"); + return ok; +} + +static int test_cand() { + const int K = 8, RK = 9, W = 2, S = 7, N = 1024, M = 2 * S, V = 131072, w = 2 + 2 * RK; + /* stats: each rank's row of its own vocabulary half, sorted, a tie across the ranks on row 3 */ + std::vector st((size_t)M * W * w); + std::vector lse(M); + std::vector>> all(M); + for (int m = 0; m < M; ++m) { + double tot = 0, gmx = -INFINITY; + std::vector mxr(W), sumr(W); + for (int r = 0; r < W; ++r) { + std::vector> v; + for (int j = 0; j < K; ++j) v.push_back({ 2.f * nrm() + 3.f, r * (V / W) + (int)(rng() % (V / W)) }); + if (m == 3 && r == 1) v[0] = { all[m][0].first, all[m][0].second + V / W }; /* a tie */ + std::sort(v.begin(), v.end(), [](auto& a, auto& b) { return a.first > b.first || (a.first == b.first && a.second < b.second); }); + const float mx = v[0].first, sum = 1.0f + 300.f * (float)(rng() % 100) / 100.f; + float* row = &st[((size_t)m * W + r) * w]; + row[0] = mx; row[1] = sum; + for (int j = 0; j < K; ++j) { row[2 + 2 * j] = (float)v[j].second; row[3 + 2 * j] = v[j].first; all[m].push_back(v[j]); } + /* the ninth pair, below the eighth: carried for the all-gather's 16-byte rows, never kept */ + row[2 + 2 * K] = (float)(r * (V / W)); row[3 + 2 * K] = v[K - 1].first - 1.0f; + mxr[r] = mx; sumr[r] = sum; gmx = std::max(gmx, (double)mx); + } + for (int r = 0; r < W; ++r) tot += sumr[r] * std::exp(mxr[r] - gmx); + lse[m] = gmx + std::log(tot); + std::sort(all[m].begin(), all[m].end(), [](auto& a, auto& b) { return a.first > b.first || (a.first == b.first && a.second < b.second); }); + } + std::vector pasf, slotf, rankf; + auto pas = bfv((size_t)M * N, 1.f, &pasf), slot = bfv((size_t)S * N, 0.5f, &slotf), rank = bfv((size_t)K * N, 0.5f, &rankf); + std::vector lnw(5), lnb(5), upw((size_t)N * 5), upb(N); + for (auto* v : { &lnw, &lnb, &upw, &upb }) for (auto& x : *v) x = nrm() * 0.7f; + std::vector cand((size_t)M * K, -7); + std::vector feat((size_t)M * K * N), base((size_t)M * K * N); + RadTensor t[11] = { + tens(st.data(), RAD_F32, { M, W * w }), tens(pas.data(), RAD_BF16, { M, N }), + tens(lnw.data(), RAD_F32, { 5 }), tens(lnb.data(), RAD_F32, { 5 }), + tens(upw.data(), RAD_F32, { N, 5 }), tens(upb.data(), RAD_F32, { N }), + tens(slot.data(), RAD_BF16, { S, N }), tens(rank.data(), RAD_BF16, { K, N }), + tens(cand.data(), RAD_I32, { M, K }), tens(feat.data(), RAD_BF16, { M * K, N }), + tens(base.data(), RAD_BF16, { M * K, N }), + }; + Params P; + P.i("M", M); P.i("k", K); P.i("world", W); P.i("steps", S); P.i("n", N); P.str("dtype", "bf16"); P.f("eps", 1e-5); + P.i("row_k", RK); + RadArgs a{}; a.t = t; a.n_t = 11; a.p = P.p.data(); a.n_p = (int)P.p.size(); + const int rc = r4d_rad_lili_cand(&a, nullptr); + if (rc != RAD_OK) { std::printf(" lili_cand launch %d\n", rc); return 1; } + bool ok = true; + std::vector rf, rb; + std::vector gf, gb; + for (int m = 0; m < M; ++m) { + double lp[8]; + for (int j = 0; j < K; ++j) { + ok = ok && cand[(size_t)m * K + j] == all[m][j].second; + lp[j] = all[m][j].first - lse[m]; + } + for (int j = 0; j < K; ++j) { + const double f[5] = { lp[j], std::exp(lp[j]), lp[j] - lp[0], (double)j / (K - 1), j == 0 ? 1.0 : 0.0 }; + double mean = 0, var = 0; + for (double x : f) mean += x; + mean /= 5; + for (double x : f) var += (x - mean) * (x - mean); + var /= 5; + double y[5]; + for (int i = 0; i < 5; ++i) y[i] = (f[i] - mean) / std::sqrt(var + 1e-5) * lnw[i] + lnb[i]; + for (int c = 0; c < N; ++c) { + double u = upb[c]; + for (int i = 0; i < 5; ++i) u += upw[(size_t)c * 5 + i] * y[i]; + rf.push_back(u / (1 + std::exp(-u))); + rb.push_back((double)pasf[(size_t)m * N + c] + slotf[(size_t)(m % S) * N + c] + rankf[(size_t)j * N + c]); + gf.push_back(rad_bf16_to_f32(feat[((size_t)m * K + j) * N + c])); + gb.push_back(rad_bf16_to_f32(base[((size_t)m * K + j) * N + c])); + } + } + } + std::printf(" lili_cand ids (two ranks, a tie) %s\n", ok ? "PASS" : "FAIL"); + ok = close("lili_cand features", rf, gf, 5e-3) && ok; + ok = close("lili_cand additive part", rb, gb, 5e-3) && ok; + return ok ? 0 : 1; +} + +static int test_attn() { + const int S = 7, K = 8, L = S * K, NH = 8, HD = 128, N = NH * HD, NS = 2, M = NS * L; + std::vector qf; + auto qkv = bfv((size_t)M * 3 * N, 0.25f, &qf); + std::vector rel((size_t)NH * (2 * S + 1)), same(NH); + for (auto& x : rel) x = nrm(); + for (auto& x : same) x = nrm(); + std::vector out((size_t)M * N, 0xffff); + RadTensor t[4] = { tens(qkv.data(), RAD_BF16, { M, 3 * N }), tens(rel.data(), RAD_F32, { NH, 2 * S + 1 }), + tens(same.data(), RAD_F32, { NH }), tens(out.data(), RAD_BF16, { M, N }) }; + Params P; + P.i("M", M); P.i("steps", S); P.i("k", K); P.i("n_head", NH); P.i("head_dim", HD); P.str("dtype", "bf16"); + RadArgs a{}; a.t = t; a.n_t = 4; a.p = P.p.data(); a.n_p = (int)P.p.size(); + const int rc = r4d_rad_lili_attn(&a, nullptr); + if (rc != RAD_OK) { std::printf(" lili_attn launch %d\n", rc); return 1; } + std::vector ref((size_t)M * N); + const double scale = 1.0 / std::sqrt((double)HD); + for (int i = 0; i < M; ++i) for (int h = 0; h < NH; ++h) { + const int q0 = i / L * L, si = (i - q0) / K; + std::vector sc(L); + double mx = -INFINITY; + for (int j = 0; j < L; ++j) { + double d = 0; + for (int e = 0; e < HD; ++e) d += (double)qf[(size_t)i * 3 * N + h * HD + e] * qf[(size_t)(q0 + j) * 3 * N + N + h * HD + e]; + const int sj = j / K; + sc[j] = d * scale + rel[(size_t)h * (2 * S + 1) + si - sj + S] + (si == sj ? same[h] : 0.f); + mx = std::max(mx, sc[j]); + } + double sum = 0; + for (auto& x : sc) { x = std::exp(x - mx); sum += x; } + for (int e = 0; e < HD; ++e) { + double acc = 0; + for (int j = 0; j < L; ++j) acc += sc[j] * qf[(size_t)(q0 + j) * 3 * N + 2 * N + h * HD + e]; + ref[(size_t)i * N + h * HD + e] = acc / sum; + } + } + std::vector got(out.size()); + for (size_t i = 0; i < out.size(); ++i) got[i] = rad_bf16_to_f32(out[i]); + return close("lili_attn two lattices", ref, got, 5e-3) ? 0 : 1; +} + +static int test_factor() { + const int L = 56, N = 1024, NS = 3, M = NS * L; + std::vector hf, af; + auto h = bfv((size_t)M * N, 1.f, &hf), an = bfv((size_t)NS * N, 1.f, &af); + std::vector y((size_t)M * 3 * N); + RadTensor t[3] = { tens(h.data(), RAD_BF16, { M, N }), tens(an.data(), RAD_BF16, { NS, N }), + tens(y.data(), RAD_BF16, { M, 3 * N }) }; + Params P; + P.i("M", M); P.i("L", L); P.i("n", N); P.str("dtype", "bf16"); + RadArgs a{}; a.t = t; a.n_t = 3; a.p = P.p.data(); a.n_p = (int)P.p.size(); + if (r4d_rad_lili_factor(&a, nullptr) != RAD_OK) { std::printf(" lili_factor launch failed\n"); return 1; } + long bad = 0; + for (int i = 0; i < M; ++i) for (int c = 0; c < N; ++c) { + const uint16_t* r = &y[(size_t)i * 3 * N]; + bad += r[c] != h[(size_t)i * N + c]; + bad += r[N + c] != an[(size_t)(i / L) * N + c]; + bad += r[2 * N + c] != rad_f32_to_bf16(hf[(size_t)i * N + c] * af[(size_t)(i / L) * N + c]); + } + std::printf(" %-34s bad %ld %s\n", "lili_factor (bit for bit)", bad, bad ? "FAIL" : "PASS"); + return bad ? 1 : 0; +} + +static int test_walk() { + const int S = 7, K = 8, N = 1024, M = 5, R = S * K; + std::vector ef, af; + auto ed = bfv((size_t)M * R * 2 * N, 1.f, &ef), ao = bfv((size_t)M * N, 1.f, &af); + std::vector cand((size_t)M * S * K), tok((size_t)M * S, -9); + for (auto& c : cand) c = (int32_t)(rng() % 131072); + std::vector scores((size_t)M * S * K * K); + RadTensor t[5] = { tens(ed.data(), RAD_BF16, { M * R, 2 * N }), tens(ao.data(), RAD_BF16, { M, N }), + tens(cand.data(), RAD_I32, { M * S, K }), tens(tok.data(), RAD_I32, { M, S }), + tens(scores.data(), RAD_F32, { M, S, K, K }) }; + Params P; + P.i("M", M); P.i("steps", S); P.i("k", K); P.i("n", N); P.str("dtype", "bf16"); P.f("eps", 1e-4); P.f("scale", 8.0); + RadArgs a{}; a.t = t; a.n_t = 5; a.p = P.p.data(); a.n_p = (int)P.p.size(); + if (r4d_rad_lili_walk(&a, nullptr) != RAD_OK) { std::printf(" lili_walk launch failed\n"); return 1; } + std::vector ref((size_t)M * S * K * K); + long tbad = 0, near = 0; + for (int m = 0; m < M; ++m) { + auto vec = [&](const float* p, std::vector& v) { + double ss = 0; + v.assign(p, p + N); + for (double x : v) ss += x * x; + const double inv = 1.0 / std::max(std::sqrt(ss), 1e-4); + for (double& x : v) x *= inv; + }; + std::vector> vo(R), vi(R); + std::vector va; + vec(&af[(size_t)m * N], va); + for (int r = 0; r < R; ++r) { + vec(&ef[((size_t)m * R + r) * 2 * N], vo[r]); + vec(&ef[((size_t)m * R + r) * 2 * N + N], vi[r]); + } + auto dot = [&](const std::vector& x, const std::vector& y) { + double s = 0; + for (int c = 0; c < N; ++c) s += x[c] * y[c]; + return 8.0 * s; + }; + double* sc = &ref[(size_t)m * S * K * K]; + for (int j = 0; j < K; ++j) { const double v = dot(va, vi[j]); for (int i = 0; i < K; ++i) sc[i * K + j] = v; } + for (int s = 1; s < S; ++s) for (int i = 0; i < K; ++i) for (int j = 0; j < K; ++j) + sc[(s * K + i) * K + j] = dot(vo[(s - 1) * K + i], vi[s * K + j]); + /* The walk on the reference scores; a step whose two best differ by less than f32 noise + * may legitimately go the other way, and then the rest of the path is not compared. */ + int prev = 0; + for (int s = 0; s < S; ++s) { + const double* row = sc + (s * K + prev) * K; + int best = 0; + for (int j = 1; j < K; ++j) if (row[j] > row[best]) best = j; + double second = -INFINITY; + for (int j = 0; j < K; ++j) if (j != best) second = std::max(second, row[j]); + if (row[best] - second < 1e-4) { ++near; break; } + tbad += tok[(size_t)m * S + s] != cand[((size_t)m * S + s) * K + best]; + prev = best; + } + } + std::printf(" %-34s bad %ld near-ties %ld %s\n", "lili_walk tokens", tbad, near, tbad ? "FAIL" : "PASS"); + const bool ok = close("lili_walk scores", ref, scores, 1e-4) && tbad == 0; + return ok ? 0 : 1; +} + +int main() { + int fails = 0; + fails += test_cand(); + fails += test_attn(); + fails += test_factor(); + fails += test_walk(); + std::printf("lili: %d failure(s)\n", fails); + return fails ? 1 : 0; +} diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index 5d9688b6..570517f6 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -1079,6 +1079,7 @@ TEST(op_vocabulary) { "lora_shrink", "lora_expand", "lora_expand_mm", "grid_embed_aa", "attn_paged", "attn_dense", "kv_store", "kv_store_streamed", "rope", "rope_table", + "attn_paged_sink", "qk_norm_rope", "qsa_block_key", /* libr4d's row-form names, served by the base op's row. */ "rmsnorm_rows", "rope_rows", "gemm_nt_q_short", "gemm_nt_q_gated_wide", @@ -1149,6 +1150,8 @@ TEST(op_vocabulary) { /* A pipelined prefill's first-piece KV length, a device length less a device offset. */ "sub_i32", "position_scale", "embed_attn", "ministral_rope", "pixtral_rope", "pixtral_merge", + /* LiLiCorr's candidate correlator (Nemotron-3.5-Bolt's drafter). */ + "lili_cand", "lili_attn", "lili_factor", "lili_walk", }; for (const char* op : kOps) { if (!kern(op)) fprintf(stderr, " missing op '%s'\n", op); @@ -1157,16 +1160,18 @@ TEST(op_vocabulary) { CHECK_EQ(api().kernel_count(), (int)(sizeof(kOps) / sizeof(kOps[0]))); /* The structural constraint on the paged block, and only that; everything else must match - * anything. attn_paged_tree is attn_paged's row with the tree operand, the same constraint. */ + * anything. attn_paged_tree, attn_paged_anchor_window and attn_paged_sink take attn_paged's. */ CHECK_EQ(kern("attn_paged")->n_constraints, 1); CHECK(std::strcmp(kern("attn_paged")->constraints[0].key, "block_size") == 0); CHECK_EQ(kern("attn_paged_tree")->n_constraints, 1); + CHECK_EQ(kern("attn_paged_sink")->n_constraints, 1); + CHECK(std::strcmp(kern("attn_paged_sink")->constraints[0].key, "block_size") == 0); CHECK_EQ(kern("kv_store")->n_constraints, 1); CHECK_EQ(kern("gemm_nt")->n_constraints, 0); CHECK_EQ(kern("gdn_chunk_scan")->n_constraints, 0); int constrained = 0; for (int i = 0; i < api().kernel_count(); ++i) constrained += api().kernel_at(i)->n_constraints > 0; - CHECK_EQ(constrained, 4); + CHECK_EQ(constrained, 5); } /* ================================================================== the numerics @@ -3196,6 +3201,47 @@ TEST(op_attn_paged) { CHECK_NEAR(out2.at(5), 1.0f, 1e-6); } +TEST(op_attn_paged_sink) { + /* op_attn_paged's cache and queries, non-causal, with a sink logit a head: token 0 now sees both + * keys too, and each sink adds exp(sink) to the denominator only. Head 0, token 0, q = [1,0]: + * scores 1/sqrt(2) and 0, so weights 1, exp(-1/sqrt(2)) and exp(sink0 - 1/sqrt(2)). */ + const float sc = 1.0f / 1.41421356f; + T q(RAD_F32, {2, 2, 2}); + q.f({ 1, 0, 0, 1, + 0, 1, 1, 0 }); + T kv(RAD_F32, {1, 1, 2, 4}); + kv.f({ 1, 0, 1, 0, + 0, 1, 0, 1 }); + T bt(RAD_I32, {1, 1}); bt.n({0}); + T su(RAD_I32, {1}); su.n({2}); + T sk(RAD_F32, {2}); sk.f({ 0.5f, 3.0f }); /* head 1's sink lies above every score */ + T out(RAD_F32, {2, 2, 2}); + A a; a.t(q).t(kv).t(bt).t(su).tnull().tnull().tnull().t(sk).t(out) + .i("q_len", 2).i("head_dim", 2).i("gqa", 2).i("block_size", 2) + .i("causal", 0).i("window", 0).s("q_dtype", "f32").s("kv_dtype", "f32"); + CHECK_OK(run("attn_paged_sink", a)); + const float w = std::exp(-sc); + const float d0 = 1.0f + w + std::exp(0.5f - sc); /* head 0, either token */ + CHECK_NEAR(out.at(0), 1.0f / d0, 1e-6); CHECK_NEAR(out.at(1), w / d0, 1e-6); + CHECK_NEAR(out.at(4), w / d0, 1e-6); CHECK_NEAR(out.at(5), 1.0f / d0, 1e-6); + const float d1 = 1.0f + w + std::exp(3.0f - sc); /* head 1 */ + CHECK_NEAR(out.at(2), w / d1, 1e-6); CHECK_NEAR(out.at(3), 1.0f / d1, 1e-6); + CHECK_NEAR(out.at(6), 1.0f / d1, 1e-6); CHECK_NEAR(out.at(7), w / d1, 1e-6); + + /* A sink far below every score changes nothing: attn_paged's values, causal. */ + T sk2(RAD_F32, {2}); sk2.f({ -1e30f, -1e30f }); + T o1(RAD_F32, {2, 2, 2}), o2(RAD_F32, {2, 2, 2}); + A b; b.t(q).t(kv).t(bt).t(su).tnull().tnull().tnull().t(o1) + .i("q_len", 2).i("head_dim", 2).i("gqa", 2).i("block_size", 2) + .i("causal", 1).i("window", 0).s("q_dtype", "f32").s("kv_dtype", "f32"); + CHECK_OK(run("attn_paged", b)); + A c; c.t(q).t(kv).t(bt).t(su).tnull().tnull().tnull().t(sk2).t(o2) + .i("q_len", 2).i("head_dim", 2).i("gqa", 2).i("block_size", 2) + .i("causal", 1).i("window", 0).s("q_dtype", "f32").s("kv_dtype", "f32"); + CHECK_OK(run("attn_paged_sink", c)); + for (int i = 0; i < 8; ++i) CHECK_NEAR(o2.at(i), o1.at(i), 1e-7); +} + TEST(op_attn_paged_ragged) { /* A ragged batch, as a serving step really looks: sequence 0 prefills two tokens while * sequence 1 decodes one. total_q is 3 and n_seq is 2, so without cu_seqlens this batch cannot @@ -10010,6 +10056,13 @@ std::vector geometries() { G("mtp_enter", "M", 2, a.i("M", R).i("n", 8).i("hc", 2).d("eps", 1e-6).s("dtype", "f32")), G("grid_embed", "M", 3, a.i("M", R).i("n", 8).i("side", 4).s("dtype", "f32")), G("grid_embed_aa", "M", 3, a.i("M", R).i("n", 8).i("side", 4).s("dtype", "f32")), + G("lili_cand", "M", 3, a.i("M", R).i("k", 4).i("world", 1).i("steps", 3).i("n", 8) + .s("dtype", "f32")), + G("lili_attn", "M", 8, a.i("M", R).i("steps", 2).i("k", 2).i("n_head", 2).i("head_dim", 4) + .s("dtype", "f32")), + G("lili_factor", "M", 8, a.i("M", R).i("L", 4).i("n", 8).s("dtype", "f32")), + G("lili_walk", "M", 2, a.i("M", R).i("steps", 3).i("k", 2).i("n", 8).s("dtype", "f32") + .d("eps", 1e-4).d("scale", 8.0)), G("layernorm", "M", 3, a.i("M", R).i("n", 8).d("eps", 1e-6).s("dtype", "f32")), G("add", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")), G("mul", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")), @@ -10101,6 +10154,10 @@ std::vector geometries() { .i("block_size", 4).i("causal", 1).i("window", 0) .s("q_dtype", "f32").s("kv_dtype", "f32").i("n_head", 4) .i("ctx", 9)), + G("attn_paged_sink", "q_len", 3, a.i("q_len", R).i("head_dim", 8).i("gqa", 2) + .i("block_size", 4).i("causal", 0).i("window", 0) + .s("q_dtype", "f32").s("kv_dtype", "f32").i("n_head", 4) + .i("ctx", 9)), G("attn_dense", "M", 6, a.i("M", R).i("head_dim", 8).i("gqa", 2).i("causal", 1) .s("dtype", "f32").i("n_head", 4)), /* One-row segments, so M is also the segment count (n_seq, the description's hint for @@ -10371,7 +10428,9 @@ bool undrawable(const char* op) { // Complete raster grids need the hand-built cases in nemotron35_test, not random indices. return !std::strcmp(op, "givens_dense_quant") || !std::strcmp(op, "givens_rotate") || !std::strcmp(op, "sample_merge_topk") || !std::strcmp(op, "gather_rows2") || - !std::strcmp(op, "pixtral_merge"); + !std::strcmp(op, "pixtral_merge") || + /* sample_logprobs rows (sorted pairs, positive sums): avx_check_hand.cpp builds them */ + !std::strcmp(op, "lili_cand"); } uint32_t lcg(uint32_t* s) { *s = *s * 1664525u + 1013904223u; return *s >> 8; }