From 63416510a0c2ab63a7c923beadd165a4969e11b6 Mon Sep 17 00:00:00 2001 From: keptn42 Date: Sat, 31 Oct 2026 10:46:28 +0000 Subject: [PATCH] ops: ssd_update and ple_conv_bias, Mamba-2's scan and convolution ssd_update is Mamba-2's selective state update, a token at a time, with kda_update's rollback contract: per_candidate, or the anchor form (one committed state and a scratch of per-token records). libref, libavx and a libr4d kernel at a 128-wide state (r4d_ssd.hip, r4d_kda.hip's register layout). ple_conv_bias is ple_conv with a per-channel bias inside the silu, Mamba-2's conv1d, an op of its own so ple_conv's callers keep their operand list. ref_test, avx_check_hand and selftest cases; docs/OPS.md. --- docs/OPS.md | 31 ++++ libavx/CMakeLists.txt | 1 + libavx/avx_cases.cpp | 4 + libavx/avx_check_hand.cpp | 40 +++++ libavx/avx_isa.h | 4 +- libavx/avx_misc.cpp | 17 ++- libavx/avx_registry.cpp | 17 +++ libavx/avx_ssd.cpp | 194 ++++++++++++++++++++++++ libr4d/CMakeLists.txt | 2 + libr4d/r4d_ple_conv_bf16.hip | 24 ++- libr4d/r4d_plugin.h | 3 + libr4d/r4d_rows.cpp | 55 +++++++ libr4d/r4d_selftest.cpp | 174 +++++++++++++++++++++ libr4d/r4d_shapes.cpp | 20 +++ libr4d/r4d_ssd.hip | 282 +++++++++++++++++++++++++++++++++++ libref/ref_ops.h | 4 + libref/ref_ple.cpp | 16 +- libref/ref_registry.cpp | 28 ++++ libref/ref_shapes.cpp | 42 ++++++ libref/ref_ssd.cpp | 233 +++++++++++++++++++++++++++++ tests/ref_test.cpp | 182 +++++++++++++++++++++- 21 files changed, 1362 insertions(+), 11 deletions(-) create mode 100644 libavx/avx_ssd.cpp create mode 100644 libr4d/r4d_ssd.hip create mode 100644 libref/ref_ssd.cpp diff --git a/docs/OPS.md b/docs/OPS.md index 95c64a25..3a47167c 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -2357,6 +2357,7 @@ wrong. | op | params | operands | |---|---|---| | `kda_update` | `M`(range) `heads` `head_k` `head_v` `lower_bound`:f64 `scale`:f64 `l2_eps`:f64 `mode` `dtype` `state_form`/opt | `q`, `k`, `v`, `a`, `b`, `A_log`w, `dt_bias`w, `state`:inout, `state_idx`, `cu`, `num_accepted`?, `has_init`? → `o` | +| `ssd_update` | `M`(range) `heads` `head_dim` `d_state` `groups` `mode` `dtype` `state_form`/opt | `x`, `B`, `C`, `dt`, `A_log`w, `dt_bias`w, `D`w, `state`:inout, `state_idx`, `cu`, `num_accepted`?, `has_init`? → `o` | | `gdn_conv_prep` | `M`(range) `head_k` `head_v` `chunk`/der `conv_width` `l2_eps`:f64/opt `softplus_thr`:f64/opt | `x`, `w`w, `b`w?, `A_log`w, `dt_bias`w, `conv_state`:inout, `cu`, `a`?, `b_gate`?, `cache_idx`?, `has_init`? → `q`,`k`,`v`,`g`,`beta` | | `gdn_conv_update` | `q_len`(range) `head_k` `head_v` `conv_width` `max_query_len`/opt | `x`, `w`w, `b`w?, `conv_state`:inout, `state_idx`, `num_accepted`, `cu` → `q`,`k`,`v` | | `gdn_kkt_solve` | `M`(range) `head_k` `chunk`/der | `k`, `beta`, `g`, `cu` → `A` | @@ -2399,6 +2400,26 @@ Under `anchor`, `verify` replays the accepted prefix in a separate dispatch befo no value row overwrites factors another is still reading. A sequence whose window or slots are out of bounds is skipped on the device, not refused. +**`ssd_update` is Mamba-2's selective state update** (the SSD recurrence, token by token). Per token +and head `h`, with `g = h / (heads / groups)` the head's B/C group: + + dt' = softplus(dt[h] + dt_bias[h]) A = -exp(A_log[h]) + S = e^{dt' A} S + dt' x[h] B[g]^T o[h] = S C[g] + D[h] x[h] + +It is a delta-net head without the delta: one scalar decay per head and token, no beta and no l2 +norm on B or C, and the skip term `D`, so the gdn ops cannot run it. dt is not clamped: the +checkpoints carry `time_step_limit = (0, inf)`, which mamba_ssm's kernels and vLLM pass, while +transformers' CPU fallback clamps at `time_step_min`, which on a real prompt binds for about one +(token, head) pair in eight. softplus is the identity above 20, as in torch and mamba_ssm. +`state` is f32 `[slots, heads, head_dim, d_state]`; `x` and `o` may be `[M, heads, head_dim]` or +flat, `B` and `C` `[M, groups, d_state]` or flat, `dt` one value per (token, head). Heads read their +group in blocks (heads `0 .. heads/groups - 1` read group 0), the mamba_ssm convention, not +round-robin. `o` excludes the model's gated norm. The rollback contract is `kda_update`'s, in both +forms. Under `anchor` the scratch holds, per head, the replay count and one record per window token: +the decay `e^{dt' A}`, `u = dt' x` (`head_dim`) and `B` (`d_state`), as many as the +`[head_dim, d_state]` block holds and at most 32 (a 64 x 128 head holds 42). The replay applies a +record with the window's own update, so the committed state is the per-candidate one bit for bit. + **Speculative rollback is part of the schema** (`spec.md` §10). The recurrent state and the conv window have already absorbed rejected tokens, so the state cache is a rolling window of `conv_width-1 + n_spec` entries read at the slot the last accepted token left, and a rejection is a @@ -2592,6 +2613,7 @@ whole form elsewhere (the host mailbox included), which keeps every promise `sp` | `ngram_ids` | `M`(range) `heads` `ngram` `eos` | `tok`, `state`:inout, `cu`, `mult`w, `vocab_sizes`w, `offsets`w, `cache_idx`?, `has_init`?, `num_accepted`? → `ids`, `ahead_ids`? | | `ple_gate` | `M`(range) `n` `hc` `eps`:f64 `dtype` `wadd`:f64/opt `gate_eps`:f64/opt | `k`, `q`, `v`, `w_key`w, `w_query`w, `w_conv`w → `gv`, `gvn` | | `ple_conv` | `M`(range) `n` `width` `dilation` `dtype` | `x`, `w`w, `conv_state`:inout, `cu`, `resid`?, `cache_idx`?, `has_init`?, `num_accepted`? → `y` | +| `ple_conv_bias` | `M`(range) `n` `width` `dilation` `dtype` | `x`, `w`w, `conv_state`:inout, `cu`, `resid`?, `cache_idx`?, `has_init`?, `num_accepted`?, `b`w → `y` | | `causal_conv1d` | `M`(range) `n` `width` `dtype` | `x`, `w`w, `conv_state`:inout, `cu`, `cache_idx`?, `has_init`?, `num_accepted`? → `y` | `logits_gemm` is separate from `gemm_nt` because `lm_head` is its own access class @@ -2823,6 +2845,15 @@ prefill's question and `num_accepted` decode's. The residual add is folded in because the reference is `gv + silu(conv(gvn))` and both tensors are `[M, hc*n]`. `resid` absent leaves the plain convolution. +### `ple_conv_bias` + + y[t] = resid[t] + silu( b[c] + sum_j w[c][j] * x[t - (width-1-j)*dilation] ) + +`ple_conv` with `b`, a per-channel bias inside the activation, before `y`. At dilation one with no +`resid` it is Mamba-2's `conv1d` over its `[x | B | C]` channels, so the Mamba block keeps the +window and rollback contract above. It is an op of its own, as `attn_paged_sink` is beside +`attn_paged`, so the architectures that issue `ple_conv` keep their operand list. + ### `causal_conv1d` y[t] = sum_j w[c][j] * x[t - (width-1-j)] diff --git a/libavx/CMakeLists.txt b/libavx/CMakeLists.txt index 531567ec..a17b6b3e 100644 --- a/libavx/CMakeLists.txt +++ b/libavx/CMakeLists.txt @@ -52,6 +52,7 @@ set(AVX_KERNEL_SRC avx_qsa.cpp avx_moe.cpp avx_gdn.cpp + avx_ssd.cpp avx_sample.cpp avx_misc.cpp avx_gen.cpp diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index cd49faf4..67ab11c0 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -179,6 +179,10 @@ std::vector build_cases() { add("kda_update", { HI("M", 3), HI("heads", 2), HI("head_k", 32), HI("head_v", 32), HF("lower_bound", -5), HF("scale", 0.1767766952966369), HF("l2_eps", 1e-6), HS("mode", mode), HS("dtype", dt) }); + /* Nemotron-H's per-rank shape at four ranks is 32 heads x 64 over 2 groups of 128. */ + for (const char* mode : { "prefill", "verify" }) + add("ssd_update", { HI("M", 3), HI("heads", 4), HI("head_dim", 16), HI("d_state", 32), + HI("groups", 2), HS("mode", mode), HS("dtype", dt) }); add("hc_write", { HI("M", 5), HI("n", 128), HI("hc", 4), HS("dtype", dt) }); add("hc_project",{ HI("M", 5), HI("n", 128), HI("hc", 4), HF("scale", 1.0), HS("dtype", dt) }); diff --git a/libavx/avx_check_hand.cpp b/libavx/avx_check_hand.cpp index f3c5c55f..88c9fe4b 100644 --- a/libavx/avx_check_hand.cpp +++ b/libavx/avx_check_hand.cpp @@ -630,6 +630,46 @@ void shape_cases(std::vector& hs) { .ps("state_form", "anchor"); hs.push_back(std::move(h)); } + /* Nemotron-H's Mamba-2 under the same two-copy state: a scratch holding three records of + * 1 + head_dim + d_state floats (decay, u, B) behind the count. */ + for (const char* mode : { "prefill", "verify" }) + for (int accepted : { 1, 2, 3 }) + for (int cold : { 0, 1 }) { + constexpr int64_t P = 16, N = 32, R = 1 + P + N; + Hand h("SSD anchor accepted-prefix replay", "ssd_update", 0.01); + h.dense(RAD_BF16, { 2, 1, P }, hfill(221, 0.25f)) + .dense(RAD_BF16, { 2, 1, N }, hfill(222, 0.25f)) + .dense(RAD_BF16, { 2, 1, N }, hfill(223, 0.25f)) + .dense(RAD_BF16, { 2, 1 }, hfill(224, 0.25f)) + .dense(RAD_F32, { 1 }, [](int64_t) { return 0.0f; }) + .dense(RAD_F32, { 1 }, [](int64_t) { return -1.0f; }) + .dense(RAD_F32, { 1 }, [](int64_t) { return 0.5f; }) + .dense( + RAD_F32, { 2, 1, P, N }, + [](int64_t i) { + if (i < P * N) return 0.125f; + i -= P * N; + if (!i) return 3.0f; + if (i > 3 * R) return 0.0f; + const int64_t at = (i - 1) % R; + return at == 0 ? 0.75f : at <= P ? 0.01f : 0.125f; + }, + true) + .dense(RAD_I32, { 1, 6 }, [](int64_t i) { return i < 3 ? 0.0f : 1.0f; }) + .idx({ 0, 2 }) + .idx({ accepted }) + .idx({ cold ? 0 : 1 }) + .dense(RAD_BF16, { 2, 1, P }, hfill(225), true) + .pi("M", 2) + .pi("heads", 1) + .pi("head_dim", P) + .pi("d_state", N) + .pi("groups", 1) + .ps("mode", mode) + .ps("dtype", "bf16") + .ps("state_form", "anchor"); + hs.push_back(std::move(h)); + } for (const char* mode : { "absorb", "expand" }) { const bool absorb = !std::strcmp(mode, "absorb"); const int64_t in = absorb ? 17 : 31, out = absorb ? 31 : 17; diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index c722a820..0f3617a5 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -73,7 +73,7 @@ int avx_par_force(int threads); X(hc_read) X(hc_write) X(hc_project) X(mtp_enter) \ X(layernorm) X(mhc_pre) X(mhc_post) X(mhc_contract) \ X(kda_update) X(mhc_pre_partial) X(mhc_pre_finish) \ - X(swiglu_clamped) \ + X(swiglu_clamped) X(ssd_update) \ X(swiglu_step) \ X(router_sigmoid_topk) \ X(router_sigmoid_group_topk) \ @@ -88,7 +88,7 @@ int avx_par_force(int threads); 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) \ + X(scatter_rows) X(ngram_ids) X(ple_conv_bias) \ X(ple_gate) X(ple_conv) X(cast) X(softmax) \ X(scale_rows) X(scale) X(fill) X(act_mul) \ X(seg_mean_bf16_sum) \ diff --git a/libavx/avx_misc.cpp b/libavx/avx_misc.cpp index 75b5cc6f..6c75714d 100644 --- a/libavx/avx_misc.cpp +++ b/libavx/avx_misc.cpp @@ -157,11 +157,12 @@ AVX_KERNEL(ple_gate) { struct ConvOps { const RadTensor *x, *w, *cs, *cu, *resid, *sidx, *hini, *nacc, *y; bool silu; + const RadTensor* b; /* per-channel bias inside the activation (Mamba-2's conv1d), or null */ }; static int depthwise_causal_conv(const RadArgs* a, const ConvOps& o) { const RadTensor *x = o.x, *w = o.w, *cs = o.cs, *cu = o.cu, *resid = o.resid; - const RadTensor *sidx = o.sidx, *hini = o.hini, *nacc = o.nacc, *y = o.y; + const RadTensor *sidx = o.sidx, *hini = o.hini, *nacc = o.nacc, *y = o.y, *b = o.b; if (!x || !w || !cs || !cu || !y) return RAD_E_INVAL; const int64_t n = p_int(a, "n", 0); @@ -180,6 +181,7 @@ static int depthwise_causal_conv(const RadArgs* a, const ConvOps& o) { if (N <= 0) return RAD_E_SHAPE; if (numel(x) < M * n || numel(y) < M * n || numel(w) < n * wid) return RAD_E_SHAPE; if (resid && numel(resid) < M * n) return RAD_E_SHAPE; + if (b && numel(b) != n) return RAD_E_SHAPE; const int64_t state_len = cs->rank >= 3 ? cs->shape[cs->rank - 1] : hist_len; if (cs->data && state_len < hist_len) return RAD_E_SHAPE; @@ -222,9 +224,10 @@ static int depthwise_causal_conv(const RadArgs* a, const ConvOps& o) { * on the stack, so `width` needs no bound of its own. */ float* tap = scratch_f32((size_t)wid); for (int64_t j = 0; j < wid; ++j) tap[j] = ldt(w, c * wrow + j * wcol); + const float bias = b ? ldt(b, c * laststride(b)) : 0.0f; for (int64_t t = 0; t < slen; ++t) { - float acc = 0.0f; + float acc = bias; for (int64_t j = 0; j < wid; ++j) { const int64_t src = t - hist_len + j * dil; const float vv = src >= 0 ? ldt(x, (bos + src) * xrow + c * xcol) @@ -277,6 +280,16 @@ AVX_KERNEL(ple_conv) { rad_arg_in(a, 6), rad_arg_in(a, 7), rad_arg_in(a, 8), true }); } +/* ple_conv's operands with `b`, a per-channel bias inside the silu, before `y`: Mamba-2's + * conv1d at dilation one. */ +AVX_KERNEL(ple_conv_bias) { + if (a->n_t < 10 || !rad_arg_in(a, 8)) return RAD_E_INVAL; + return depthwise_causal_conv(a, { rad_arg_in(a, 0), rad_arg_in(a, 1), rad_arg_in(a, 2), + rad_arg_in(a, 3), rad_arg_in(a, 4), rad_arg_in(a, 5), + rad_arg_in(a, 6), rad_arg_in(a, 7), rad_arg_in(a, 9), true, + rad_arg_in(a, 8) }); +} + /* ple_conv's operands without `resid`, dilation 1, no activation. */ AVX_KERNEL(causal_conv1d) { if (a->n_t < 8) return RAD_E_INVAL; diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index aa3ff906..39f7961b 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -87,6 +87,11 @@ static const RadParamSpec pKdaUpdate[] = { P_INT("M"), P_INT("heads"), P_INT("he static const RadOperandSpec oKdaUpdate[] = { OPD("q"), OPD("k"), OPD("v"), OPD("a"), OPD("b"), WGT("A_log"), WGT("dt_bias"), INOUT("state"), OPD("state_idx"), OPD("cu"), OPD_O("num_accepted"), OPD_O("has_init"), OUT("o") }; +static const RadParamSpec pSsdUpdate[] = { P_INT("M"), P_INT("heads"), P_INT("head_dim"), + P_INT("d_state"), P_INT("groups"), P_STR("mode"), P_STR("dtype"), P_STRO("state_form") }; +static const RadOperandSpec oSsdUpdate[] = { OPD("x"), OPD("B"), OPD("C"), OPD("dt"), + WGT("A_log"), WGT("dt_bias"), WGT("D"), INOUT("state"), OPD("state_idx"), OPD("cu"), + OPD_O("num_accepted"), OPD_O("has_init"), OUT("o") }; static const RadParamSpec pNgramIds[] = { P_INT("M"), P_INT("heads"), P_INT("ngram"), P_INT("eos") }; @@ -106,6 +111,11 @@ static const RadParamSpec pPleConv[] = { P_INT("M"), P_INT("n"), P_INT("width" static const RadOperandSpec oPleConv[] = { OPD("x"), WGT("w"), INOUT("conv_state"), OPD("cu"), OPD_O("resid"), OPD_O("cache_idx"), OPD_O("has_init"), OPD_O("num_accepted"), OUT("y") }; +/* ple_conv's operands with `b`, a per-channel bias inside the silu, before `y`. */ +static const RadOperandSpec oPleConvBias[] = { OPD("x"), WGT("w"), INOUT("conv_state"), OPD("cu"), + OPD_O("resid"), OPD_O("cache_idx"), + OPD_O("has_init"), OPD_O("num_accepted"), WGT("b"), + OUT("y") }; static const RadParamSpec pCausalConv[] = { P_INT("M"), P_INT("n"), P_INT("width"), P_STR("dtype") }; static const RadOperandSpec oCausalConv[] = { OPD("x"), WGT("w"), INOUT("conv_state"), OPD("cu"), @@ -977,6 +987,7 @@ static const RadOpSchema kSchemas[] = { { "mhc_post", ARR(pHcWrite), ARR(oMhcPost), "Source-to-destination manifold residual update." }, { "mhc_contract", ARR(pHcWrite), ARR(oMhcContract), "Mean over manifold residual streams." }, { "kda_update", ARR(pKdaUpdate), ARR(oKdaUpdate), "Bounded per-channel KDA with candidate-state rollback." }, +{ "ssd_update", ARR(pSsdUpdate), ARR(oSsdUpdate), "Mamba-2 scalar-decay state update with candidate-state rollback, per_candidate or anchor." }, { "hc_read", ARR(pHcRead), ARR(oHcRead), "The read half of a gated residual: grouped norm, low-rank gate, stream mix, and optionally the " "block-scaled fp8 form of x and its Hadamard-rotated twin. See docs/OPS.md for the three facts " @@ -1077,6 +1088,8 @@ static const RadOpSchema kSchemas[] = { "PLE gate: three grouped norms, a dot, a signed sqrt." }, { "ple_conv", ARR(pPleConv), ARR(oPleConv), "PLE's dilated depthwise conv, silu and residual add." }, +{ "ple_conv_bias", ARR(pPleConv), ARR(oPleConvBias), + "ple_conv with a per-channel bias inside the silu (Mamba-2's conv1d)." }, { "causal_conv1d", ARR(pCausalConv), ARR(oCausalConv), "depthwise causal conv with ple_conv's window, no activation and no residual (LFM2)." }, { "ngram_ids", ARR(pNgramIds), ARR(oNgramIds), "hashed n-gram row ids for PLE." }, @@ -1646,6 +1659,7 @@ SIMPLE("avx_mhc_pre_finish", "mhc_pre_finish", "norm", "manifold gates from proj SIMPLE("avx_mhc_post", "mhc_post", "norm", "manifold residual update", DT_FLOAT, L(mhc_post)), SIMPLE("avx_mhc_contract", "mhc_contract", "norm", "mean of residual streams", DT_FLOAT, L(mhc_contract)), SIMPLE("avx_kda_update", "kda_update", "gdn", "bounded KDA and candidate-state rollback", DT_FLOAT, L(kda_update)), +SIMPLE("avx_ssd_update", "ssd_update", "gdn", "Mamba-2 recurrence and candidate-state rollback", DT_FLOAT, L(ssd_update)), ROWL("avx_hc_read", "hc_read", "norm", "gated residual read: grouped norm, low-rank gate, stream mix", DT_FLOAT ", or mixing matrices of E4M3 / int8 codes with a scale plane, joined", L(hc_read), @@ -1747,6 +1761,9 @@ SIMPLE("avx_ple_gate", "ple_gate", "norm", "PLE gate: three grouped norms, a dot DT_FLOAT, L(ple_gate)), SIMPLE("avx_ple_conv", "ple_conv", "norm", "PLE's dilated depthwise conv, silu and residual add", DT_FLOAT, L(ple_conv)), +SIMPLE("avx_ple_conv_bias", "ple_conv_bias", "norm", + "ple_conv with a per-channel bias inside the silu (Mamba-2's conv1d)", DT_FLOAT, + L(ple_conv_bias)), SIMPLE("avx_causal_conv1d", "causal_conv1d", "conv", "depthwise causal conv, no activation", DT_FLOAT, L(causal_conv1d)), SIMPLE("avx_cast", "cast", "elem", "dtype conversion", DT_ANY, L(cast)), diff --git a/libavx/avx_ssd.cpp b/libavx/avx_ssd.cpp new file mode 100644 index 00000000..72466d90 --- /dev/null +++ b/libavx/avx_ssd.cpp @@ -0,0 +1,194 @@ +/* avx_ssd.cpp -- the Mamba-2 selective state update (ssd_update), libref/ref_ssd.cpp's arithmetic + * with the d_state reduction in this ISA level's vectors, in both state forms. + * + * A token widens its group's B and C rows once; each head then decays and updates its + * [head_dim, d_state] state row by row and reads the row against C in the same pass. The anchor + * form's replay applies a record with the window's own update (row_axpy is row_update without the + * read), so the committed state is this library's per-candidate state bit for bit. */ +#include "avx_vec.h" +#include "avx_common.h" + +#include +#include +#include + +using namespace avx; + +namespace { +bool headed(const RadTensor& t, int64_t tokens, int64_t heads, int64_t width) { + return t.data && t.shape[0] == tokens && + ((t.rank == 3 && t.shape[1] == heads && t.shape[2] == width) || + (t.rank == 2 && t.shape[1] == heads * width)); +} +int64_t off(const RadTensor& t, int64_t token, int64_t head, int64_t d, int64_t width) { + return token * t.stride[0] + head * (t.rank == 3 ? t.stride[1] : width * t.stride[1]) + + d * laststride(&t); +} +float softplus(float v) { return v > 20.0f ? v : std::log1p(std::exp(v)); } + +/* s = s * decay + u * b over one state row, as row_update does it, without the read. */ +void row_axpy(float* s, const float* b, float decay, float u, int64_t n) { + const vf vd = vf_set1(decay), vu = vf_set1(u); + int64_t d = 0; + for (; d + VF_N <= n; d += VF_N) + vf_storeu(s + d, vf_fma(vf_loadu(s + d), vd, vf_mul(vu, vf_loadu(b + d)))); + for (; d < n; ++d) s[d] = s[d] * decay + u * b[d]; +} +int64_t anchor_tokens(int64_t P, int64_t Nst) { + const int64_t fit = (P * Nst - 1) / (1 + P + Nst); + return fit < 32 ? fit : 32; +} + +/* s = s * decay + u * b over one state row, and the row's dot with c. */ +float row_update(float* s, const float* b, const float* c, float decay, float u, int64_t n) { + const vf vd = vf_set1(decay), vu = vf_set1(u); + vf acc = vf_zero(); + int64_t d = 0; + for (; d + VF_N <= n; d += VF_N) { + const vf r = vf_fma(vf_loadu(s + d), vd, vf_mul(vu, vf_loadu(b + d))); + vf_storeu(s + d, r); + acc = vf_fma(r, vf_loadu(c + d), acc); + } + float result = vf_hsum(acc); + for (; d < n; ++d) { + s[d] = s[d] * decay + u * b[d]; + result += s[d] * c[d]; + } + return result; +} +} // namespace + +AVX_KERNEL(ssd_update) { + if (!a || a->n_t < 13) return RAD_E_INVAL; + for (int i = 0; i < 10; ++i) + if (!rad_arg_in(a, i)) return RAD_E_INVAL; + if (!rad_arg_in(a, 12)) return RAD_E_INVAL; + const int64_t H = p_int(a, "heads", 0), P = p_int(a, "head_dim", 0); + const int64_t Nst = p_int(a, "d_state", 0), G = p_int(a, "groups", 0); + const char* mode = p_str(a, "mode", ""); + const bool verify = !std::strcmp(mode, "verify"); + if (!verify && std::strcmp(mode, "prefill")) return RAD_E_INVAL; + const char* form = p_str(a, "state_form", "per_candidate"); + const bool anchor = !std::strcmp(form, "anchor"); + if (!anchor && std::strcmp(form, "per_candidate")) return RAD_E_INVAL; + if (H < 1 || P < 1 || Nst < 1 || G < 1 || H % G) return RAD_E_SHAPE; + const int64_t rec = 1 + P + Nst, deepest = anchor_tokens(P, Nst); + if (anchor && deepest < 1) return RAD_E_SHAPE; + const auto &x = a->t[0], &B = a->t[1], &C = a->t[2], &dt = a->t[3]; + const auto &al = a->t[4], &dtb = a->t[5], &dskip = a->t[6], &s = a->t[7]; + const auto &idx = a->t[8], &cu = a->t[9], &out = a->t[12]; + const auto* accepted = rad_arg_in(a, 10); + const auto* init = rad_arg_in(a, 11); + if (x.rank < 2 || cu.rank != 1 || cu.dtype != RAD_I32 || cu.shape[0] < 2) return RAD_E_SHAPE; + const int64_t T = x.shape[0], N = cu.shape[0] - 1, slots = s.shape[0]; + if (T < 1) return RAD_E_SHAPE; + if (!headed(x, T, H, P) || !headed(B, T, G, Nst) || !headed(C, T, G, Nst) || + !headed(dt, T, H, 1) || !headed(out, T, H, P) || numel(&al) != H || numel(&dtb) != H || + numel(&dskip) != H || s.rank != 4 || s.dtype != RAD_F32 || s.shape[1] != H || + s.shape[2] != P || s.shape[3] != Nst || idx.rank != 2 || idx.dtype != RAD_I32 || + idx.shape[0] < N || idx.shape[1] < 1 || + (accepted && (accepted->dtype != RAD_I32 || numel(accepted) < N)) || + (init && (init->dtype != RAD_I32 || numel(init) < N))) + return RAD_E_SHAPE; + const int64_t width = idx.shape[1]; + for (int64_t seq = 0; seq < N; ++seq) { + const int64_t begin = ldi(&cu, seq * cu.stride[0]); + const int64_t end = ldi(&cu, (seq + 1) * cu.stride[0]); + const int64_t na = accepted ? ldi(accepted, offlin(accepted, seq)) : 1; + const int64_t most = anchor ? deepest : width; + if (begin < 0 || end < begin || end > T || na < 1 || na > most || + (verify && end - begin > most) || (anchor && width < 2)) + return RAD_E_SHAPE; + for (int64_t j = 0; j < width; ++j) + if (ldi(&idx, seq * idx.stride[0] + j * idx.stride[1]) >= slots) return RAD_E_SHAPE; + if (anchor) { + const int64_t read = ldi(&idx, seq * idx.stride[0]); + const int64_t scratch = ldi(&idx, seq * idx.stride[0] + (width / 2) * idx.stride[1]); + if (read >= 0 && (scratch < 0 || scratch == read)) return RAD_E_SHAPE; + if (verify && read >= 0 && (!init || ldi(init, offlin(init, seq)))) + for (int64_t h = 0; h < H; ++h) { + const float count = ldt(&s, scratch * s.stride[0] + h * s.stride[1]); + if (!std::isfinite(count) || count < 0 || count > (float)deepest || + count != std::floor(count) || (count > 0 && na > count)) + return RAD_E_SHAPE; + } + } + } + const int64_t per_group = H / G; + AVX_PARALLEL_FOR_IF(N * H * P * Nst >= AVX_PAR_MIN) + for (int64_t sh = 0; sh < N * H; ++sh) { + const int64_t seq = sh / H, head = sh % H, grp = head / per_group; + const int64_t begin = ldi(&cu, seq * cu.stride[0]); + const int64_t end = ldi(&cu, (seq + 1) * cu.stride[0]); + if (begin == end) continue; + const int64_t na = accepted ? ldi(accepted, offlin(accepted, seq)) : 1; + const int64_t read = + ldi(&idx, seq * idx.stride[0] + (verify && !anchor ? na - 1 : 0) * idx.stride[1]); + if (read < 0) { + for (int64_t t = begin; t < end; ++t) + for (int64_t e = 0; e < P; ++e) stt(&out, off(out, t, head, e, P), 0); + continue; + } + const bool initialized = !init || ldi(init, offlin(init, seq)) != 0; + std::vector S((size_t)(P * Nst)), b((size_t)Nst), c((size_t)Nst); + const int64_t sb = read * s.stride[0] + head * s.stride[1]; + for (int64_t e = 0; e < P; ++e) + for (int64_t d = 0; d < Nst; ++d) + S[e * Nst + d] = initialized ? ldt(&s, sb + e * s.stride[2] + d * s.stride[3]) : 0; + const int64_t scratch = + anchor ? ldi(&idx, seq * idx.stride[0] + (width / 2) * idx.stride[1]) : 0; + auto factor_at = [&](int64_t i) { + return scratch * s.stride[0] + head * s.stride[1] + (i / Nst) * s.stride[2] + + (i % Nst) * s.stride[3]; + }; + if (anchor && verify) { + /* The accepted prefix of the previous window, onto the committed state, published. */ + const int64_t replay = initialized ? (int64_t)ldt(&s, factor_at(0)) : 0; + for (int64_t t = 0; t < (replay ? na : 0); ++t) { + const int64_t f = 1 + t * rec; + const float decay = ldt(&s, factor_at(f)); + for (int64_t d = 0; d < Nst; ++d) b[(size_t)d] = ldt(&s, factor_at(f + 1 + P + d)); + for (int64_t e = 0; e < P; ++e) + row_axpy(&S[e * Nst], b.data(), decay, ldt(&s, factor_at(f + 1 + e)), Nst); + } + for (int64_t e = 0; e < P; ++e) + for (int64_t d = 0; d < Nst; ++d) + stt(&s, sb + e * s.stride[2] + d * s.stride[3], S[e * Nst + d]); + } + const float A = -std::exp(ldt(&al, head * laststride(&al))); + const float bias = ldt(&dtb, head * laststride(&dtb)); + const float skip = ldt(&dskip, head * laststride(&dskip)); + for (int64_t t = begin; t < end; ++t) { + const float step = softplus(ldt(&dt, off(dt, t, head, 0, 1)) + bias); + const float decay = std::exp(step * A); + for (int64_t d = 0; d < Nst; ++d) { + b[d] = ldt(&B, off(B, t, grp, d, Nst)); + c[d] = ldt(&C, off(C, t, grp, d, Nst)); + } + const int64_t f = 1 + (t - begin) * rec; + if (anchor && verify) { + stt(&s, factor_at(f), decay); + for (int64_t d = 0; d < Nst; ++d) stt(&s, factor_at(f + 1 + P + d), b[d]); + } + for (int64_t e = 0; e < P; ++e) { + const float xe = ldt(&x, off(x, t, head, e, P)); + const float u = step * xe; + if (anchor && verify) stt(&s, factor_at(f + 1 + e), u); + const float r = row_update(&S[e * Nst], b.data(), c.data(), decay, u, Nst); + stt(&out, off(out, t, head, e, P), r + skip * xe); + } + if ((verify && !anchor) || (!verify && t + 1 == end)) { + const int64_t write = + ldi(&idx, seq * idx.stride[0] + (verify ? t - begin : 0) * idx.stride[1]); + if (write >= 0) + for (int64_t e = 0; e < P; ++e) + for (int64_t d = 0; d < Nst; ++d) + stt(&s, write * s.stride[0] + head * s.stride[1] + e * s.stride[2] + + d * s.stride[3], + S[e * Nst + d]); + } + } + if (anchor) stt(&s, factor_at(0), verify ? (float)(end - begin) : 0.0f); + } + return RAD_OK; +} diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index 931a7020..5eb1d250 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -118,6 +118,8 @@ set(R4D_UNITS "r4d_dsa|" "r4d_mla|" "r4d_kda|" + # Mamba-2's selective state update (Nemotron-H), the KDA kernel's register layout. + "r4d_ssd|" "r4d_moe_mxfp4|" "r4d_fp8_f32scale|" "r4d_ngram_ids|" diff --git a/libr4d/r4d_ple_conv_bf16.hip b/libr4d/r4d_ple_conv_bf16.hip index 6ad534ea..95446575 100644 --- a/libr4d/r4d_ple_conv_bf16.hip +++ b/libr4d/r4d_ple_conv_bf16.hip @@ -60,7 +60,8 @@ __global__ __launch_bounds__(kPcThreads) void ple_conv_kernel( uint16_t* __restrict__ cs, const int32_t* __restrict__ cu, const uint16_t* __restrict__ resid, const int32_t* __restrict__ sidx, const int32_t* __restrict__ hini, const int32_t* __restrict__ nacc, - uint16_t* __restrict__ y, uint32_t n, uint32_t wid, uint32_t dil, uint32_t hist, + uint16_t* __restrict__ y, const uint16_t* __restrict__ bias, + uint32_t n, uint32_t wid, uint32_t dil, uint32_t hist, uint32_t xld, uint32_t rld, uint32_t yld, uint32_t wld, long long cs_slot, long long cs_ch, long long cs_tok, long long state_len) { @@ -92,8 +93,9 @@ __global__ __launch_bounds__(kPcThreads) void ple_conv_kernel( const uint16_t* __restrict__ hc = warm ? dst + off * cs_tok : nullptr; uint16_t* __restrict__ yc = y + (size_t)bos * yld + c; + const float b0 = bias ? bf16_to_f32(bias[c]) : 0.0f; for (int32_t t = t0; t < t1; ++t) { - float acc = 0.0f; + float acc = b0; #pragma unroll for (uint32_t j = 0; j < kPcMaxW; ++j) { if (j < wid) { @@ -150,17 +152,21 @@ __global__ __launch_bounds__(kPcThreads) void ple_conv_kernel( } enum { PC_X = 0, PC_W, PC_CS, PC_CU, PC_RESID, PC_CIDX, PC_HINIT, PC_NACC, PC_Y }; +/* ple_conv_bias: ple_conv's operands with `b`, the per-channel bias inside the silu (Mamba-2's + * conv1d), before `y`. */ +enum { PB_B = PC_Y, PB_Y }; /* causal_conv1d's operands: ple_conv's without `resid`. */ enum { CC_X = 0, CC_W, CC_CS, CC_CU, CC_CIDX, CC_HINIT, CC_NACC, CC_Y }; int conv_launch(const RadArgs* a, RadStream s, bool silu, const RadTensor* x, const RadTensor* w, const RadTensor* cs, const RadTensor* cu, const RadTensor* resid, const RadTensor* cidx, const RadTensor* hini, const RadTensor* nacc, - const RadTensor* y) { + const RadTensor* y, const RadTensor* b = nullptr) { if (!x || !w || !cu || !y) return R4D_NO(RAD_E_INVAL); if (x->dtype != RAD_BF16 || w->dtype != RAD_BF16 || y->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); if (resid && resid->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); + if (b && b->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); if (cs && cs->data && cs->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); if (cu->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE); if (cidx && cidx->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE); @@ -188,6 +194,7 @@ int conv_launch(const RadArgs* a, RadStream s, bool silu, const RadTensor* x, co * the band's upper bound and a grid sized by it would run off the arena. */ if (T <= 0 || ty != T || (resid && tr != T)) return R4D_NO(RAD_E_SHAPE); if (wrows < n) return R4D_NO(RAD_E_SHAPE); + if (b && (r4d_numel(b) != n || !r4d_contig(b))) return R4D_NO(RAD_E_SHAPE); const long long N = r4d_numel(cu) - 1; if (N <= 0) return R4D_NO(RAD_E_SHAPE); @@ -218,7 +225,8 @@ int conv_launch(const RadArgs* a, RadStream s, bool silu, const RadTensor* x, co cidx ? (const int32_t*)r4d_addr(cidx) : nullptr, hini ? (const int32_t*)r4d_addr(hini) : nullptr, nacc ? (const int32_t*)r4d_addr(nacc) : nullptr, - (uint16_t*)r4d_addr(y), (uint32_t)n, (uint32_t)wid, (uint32_t)dil, + (uint16_t*)r4d_addr(y), b ? (const uint16_t*)r4d_addr(b) : nullptr, + (uint32_t)n, (uint32_t)wid, (uint32_t)dil, (uint32_t)hist, (uint32_t)xld, (uint32_t)rld, (uint32_t)yld, (uint32_t)wld, cs_slot, cs_ch, cs_tok, state_len); return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); @@ -232,6 +240,14 @@ extern "C" int r4d_rad_ple_conv(const RadArgs* a, RadStream s) { r4d_opt(a, PC_HINIT), r4d_opt(a, PC_NACC), r4d_opt(a, PC_Y)); } +extern "C" int r4d_rad_ple_conv_bias(const RadArgs* a, RadStream s) { + const RadTensor* b = r4d_opt(a, PB_B); + if (!b) return R4D_NO(RAD_E_INVAL); + return conv_launch(a, s, true, r4d_opt(a, PC_X), r4d_opt(a, PC_W), r4d_opt(a, PC_CS), + r4d_opt(a, PC_CU), r4d_opt(a, PC_RESID), r4d_opt(a, PC_CIDX), + r4d_opt(a, PC_HINIT), r4d_opt(a, PC_NACC), r4d_opt(a, PB_Y), b); +} + extern "C" int r4d_rad_causal_conv1d(const RadArgs* a, RadStream s) { if (r4d_geti_or(a, "dilation", 1) != 1) return R4D_NO(RAD_E_INVAL); return conv_launch(a, s, false, r4d_opt(a, CC_X), r4d_opt(a, CC_W), r4d_opt(a, CC_CS), diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index f2d37ccc..41217bd0 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -470,6 +470,7 @@ int r4d_rad_mhc_pre(const RadArgs*, RadStream); int r4d_rad_mhc_pre_partial(const RadArgs*, RadStream); int r4d_rad_mhc_pre_finish(const RadArgs*, RadStream); int r4d_rad_kda_update(const RadArgs*, RadStream); +int r4d_rad_ssd_update(const RadArgs*, RadStream); int r4d_rad_moe_mxfp4(const RadArgs*, RadStream); int r4d_rad_layout_moe_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int, RadLayout*); @@ -818,6 +819,7 @@ int r4d_rad_embed_lookup_q (const RadArgs*, RadStream); int r4d_rad_ngram_ids (const RadArgs*, RadStream); int r4d_rad_ple_gate (const RadArgs*, RadStream); int r4d_rad_ple_conv (const RadArgs*, RadStream); +int r4d_rad_ple_conv_bias (const RadArgs*, RadStream); int r4d_rad_causal_conv1d (const RadArgs*, RadStream); int r4d_rad_cast (const RadArgs*, RadStream); int r4d_rad_gather_rows (const RadArgs*, RadStream); @@ -954,6 +956,7 @@ int r4d_shape_mhc_pre(const RadParam*, int, int, RadOpdDesc*); int r4d_shape_mhc_pre_partial(const RadParam*, int, int, RadOpdDesc*); int r4d_shape_mhc_pre_finish(const RadParam*, int, int, RadOpdDesc*); int r4d_shape_kda_update(const RadParam*, int, int, RadOpdDesc*); +int r4d_shape_ssd_update(const RadParam*, int, int, RadOpdDesc*); int r4d_shape_moe_mxfp4(const RadParam*, int, int, RadOpdDesc*); int r4d_shape_mhc_post(const RadParam*, int, int, RadOpdDesc*); int r4d_shape_mhc_contract(const RadParam*, int, int, RadOpdDesc*); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 38407e54..3f77ec71 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -631,6 +631,17 @@ static const RadOperandSpec oKdaUpdate[] = { {"cu", RAD_OPD_IN, 0}, {"num_accepted", RAD_OPD_IN, 1}, {"has_init", RAD_OPD_IN, 1}, {"o", RAD_OPD_OUT, 0}, }; +static const RadParamSpec pSsdUpdate[] = { + P_INT("M"), P_INT("heads"), P_INT("head_dim"), P_INT("d_state"), P_INT("groups"), + P_STR("mode"), P_STR("dtype"), P_STRO("state_form"), +}; +static const RadOperandSpec oSsdUpdate[] = { + {"x", RAD_OPD_IN, 0}, {"B", RAD_OPD_IN, 0}, {"C", RAD_OPD_IN, 0}, + {"dt", RAD_OPD_IN, 0}, {"A_log", RAD_OPD_WEIGHT, 0}, {"dt_bias", RAD_OPD_WEIGHT, 0}, + {"D", RAD_OPD_WEIGHT, 0}, {"state", RAD_OPD_INOUT, 0}, {"state_idx", RAD_OPD_IN, 0}, + {"cu", RAD_OPD_IN, 0}, {"num_accepted", RAD_OPD_IN, 1}, {"has_init", RAD_OPD_IN, 1}, + {"o", RAD_OPD_OUT, 0}, +}; static const RadOperandSpec oHcWrite[] = { { "y", RAD_OPD_IN, 0 }, { "inj", RAD_OPD_IN, 0 }, { "h", RAD_OPD_INOUT, 0 }, }; @@ -2322,6 +2333,19 @@ static const RadOperandSpec oPleConv[] = { { "num_accepted", RAD_OPD_IN, 1 }, { "y", RAD_OPD_OUT, 0 }, }; +/* ple_conv's operands with `b`, a per-channel bias inside the silu, before `y`. */ +static const RadOperandSpec oPleConvBias[] = { + { "x", RAD_OPD_IN, 0 }, + { "w", RAD_OPD_WEIGHT, 0 }, + { "conv_state", RAD_OPD_INOUT, 0 }, + { "cu", RAD_OPD_IN, 0 }, + { "resid", RAD_OPD_IN, 1 }, + { "cache_idx", RAD_OPD_IN, 1 }, + { "has_init", RAD_OPD_IN, 1 }, + { "num_accepted", RAD_OPD_IN, 1 }, + { "b", RAD_OPD_WEIGHT, 0 }, + { "y", RAD_OPD_OUT, 0 }, +}; /* ple_conv's operands without `resid`, its parameters without `dilation`. */ static const RadParamSpec pCausalConv[] = { { "M", RAD_P_INT, RAD_REQUIRED }, @@ -3310,6 +3334,11 @@ static const RadOpSchema kSchemas[] = { "Absent, every token commits: the read is at offset zero and the last " "(width-1)*dilation inputs land at offset zero, which is the prefill chunk. " "`resid` absent drops the add and leaves the plain convolution."), + SCHEMA("ple_conv_bias", pPleConv, oPleConvBias, + "ple_conv with `b`, a per-channel bias added inside the silu: y[t] = resid[t] + " + "silu(b[c] + sum_j w[c][j] * x[t - (width-1-j)*dilation]). At dilation one with no " + "`resid` it is Mamba-2's conv1d. The window, `has_init`, `cache_idx` and " + "`num_accepted` are ple_conv's."), SCHEMA("causal_conv1d", pCausalConv, oCausalConv, "y[t] = sum_j w[c][j] * x[t - (width-1-j)], ple_conv at dilation one with no " "activation and no residual: LFM2's short convolution, whose gates the caller applies. " @@ -3491,6 +3520,11 @@ static const RadOpSchema kSchemas[] = { SCHEMA("kda_update", pKdaUpdate, oKdaUpdate, "Bounded per-channel KDA recurrence. verify stores candidate states; prefill commits final state. " "Absolute cu offsets, accepted-prefix read slot, optional cold initialization, no output norm."), + SCHEMA("ssd_update", pSsdUpdate, oSsdUpdate, + "Mamba-2 selective state update: dt' = softplus(dt + dt_bias) (no clamp), state decays by " + "exp(-exp(A_log) dt') and gains dt' x B^T; o = state C + D x. verify stores candidate " + "states; prefill commits the final state. Absolute cu offsets, accepted-prefix read slot, " + "optional cold initialization, per_candidate only."), SCHEMA("hc_read", pHcRead, oHcRead, "the read half of a gated residual: a grouped rmsnorm, a low-rank sigmoid gate, and " "the mean of the gated streams -- plus the per-branch write gains and, optionally, " @@ -4931,6 +4965,13 @@ static const RadConstraint cKdaUpdate[] = { C_EQ("head_k", 128), C_EQ("head_v", 128), C_IN("mode", "prefill verify"), C_IN("dtype", "bf16"), }; +/* Mamba-2 at a 128-wide state (four registers a lane) and heads in rows of 16 (four waves of four + * rows): Nemotron-H's 64. */ +static const RadConstraint cSsdUpdate[] = { + C_GE("M", 1), C_GE("heads", 1), C_LE("heads", 65535), + C_EQ("d_state", 128), C_GE("head_dim", 16), C_LE("head_dim", 256), + C_DIV("head_dim", 16), C_IN("mode", "prefill verify"), C_IN("dtype", "bf16"), +}; static const RadConstraint cMhcPre[] = { C_GE("M", 1), C_LE("M", 65535), C_GE("n", 1), C_LE("n", 16384), C_GE("hc", 2), C_LE("hc", 8), @@ -6050,6 +6091,14 @@ static const RadKernelInfo kKernels[] = { ROW(cPleConv), NOTUNE, nullptr, nullptr, r4d_rad_ple_conv }, +{ "ple_conv_bias_bf16", "ple_conv_bias", "norm", + "ple_conv with a per-channel bias inside the silu (Mamba-2's conv1d); one thread a channel", + "width up to 5 and dilation up to 4 -- (width-1)*dilation is a register window", + "bf16 activations, weights, bias and conv state; i32 cu, slots, has_init and num_accepted", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cPleConv), NOTUNE, + nullptr, nullptr, r4d_rad_ple_conv_bias }, + { "causal_conv1d_bf16", "causal_conv1d", "conv", "depthwise causal conv with no activation (ple_conv's kernel); one thread a channel", "width 2 to 8, undilated", @@ -8072,6 +8121,12 @@ R4D_WIN_TREE_PAIR(512, 4) R4D_WIN_TREE_PAIR(512, 8) RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cKdaUpdate), NOTUNE, nullptr, nullptr, r4d_rad_kda_update, nullptr, nullptr, nullptr, r4d_shape_kda_update }, +{ "ssd_update_n128_bf16", "ssd_update", "gdn", "Mamba-2 recurrence and candidate states", + "heads 1..65535, d_state 128, head_dim a multiple of 16 up to 256, prefill and verify", + "bf16 activations, f32 A_log, dt_bias, D and state", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cSsdUpdate), NOTUNE, + nullptr, nullptr, r4d_rad_ssd_update, nullptr, nullptr, nullptr, + r4d_shape_ssd_update }, { "mhc_pre_bf16", "mhc_pre", "norm", "manifold residual gates and Sinkhorn mixing", "M 1..65535, n 1..16384, hc 2..8, iterations 1..256", "bf16 activation, f32 weights and coefficients", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMhcPre), NOTUNE, diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 839df4ed..a3f67ab8 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -18949,6 +18949,172 @@ static void kda_check(const Plugin& pl, const char* mode, bool cold, int accepte dlclose(ref); } +/* ssd_update against libref, as kda_check: two sequences over pitched planes, in prefill or verify, + * warm or cold, read at an accepted prefix; output, every written state slot and the red zones. */ +static void ssd_check(const Plugin& pl, const char* mode, bool cold, int accepted_count, + bool anchor = false) { + const char* name = "ssd_update_n128_bf16"; + const auto* row = find(pl, name); + if (!row || !g_plugin) { + ok(name, false, "row or plugin path absent"); + return; + } + std::string path(g_plugin); + path = path.substr(0, path.find_last_of('/') + 1) + "libref.so"; + void* ref = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + if (!ref) { + ok(name, false, "reference plugin unavailable"); + return; + } + auto count = (int (*)(void))dlsym(ref, "rad_kernel_count"); + auto at = (const RadKernelInfo* (*)(int))dlsym(ref, "rad_kernel_at"); + const RadKernelInfo* oracle = nullptr; + if (count && at) + for (int i = 0; i < count(); ++i) + if (!std::strcmp(at(i)->op, "ssd_update")) { + oracle = at(i); + break; + } + if (!oracle) { + ok(name, false, "reference operation unavailable"); + dlclose(ref); + return; + } + /* Two heads a group, so B and C are shared and the group index is exercised. */ + const int H = 4, G = 2, T0 = 6, P = 64, N = 128; + const std::vector> shapes = { + { T0, H, P }, { T0, G, N }, { T0, G, N }, { T0, H }, { H }, + { H }, { H }, { 8, H, P, N }, { 2, anchor ? 6 : 3 }, { 3 }, + { 2 }, { 2 }, { T0, H, P }, + }; + std::vector> bytes(13), visible(13); + std::vector host, device; + std::vector allocations; + auto offset = [](const RadTensor& t, int64_t logical) { + int64_t physical = 0; + for (int d = (int)t.rank - 1; d >= 0; --d) { + physical += (logical % t.shape[d]) * t.stride[d]; + logical /= t.shape[d]; + } + return physical; + }; + for (int i = 0; i < 13; ++i) { + /* A_log, dt_bias and D (4..6) are f32, as the plugin declares them, and so is the state. */ + const uint32_t dt = i >= 8 && i <= 11 ? (uint32_t)RAD_I32 + : i >= 4 && i <= 7 ? (uint32_t)RAD_F32 + : (uint32_t)RAD_BF16; + auto ht = T(nullptr, dt, shapes[(size_t)i]); + if (ht.rank >= 2) { + int64_t pitch = ht.shape[ht.rank - 1] + 4; + for (int d = (int)ht.rank - 2; d >= 0; --d) { + ht.stride[d] = pitch; + pitch = ht.shape[d] * pitch + 8; + } + } + const size_t size = (size_t)(ht.shape[0] * ht.stride[0]) * esz(dt) + 256; + bytes[(size_t)i].assign(size, 0xa5); + visible[(size_t)i].assign(size, 0); + ht.data = bytes[(size_t)i].data() + 128; + int64_t count0 = 1; + for (uint32_t d = 0; d < ht.rank; ++d) count0 *= ht.shape[d]; + for (int64_t j = 0; j < count0; ++j) { + const int64_t off0 = offset(ht, j); + const float value = + (float)((int)(st_mix32((uint32_t)(i * 173 + j)) % 2001) - 1000) / 2000; + if (dt == RAD_F32) + ((float*)ht.data)[off0] = value; + else if (dt == RAD_BF16) + ((uint16_t*)ht.data)[off0] = h_to_bf16(value); + else + ((int*)ht.data)[off0] = 0; + for (size_t b0 = 0; b0 < esz(dt); ++b0) + visible[(size_t)i][128 + (size_t)off0 * esz(dt) + b0] = 1; + } + host.push_back(ht); + } + auto integers = [&](int i, std::initializer_list values) { + int64_t j = 0; + for (int v : values) ((int*)host[(size_t)i].data)[offset(host[(size_t)i], j++)] = v; + }; + if (anchor) { + /* Committed 2 and 5, scratch 0 and 6, each scratch's counts zero: nothing to replay. */ + integers(8, { 2, 2, 2, 0, 0, 0, 5, 5, 5, 6, 6, 6 }); + integers(9, { 0, 3, 6 }); + for (int slot : { 0, 6 }) + for (int h = 0; h < H; ++h) + ((float*)host[7].data)[slot * host[7].stride[0] + h * host[7].stride[1]] = 0; + } else { + integers(8, { 2, 0, 3, 5, 6, 7 }); + integers(9, { 1, 3, 6 }); + } + integers(10, { accepted_count, 1 }); + integers(11, { cold ? 0 : 1, 1 }); + for (int i = 0; i < 13; ++i) { + void* d = dalloc(bytes[(size_t)i].size()); + if (!d) { + ok(name, false, "allocation failed"); + dlclose(ref); + return; + } + allocations.push_back(d); + st_memcpy(d, bytes[(size_t)i].data(), bytes[(size_t)i].size(), hipMemcpyHostToDevice); + auto dt = host[(size_t)i]; + dt.data = (char*)d + 128; + device.push_back(dt); + } + std::vector ps = { + PI("M", T0 + 7), PI("heads", H), PI("head_dim", P), PI("d_state", N), + PI("groups", G), PS("mode", mode), PS("dtype", "bf16"), + PS("state_form", anchor ? "anchor" : "per_candidate") + }; + RadArgs args{}; + args.t = host.data(); + args.n_t = 13; + args.p = ps.data(); + args.n_p = (int)ps.size(); + args.world_size = 1; + const int rc = oracle->launch(&args, nullptr); + ok("SSD host oracle", rc == RAD_OK); + if (rc == RAD_OK) run_case(row, device, ps); + if (rc == RAD_OK && anchor && !std::strcmp(mode, "verify")) { + // A second window must replay only the accepted prefix of the first window. + integers(11, { 1, 1 }); + st_memcpy(allocations[11], bytes[11].data(), bytes[11].size(), hipMemcpyHostToDevice); + args.t = host.data(); + ok("SSD anchor second-window host replay", oracle->launch(&args, nullptr) == RAD_OK); + run_case(row, device, ps); + } + bool matches = rc == RAD_OK, guards = true; + for (int i : { 7, 12 }) + if (rc == RAD_OK) { + std::vector got(bytes[(size_t)i].size()); + st_memcpy(got.data(), allocations[(size_t)i], got.size(), hipMemcpyDeviceToHost); + for (size_t j = 0; j < got.size(); ++j) + if (!visible[(size_t)i][j]) guards = guards && got[j] == 0xa5; + const auto& ht = host[(size_t)i]; + int64_t count0 = 1; + for (uint32_t d = 0; d < ht.rank; ++d) count0 *= ht.shape[d]; + for (int64_t j = 0; j < count0; ++j) { + const auto off0 = offset(ht, j); + const float expected = ht.dtype == RAD_F32 + ? ((const float*)ht.data)[off0] + : h_bf16(((const uint16_t*)ht.data)[off0]); + const float actual = ht.dtype == RAD_F32 + ? ((const float*)(got.data() + 128))[off0] + : h_bf16(((const uint16_t*)(got.data() + 128))[off0]); + const float tol = + ht.dtype == RAD_F32 ? 2e-5f : 0.008f + 0.008f * std::fabs(expected); + matches = matches && std::isfinite(actual) && std::fabs(actual - expected) <= tol; + } + } + ok(fmt("SSD %s %s cold=%d accepted=%d: output, state, untouched slots", + anchor ? "anchor" : "candidate", mode, cold, accepted_count) + .c_str(), + matches); + ok("SSD pitched rows and state red zones", guards); + dlclose(ref); +} + /* One launch, then a 200 ms warm-up and `iters` timed launches (st_time_us: --cold gives the * median of flushed launches). -1 when the row refuses the arguments. */ static double form_us(const RadKernelInfo* r, RadArgs* a, int iters) { @@ -33194,6 +33360,14 @@ static void device_phase(const Plugin& pl) { mla_check(pl, 33, 8, 17, "mla_attn_matrix_bf16", MlaFill::ragged, nullptr, 1); mla_check(pl, 7, 8, 513, "mla_attn_matrix_bf16", MlaFill::prefill, nullptr, 1); } + if (sel("ssd_update_n128_bf16")) + for (const char* mode : { "prefill", "verify" }) + for (int accepted : { 1, 2, 3 }) { + ssd_check(pl, mode, false, accepted); + ssd_check(pl, mode, true, accepted); + ssd_check(pl, mode, false, accepted, true); + ssd_check(pl, mode, true, accepted, true); + } if (sel("kda_update_k128_v128_bf16")) { for (const char* mode : { "prefill", "verify" }) for (int accepted : { 1, 2, 3 }) { diff --git a/libr4d/r4d_shapes.cpp b/libr4d/r4d_shapes.cpp index fb140501..680d74cf 100644 --- a/libr4d/r4d_shapes.cpp +++ b/libr4d/r4d_shapes.cpp @@ -421,6 +421,26 @@ extern "C" int r4d_shape_kda_update(const RadParam* p, int n_p, int operand, Rad R4D_PICK(l); } +extern "C" int r4d_shape_ssd_update(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const char* form = rad_param_gets(p, n_p, "state_form", ""); + if (!std::strcmp(form, "anchor")) return RAD_E_UNSUPPORTED; + const int64_t M = pi(p, n_p, "M"), H = pi(p, n_p, "heads"), P = pi(p, n_p, "head_dim"); + const int64_t N = pi(p, n_p, "d_state"), G = pi(p, n_p, "groups"); + if (G < 1 || H % G) return RAD_E_UNSUPPORTED; + const uint32_t D = dt_act(p, n_p, "dtype"); + const char* mode = rad_param_gets(p, n_p, "mode", ""); + const int64_t history = !std::strcmp(mode, "verify") ? M : 1; + const RadOpdDesc l[] = { + opd(D, M, H, P), opd(D, M, G, N), opd(D, M, G, N), opd(D, M, H), + opd((uint32_t)RAD_F32, H), opd((uint32_t)RAD_F32, H), opd((uint32_t)RAD_F32, H), + opd((uint32_t)RAD_F32, history + 1, H, P, N), + opd_idx(1, history, history + 1, -1, RAD_OPD_F_IDX_UNIQUE), + opd_idx(2, 0, M, -1, RAD_OPD_F_IDX_CU), + opd_idx(1, 0, 0, 1), opd_idx(1, 0, 0, 1), opd(D, M, H, P), + }; + R4D_PICK(l); +} + extern "C" int r4d_shape_mhc_pre(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), hc = pi(p, n_p, "hc"); const uint32_t D = dt_act(p, n_p, "dtype"); diff --git a/libr4d/r4d_ssd.hip b/libr4d/r4d_ssd.hip new file mode 100644 index 00000000..e156c3dd --- /dev/null +++ b/libr4d/r4d_ssd.hip @@ -0,0 +1,282 @@ +/* Mamba-2's selective state update (ssd_update): libref/ref_ssd.cpp's recurrence, a token at a time. + * One wave owns four rows of a head's [head_dim, d_state] state and keeps each row's 128-wide state + * in four registers a lane, as r4d_kda.hip does; the rows' output reductions interleave and the + * next token's operands load while this one is reduced. Prefill runs the same recurrence and + * commits only its final state; verify writes every candidate's (per_candidate), or each token's + * record into the scratch slot (anchor, docs/OPS.md): the decay, u = dt' x and B, replayed onto the + * committed state by a separate dispatch before the next window, as r4d_kda.hip's replay is, so no + * wave overwrites a record another is still reading. The replay applies a record with the window's + * own fmaf, so the committed state is the per-candidate one bit for bit. */ +#include +#include "r4d_args.h" +#include "r4d_common.h" +#include "r4d_emit.h" +#include +#include +#include +#include + +namespace { +struct SsdMeta { + long xr, xh, br, bh, cr, ch, dr, dh, os0, os1; + long ss0, ss1, ss2, is0, is1, cs0, as0, hs0; + int tokens, slots, width, verify, per_group; + /* The anchor form: the record length 1 + head_dim + d_state and the most records a head's + * block holds (at most 32). */ + int anchor, head_dim, rec, deepest; +}; + +__device__ __forceinline__ float softplus(float v) { return v > 20.0f ? v : log1pf(expf(v)); } + +/* Element i of a head's scratch block, rows of 128 at the state's row pitch. */ +__device__ __forceinline__ long factor_offset(long base, int i, long pitch) { + return base + (long)(i / 128) * pitch + (i % 128); +} + +/* The previous window's accepted prefix onto the committed state (column 0), published; a cold + * sequence's committed rows are zeroed instead. One wave a state row. */ +__global__ void ssd_replay_kernel(float* state, const int* idx, const int* cu, const int* accepted, + const int* init, SsdMeta m) { + const int lane = threadIdx.x & 31, e = blockIdx.x * 4 + (threadIdx.x >> 5), head = blockIdx.y, + seq = blockIdx.z; + if (cu[(long)seq * m.cs0] == cu[(long)(seq + 1) * m.cs0]) return; + const int anchor = idx[(long)seq * m.is0], + scratch = idx[(long)seq * m.is0 + (m.width / 2) * m.is1]; + if (anchor < 0 || anchor >= m.slots || scratch < 0 || scratch >= m.slots || anchor == scratch) + return; + const long fb = (long)scratch * m.ss0 + (long)head * m.ss1; + const long sb = (long)anchor * m.ss0 + (long)head * m.ss1 + (long)e * m.ss2; + if (init && !init[(long)seq * m.hs0]) { +#pragma unroll + for (int d = 0; d < 4; ++d) state[sb + lane + d * 32] = 0; + return; + } + const float count = state[fb]; + const int na = accepted ? accepted[(long)seq * m.as0] : 1; + if (!(count >= 0 && count <= (float)m.deepest) || count != floorf(count) || na < 1 || + na > m.deepest || (count > 0 && na > count)) + return; + float s[4]; +#pragma unroll + for (int d = 0; d < 4; ++d) s[d] = state[sb + lane + d * 32]; + for (int t = 0; t < (count > 0 ? na : 0); ++t) { + const int f = 1 + t * m.rec; + const float decay = state[factor_offset(fb, f, m.ss2)]; + const float u = state[factor_offset(fb, f + 1 + e, m.ss2)]; +#pragma unroll + for (int d = 0; d < 4; ++d) + s[d] = fmaf(s[d], decay, + u * state[factor_offset(fb, f + 1 + m.head_dim + lane + 32 * d, m.ss2)]); + } +#pragma unroll + for (int d = 0; d < 4; ++d) state[sb + lane + d * 32] = s[d]; +} + +template +__global__ void ssd_rows_kernel(const uint16_t* x, const uint16_t* B, const uint16_t* C, + const uint16_t* dt, const float* alog, const float* dtb, + const float* dskip, float* state, uint16_t* out, const int* idx, + const int* cu, const int* accepted_ptr, const int* init, + SsdMeta m) { + const int lane = threadIdx.x & 31, e0 = (blockIdx.x * 4 + (threadIdx.x >> 5)) * R; + const int head = blockIdx.y, seq = blockIdx.z, grp = head / m.per_group; + const int begin = cu[(long)seq * m.cs0], end = cu[(long)(seq + 1) * m.cs0]; + const int accepted = accepted_ptr ? accepted_ptr[(long)seq * m.as0] : 1; + const int most = m.anchor ? m.deepest : m.width; + if (begin < 0 || end <= begin || end > m.tokens || accepted < 1 || accepted > most || + (m.verify && end - begin > most)) + return; + const int read = idx[(long)seq * m.is0 + (m.verify && !m.anchor ? accepted - 1 : 0) * m.is1]; + if (read >= m.slots) return; + uint16_t* const out_row = out + (long)head * m.os1 + e0; + if (read < 0) { + if (lane < R) + for (int t = begin; t < end; ++t) out_row[(long)t * m.os0 + lane] = 0; + return; + } + /* Under anchor the replay dispatch has already published the accepted prefix (or zeroed a cold + * sequence) at column 0. */ + const bool initialized = (m.anchor && m.verify) || !init || init[(long)seq * m.hs0] != 0; + const int scratch = m.anchor ? idx[(long)seq * m.is0 + (m.width / 2) * m.is1] : 0; + if (m.anchor && (scratch < 0 || scratch >= m.slots || scratch == read)) return; + const long fb = (long)scratch * m.ss0 + (long)head * m.ss1; + const long initial = (long)read * m.ss0 + (long)head * m.ss1 + (long)e0 * m.ss2; + float s[R][4]; +#pragma unroll + for (int r = 0; r < R; ++r) +#pragma unroll + for (int d = 0; d < 4; ++d) + s[r][d] = initialized ? state[initial + r * m.ss2 + lane + 32 * d] : 0; + const float A = -expf(alog[head]), bias = dtb[head], skip = dskip[head]; + const uint16_t* const xb = x + (long)head * m.xh + e0; + const uint16_t* const bb = B + (long)grp * m.bh + lane; + const uint16_t* const cb = C + (long)grp * m.ch + lane; + const uint16_t* const db = dt + (long)head * m.dh; + struct Token { + uint32_t b[4], c[4], x[R], dt; + }; + auto fetch = [&](int t, Token& o) { +#pragma unroll + for (int d = 0; d < 4; ++d) { + o.b[d] = ldg_u16(bb + (long)t * m.br + 32 * d); + o.c[d] = ldg_u16(cb + (long)t * m.cr + 32 * d); + } +#pragma unroll + for (int r = 0; r < R; ++r) o.x[r] = ldg_u16(xb + (long)t * m.xr + r); + o.dt = ldg_u16(db + (long)t * m.dr); + }; + Token cur; + fetch(begin, cur); + for (int t = begin; t < end; ++t) { + Token next; + /* The last token loads itself again rather than a row past `end`. */ + fetch(t + 1 < end ? t + 1 : t, next); + const float step = softplus(bf16w_lo(cur.dt) + bias); + const float decay = expf(step * A); + float bv[4], cv[4], xv[R], acc[R]; +#pragma unroll + for (int d = 0; d < 4; ++d) { + bv[d] = bf16w_lo(cur.b[d]); + cv[d] = bf16w_lo(cur.c[d]); + } + const bool record = m.anchor && m.verify; + const int f = 1 + (t - begin) * m.rec; + if (record && e0 == 0) { + if (!lane) state[factor_offset(fb, f, m.ss2)] = decay; +#pragma unroll + for (int d = 0; d < 4; ++d) + state[factor_offset(fb, f + 1 + m.head_dim + lane + 32 * d, m.ss2)] = bv[d]; + } +#pragma unroll + for (int r = 0; r < R; ++r) { + xv[r] = bf16w_lo(cur.x[r]); + const float u = step * xv[r]; + if (record && lane == r) state[factor_offset(fb, f + 1 + e0 + r, m.ss2)] = u; + acc[r] = 0; +#pragma unroll + for (int d = 0; d < 4; ++d) { + s[r][d] = fmaf(s[r][d], decay, u * bv[d]); + acc[r] += s[r][d] * cv[d]; + } + } + float mine = 0; +#pragma unroll + for (int r = 0; r < R; ++r) { + const float y = r4d_wave_sum(acc[r]) + skip * xv[r]; + if (lane == r) mine = y; + } + if (lane < R) out_row[(long)t * m.os0 + lane] = f32_to_bf16(mine); + if ((m.verify && !m.anchor) || (!m.verify && t + 1 == end)) { + const int write = idx[(long)seq * m.is0 + (m.verify ? t - begin : 0) * m.is1]; + if (write >= 0 && write < m.slots) { + const long target = (long)write * m.ss0 + (long)head * m.ss1 + (long)e0 * m.ss2; +#pragma unroll + for (int r = 0; r < R; ++r) +#pragma unroll + for (int d = 0; d < 4; ++d) state[target + r * m.ss2 + lane + 32 * d] = s[r][d]; + } + } + cur = next; + } + if (m.anchor && e0 == 0 && !lane) state[fb] = m.verify ? (float)(end - begin) : 0.0f; +} + +/* A [tokens, heads, width] bf16 plane as rank 3, or rank 2 [tokens, heads * width]: its row and + * head pitches. */ +bool headed(const RadTensor& t, long tokens, long heads, long width, long* row, long* head) { + if (!t.data || t.dtype != RAD_BF16 || t.shape[0] != tokens || t.stride[0] > INT_MAX) + return false; + if (t.rank == 3 && t.shape[1] == heads && t.shape[2] == width && t.stride[2] == 1 && + t.stride[1] >= width && t.stride[1] <= INT_MAX) { + *row = t.stride[0]; + *head = t.stride[1]; + return true; + } + if (t.rank == 2 && t.shape[1] == heads * width && t.stride[1] == 1 && + t.stride[0] >= heads * width) { + *row = t.stride[0]; + *head = width; + return true; + } + return false; +} +bool vector(const RadTensor& t, uint32_t dt, long n) { + return t.data && t.dtype == dt && t.rank == 1 && t.shape[0] >= n && t.stride[0] == 1; +} + +constexpr int kRows = 4, kState = 128; + +int body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 13) return RAD_E_INVAL; + const long H = r4d_geti_or(a, "heads", 0), P = r4d_geti_or(a, "head_dim", 0); + const long N = r4d_geti_or(a, "d_state", 0), G = r4d_geti_or(a, "groups", 0); + if (H < 1 || H > 65535 || N != kState || P < 4 * kRows || P % (4 * kRows) || G < 1 || H % G) + return RAD_E_SHAPE; + const char* form = r4d_gets(a, "state_form"); + const bool anchor = form && !std::strcmp(form, "anchor"); + if (form && !anchor && std::strcmp(form, "per_candidate")) return RAD_E_INVAL; + const char* mode = r4d_gets(a, "mode"); + if (!mode || (std::strcmp(mode, "verify") && std::strcmp(mode, "prefill"))) return RAD_E_INVAL; + SsdMeta m{}; + m.verify = !std::strcmp(mode, "verify"); + m.anchor = anchor ? 1 : 0; + m.head_dim = (int)P; + m.rec = (int)(1 + P + N); + m.deepest = (int)std::min(32, (P * N - 1) / m.rec); + const auto &state = a->t[7], &idx = a->t[8], &cu = a->t[9]; + const long tokens = a->t[0].shape[0]; + if (tokens < 1 || tokens > INT_MAX || state.rank != 4 || state.dtype != RAD_F32 || + !state.data || state.shape[0] < 1 || state.shape[0] > INT_MAX || state.shape[1] != H || + state.shape[2] != P || state.shape[3] != N || state.stride[3] != 1 || + state.stride[2] < N || state.stride[1] < P * state.stride[2] || + state.stride[0] < H * state.stride[1] || cu.rank != 1 || cu.dtype != RAD_I32 || + !cu.data || cu.shape[0] < 2 || cu.shape[0] > 65536 || cu.stride[0] < 1 || + idx.rank != 2 || idx.dtype != RAD_I32 || !idx.data || idx.shape[0] < cu.shape[0] - 1 || + idx.shape[1] < 1 || idx.shape[1] > INT_MAX || idx.stride[1] < 1 || + idx.stride[0] < idx.shape[1] * idx.stride[1] || (anchor && idx.shape[1] < 2)) + return RAD_E_SHAPE; + if (!headed(a->t[0], tokens, H, P, &m.xr, &m.xh) || + !headed(a->t[1], tokens, G, N, &m.br, &m.bh) || + !headed(a->t[2], tokens, G, N, &m.cr, &m.ch) || + !headed(a->t[3], tokens, H, 1, &m.dr, &m.dh) || + !headed(a->t[12], tokens, H, P, &m.os0, &m.os1) || !vector(a->t[4], RAD_F32, H) || + !vector(a->t[5], RAD_F32, H) || !vector(a->t[6], RAD_F32, H)) + return RAD_E_SHAPE; + const RadTensor *accepted = rad_arg_in(a, 10), *init = rad_arg_in(a, 11); + if ((accepted && !vector(*accepted, RAD_I32, cu.shape[0] - 1)) || + (init && !vector(*init, RAD_I32, cu.shape[0] - 1))) + return RAD_E_SHAPE; + m.tokens = (int)tokens; + m.slots = (int)state.shape[0]; + m.width = (int)idx.shape[1]; + m.per_group = (int)(H / G); + m.ss0 = state.stride[0]; + m.ss1 = state.stride[1]; + m.ss2 = state.stride[2]; + m.is0 = idx.stride[0]; + m.is1 = idx.stride[1]; + m.cs0 = cu.stride[0]; + if (accepted) m.as0 = accepted->stride[0]; + if (init) m.hs0 = init->stride[0]; + const unsigned seqs = (unsigned)(cu.shape[0] - 1); + if (anchor && m.verify) { + const dim3 rgrid((unsigned)(P / 4), (unsigned)H, seqs); + const int rc = R4D_EMIT(stream, ssd_replay_kernel, rgrid, dim3(128), 0, + (float*)state.data, (const int*)idx.data, + (const int*)cu.data, + accepted ? (const int*)accepted->data : nullptr, + init ? (const int*)init->data : nullptr, m); + if (rc != RAD_OK) return rc; + } + const dim3 grid((unsigned)(P / (4 * kRows)), (unsigned)H, seqs); + return R4D_EMIT(stream, (ssd_rows_kernel), grid, dim3(128), 0, + (const uint16_t*)a->t[0].data, (const uint16_t*)a->t[1].data, + (const uint16_t*)a->t[2].data, (const uint16_t*)a->t[3].data, + (const float*)a->t[4].data, (const float*)a->t[5].data, + (const float*)a->t[6].data, (float*)state.data, (uint16_t*)a->t[12].data, + (const int*)idx.data, (const int*)cu.data, + accepted ? (const int*)accepted->data : nullptr, + init ? (const int*)init->data : nullptr, m); +} +} +extern "C" int r4d_rad_ssd_update(const RadArgs* a, RadStream stream) { return body(a, stream); } diff --git a/libref/ref_ops.h b/libref/ref_ops.h index b63f168d..cb5f175d 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -65,6 +65,7 @@ int ref_mhc_pre_finish (const RadArgs*, RadStream); int ref_mhc_post (const RadArgs*, RadStream); int ref_mhc_contract (const RadArgs*, RadStream); int ref_kda_update (const RadArgs*, RadStream); +int ref_ssd_update (const RadArgs*, RadStream); int ref_hc_read (const RadArgs*, RadStream); int ref_hc_write (const RadArgs*, RadStream); int ref_hc_project (const RadArgs*, RadStream); @@ -118,6 +119,7 @@ int ref_scatter_rows (const RadArgs*, RadStream); int ref_ngram_ids (const RadArgs*, RadStream); int ref_ple_gate (const RadArgs*, RadStream); int ref_ple_conv (const RadArgs*, RadStream); +int ref_ple_conv_bias (const RadArgs*, RadStream); int ref_causal_conv1d (const RadArgs*, RadStream); int ref_cast (const RadArgs*, RadStream); int ref_softmax (const RadArgs*, RadStream); @@ -354,6 +356,7 @@ REF_SHAPE_FN(ref_mhc_pre_finish); REF_SHAPE_FN(ref_mhc_post); REF_SHAPE_FN(ref_mhc_contract); REF_SHAPE_FN(ref_kda_update); +REF_SHAPE_FN(ref_ssd_update); REF_SHAPE_FN(ref_hc_read); REF_SHAPE_FN(ref_hc_write); REF_SHAPE_FN(ref_hc_project); @@ -407,6 +410,7 @@ REF_SHAPE_FN(ref_scatter_rows); REF_SHAPE_FN(ref_ngram_ids); REF_SHAPE_FN(ref_ple_gate); REF_SHAPE_FN(ref_ple_conv); +REF_SHAPE_FN(ref_ple_conv_bias); REF_SHAPE_FN(ref_causal_conv1d); REF_SHAPE_FN(ref_cast); REF_SHAPE_FN(ref_softmax); diff --git a/libref/ref_ple.cpp b/libref/ref_ple.cpp index 01a1ffea..d3b2adb5 100644 --- a/libref/ref_ple.cpp +++ b/libref/ref_ple.cpp @@ -195,11 +195,12 @@ int ref_ple_gate(const RadArgs* a, RadStream) { struct ConvArgs { const RadTensor *x, *w, *cs, *cu, *resid, *sidx, *hini, *nacc, *y; bool silu; + const RadTensor* b; /* per-channel bias inside the activation (Mamba-2's conv1d), or null */ }; static int depthwise_causal_conv(const RadArgs* a, const ConvArgs& o) { const RadTensor *x = o.x, *w = o.w, *cs = o.cs, *cu = o.cu, *resid = o.resid; - const RadTensor *sidx = o.sidx, *hini = o.hini, *nacc = o.nacc, *y = o.y; + const RadTensor *sidx = o.sidx, *hini = o.hini, *nacc = o.nacc, *y = o.y, *b = o.b; if (!x || !w || !cs || !cu || !y) return RAD_E_INVAL; const int64_t n = p_int(a, "n", 0); @@ -217,6 +218,7 @@ static int depthwise_causal_conv(const RadArgs* a, const ConvArgs& o) { if (N <= 0) return RAD_E_SHAPE; if (numel(x) < M * n || numel(y) < M * n || numel(w) < n * wid) return RAD_E_SHAPE; if (resid && numel(resid) < M * n) return RAD_E_SHAPE; + if (b && numel(b) != n) return RAD_E_SHAPE; const int64_t state_len = cs->rank >= 3 ? cs->shape[cs->rank - 1] : hist_len; if (cs->data && state_len < hist_len) return RAD_E_SHAPE; @@ -263,8 +265,9 @@ static int depthwise_causal_conv(const RadArgs* a, const ConvArgs& o) { for (int64_t i = 0; i < hist_len; ++i) hist[i] = (warm && cs->data) ? ldt(cs, base + (off + i) * cs_t) : 0.0f; + const float bias = b ? ldt(b, c * laststride(b)) : 0.0f; for (int64_t t = 0; t < slen; ++t) { - float acc = 0.0f; + float acc = bias; for (int64_t j = 0; j < wid; ++j) { const int64_t src = t - hist_len + j * dil; const float v = src >= 0 ? ldt(x, (bos + src) * xrow + c * xcol) @@ -300,6 +303,15 @@ int ref_ple_conv(const RadArgs* a, RadStream) { t_in(a, 5), t_in(a, 6), t_in(a, 7), t_in(a, 8), true }); } +/* ple_conv's operands with `b`, a per-channel bias inside the silu, before `y`: Mamba-2's + * conv1d at dilation one. */ +int ref_ple_conv_bias(const RadArgs* a, RadStream) { + if (a->n_t < 10 || !t_in(a, 8)) return RAD_E_INVAL; + return depthwise_causal_conv(a, { t_in(a, 0), t_in(a, 1), t_in(a, 2), t_in(a, 3), t_in(a, 4), + t_in(a, 5), t_in(a, 6), t_in(a, 7), t_in(a, 9), true, + t_in(a, 8) }); +} + /* ple_conv's operands without `resid`, at dilation one and with no activation. */ int ref_causal_conv1d(const RadArgs* a, RadStream) { if (a->n_t < 8) return RAD_E_INVAL; diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index 8436cdcf..38a29535 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -112,6 +112,10 @@ static const RadParamSpec pPleConv[] = { P_INT("M"), P_INT("n"), P_INT("width"), static const RadOperandSpec oPleConv[] = { OPD("x"), WGT("w"), INOUT("conv_state"), OPD("cu"), OPD_O("resid"), OPD_O("cache_idx"), OPD_O("has_init"), OPD_O("num_accepted"), OUT("y") }; +/* ple_conv's operands with `b`, a per-channel bias inside the silu, before `y`. */ +static const RadOperandSpec oPleConvBias[] = { OPD("x"), WGT("w"), INOUT("conv_state"), OPD("cu"), + OPD_O("resid"), OPD_O("cache_idx"), OPD_O("has_init"), + OPD_O("num_accepted"), WGT("b"), OUT("y") }; static const RadParamSpec pCausalConv[] = { P_INT("M"), P_INT("n"), P_INT("width"), P_STR("dtype") }; static const RadOperandSpec oCausalConv[] = { OPD("x"), WGT("w"), INOUT("conv_state"), OPD("cu"), @@ -146,6 +150,12 @@ static const RadParamSpec pKdaUpdate[] = { P_INT("M"), P_INT("heads"), P_INT("he static const RadOperandSpec oKdaUpdate[] = { OPD("q"), OPD("k"), OPD("v"), OPD("a"), OPD("b"), WGT("A_log"), WGT("dt_bias"), INOUT("state"), OPD("state_idx"), OPD("cu"), OPD_O("num_accepted"), OPD_O("has_init"), OUT("o") }; +/* Mamba-2's selective state update: kda_update's rollback contract with a scalar decay per head. */ +static const RadParamSpec pSsdUpdate[] = { P_INT("M"), P_INT("heads"), P_INT("head_dim"), + P_INT("d_state"), P_INT("groups"), P_STR("mode"), P_STR("dtype"), P_STRO("state_form") }; +static const RadOperandSpec oSsdUpdate[] = { OPD("x"), OPD("B"), OPD("C"), OPD("dt"), + WGT("A_log"), WGT("dt_bias"), WGT("D"), INOUT("state"), OPD("state_idx"), OPD("cu"), + OPD_O("num_accepted"), OPD_O("has_init"), OUT("o") }; /* The MTP head's entry for a wide residual stream. `ngroup` is hc for a grouped norm over the * sub-streams, 1 for a flat one over the whole row (see ref_hc.cpp). */ static const RadParamSpec pMtpEnter[] = { P_INT("M"), P_INT("n"), P_INT("hc"), @@ -1164,6 +1174,15 @@ static const RadOpSchema kSchemas[] = { "verify reads state_idx[seq,num_accepted-1] and writes each candidate state_idx[seq,t]; " "prefill reads/writes column zero, committing only the final state. cu offsets are absolute; " "has_init=0 starts from zero and a negative initial slot emits zero output. No output norm." }, +{ "ssd_update", ARR(pSsdUpdate), ARR(oSsdUpdate), + "Mamba-2 selective state update: dt'=softplus(dt+dt_bias) (identity above 20, no clamp), " + "S*=exp(-exp(A_log)*dt'); S+=dt'*x*B^T; o=S*C+D*x, B and C shared by heads/groups heads. " + "State is f32 [slot,heads,head_dim,d_state]. verify reads state_idx[seq,num_accepted-1] and " + "writes each candidate state_idx[seq,t]; prefill reads/writes column zero, committing only the " + "final state. cu offsets are absolute; has_init=0 starts from zero and a negative initial slot " + "emits zero output. state_form anchor: one committed state (column 0) and a scratch slot " + "(column width/2) of per-token records (decay, dt' x, B) replayed up to num_accepted. No output " + "norm." }, { "hc_read", ARR(pHcRead), ARR(oHcRead), "The read half of a gated residual. N = grouped_rmsnorm(h) -- one rsqrt per `n`-wide stream, " "one gain of hc*n over all of them, `w + wadd`; g = sigmoid(mix_up @ silu(mix_down @ N / hc)); " @@ -1351,6 +1370,10 @@ static const RadOpSchema kSchemas[] = { "(width-1)*dilation - 1 slots plus one a token. Absent, every token commits: the read is at " "offset zero and the last (width-1)*dilation inputs land at offset zero, which is the prefill " "chunk. `resid` absent drops the add and leaves the plain convolution." }, +{ "ple_conv_bias", ARR(pPleConv), ARR(oPleConvBias), + "ple_conv with `b`, a per-channel bias added inside the silu: y[t] = resid[t] + silu(b[c] + " + "sum_j w[c][j] * x[t - (width-1-j)*dilation]). At dilation one with no `resid` it is Mamba-2's " + "conv1d. The window, `has_init`, `cache_idx` and `num_accepted` are ple_conv's." }, { "causal_conv1d", ARR(pCausalConv), ARR(oCausalConv), "y[t] = sum_j w[c][j] * x[t - (width-1-j)], a DEPTHWISE CAUSAL convolution with no activation " "and no residual (LFM2's short convolution, whose gates the caller applies). The state, " @@ -2317,6 +2340,8 @@ SIMPLE("ref_mhc_contract", "mhc_contract", "norm", "mean of manifold residual st ref_mhc_contract), SIMPLE("ref_kda_update", "kda_update", "gdn", "bounded per-channel delta recurrence and candidate rollback", DT_FLOAT, ref_kda_update), +SIMPLE("ref_ssd_update", "ssd_update", "gdn", "Mamba-2 scalar-decay recurrence and candidate rollback", DT_FLOAT, + ref_ssd_update), ROWL("ref_hc_read", "hc_read", "norm", "gated residual read: grouped norm, low-rank gate, stream mix", DT_FLOAT ", or mixing matrices of E4M3 / int8 codes with a scale plane, joined", @@ -2423,6 +2448,9 @@ SIMPLE("ref_ple_gate", "ple_gate", "norm", "PLE gate: three grouped norms, a dot DT_FLOAT, ref_ple_gate), SIMPLE("ref_ple_conv", "ple_conv", "norm", "PLE's dilated depthwise conv, silu and residual add", DT_FLOAT, ref_ple_conv), +SIMPLE("ref_ple_conv_bias", "ple_conv_bias", "norm", + "ple_conv with a per-channel bias inside the silu (Mamba-2's conv1d)", DT_FLOAT, + ref_ple_conv_bias), SIMPLE("ref_causal_conv1d", "causal_conv1d", "conv", "depthwise causal conv, no activation", DT_FLOAT, ref_causal_conv1d), SIMPLE("ref_gather_rows", "gather_rows", "elem", "y[i,:] = x[idx[i],:]", DT_ANY, ref_gather_rows), diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index ea5a76a6..7450e6aa 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -358,6 +358,27 @@ int ref_kda_update_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou return o.finish("kda_update", operand, out); } +int ref_ssd_update_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const char* form = gs(p, n_p, "state_form"); + if (form && !std::strcmp(form, "anchor")) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), H = gi(p, n_p, "heads", 0); + const int64_t P = gi(p, n_p, "head_dim", 0), N = gi(p, n_p, "d_state", 0); + const int64_t G = gi(p, n_p, "groups", 0); + if (M < 1 || H < 1 || P < 1 || N < 1 || G < 1 || H % G) return RAD_E_UNSUPPORTED; + const char* mode = gs(p, n_p, "mode"); + const int64_t history = mode && !std::strcmp(mode, "verify") ? M : 1; + Opd o; + o.t(D, {M, H, P}); o.t(D, {M, G, N}); o.t(D, {M, G, N}); o.t(D, {M, H}); + o.t((uint32_t)RAD_F32, {H}); o.t((uint32_t)RAD_F32, {H}); o.t((uint32_t)RAD_F32, {H}); + o.t((uint32_t)RAD_F32, {history + 1, H, P, N}); + o.t_idx({1, history}, history + 1, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); + o.t_idx({2}, M, -1, (uint32_t)RAD_OPD_F_IDX_CU); + o.t_idx({1}, 0, 1, 0); o.t_idx({1}, 0, 1, 0); + o.t(D, {M, H, P}); + return o.finish("ssd_update", operand, out); +} + int ref_mhc_pre_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), hc = gi(p, n_p, "hc", 0); @@ -1055,6 +1076,27 @@ int ref_ple_conv_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) return o.finish("ple_conv", operand, out); } +/* ple_conv's description with `b` before `y`. */ +int ref_ple_conv_bias_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); + const int64_t wid = gi(p, n_p, "width", 0), dil = gi(p, n_p, "dilation", 1); + if (M <= 0 || n <= 0 || wid <= 0 || dil <= 0) return RAD_E_UNSUPPORTED; + const int64_t S = 1, hist = (wid - 1) * dil, depth = hist - 1 + M; + Opd o; + o.t(D, { M, n }); /* x */ + o.t(D, { n, wid }); /* w */ + o.t(D, { S, n, depth }); /* conv_state, INOUT */ + o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu */ + o.t(D, { M, n }); /* resid */ + o.t_idx({ S }, S, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* cache_idx */ + o.t_idx({ S }, 0, 1, 0); /* has_init: warm */ + o.t_idx({ S }, 0, M, 0); /* num_accepted: read at M - 1 */ + o.t(D, { n }); /* b */ + o.t(D, { M, n }); /* y */ + return o.finish("ple_conv_bias", operand, out); +} + /* ple_conv's description without `resid` and at dilation one. */ int ref_causal_conv1d_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); diff --git a/libref/ref_ssd.cpp b/libref/ref_ssd.cpp new file mode 100644 index 00000000..ce446fca --- /dev/null +++ b/libref/ref_ssd.cpp @@ -0,0 +1,233 @@ +/* ref_ssd.cpp -- the Mamba-2 selective state update (SSD), token by token. + * + * ============================== The algorithm ============================== + * + * Per token, per head h of `heads`, with the state S shaped [head_dim, d_state] and g = h / (heads / + * groups) the head's B/C group: + * + * dt' = softplus(dt[h] + dt_bias[h]) A = -exp(A_log[h]) + * S *= e^{dt' A} + * S += dt' . x[h] B[g]^T o[h] = S C[g] + D[h] . x[h] + * + * A Mamba-2 head is a gated delta net head without the delta: one scalar decay per head and token, + * no beta, no l2 norm on B or C, and the skip term D. The gdn ops cannot run it (their rank-1 update + * subtracts S k and their keys are normalised), so it is an op of its own. + * + * dt is not clamped. The checkpoint's `time_step_limit` is (0, inf), which is what mamba_ssm's + * kernels and vLLM pass; transformers' CPU fallback clamps dt at `time_step_min` and is not what + * the model was trained or is served with. softplus keeps torch's and mamba_ssm's threshold: above + * 20 it is the identity. + * + * The output excludes the model's gated norm. + * + * ============================== The layouts ============================== + * + * x, o [T, heads, head_dim] or [T, heads*head_dim] + * B, C [T, groups, d_state] or [T, groups*d_state] + * dt [T, heads] A_log, dt_bias, D [heads], f32 + * state [n_slots, heads, head_dim, d_state], f32 state_idx [N, W] cu [N+1] + * + * The rollback contract is kda_update's, in both forms. `per_candidate`: `mode=verify` reads column + * `num_accepted - 1` of the sequence's `state_idx` row and writes the state after token t of the + * window to column t; `mode=prefill` reads column zero and writes only the final state there. + * `has_init` 0 starts from zero, a negative read slot gives zero output and a negative write slot + * is skipped. + * + * `anchor`: column zero is the committed state and column `width/2` a scratch slot of the same + * shape. Per head the scratch holds a replay count and then one record per window token: the + * decay e^{dt' A}, u = dt' x (head_dim) and B (d_state), 1 + head_dim + d_state floats, as many as + * the [head_dim, d_state] block holds, at most 32 (a 64 x 128 head holds 42). `mode=verify` first + * replays the previous window's accepted prefix (`num_accepted` records, at most the stored count) + * onto the committed state, publishes it, then runs the window from it writing each token's record + * and the window length as the new count. The rank-1 update is replayed with the same arithmetic, + * so the committed state is the per-candidate form's bit for bit. `mode=prefill` commits its final + * state and sets the count to zero; a zeroed scratch replays nothing. + */ +#include "ref_common.h" +#include "ref_ops.h" + +#include +#include +#include + +using namespace ref; + +namespace { + +/* Rows of `width` columns per (token, head), whether the tensor is 3-D or flattened to 2-D. */ +bool headed(const RadTensor& t, int64_t tokens, int64_t heads, int64_t width) { + return t.data && t.shape[0] == tokens && + ((t.rank == 3 && t.shape[1] == heads && t.shape[2] == width) || + (t.rank == 2 && t.shape[1] == heads * width)); +} +int64_t off(const RadTensor& t, int64_t token, int64_t head, int64_t d, int64_t width) { + return token * t.stride[0] + head * (t.rank == 3 ? t.stride[1] : width * t.stride[1]) + + d * laststride(&t); +} +float softplus(float v) { return v > 20.0f ? v : std::log1p(std::exp(v)); } + +/* The anchor scratch's records: per window token 1 + head_dim + d_state floats behind the count. */ +int64_t anchor_tokens(int64_t P, int64_t Nst) { + const int64_t fit = (P * Nst - 1) / (1 + P + Nst); + return fit < 32 ? fit : 32; +} + +} // namespace + +int ref_ssd_update(const RadArgs* a, RadStream) { + if (!a || a->n_t < 13) return RAD_E_INVAL; + for (int i = 0; i < 10; ++i) + if (!rad_arg_in(a, i)) return RAD_E_INVAL; + if (!rad_arg_in(a, 12)) return RAD_E_INVAL; + const int64_t H = p_int(a, "heads", 0), P = p_int(a, "head_dim", 0); + const int64_t Nst = p_int(a, "d_state", 0), G = p_int(a, "groups", 0); + const char* mode = p_str(a, "mode", ""); + const bool verify = !std::strcmp(mode, "verify"); + if (!verify && std::strcmp(mode, "prefill")) return RAD_E_INVAL; + const char* form = p_str(a, "state_form", "per_candidate"); + const bool anchor = !std::strcmp(form, "anchor"); + if (!anchor && std::strcmp(form, "per_candidate")) return RAD_E_INVAL; + if (H <= 0 || P <= 0 || Nst <= 0 || G <= 0 || H % G) return RAD_E_SHAPE; + const int64_t rec = 1 + P + Nst, deepest = anchor_tokens(P, Nst); + if (anchor && deepest < 1) return RAD_E_SHAPE; + const auto &x = a->t[0], &B = a->t[1], &C = a->t[2], &dt = a->t[3]; + const auto &alog = a->t[4], &dtb = a->t[5], &dskip = a->t[6], &state = a->t[7]; + const auto &idx = a->t[8], &cu = a->t[9]; + const RadTensor *accepted = rad_arg_in(a, 10), *init = rad_arg_in(a, 11); + const auto& out = a->t[12]; + if (x.rank < 2 || cu.rank != 1 || cu.dtype != RAD_I32 || cu.shape[0] < 2) return RAD_E_SHAPE; + const int64_t T = x.shape[0], N = cu.shape[0] - 1; + if (T < 1) return RAD_E_SHAPE; + if (!headed(x, T, H, P) || !headed(B, T, G, Nst) || !headed(C, T, G, Nst) || + !headed(dt, T, H, 1) || !headed(out, T, H, P) || numel(&alog) != H || numel(&dtb) != H || + numel(&dskip) != H || state.rank != 4 || state.dtype != RAD_F32 || state.shape[1] != H || + state.shape[2] != P || state.shape[3] != Nst || idx.dtype != RAD_I32 || idx.rank != 2 || + idx.shape[0] < N || idx.shape[1] < 1 || + (accepted && (accepted->dtype != RAD_I32 || numel(accepted) < N)) || + (init && (init->dtype != RAD_I32 || numel(init) < N))) + return RAD_E_SHAPE; + const int64_t width = idx.shape[1], slots = state.shape[0]; + /* Every address is checked before any state is written, so a malformed batch cannot leave a + * partly committed prefix behind an error. */ + for (int64_t seq = 0; seq < N; ++seq) { + const int64_t begin = ld_int(cu.dtype, cu.data, seq * cu.stride[0]); + const int64_t end = ld_int(cu.dtype, cu.data, (seq + 1) * cu.stride[0]); + const int64_t na = + accepted ? ld_int(accepted->dtype, accepted->data, offlin(accepted, seq)) : 1; + const int64_t most = anchor ? deepest : width; + if (begin < 0 || end < begin || end > T || na < 1 || na > most || + (verify && end - begin > most) || (anchor && width < 2)) + return RAD_E_SHAPE; + for (int64_t j = 0; j < width; ++j) + if (ld_int(idx.dtype, idx.data, seq * idx.stride[0] + j * idx.stride[1]) >= slots) + return RAD_E_SHAPE; + if (anchor) { + const int64_t read = ld_int(idx.dtype, idx.data, seq * idx.stride[0]); + const int64_t scratch = + ld_int(idx.dtype, idx.data, seq * idx.stride[0] + (width / 2) * idx.stride[1]); + if (read >= 0 && (scratch < 0 || scratch == read)) return RAD_E_SHAPE; + if (verify && read >= 0 && + (!init || ld_int(init->dtype, init->data, offlin(init, seq)))) + for (int64_t h = 0; h < H; ++h) { + const float count = + ldt(&state, scratch * state.stride[0] + h * state.stride[1]); + if (!std::isfinite(count) || count < 0 || count > (float)deepest || + count != std::floor(count) || (count > 0 && na > count)) + return RAD_E_SHAPE; + } + } + } + const int64_t per_group = H / G; +#pragma omp parallel for schedule(static) + for (int64_t sh = 0; sh < N * H; ++sh) { + const int64_t seq = sh / H, head = sh % H, grp = head / per_group; + const int64_t begin = ld_int(cu.dtype, cu.data, seq * cu.stride[0]); + const int64_t end = ld_int(cu.dtype, cu.data, (seq + 1) * cu.stride[0]); + if (begin == end) continue; + const int64_t na = + accepted ? ld_int(accepted->dtype, accepted->data, offlin(accepted, seq)) : 1; + const int64_t read = + ld_int(idx.dtype, idx.data, + seq * idx.stride[0] + (verify && !anchor ? na - 1 : 0) * idx.stride[1]); + if (read < 0) { + for (int64_t t = begin; t < end; ++t) + for (int64_t e = 0; e < P; ++e) stt(&out, off(out, t, head, e, P), 0); + continue; + } + const bool initialized = !init || ld_int(init->dtype, init->data, offlin(init, seq)) != 0; + std::vector S((size_t)(P * Nst)), b((size_t)Nst), c((size_t)Nst); + const int64_t sb = read * state.stride[0] + head * state.stride[1]; + for (int64_t e = 0; e < P; ++e) + for (int64_t d = 0; d < Nst; ++d) + S[e * Nst + d] = + initialized ? ldt(&state, sb + e * state.stride[2] + d * state.stride[3]) : 0; + const int64_t scratch = + anchor ? ld_int(idx.dtype, idx.data, seq * idx.stride[0] + (width / 2) * idx.stride[1]) + : 0; + auto factor_at = [&](int64_t i) { + return scratch * state.stride[0] + head * state.stride[1] + + (i / Nst) * state.stride[2] + (i % Nst) * state.stride[3]; + }; + if (anchor && verify) { + /* The accepted prefix of the previous window, onto the committed state, published. */ + const int64_t replay = initialized ? (int64_t)ldt(&state, factor_at(0)) : 0; + for (int64_t t = 0; t < (replay ? na : 0); ++t) { + const int64_t f = 1 + t * rec; + const float decay = ldt(&state, factor_at(f)); + for (int64_t d = 0; d < Nst; ++d) b[(size_t)d] = ldt(&state, factor_at(f + 1 + P + d)); + for (int64_t e = 0; e < P; ++e) { + const float u = ldt(&state, factor_at(f + 1 + e)); + for (int64_t d = 0; d < Nst; ++d) { + float& s = S[e * Nst + d]; + s = s * decay + u * b[d]; + } + } + } + for (int64_t e = 0; e < P; ++e) + for (int64_t d = 0; d < Nst; ++d) + stt(&state, sb + e * state.stride[2] + d * state.stride[3], S[e * Nst + d]); + } + const float A = -std::exp(ldt(&alog, head * laststride(&alog))); + const float bias = ldt(&dtb, head * laststride(&dtb)); + const float skip = ldt(&dskip, head * laststride(&dskip)); + for (int64_t t = begin; t < end; ++t) { + const float step = softplus(ldt(&dt, off(dt, t, head, 0, 1)) + bias); + const float decay = std::exp(step * A); + for (int64_t d = 0; d < Nst; ++d) { + b[d] = ldt(&B, off(B, t, grp, d, Nst)); + c[d] = ldt(&C, off(C, t, grp, d, Nst)); + } + const int64_t f = 1 + (t - begin) * rec; + if (anchor && verify) { + stt(&state, factor_at(f), decay); + for (int64_t d = 0; d < Nst; ++d) stt(&state, factor_at(f + 1 + P + d), b[d]); + } + for (int64_t e = 0; e < P; ++e) { + const float xe = ldt(&x, off(x, t, head, e, P)); + const float u = step * xe; + if (anchor && verify) stt(&state, factor_at(f + 1 + e), u); + float result = 0; + for (int64_t d = 0; d < Nst; ++d) { + float& s = S[e * Nst + d]; + s = s * decay + u * b[d]; + result += s * c[d]; + } + stt(&out, off(out, t, head, e, P), result + skip * xe); + } + if ((verify && !anchor) || (!verify && t + 1 == end)) { + const int64_t write = + ld_int(idx.dtype, idx.data, + seq * idx.stride[0] + (verify ? t - begin : 0) * idx.stride[1]); + if (write >= 0) + for (int64_t e = 0; e < P; ++e) + for (int64_t d = 0; d < Nst; ++d) + stt(&state, + write * state.stride[0] + head * state.stride[1] + + e * state.stride[2] + d * state.stride[3], + S[e * Nst + d]); + } + } + if (anchor) stt(&state, factor_at(0), verify ? (float)(end - begin) : 0.0f); + } + return RAD_OK; +} diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index 570517f6..59e3ba5f 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -411,6 +411,152 @@ TEST(kda_prefill_commits_final_state_and_uses_absolute_cu_offsets) { CHECK_EQ(out.at(2), 0.0f); } +/* dt = 0 with no bias gives softplus(0) = ln 2, so A_log 0 and ln 2 decay by exactly 1/2 and 1/4. */ +TEST(ssd_prefill_decays_per_head_and_adds_the_skip) { + const float l2 = std::log(2.0f); + T x(RAD_F32, {2, 2, 1}); x.f({1, 2, 3, 4}); + T B(RAD_F32, {2, 1, 2}); B.f({1, 0, 0, 1}); + T C(RAD_F32, {2, 1, 2}); C.f({1, 1, 1, 0}); + T dt(RAD_F32, {2, 2}), dtb(RAD_F32, {2}); + T alog(RAD_F32, {2}); alog.f({0, l2}); + T D(RAD_F32, {2}); D.f({1, 0}); + T state(RAD_F32, {1, 2, 1, 2}); state.f({9, 9, 9, 9}); + T idx(RAD_I32, {1, 1}); idx.n({0}); + T cu(RAD_I32, {2}); cu.n({0, 2}); + T init(RAD_I32, {1}); init.n({0}); + T out(RAD_F32, {2, 2, 1}); + A a; a.t(x).t(B).t(C).t(dt).t(alog).t(dtb).t(D).t(state).t(idx).t(cu).tnull().t(init).t(out) + .i("M", 2).i("heads", 2).i("head_dim", 1).i("d_state", 2).i("groups", 1) + .s("mode", "prefill").s("dtype", "f32"); + REQUIRE_EQ(run("ssd_update", a), RAD_OK); + /* has_init 0 ignores the 9s; head 0 carries D = 1, head 1 none. */ + CHECK_NEAR(out.at(0), l2 + 1, 3e-6); + CHECK_NEAR(out.at(1), 2 * l2, 3e-6); + CHECK_NEAR(out.at(2), l2 / 2 + 3, 3e-6); + CHECK_NEAR(out.at(3), l2 / 2, 3e-6); + CHECK_NEAR(state.at(0), l2 / 2, 3e-6); + CHECK_NEAR(state.at(1), 3 * l2, 3e-6); + CHECK_NEAR(state.at(2), l2 / 2, 3e-6); + CHECK_NEAR(state.at(3), 4 * l2, 3e-6); + /* Above softplus's threshold of 20 dt passes through: e^{-25} is zero to f32 at this scale. */ + dt.f({25, 0, 0, 0}); + REQUIRE_EQ(run("ssd_update", a), RAD_OK); + CHECK_NEAR(out.at(0), 25 + 1, 3e-5); + a.ps[4].ival = 3; + CHECK_EQ(run("ssd_update", a), RAD_E_SHAPE); +} + +TEST(ssd_candidate_states_restore_the_accepted_prefix) { + const float l2 = std::log(2.0f); + T x(RAD_F32, {2, 1, 1}); x.f({2, 2}); + T B(RAD_F32, {2, 1, 1}); B.f({1, 1}); + T C(RAD_F32, {2, 1, 1}); C.f({1, 1}); + T dt(RAD_F32, {2, 1}), alog(RAD_F32, {1}), dtb(RAD_F32, {1}), D(RAD_F32, {1}); + T state(RAD_F32, {3, 1, 1, 1}); state.f({4, 0, 123}); + T idx(RAD_I32, {1, 2}); idx.n({0, 1}); + T cu(RAD_I32, {2}); cu.n({0, 2}); + T accepted(RAD_I32, {1}); accepted.n({1}); + T out(RAD_F32, {2, 1, 1}); + A a; a.t(x).t(B).t(C).t(dt).t(alog).t(dtb).t(D).t(state).t(idx).t(cu).t(accepted).tnull().t(out) + .i("M", 2).i("heads", 1).i("head_dim", 1).i("d_state", 1).i("groups", 1) + .s("mode", "verify").s("dtype", "f32"); + REQUIRE_EQ(run("ssd_update", a), RAD_OK); + CHECK_NEAR(out.at(0), 2 + 2 * l2, 3e-6); + CHECK_NEAR(out.at(1), 1 + 3 * l2, 3e-6); + CHECK_NEAR(state.at(0), 2 + 2 * l2, 3e-6); + CHECK_NEAR(state.at(1), 1 + 3 * l2, 3e-6); + CHECK_EQ(state.at(2), 123.0f); + /* The next step keeps only candidate 0 and reads its slot. */ + cu.n({0, 1}); + REQUIRE_EQ(run("ssd_update", a), RAD_OK); + CHECK_NEAR(out.at(0), 1 + 3 * l2, 3e-6); + /* Keeping both instead starts from slot 1. */ + state.f({4, 1 + 3 * l2, 123}); + accepted.n({2}); + REQUIRE_EQ(run("ssd_update", a), RAD_OK); + CHECK_NEAR(out.at(0), 0.5f * (1 + 3 * l2) + 2 * l2, 3e-6); + accepted.n({3}); + CHECK_EQ(run("ssd_update", a), RAD_E_SHAPE); +} + +/* The anchor form against the per-candidate one over two verify windows: the same outputs, and the + * committed state after a window is the candidate state its accepted prefix left, bit for bit. */ +TEST(ssd_anchor_replays_only_the_accepted_prefix_of_the_previous_window) { + constexpr int H = 2, P = 8, N = 16, W = 3; + for (int accepted : { 1, 2, 3 }) { + T x(RAD_F32, { W, H, P }), B(RAD_F32, { W, 1, N }), C(RAD_F32, { W, 1, N }); + T dt(RAD_F32, { W, H }), al(RAD_F32, { H }), dtb(RAD_F32, { H }), D(RAD_F32, { H }); + T anchor(RAD_F32, { 2, H, P, N }), candidate(RAD_F32, { W, H, P, N }); + T ai(RAD_I32, { 1, 6 }), ci(RAD_I32, { 1, W }), cu(RAD_I32, { 2 }), na(RAD_I32, { 1 }), + init(RAD_I32, { 1 }); + T ao(RAD_F32, { W, H, P }), co(RAD_F32, { W, H, P }); + std::vector v(W * H * P); + for (size_t j = 0; j < v.size(); ++j) v[j] = (float)((int)(j % 13) - 6) * 0.125f; + x.f(v); + std::vector bc(W * N); + for (size_t j = 0; j < bc.size(); ++j) bc[j] = (float)((int)(j % 7) - 3) * 0.25f; + B.f(bc); + for (size_t j = 0; j < bc.size(); ++j) bc[j] = (float)((int)(j % 5) - 2) * 0.5f; + C.f(bc); + dt.f({ 0.5f, -1, 0, 1, -0.5f, 2 }); + al.f({ 0, -0.5f }); + dtb.f({ 0.25f, -0.25f }); + D.f({ 1, 0.5f }); + anchor.f(std::vector(2 * H * P * N, 0)); + candidate.f(std::vector(W * H * P * N, 0)); + ai.n({ 0, 0, 0, 1, 1, 1 }); + ci.n({ 0, 1, 2 }); + cu.n({ 0, W }); + na.n({ 1 }); + init.n({ 1 }); + auto args = [&](T& state, T& idx, T& out, bool anc) { + A a; + a.t(x).t(B).t(C).t(dt).t(al).t(dtb).t(D).t(state).t(idx).t(cu).t(na).t(init).t(out) + .i("M", W).i("heads", H).i("head_dim", P).i("d_state", N).i("groups", 1) + .s("mode", "verify").s("dtype", "f32"); + if (anc) a.s("state_form", "anchor"); + return a; + }; + A a = args(anchor, ai, ao, true), c = args(candidate, ci, co, false); + REQUIRE_EQ(run("ssd_update", a), RAD_OK); + REQUIRE_EQ(run("ssd_update", c), RAD_OK); + for (int j = 0; j < W * H * P; ++j) CHECK_EQ(ao.at(j), co.at(j)); + /* Nothing is committed before the next step says how much was accepted. */ + for (int j = 0; j < H * P * N; ++j) CHECK_EQ(anchor.at(j), 0); + std::vector committed(H * P * N); + for (int j = 0; j < H * P * N; ++j) + committed[j] = candidate.at((accepted - 1) * H * P * N + j); + na.n({ accepted }); + REQUIRE_EQ(run("ssd_update", a), RAD_OK); + REQUIRE_EQ(run("ssd_update", c), RAD_OK); + for (int j = 0; j < W * H * P; ++j) CHECK_EQ(ao.at(j), co.at(j)); + for (int j = 0; j < H * P * N; ++j) CHECK_EQ(anchor.at(j), committed[j]); + const auto saved = anchor.mem; + na.n({ 4 }); + CHECK_EQ(run("ssd_update", a), RAD_E_SHAPE); + CHECK(anchor.mem == saved); + } +} + +/* Head h reads group h / (heads / groups): heads 0 and 1 share group 0, not heads 0 and 2. */ +TEST(ssd_heads_read_their_group_in_blocks) { + const float l2 = std::log(2.0f); + T x(RAD_F32, {1, 4, 1}); x.f({1, 1, 1, 1}); + T B(RAD_F32, {1, 2, 2}); B.f({1, 0, 0, 1}); + T C(RAD_F32, {1, 2, 2}); C.f({1, 0, 0, 2}); + T dt(RAD_F32, {1, 4}), alog(RAD_F32, {4}), dtb(RAD_F32, {4}), D(RAD_F32, {4}); + T state(RAD_F32, {1, 4, 1, 2}); + T idx(RAD_I32, {1, 1}); idx.n({0}); + T cu(RAD_I32, {2}); cu.n({0, 1}); + T out(RAD_F32, {1, 4, 1}); + A a; a.t(x).t(B).t(C).t(dt).t(alog).t(dtb).t(D).t(state).t(idx).t(cu).tnull().tnull().t(out) + .i("M", 1).i("heads", 4).i("head_dim", 1).i("d_state", 2).i("groups", 2) + .s("mode", "prefill").s("dtype", "f32"); + REQUIRE_EQ(run("ssd_update", a), RAD_OK); + const float want[] = {l2, l2, 2 * l2, 2 * l2}; + for (int h = 0; h < 4; ++h) CHECK_NEAR(out.at(h), want[h], 3e-6); +} + TEST(mla_attention_reads_one_latent_and_masks_the_last_selected_page) { T q(RAD_F32, { 1, 1, 2 }), kv(RAD_F32, { 2, 1, 2, 2 }), bt(RAD_I32, { 1, 2 }); T len(RAD_I32, { 1 }), out(RAD_F32, { 1, 1, 2 }); @@ -1049,7 +1195,7 @@ TEST(op_vocabulary) { "mtp_enter", "mhc_pre", "mhc_pre_partial", "mhc_pre_finish", "mhc_post", "mhc_contract", "swiglu_clamped", "router_sigmoid_topk", "dsa_pool", "dsa_query", "dsa_score", "mla_attn", "mla_project", "gemm_nt_f32", "swiglu_step", "router_sigmoid_group_topk", "mla_attn_paged", - "kda_update", + "kda_update", "ssd_update", "layernorm", "add", "mul", "mul_weight", "silu_mul", "gelu_mul", "act_mul", "seg_mean", "seg_softmax_pool", "seg_mean_bf16_sum", @@ -1059,6 +1205,8 @@ TEST(op_vocabulary) { "seg_sinusoid", "attn_local_rel", "gelu", "silu", "sigmoid", "logit_softcap", "scale", "fill", "gather_rows", "scatter_rows", "ngram_ids", "ple_gate", "ple_conv", "causal_conv1d", + /* Mamba-2's conv1d (Nemotron-3.5-Bolt): ple_conv with a bias inside the silu. */ + "ple_conv_bias", "embed_lookup_q", "cast", "scale_rows", "softmax", @@ -1726,6 +1874,34 @@ TEST(op_ple_gate) { * accumulate to 100a + 10b + c and any misread tap changes a digit. silu is applied after, so * the expectation is silu of that number. */ +/* Mamba-2's conv1d: ple_conv_bias at dilation one and with no residual. The bias + * must sit inside the activation, so silu(b + conv) and not b + silu(conv). */ +TEST(op_ple_conv_bias_is_inside_the_silu) { + auto silu = [](float v) { return v / (1.0f + std::exp(-v)); }; + T x(RAD_F32, {3, 2}); x.f({ 1, 10, 2, 20, 3, 30 }); + T w(RAD_F32, {2, 2}); w.f({ 1, 1, 0.5f, -1 }); + T cs(RAD_F32, {1, 2, 1}); cs.f({ 4, 8 }); + T cu(RAD_I32, {2}); cu.n({ 0, 3 }); + T ci(RAD_I32, {1}); ci.n({ 0 }); + T hi(RAD_I32, {1}); hi.n({ 1 }); + T y(RAD_F32, {3, 2}); + T b(RAD_F32, {2}); b.f({ -2, 3 }); + A a; a.t(x).t(w).t(cs).t(cu).tnull().t(ci).t(hi).tnull().t(b).t(y) + .i("M", 3).i("n", 2).i("width", 2).i("dilation", 1).s("dtype", "f32"); + CHECK_OK(run("ple_conv_bias", a)); + /* channel 0: taps (prev, cur) * (1, 1) - 2; channel 1: (prev, cur) * (0.5, -1) + 3 */ + CHECK_NEAR(y.at(0), silu(4 + 1 - 2.0f), 1e-5); + CHECK_NEAR(y.at(1), silu(0.5f * 8 - 10 + 3.0f), 1e-5); + CHECK_NEAR(y.at(2), silu(1 + 2 - 2.0f), 1e-5); + CHECK_NEAR(y.at(5), silu(0.5f * 20 - 30 + 3.0f), 1e-5); + /* the window keeps the inputs, not the biased sums */ + CHECK_EQ(cs.at(0), 3.0f); + CHECK_EQ(cs.at(1), 30.0f); + T bad(RAD_F32, {3}); + a.ts[8] = bad.t; + CHECK_EQ(run("ple_conv_bias", a), RAD_E_SHAPE); +} + TEST(op_ple_conv) { auto silu = [](float v) { return v / (1.0f + std::exp(-v)); }; const int n = 1, wid = 3, dil = 2, hist = (wid - 1) * dil; /* 4 */ @@ -10098,6 +10274,8 @@ std::vector geometries() { G("scatter_rows", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")), G("ple_gate", "M", 2, a.i("M", R).i("n", 8).i("hc", 2).d("eps", 1e-6).s("dtype", "f32")), G("ple_conv", "M", 6, a.i("M", R).i("n", 8).i("width", 3).i("dilation", 2).s("dtype", "f32")), + G("ple_conv_bias", "M", 6, a.i("M", R).i("n", 8).i("width", 4).i("dilation", 1) + .s("dtype", "f32")), G("causal_conv1d", "M", 6, a.i("M", R).i("n", 8).i("width", 4).s("dtype", "f32")), G("ngram_ids", "M", 4, a.i("M", R).i("heads", 2).i("ngram", 3).i("eos", 1)), G("cast", "M", 3, a.i("M", R).i("n", 8).s("from", "f32").s("to", "bf16")), @@ -10296,6 +10474,8 @@ std::vector geometries() { G("kda_update", "M", 3, a.i("M", R).i("heads", 2).i("head_k", 8).i("head_v", 8) .d("lower_bound", -5.0).d("scale", 0.35).d("l2_eps", 1e-6) .s("mode", "prefill").s("dtype", "f32")), + G("ssd_update", "M", 3, a.i("M", R).i("heads", 4).i("head_dim", 4).i("d_state", 8) + .i("groups", 2).s("mode", "prefill").s("dtype", "f32")), G("mla_attn", "M", 3, a.i("M", R).i("latent_dim", 8).i("heads", 2).i("blocks", 2) .i("block_size", 4).d("scale", 0.125).s("dtype", "f32")), G("mla_project", "M", 3, a.i("M", R).i("heads", 2).i("head_dim", 4).i("latent_dim", 6)