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:
keptn42 committed 2026-11-04 22:08:52 +01:00
1 parent 3b278dcec3
commit 63416510a0
21 files changed
+1362 -11

No files matched your search

+2
View File
@@ -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|"
+20 -4
View File
@@ -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),
+3
View File
@@ -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*);
+55
View File
@@ -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,
+174
View File
@@ -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<std::vector<int64_t>> 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<std::vector<uint8_t>> bytes(13), visible(13);
std::vector<RadTensor> host, device;
std::vector<void*> 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<int> 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<RadParam> 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<uint8_t> 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 }) {
+20
View File
@@ -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");
+282
View File
@@ -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 <hip/hip_runtime.h>
#include "r4d_args.h"
#include "r4d_common.h"
#include "r4d_emit.h"
#include <climits>
#include <cmath>
#include <algorithm>
#include <cstring>
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 <int R>
__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<long>(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<kRows>), 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); }