Archived
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.
This commit is contained in:
1 parent
3b278dcec3
commit
63416510a0
21 files changed
+1362
-11
No files matched your search
@@ -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);
|
||||
|
||||
+14
-2
@@ -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;
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 <cmath>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
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<float> 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;
|
||||
}
|
||||
Reference in new issue
Block a user