Commit d39c260e6 for llama.cpp
commit d39c260e6ced1f8199e70a3cdebdb69edf9ecd04
Author: Jeff Bolz <jbolz@nvidia.com>
Date: Thu Dec 3 07:21:52 2026 -0600
vulkan: SSM_SCAN optimizations and coopmat2 support (#32916)
* vulkan: SSM_SCAN optimizations and coopmat2 support
Add a prefill shader that does multiple rows at a time, prefetches/stages
through shared memory. The subgroup reduction only runs once per block of tokens.
Doing multiple rows at a time amortizes some of the load overhead and stalls.
Uses larger (vec4) loads. Spreads the "A"/softplus work across threads rather than
repeating on every thread.
Add a coopmat2 shader that implements the chunked matrix form, similar to CUDA
and Metal backends. Each workgroup does 32 rows of a head. Claude verified that
the KLD relative to the fp32 baseline was no worse than CUDA's SSD path relative
to its fp32 baseline.
Add more test coverage for different layouts/views/alignment.
* allow d_state 96 in the fast shaders
* vulkan: SSM_SCAN: address review feedback
- The prefill shader uses chunks of 8 tokens at d_state 128. 16 used
enough shared memory to lower the occupancy on AMD.
- constexpr constants instead of defines. The ones only the coopmat2
shader uses, and its shared memory size, are inside its #if, so that
builds without coopmat2 have no unused constants.
- The prefill shaders no longer need 16-byte aligned binding offsets,
which AMD and Intel only align to 4 bytes.
- The prefill shader is disabled on Intel, where it spills and is slower
than the per-token shader.
- Fewer comments.
Assisted-by: Claude Opus 5.5
* vulkan: SSM_SCAN: use log1p in softplus
softplus(dt) computed log(1 + exp(dt)), which loses precision when
exp(dt) is small. The scan shaders now use the log1p helper from
utils.glsl, as the CPU and CUDA backends use log1pf.
Assisted-by: Claude Opus 5.5
diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h b/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h
index c64d67ec2..d3d2d0dba 100644
--- a/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h
+++ b/ggml/src/ggml-vulkan/ggml-vulkan-push-constants.h
@@ -825,6 +825,7 @@ struct vk_op_ssm_scan_push_constants {
uint32_t nb02, nb03, nb12, nb13;
uint32_t nb21, nb22, nb31;
uint32_t nb42, nb43, nb52, nb53;
+ uint32_t off0, off1, off2, off3, off4, off5, off6; // bytes from each source's binding to its data
uint32_t s_off;
uint32_t n_head, d_head, n_group, n_tok;
uint32_t n_seq, K;
diff --git a/ggml/src/ggml-vulkan/ggml-vulkan-types.h b/ggml/src/ggml-vulkan/ggml-vulkan-types.h
index 1514e228f..27ce14ca5 100644
--- a/ggml/src/ggml-vulkan/ggml-vulkan-types.h
+++ b/ggml/src/ggml-vulkan/ggml-vulkan-types.h
@@ -829,6 +829,7 @@ struct vk_device_struct {
bool coopmat2;
bool coopmat2_bf16_support {};
bool coopmat2_gdn_support {};
+ bool coopmat2_ssm_support {};
bool coopmat2_decode_vector;
uint32_t coopmat2_reserved_shmem {};
@@ -1047,6 +1048,11 @@ struct vk_device_struct {
vk_pipeline pipeline_ssm_scan_f32_d96;
vk_pipeline pipeline_ssm_scan_f32_d128;
vk_pipeline pipeline_ssm_scan_f32_d256;
+ vk_pipeline pipeline_ssm_scan_prefill_f32_d96;
+ vk_pipeline pipeline_ssm_scan_prefill_f32_d128;
+ vk_pipeline pipeline_ssm_scan_prefill_f32_d256;
+ vk_pipeline pipeline_ssm_scan_cm2_f32_d96;
+ vk_pipeline pipeline_ssm_scan_cm2_f32_d128;
vk_pipeline pipeline_ssm_conv_f32;
vk_pipeline pipeline_ssm_conv_silu_f32;
vk_pipeline pipeline_ssm_conv_bias_silu_f32;
diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp
index e80fb170d..939ddab8d 100644
--- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp
+++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp
@@ -1759,6 +1759,61 @@ static uint32_t ggml_vk_gated_delta_net_shmem_size(uint32_t v, bool coopmat2, bo
return qk + state + p_inv + delta_solved + lower + scan;
}
+// Specialization constants of ssm_scan_cm2.comp and ssm_scan_prefill.comp.
+static constexpr uint32_t GGML_VK_SSM_CM2_T = 32;
+static constexpr uint32_t GGML_VK_SSM_CM2_ROWS = 32;
+static constexpr uint32_t GGML_VK_SSM_PREFILL_WG_SIZE = 128;
+static constexpr uint32_t GGML_VK_SSM_PREFILL_LPR = 16;
+static constexpr uint32_t GGML_VK_SSM_PREFILL_R = 2;
+
+#if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
+static constexpr uint32_t GGML_VK_SSM_CM2_WG_SIZE = 128;
+static constexpr uint32_t GGML_VK_SSM_CM2_PAD = 8;
+
+static uint32_t ggml_vk_ssm_scan_cm2_shmem_size(uint32_t d_state) {
+ const uint32_t T = GGML_VK_SSM_CM2_T;
+ const uint32_t rows = GGML_VK_SSM_CM2_ROWS;
+ const uint32_t pad = GGML_VK_SSM_CM2_PAD;
+ const uint32_t f16_size = sizeof(ggml_fp16_t);
+
+ const uint32_t c_b = 2 * T * (d_state + pad) * f16_size;
+ const uint32_t s = rows * (d_state + pad) * f16_size;
+ const uint32_t x = 3 * T * (rows + pad) * f16_size;
+ const uint32_t m = T * (T + pad) * f16_size;
+ const uint32_t scan = 2 * T * sizeof(float);
+
+ return c_b + s + x + m + scan;
+}
+#endif
+
+// d_state must be a multiple of 4 * LPR.
+static constexpr uint32_t ggml_vk_ssm_scan_prefill_lpr(uint32_t d_state) {
+ return d_state % (4 * GGML_VK_SSM_PREFILL_LPR) == 0 ? GGML_VK_SSM_PREFILL_LPR : GGML_VK_SSM_PREFILL_LPR / 2;
+}
+
+static constexpr uint32_t ggml_vk_ssm_scan_prefill_rows(uint32_t d_state) {
+ return GGML_VK_SSM_PREFILL_WG_SIZE / ggml_vk_ssm_scan_prefill_lpr(d_state) * GGML_VK_SSM_PREFILL_R;
+}
+
+// Tokens per chunk. 16 at d_state 128 uses enough shared memory to lower the occupancy on AMD.
+static constexpr uint32_t ggml_vk_ssm_scan_prefill_tokens(uint32_t d_state) {
+ return d_state == 96 ? 16 : 8;
+}
+
+template <uint32_t d_state>
+static constexpr uint32_t ggml_vk_ssm_scan_prefill_shmem_size() {
+ constexpr uint32_t T = ggml_vk_ssm_scan_prefill_tokens(d_state);
+ constexpr uint32_t rows = ggml_vk_ssm_scan_prefill_rows(d_state);
+ constexpr uint32_t wg = GGML_VK_SSM_PREFILL_WG_SIZE;
+ constexpr uint32_t lpr = ggml_vk_ssm_scan_prefill_lpr(d_state);
+ static_assert((lpr & (lpr - 1)) == 0 && wg % lpr == 0);
+ static_assert(d_state % (4 * lpr) == 0);
+ static_assert((T * d_state / 4) % wg == 0 && rows % 4 == 0 && T * rows / 4 <= wg);
+ static_assert((T * GGML_VK_SSM_PREFILL_R) % lpr == 0);
+
+ return 2 * T * (2 * d_state + rows + 1) * sizeof(float);
+}
+
static bool ggml_vk_matmul_shmem_support(const vk_device& device, const std::vector<uint32_t>& warptile, bool mul_mat_id, ggml_type src0_type) {
uint32_t lut_size = 0;
@@ -4467,6 +4522,35 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_f32_d256, "ssm_scan_256_f32", ssm_scan_f32_len, ssm_scan_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1}, {256, device->subgroup_size, 256}, 1, true, true);
}
+ // The prefill shader spills and is slower than the per-token shader on Intel.
+ if (device->vendor_id != VK_VENDOR_ID_INTEL &&
+ device->subgroup_shuffle && device->subgroup_require_full_support &&
+ device->subgroup_size >= GGML_VK_SSM_PREFILL_LPR &&
+ device->properties.limits.maxComputeWorkGroupInvocations >= GGML_VK_SSM_PREFILL_WG_SIZE &&
+ device->properties.limits.maxComputeWorkGroupSize[0] >= GGML_VK_SSM_PREFILL_WG_SIZE) {
+ const uint32_t max_shmem = device->properties.limits.maxComputeSharedMemorySize;
+ if (ggml_vk_ssm_scan_prefill_shmem_size<96>() <= max_shmem) {
+ ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_prefill_f32_d96, "ssm_scan_prefill_d96_f32", ssm_scan_prefill_f32_len, ssm_scan_prefill_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1},
+ {GGML_VK_SSM_PREFILL_WG_SIZE, 96, ggml_vk_ssm_scan_prefill_tokens(96), ggml_vk_ssm_scan_prefill_lpr(96), GGML_VK_SSM_PREFILL_R}, 1, true, true);
+ }
+ if (ggml_vk_ssm_scan_prefill_shmem_size<128>() <= max_shmem) {
+ ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_prefill_f32_d128, "ssm_scan_prefill_d128_f32", ssm_scan_prefill_f32_len, ssm_scan_prefill_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1},
+ {GGML_VK_SSM_PREFILL_WG_SIZE, 128, ggml_vk_ssm_scan_prefill_tokens(128), ggml_vk_ssm_scan_prefill_lpr(128), GGML_VK_SSM_PREFILL_R}, 1, true, true);
+ }
+ if (ggml_vk_ssm_scan_prefill_shmem_size<256>() <= max_shmem) {
+ ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_prefill_f32_d256, "ssm_scan_prefill_d256_f32", ssm_scan_prefill_f32_len, ssm_scan_prefill_f32_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1},
+ {GGML_VK_SSM_PREFILL_WG_SIZE, 256, ggml_vk_ssm_scan_prefill_tokens(256), ggml_vk_ssm_scan_prefill_lpr(256), GGML_VK_SSM_PREFILL_R}, 1, true, true);
+ }
+ }
+#if defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
+ if (device->coopmat2 && device->coopmat2_ssm_support) {
+ ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_cm2_f32_d96, "ssm_scan_cm2_d96_f32", ssm_scan_f32_cm2_len, ssm_scan_f32_cm2_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1},
+ {GGML_VK_SSM_CM2_WG_SIZE, 96, GGML_VK_SSM_CM2_T, GGML_VK_SSM_CM2_ROWS, GGML_VK_SSM_CM2_PAD}, 1, true, true, GGML_VK_SSM_CM2_T);
+ ggml_vk_create_pipeline(device, device->pipeline_ssm_scan_cm2_f32_d128, "ssm_scan_cm2_d128_f32", ssm_scan_f32_cm2_len, ssm_scan_f32_cm2_data, "main", 8, sizeof(vk_op_ssm_scan_push_constants), {1, 1, 1},
+ {GGML_VK_SSM_CM2_WG_SIZE, 128, GGML_VK_SSM_CM2_T, GGML_VK_SSM_CM2_ROWS, GGML_VK_SSM_CM2_PAD}, 1, true, true, GGML_VK_SSM_CM2_T);
+ }
+#endif
+
ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_f32, "ssm_conv_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 4, sizeof(vk_op_ssm_conv_push_constants), {32, 16, 1}, {32, 16, 0, 0}, 1);
ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_silu_f32, "ssm_conv_silu_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 4, sizeof(vk_op_ssm_conv_push_constants), {32, 16, 1}, {32, 16, 0, 1}, 1);
ggml_vk_create_pipeline(device, device->pipeline_ssm_conv_bias_silu_f32, "ssm_conv_bias_silu_f32", ssm_conv_f32_len, ssm_conv_f32_data, "main", 4, sizeof(vk_op_ssm_conv_push_constants), {32, 16, 1}, {32, 16, 1, 1}, 1);
@@ -5448,6 +5532,16 @@ vk_device ggml_vk_get_device(size_t idx) {
found_fp32_128 = true;
}
}
+ // The SSM scan's matrix dimensions are d_state (96 or 128), T and ROWS.
+ const auto ssm_dims_ok = [](uint32_t g) {
+ return g != 0 && 96 % g == 0 && 128 % g == 0 && GGML_VK_SSM_CM2_T % g == 0 && GGML_VK_SSM_CM2_ROWS % g == 0;
+ };
+ if (prop.workgroupInvocations == GGML_VK_SSM_CM2_WG_SIZE &&
+ prop.CType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
+ prop.ResultType == VK_COMPONENT_TYPE_FLOAT32_KHR &&
+ ssm_dims_ok(prop.MGranularity) && ssm_dims_ok(prop.NGranularity) && ssm_dims_ok(prop.KGranularity)) {
+ device->coopmat2_ssm_support = true;
+ }
if (prop.workgroupInvocations == 256 &&
prop.MGranularity <= 32 &&
prop.NGranularity <= 32 &&
@@ -5493,6 +5587,15 @@ vk_device ggml_vk_get_device(size_t idx) {
#endif
}
}
+ // The shared memory of d_state 128 also covers 96.
+ device->coopmat2_ssm_support = device->coopmat2_ssm_support &&
+ coopmat2_props.cooperativeMatrixWorkgroupScopeMaxWorkgroupSize >= GGML_VK_SSM_CM2_WG_SIZE &&
+ device->properties.limits.maxComputeWorkGroupInvocations >= GGML_VK_SSM_CM2_WG_SIZE &&
+ device->properties.limits.maxComputeWorkGroupSize[0] >= GGML_VK_SSM_CM2_WG_SIZE &&
+ device->subgroup_size_control &&
+ device->subgroup_min_size <= GGML_VK_SSM_CM2_T && GGML_VK_SSM_CM2_T <= device->subgroup_max_size &&
+ uint64_t(ggml_vk_ssm_scan_cm2_shmem_size(128)) + coopmat2_props.cooperativeMatrixWorkgroupScopeReservedSharedMemory <=
+ device->properties.limits.maxComputeSharedMemorySize;
device->coopmat2_gdn_support = device->coopmat2_gdn_support &&
coopmat2_props.cooperativeMatrixWorkgroupScopeMaxWorkgroupSize >= 128 &&
device->properties.limits.maxComputeWorkGroupInvocations >= 128 &&
@@ -12249,7 +12352,40 @@ void ggml_vk_ssm_scan(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_te
bool is_mamba2 = (src3->nb[1] == sizeof(float));
GGML_ASSERT(is_mamba2);
+ // The shaders add each source's offset from its aligned binding.
+ vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
+ vk_subbuffer src_buf[7] = {};
+ uint32_t src_off[7] = {};
+ for (int i = 0; i < 7 && dst->src[i] != nullptr; i++) {
+ src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i], true);
+ src_off[i] = get_misalign_bytes(ctx, dst->src[i]);
+ }
+
+ const uint32_t d_state = src0->ne[0];
+ const uint32_t K = (uint32_t) ggml_get_op_params_i32(dst, 0);
+
+ // The prefill shaders read x, B and C as vec4.
+ auto vec4_aligned = [&](int i) {
+ const ggml_tensor * t = dst->src[i];
+ return src_off[i] % 16 == 0 && t->nb[2] % 16 == 0 && t->nb[3] % 16 == 0;
+ };
+ const bool vec4 = head_dim % 4 == 0 && vec4_aligned(1) && vec4_aligned(4) && vec4_aligned(5);
vk_pipeline pipeline = ggml_vk_op_get_pipeline(ctx, src0, src1, src2, dst, dst->op);
+ uint32_t prefill_rows = 0;
+ if (vec4 && K <= 1 && n_tok >= 8) {
+ vk_pipeline cm2 = d_state == 96 ? ctx->device->pipeline_ssm_scan_cm2_f32_d96 :
+ d_state == 128 ? ctx->device->pipeline_ssm_scan_cm2_f32_d128 : nullptr;
+ vk_pipeline prefill = d_state == 96 ? ctx->device->pipeline_ssm_scan_prefill_f32_d96 :
+ d_state == 128 ? ctx->device->pipeline_ssm_scan_prefill_f32_d128 :
+ d_state == 256 ? ctx->device->pipeline_ssm_scan_prefill_f32_d256 : nullptr;
+ if (n_tok >= GGML_VK_SSM_CM2_T && cm2) {
+ pipeline = cm2;
+ prefill_rows = GGML_VK_SSM_CM2_ROWS;
+ } else if (prefill) {
+ pipeline = prefill;
+ prefill_rows = ggml_vk_ssm_scan_prefill_rows(d_state);
+ }
+ }
GGML_ASSERT(pipeline != nullptr);
ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
@@ -12263,24 +12399,19 @@ void ggml_vk_ssm_scan(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_te
(uint32_t)src3->nb[1],
(uint32_t)src4->nb[2], (uint32_t)src4->nb[3],
(uint32_t)src5->nb[2], (uint32_t)src5->nb[3],
+ src_off[0], src_off[1], src_off[2], src_off[3], src_off[4], src_off[5], src_off[6],
(uint32_t)s_off,
n_head, head_dim, n_group, n_tok,
- n_seq, (uint32_t) ggml_get_op_params_i32(dst, 0)
+ n_seq, K
};
- vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst);
- vk_subbuffer src_buf[7] = {};
- for (int i = 0; i < 7 && dst->src[i] != nullptr; i++) {
- src_buf[i] = ggml_vk_tensor_subbuffer(ctx, dst->src[i]);
- }
-
std::array<uint32_t, 3> elements;
-
- const uint32_t d_state = src0->ne[0];
- uint32_t num_subgroups = (d_state == 96 ? 128 : d_state) / ctx->device->subgroup_size;
- const uint32_t num_workgroups_x = CEIL_DIV(n_head * head_dim, num_subgroups);
- const uint32_t num_workgroups_y = n_seq;
- elements = { num_workgroups_x, num_workgroups_y, 1 };
+ if (prefill_rows) {
+ elements = { CEIL_DIV(head_dim, prefill_rows), n_head, n_seq };
+ } else {
+ const uint32_t num_subgroups = (d_state == 96 ? 128 : d_state) / ctx->device->subgroup_size;
+ elements = { CEIL_DIV(n_head * head_dim, num_subgroups), n_seq, 1 };
+ }
ggml_vk_dispatch_pipeline(ctx, subctx, pipeline,
{src_buf[0], src_buf[1], src_buf[2], src_buf[3], src_buf[4], src_buf[5], src_buf[6], dst_buf},
@@ -18082,14 +18213,14 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm
case GGML_OP_SSM_SCAN:
{
for (int i = 0; i < 6; i++) {
- if (op->src[i] && ggml_is_quantized(op->src[i]->type)) {
+ if (op->src[i]->type != GGML_TYPE_F32) {
return false;
}
}
if (op->src[6] && op->src[6]->type != GGML_TYPE_I32) {
return false;
}
- if (op->src[0]->type != GGML_TYPE_F32 || op->type != GGML_TYPE_F32) {
+ if (op->type != GGML_TYPE_F32) {
return false;
}
diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/ssm_scan.comp b/ggml/src/ggml-vulkan/vulkan-shaders/ssm_scan.comp
index ec9b9e60a..404aa836a 100644
--- a/ggml/src/ggml-vulkan/vulkan-shaders/ssm_scan.comp
+++ b/ggml/src/ggml-vulkan/vulkan-shaders/ssm_scan.comp
@@ -7,6 +7,7 @@
#endif
#include "types.glsl"
+#include "utils.glsl"
layout(constant_id = 0) const uint BLOCK_SIZE = 128;
layout(constant_id = 1) const uint SUBGROUP_SIZE = 32;
@@ -25,10 +26,12 @@ layout(binding = 5) readonly buffer Src5 { float C[]; };
layout(binding = 6) readonly buffer Src6 { int ids[]; };
layout(binding = 7) buffer Dst { float d[]; };
+// Strides and offsets are in bytes.
layout(push_constant) uniform PushConstants {
uint nb02; uint nb03; uint nb12; uint nb13;
uint nb21; uint nb22; uint nb31;
uint nb42; uint nb43; uint nb52; uint nb53;
+ uint off0; uint off1; uint off2; uint off3; uint off4; uint off5; uint off6;
uint s_off;
uint n_head;
uint d_head;
@@ -40,7 +43,7 @@ layout(push_constant) uniform PushConstants {
float softplus(float x) {
if (x <= 20.0) {
- return log(1.0 + exp(x));
+ return log1p(exp(x));
} else {
return x;
}
@@ -61,12 +64,12 @@ void main() {
const uint seq_idx = gl_WorkGroupID.y;
const uint group_off = (head_idx / (n_head / n_group)) * D_STATE * 4;
- const uint s0_base_idx = (uint(ids[seq_idx]) * nb03 + head_idx * nb02 + head_off * D_STATE) / 4;
- const uint x_base_idx = (seq_idx * nb13 + subgroup_idx * 4) / 4;
- const uint dt_base_idx = (seq_idx * nb22 + head_idx * 4) / 4;
- const uint A_base_idx = (head_idx * nb31) / 4;
- const uint B_base_idx = (seq_idx * nb43 + group_off) / 4;
- const uint C_base_idx = (seq_idx * nb53 + group_off) / 4;
+ const uint s0_base_idx = (off0 + uint(ids[off6 / 4 + seq_idx]) * nb03 + head_idx * nb02 + head_off * D_STATE) / 4;
+ const uint x_base_idx = (off1 + seq_idx * nb13 + subgroup_idx * 4) / 4;
+ const uint dt_base_idx = (off2 + seq_idx * nb22 + head_idx * 4) / 4;
+ const uint A_base_idx = (off3 + head_idx * nb31) / 4;
+ const uint B_base_idx = (off4 + seq_idx * nb43 + group_off) / 4;
+ const uint C_base_idx = (off5 + seq_idx * nb53 + group_off) / 4;
const uint y_base_idx = seq_idx * n_tok * n_head * d_head + subgroup_idx;
const uint s_base_idx = (s_off + seq_idx * nb03 + head_idx * nb02 + head_off * D_STATE) / 4;
diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/ssm_scan_cm2.comp b/ggml/src/ggml-vulkan/vulkan-shaders/ssm_scan_cm2.comp
new file mode 100644
index 000000000..01c430735
--- /dev/null
+++ b/ggml/src/ggml-vulkan/vulkan-shaders/ssm_scan_cm2.comp
@@ -0,0 +1,231 @@
+#version 450
+
+#extension GL_EXT_control_flow_attributes : require
+#extension GL_EXT_shader_explicit_arithmetic_types_float16 : require
+#extension GL_EXT_shader_explicit_arithmetic_types_int32 : require
+#extension GL_KHR_shader_subgroup_basic : require
+#extension GL_KHR_shader_subgroup_arithmetic : require
+#extension GL_KHR_shader_subgroup_shuffle : require
+#extension GL_KHR_memory_scope_semantics : require
+#extension GL_KHR_cooperative_matrix : require
+#extension GL_NV_cooperative_matrix2 : require
+
+#include "utils.glsl"
+
+// Mamba-2 selective scan in chunks of T tokens (SSD form). A workgroup computes
+// ROWS rows of one head, with the state S in an accumulator. Per chunk, with cs
+// the cumulative sum of dt * A:
+// M = (C * B^T) .* exp(cs_t - cs_s) for s <= t [T x T]
+// y = exp(cs_t) * (S * C^T) + X_dt^T * M^T [ROWS x T]
+// S = exp(cs_last) * S + X_w^T * B [ROWS x D_STATE]
+// where X_dt[s] = dt_s * x_s and X_w[s] = exp(cs_last - cs_s) * X_dt[s].
+
+layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in;
+layout(constant_id = 0) const uint WG_SIZE = 128;
+layout(constant_id = 1) const uint D_STATE = 128;
+layout(constant_id = 2) const uint T = 32; // tokens per chunk, one per subgroup lane
+layout(constant_id = 3) const uint ROWS = 32; // rows per workgroup
+layout(constant_id = 4) const uint PAD = 8;
+
+// Padded row strides of the shared arrays, in f16vec4.
+const uint D_STRIDE = (D_STATE + PAD) / 4;
+const uint ROWS_STRIDE = (ROWS + PAD) / 4;
+const uint T_STRIDE = (T + PAD) / 4;
+
+layout(binding = 0) readonly buffer Src0 { float s0[]; };
+layout(binding = 1) readonly buffer Src1 { vec4 x[]; };
+layout(binding = 2) readonly buffer Src2 { float dt[]; };
+layout(binding = 3) readonly buffer Src3 { float A[]; };
+layout(binding = 4) readonly buffer Src4 { vec4 B[]; };
+layout(binding = 5) readonly buffer Src5 { vec4 C[]; };
+layout(binding = 6) readonly buffer Src6 { int ids[]; };
+layout(binding = 7) writeonly buffer Dst { float d[]; };
+
+// Strides and offsets are in bytes.
+layout(push_constant) uniform PushConstants {
+ uint nb02; uint nb03; uint nb12; uint nb13;
+ uint nb21; uint nb22; uint nb31;
+ uint nb42; uint nb43; uint nb52; uint nb53;
+ uint off0; uint off1; uint off2; uint off3; uint off4; uint off5; uint off6;
+ uint s_off;
+ uint n_head;
+ uint d_head;
+ uint n_group;
+ uint n_tok;
+ uint n_seq;
+ uint K;
+};
+
+// coopMatLoad/Store offsets and strides are in f16vec4.
+shared f16vec4 sh_c[T * D_STRIDE]; // C [T x D_STATE]
+shared f16vec4 sh_b[T * D_STRIDE]; // B [T x D_STATE]
+shared f16vec4 sh_s[ROWS * D_STRIDE]; // S [ROWS x D_STATE]
+shared f16vec4 sh_x[2][T * ROWS_STRIDE]; // X_dt [T x ROWS], read after the second barrier
+shared f16vec4 sh_w[T * ROWS_STRIDE]; // X_w [T x ROWS]
+shared f16vec4 sh_m[T * T_STRIDE]; // M [T x T]
+shared float sh_cs[T]; // cs_t
+shared float sh_ecs[T]; // exp(cs_t)
+
+#define WG gl_ScopeWorkgroup
+#define MUA gl_MatrixUseA
+#define MUB gl_MatrixUseB
+#define MACC gl_MatrixUseAccumulator
+#define ROW gl_CooperativeMatrixLayoutRowMajor
+#define COL gl_CooperativeMatrixLayoutColumnMajor
+
+float softplus(float v) {
+ return v <= 20.0 ? log1p(exp(v)) : v;
+}
+
+float DecayMask(const in uint32_t r, const in uint32_t c, const in float cb) {
+ return c <= r ? cb * exp(sh_cs[r] - sh_cs[c]) : 0.0;
+}
+
+float ScaleCol(const in uint32_t r, const in uint32_t c, const in float v) {
+ return v * sh_ecs[c];
+}
+
+const uint NB = T * D_STATE / 4 / WG_SIZE; // vec4 of B (and C) per thread and chunk
+const uint NX = T * ROWS / 4 / WG_SIZE; // vec4 of x per thread and chunk
+
+// The next chunk's inputs.
+vec4 next_b[NB], next_c[NB], next_x[NX];
+float next_dt;
+
+// Reads past the end clamp to the last token and row.
+void load_chunk(const uint t0, const uint B_base, const uint C_base, const uint x_base, const uint dt_base, const uint row0) {
+ const uint tid = gl_LocalInvocationIndex;
+ [[unroll]] for (uint i = 0; i < NB; ++i) {
+ const uint e = tid + i * WG_SIZE;
+ const uint t = min(t0 + e / (D_STATE / 4), n_tok - 1);
+ next_b[i] = B[B_base + t * (nb42 / 16) + e % (D_STATE / 4)];
+ next_c[i] = C[C_base + t * (nb52 / 16) + e % (D_STATE / 4)];
+ }
+ [[unroll]] for (uint i = 0; i < NX; ++i) {
+ const uint e = tid + i * WG_SIZE;
+ const uint t = min(t0 + e / (ROWS / 4), n_tok - 1);
+ const uint q = min(e % (ROWS / 4), (d_head - row0) / 4 - 1);
+ next_x[i] = x[x_base + t * (nb12 / 16) + q];
+ }
+ next_dt = dt[dt_base + min(t0 + gl_SubgroupInvocationID, n_tok - 1) * (nb21 / 4)];
+}
+
+void main() {
+ const uint tid = gl_LocalInvocationIndex;
+ const uint lane = gl_SubgroupInvocationID;
+
+ const uint head = gl_WorkGroupID.y;
+ const uint seq = gl_WorkGroupID.z;
+ const uint row0 = gl_WorkGroupID.x * ROWS;
+ const uint rows = min(ROWS, d_head - row0);
+ const uint group = head / (n_head / n_group);
+ const float a = A[(off3 + head * nb31) / 4];
+
+ const uint B_base = (off4 + seq * nb43 + group * D_STATE * 4) / 16;
+ const uint C_base = (off5 + seq * nb53 + group * D_STATE * 4) / 16;
+ const uint x_base = (off1 + seq * nb13 + (head * d_head + row0) * 4) / 16;
+ const uint dt_base = (off2 + seq * nb22) / 4 + head;
+ const uint stride_y = n_head * d_head;
+ const uint y_base = seq * n_tok * stride_y + head * d_head + row0;
+
+ // Rows past the end load as zero and are not stored.
+ tensorLayoutNV<2, gl_CooperativeMatrixClampModeConstantNV> layout_s = createTensorLayoutNV(2, gl_CooperativeMatrixClampModeConstantNV);
+ layout_s = setTensorLayoutDimensionNV(layout_s, rows, D_STATE);
+ tensorLayoutNV<2, gl_CooperativeMatrixClampModeConstantNV> layout_y = createTensorLayoutNV(2, gl_CooperativeMatrixClampModeConstantNV);
+ layout_y = setTensorLayoutDimensionNV(layout_y, n_tok, rows);
+ layout_y = setTensorLayoutStrideNV(layout_y, stride_y, 1);
+ tensorViewNV<2, false, 1, 0> transpose = createTensorViewNV(2, false, 1, 0);
+
+ coopmat<float, WG, ROWS, D_STATE, MACC> S;
+ coopMatLoadTensorNV(S, s0, (off0 + uint(ids[off6 / 4 + seq]) * nb03 + head * nb02) / 4 + row0 * D_STATE, sliceTensorLayoutNV(layout_s, 0, ROWS, 0, D_STATE));
+
+ load_chunk(0, B_base, C_base, x_base, dt_base, row0);
+
+ uint buf = 0; // sh_x buffer of the current chunk
+ for (uint t0 = 0; t0 < n_tok; t0 += T) {
+ const uint valid = min(T, n_tok - t0);
+
+ // One token per lane. Every subgroup computes the scan, so the staging
+ // below can shuffle dt_t and cs_t without a barrier.
+ const float dts = lane < valid ? softplus(next_dt) : 0.0;
+ const float cs = subgroupInclusiveAdd(dts * a);
+ const float cs_last = subgroupShuffle(cs, T - 1);
+ if (gl_SubgroupID == 0) {
+ sh_cs[lane] = cs;
+ sh_ecs[lane] = exp(cs);
+ }
+
+ // Stage B and C as fp16, row t holding token t.
+ [[unroll]] for (uint i = 0; i < NB; ++i) {
+ const uint e = tid + i * WG_SIZE;
+ const uint o = (e / (D_STATE / 4)) * D_STRIDE + e % (D_STATE / 4);
+ sh_b[o] = f16vec4(next_b[i]);
+ sh_c[o] = f16vec4(next_c[i]);
+ }
+
+ // Stage X_dt and X_w. Tokens past the end have dt_t = 0.
+ [[unroll]] for (uint i = 0; i < NX; ++i) {
+ const uint e = tid + i * WG_SIZE;
+ const uint t = e / (ROWS / 4), q = e % (ROWS / 4);
+ const float dt_t = subgroupShuffle(dts, t);
+ const float cs_t = subgroupShuffle(cs, t);
+ sh_x[buf][t * ROWS_STRIDE + q] = f16vec4(next_x[i] * dt_t);
+ sh_w[t * ROWS_STRIDE + q] = f16vec4(next_x[i] * (exp(cs_last - cs_t) * dt_t));
+ }
+
+ if (t0 + T < n_tok) {
+ load_chunk(t0 + T, B_base, C_base, x_base, dt_base, row0);
+ }
+
+ coopMatStore(coopmat<float16_t, WG, ROWS, D_STATE, MACC>(S), sh_s, 0, D_STRIDE, ROW);
+ barrier();
+
+ // M = (C * B^T) .* decay [T x T]
+ {
+ coopmat<float, WG, T, T, MACC> cb = coopmat<float, WG, T, T, MACC>(0.0);
+ coopmat<float16_t, WG, T, D_STATE, MUA> c;
+ coopmat<float16_t, WG, D_STATE, T, MUB> b;
+ coopMatLoad(c, sh_c, 0, D_STRIDE, ROW);
+ coopMatLoad(b, sh_b, 0, D_STRIDE, COL);
+ cb = coopMatMulAdd(c, b, cb);
+ coopMatPerElementNV(cb, cb, DecayMask);
+ coopMatStore(coopmat<float16_t, WG, T, T, MACC>(cb), sh_m, 0, T_STRIDE, ROW);
+ }
+
+ // y = exp(cs_t) * (S * C^T) [ROWS x T]
+ coopmat<float, WG, ROWS, T, MACC> y = coopmat<float, WG, ROWS, T, MACC>(0.0);
+ {
+ coopmat<float16_t, WG, ROWS, D_STATE, MUA> s;
+ coopmat<float16_t, WG, D_STATE, T, MUB> c;
+ coopMatLoad(s, sh_s, 0, D_STRIDE, ROW);
+ coopMatLoad(c, sh_c, 0, D_STRIDE, COL);
+ y = coopMatMulAdd(s, c, y);
+ }
+ coopMatPerElementNV(y, y, ScaleCol);
+
+ // S = exp(cs_last) * S + X_w^T * B
+ {
+ coopmat<float16_t, WG, ROWS, T, MUA> w;
+ coopmat<float16_t, WG, T, D_STATE, MUB> b;
+ coopMatLoad(w, sh_w, 0, ROWS_STRIDE, COL);
+ coopMatLoad(b, sh_b, 0, D_STRIDE, ROW);
+ S *= exp(cs_last);
+ S = coopMatMulAdd(w, b, S);
+ }
+
+ barrier();
+
+ // y += X_dt^T * M^T
+ {
+ coopmat<float16_t, WG, ROWS, T, MUA> xm;
+ coopmat<float16_t, WG, T, T, MUB> m;
+ coopMatLoad(xm, sh_x[buf], 0, ROWS_STRIDE, COL);
+ coopMatLoad(m, sh_m, 0, T_STRIDE, COL);
+ y = coopMatMulAdd(xm, m, y);
+ }
+ coopMatStoreTensorNV(y, d, y_base, sliceTensorLayoutNV(layout_y, t0, T, 0, ROWS), transpose);
+ buf ^= 1;
+ }
+
+ coopMatStoreTensorNV(S, d, (s_off + seq * nb03 + head * nb02) / 4 + row0 * D_STATE, sliceTensorLayoutNV(layout_s, 0, ROWS, 0, D_STATE));
+}
diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/ssm_scan_prefill.comp b/ggml/src/ggml-vulkan/vulkan-shaders/ssm_scan_prefill.comp
new file mode 100644
index 000000000..b13c5d794
--- /dev/null
+++ b/ggml/src/ggml-vulkan/vulkan-shaders/ssm_scan_prefill.comp
@@ -0,0 +1,203 @@
+#version 450
+
+#extension GL_EXT_control_flow_attributes : require
+#extension GL_KHR_shader_subgroup_basic : require
+#extension GL_KHR_shader_subgroup_shuffle : require
+
+#include "utils.glsl"
+
+// Mamba-2 selective scan over several tokens (fp32). A workgroup computes ROWS
+// rows of one head, and the LPR lanes of a row group keep the state of R rows
+// in registers. Chunks of T tokens are staged in shared memory, and the sums
+// are reduced once per chunk.
+
+layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in;
+layout(constant_id = 0) const uint WG_SIZE = 128;
+layout(constant_id = 1) const uint D_STATE = 128;
+layout(constant_id = 2) const uint T = 16; // tokens per chunk
+layout(constant_id = 3) const uint LPR = 16; // lanes per row group
+layout(constant_id = 4) const uint R = 2; // rows per thread
+
+const uint S = D_STATE / LPR; // state values per lane and row
+const uint ROWS = WG_SIZE / LPR * R; // rows per workgroup
+const uint NB = T * D_STATE / 4 / WG_SIZE; // vec4 of B (and C) per thread and chunk
+const uint NF = T * R / LPR; // reduced sums per lane per chunk
+
+layout(binding = 0) readonly buffer Src0 { float s0[]; };
+layout(binding = 1) readonly buffer Src1 { vec4 x[]; };
+layout(binding = 2) readonly buffer Src2 { float dt[]; };
+layout(binding = 3) readonly buffer Src3 { float A[]; };
+layout(binding = 4) readonly buffer Src4 { vec4 B[]; };
+layout(binding = 5) readonly buffer Src5 { vec4 C[]; };
+layout(binding = 6) readonly buffer Src6 { int ids[]; };
+layout(binding = 7) writeonly buffer Dst { float d[]; };
+
+// Strides and offsets are in bytes.
+layout(push_constant) uniform PushConstants {
+ uint nb02; uint nb03; uint nb12; uint nb13;
+ uint nb21; uint nb22; uint nb31;
+ uint nb42; uint nb43; uint nb52; uint nb53;
+ uint off0; uint off1; uint off2; uint off3; uint off4; uint off5; uint off6;
+ uint s_off;
+ uint n_head;
+ uint d_head;
+ uint n_group;
+ uint n_tok;
+ uint n_seq;
+ uint K;
+};
+
+shared vec4 sh_b[2][T][D_STATE / 4];
+shared vec4 sh_c[2][T][D_STATE / 4];
+shared float sh_x[2][T][ROWS]; // x * dt
+shared float sh_da[2][T]; // exp(dt * A)
+
+float softplus(float v) {
+ return v <= 20.0 ? log1p(exp(v)) : v;
+}
+
+// The next chunk's inputs.
+vec4 next_b[NB], next_c[NB], next_x;
+float next_dt;
+
+// Reads past the end clamp to the last token and row. store_chunk gives
+// tokens past the end dt = 0 and dA = 1.
+void load_chunk(const uint t0, const uint B_base, const uint C_base, const uint x_base, const uint dt_base, const uint row0) {
+ const uint tid = gl_LocalInvocationIndex;
+ [[unroll]] for (uint i = 0; i < NB; ++i) {
+ const uint e = tid + i * WG_SIZE;
+ const uint t = min(t0 + e / (D_STATE / 4), n_tok - 1);
+ next_b[i] = B[B_base + t * (nb42 / 16) + e % (D_STATE / 4)];
+ next_c[i] = C[C_base + t * (nb52 / 16) + e % (D_STATE / 4)];
+ }
+ // 4 rows of x of one token, and that token's dt.
+ if (tid < T * ROWS / 4) {
+ const uint t = min(t0 + tid / (ROWS / 4), n_tok - 1);
+ const uint q = min(row0 / 4 + tid % (ROWS / 4), d_head / 4 - 1);
+ next_x = x[x_base + t * (nb12 / 16) + q];
+ next_dt = dt[dt_base + t * (nb21 / 4)];
+ }
+}
+
+void store_chunk(const uint b, const uint t0, const float a) {
+ const uint tid = gl_LocalInvocationIndex;
+ [[unroll]] for (uint i = 0; i < NB; ++i) {
+ const uint e = tid + i * WG_SIZE;
+ sh_b[b][e / (D_STATE / 4)][e % (D_STATE / 4)] = next_b[i];
+ sh_c[b][e / (D_STATE / 4)][e % (D_STATE / 4)] = next_c[i];
+ }
+ if (tid < T * ROWS / 4) {
+ const uint t = tid / (ROWS / 4), q = tid % (ROWS / 4);
+ const bool valid = t0 + t < n_tok;
+ const float dts = valid ? softplus(next_dt) : 0.0;
+ [[unroll]] for (uint k = 0; k < 4; ++k) {
+ sh_x[b][t][q * 4 + k] = next_x[k] * dts;
+ }
+ if (q == 0) {
+ sh_da[b][t] = valid ? exp(dts * a) : 1.0;
+ }
+ }
+}
+
+// Lane ln keeps every LPR-th vec4 of a row, so a row group reads contiguous
+// vec4s of B and C.
+uint state_col(const uint k, const uint ln) {
+ return ((k / 4) * LPR + ln) * 4 + k % 4;
+}
+
+void main() {
+ // Number row groups in subgroup lane order for the shuffle reduction.
+ const uint tid = gl_SubgroupID * gl_SubgroupSize + gl_SubgroupInvocationID;
+ const uint rg = tid / LPR; // row group within the workgroup
+ const uint ln = tid % LPR; // lane within the row group
+
+ const uint head = gl_WorkGroupID.y;
+ const uint seq = gl_WorkGroupID.z;
+ const uint row0 = gl_WorkGroupID.x * ROWS;
+ const uint group = head / (n_head / n_group);
+ const float a = A[(off3 + head * nb31) / 4];
+
+ const uint B_base = (off4 + seq * nb43 + group * D_STATE * 4) / 16;
+ const uint C_base = (off5 + seq * nb53 + group * D_STATE * 4) / 16;
+ const uint x_base = (off1 + seq * nb13 + head * d_head * 4) / 16;
+ const uint dt_base = (off2 + seq * nb22) / 4 + head;
+ const uint stride_y = n_head * d_head;
+ const uint y_base = seq * n_tok * stride_y + head * d_head + row0;
+
+ // state[j][k] is row row0 + rg * R + j, column state_col(k, ln).
+ float state[R][S];
+ const uint s0_base = (off0 + uint(ids[off6 / 4 + seq]) * nb03 + head * nb02) / 4;
+ const uint s_base = (s_off + seq * nb03 + head * nb02) / 4;
+ [[unroll]] for (uint j = 0; j < R; ++j) {
+ const uint row = row0 + rg * R + j;
+ [[unroll]] for (uint k = 0; k < S; ++k) {
+ state[j][k] = row < d_head ? s0[s0_base + row * D_STATE + state_col(k, ln)] : 0.0;
+ }
+ }
+
+ load_chunk(0, B_base, C_base, x_base, dt_base, row0);
+ store_chunk(0, 0, a);
+ barrier();
+
+ uint buf = 0;
+ for (uint t0 = 0; t0 < n_tok; t0 += T) {
+ const bool more = t0 + T < n_tok;
+ if (more) {
+ load_chunk(t0 + T, B_base, C_base, x_base, dt_base, row0);
+ }
+
+ float part[T * R];
+ [[unroll]] for (uint t = 0; t < T; ++t) {
+ const float dA = sh_da[buf][t];
+ vec4 bv[S / 4], cv[S / 4];
+ [[unroll]] for (uint q = 0; q < S / 4; ++q) {
+ bv[q] = sh_b[buf][t][q * LPR + ln];
+ cv[q] = sh_c[buf][t][q * LPR + ln];
+ }
+ [[unroll]] for (uint j = 0; j < R; ++j) {
+ const float xdt = sh_x[buf][t][rg * R + j];
+ float p = 0.0;
+ [[unroll]] for (uint k = 0; k < S; ++k) {
+ state[j][k] = fma(state[j][k], dA, bv[k / 4][k % 4] * xdt);
+ p = fma(state[j][k], cv[k / 4][k % 4], p);
+ }
+ part[t * R + j] = p;
+ }
+ }
+
+ // Butterfly reduction over the row group. Lane ln ends with the sums
+ // ln * NF .. ln * NF + NF - 1 of part.
+ [[unroll]] for (uint l = 0; (LPR >> l) > 1; ++l) {
+ const uint m = LPR >> (l + 1);
+ const uint h = (T * R) >> (l + 1);
+ const bool upper = (ln & m) != 0;
+ [[unroll]] for (uint i = 0; i < h; ++i) {
+ const float keep = upper ? part[i + h] : part[i];
+ const float send = upper ? part[i] : part[i + h];
+ part[i] = keep + subgroupShuffleXor(send, m);
+ }
+ }
+ [[unroll]] for (uint i = 0; i < NF; ++i) {
+ const uint f = ln * NF + i;
+ const uint t = f / R, row = rg * R + f % R;
+ if (t0 + t < n_tok && row0 + row < d_head) {
+ d[y_base + (t0 + t) * stride_y + row] = part[i];
+ }
+ }
+
+ if (more) {
+ store_chunk(buf ^ 1, t0 + T, a);
+ }
+ barrier();
+ buf ^= 1;
+ }
+
+ [[unroll]] for (uint j = 0; j < R; ++j) {
+ const uint row = row0 + rg * R + j;
+ if (row < d_head) {
+ [[unroll]] for (uint k = 0; k < S; ++k) {
+ d[s_base + row * D_STATE + state_col(k, ln)] = state[j][k];
+ }
+ }
+ }
+}
diff --git a/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp b/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp
index 29df658de..29a39be70 100644
--- a/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp
+++ b/ggml/src/ggml-vulkan/vulkan-shaders/vulkan-shaders-gen.cpp
@@ -1267,6 +1267,10 @@ void process_shaders() {
string_to_spv("ssm_scan_f32", "ssm_scan.comp", {{"A_TYPE", "float"}});
string_to_spv("ssm_scan_subgroup_f32", "ssm_scan.comp", {{"A_TYPE", "float"}, {"USE_SUBGROUP_ADD", "1"}});
+ string_to_spv("ssm_scan_prefill_f32", "ssm_scan_prefill.comp", {});
+#if defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
+ string_to_spv("ssm_scan_f32", "ssm_scan_cm2.comp", {}, true, false, true);
+#endif
string_to_spv("ssm_conv_f32", "ssm_conv.comp", {{"A_TYPE", "float"}});
diff --git a/tests/test-backend-ops.cpp b/tests/test-backend-ops.cpp
index 2cd22f70d..86701eb98 100644
--- a/tests/test-backend-ops.cpp
+++ b/tests/test-backend-ops.cpp
@@ -5682,6 +5682,8 @@ struct test_ssm_conv_concat_fusion : public test_case {
};
// GGML_OP_SSM_SCAN
+// xbc_graph: x, B and C are views of one tensor with rows [xbc_off | x | B | C | pad], as in the Mamba-2 graph.
+// off: s, dt, A and ids start off elements into their tensors.
struct test_ssm_scan : public test_case {
const ggml_type type;
@@ -5694,9 +5696,15 @@ struct test_ssm_scan : public test_case {
const bool xbc_overlap;
const int64_t K;
const bool weak_decay;
+ const bool xbc_graph;
+ const int64_t off;
+ const int64_t xbc_off;
+ const int64_t pad;
+ const bool seq_major;
std::string vars() override {
- return VARS_TO_STR10(type, d_state, head_dim, n_head, n_group, n_seq_tokens, n_seqs, xbc_overlap, K, weak_decay);
+ return VARS_TO_STR15(type, d_state, head_dim, n_head, n_group, n_seq_tokens, n_seqs, xbc_overlap, K, weak_decay,
+ xbc_graph, off, xbc_off, pad, seq_major);
}
test_ssm_scan(ggml_type type = GGML_TYPE_F32,
@@ -5708,23 +5716,41 @@ struct test_ssm_scan : public test_case {
int64_t n_seqs = 32,
bool xbc_overlap = false,
int64_t K = 1,
- bool weak_decay = false)
- : type(type), d_state(d_state), head_dim(head_dim), n_head(n_head), n_group(n_group), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs), xbc_overlap(xbc_overlap), K(K), weak_decay(weak_decay) {}
+ bool weak_decay = false,
+ bool xbc_graph = false,
+ int64_t off = 0,
+ int64_t xbc_off = 0,
+ int64_t pad = 0,
+ bool seq_major = false)
+ : type(type), d_state(d_state), head_dim(head_dim), n_head(n_head), n_group(n_group), n_seq_tokens(n_seq_tokens), n_seqs(n_seqs), xbc_overlap(xbc_overlap), K(K), weak_decay(weak_decay),
+ xbc_graph(xbc_graph), off(off), xbc_off(xbc_off), pad(pad), seq_major(seq_major) {}
double max_nmse_err() override {
// SSD path (head_dim > 1) uses FP16 intermediates (M matrix, X_dt); Mamba-1 is pure FP32.
return (head_dim > 1) ? 2e-7 : 1e-7;
}
+ int64_t n_slots() const {
+ return xbc_graph ? n_seqs + 2 : n_seqs;
+ }
+
ggml_tensor * build_graph(ggml_context * ctx) override {
- ggml_tensor * s = ggml_new_tensor_4d(ctx, type, d_state, head_dim, n_head, n_seqs);
- ggml_tensor * dt = ggml_new_tensor_3d(ctx, type, n_head, n_seq_tokens, n_seqs);
- ggml_tensor * A = ggml_new_tensor_2d(ctx, type, (head_dim > 1) ? 1 : d_state, n_head);
+ const size_t f = ggml_type_size(type);
ggml_tensor * x;
ggml_tensor * B;
ggml_tensor * C;
- if (xbc_overlap) {
+ if (xbc_graph) {
+ const int64_t d_inner = head_dim * n_head;
+ const int64_t row = xbc_off + d_inner + 2 * n_group * d_state + pad;
+ ggml_tensor * xbc = seq_major ? ggml_new_tensor_3d(ctx, type, row, n_seqs, n_seq_tokens)
+ : ggml_new_tensor_3d(ctx, type, row, n_seq_tokens, n_seqs);
+ const size_t nb_tok = seq_major ? xbc->nb[2] : xbc->nb[1];
+ const size_t nb_seq = seq_major ? xbc->nb[1] : xbc->nb[2];
+ x = ggml_view_4d(ctx, xbc, head_dim, n_head, n_seq_tokens, n_seqs, head_dim * f, nb_tok, nb_seq, xbc_off * f);
+ B = ggml_view_4d(ctx, xbc, d_state, n_group, n_seq_tokens, n_seqs, d_state * f, nb_tok, nb_seq, (xbc_off + d_inner) * f);
+ C = ggml_view_4d(ctx, xbc, d_state, n_group, n_seq_tokens, n_seqs, d_state * f, nb_tok, nb_seq, (xbc_off + d_inner + n_group * d_state) * f);
+ } else if (xbc_overlap) {
ggml_tensor * xbc = ggml_new_tensor_4d(ctx, type, d_state, n_head, n_seq_tokens, 2 * n_seqs);
x = ggml_view_4d(ctx, xbc, head_dim, n_head, n_seq_tokens, n_seqs,
xbc->nb[1], xbc->nb[2], xbc->nb[3], xbc->nb[3]);
@@ -5737,7 +5763,19 @@ struct test_ssm_scan : public test_case {
B = ggml_new_tensor_4d(ctx, type, d_state, n_group, n_seq_tokens, n_seqs);
C = ggml_new_tensor_4d(ctx, type, d_state, n_group, n_seq_tokens, n_seqs);
}
- ggml_tensor * ids = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_seqs);
+
+ const int64_t A_ne0 = (head_dim > 1) ? 1 : d_state;
+ ggml_tensor * s_all = ggml_new_tensor_1d(ctx, type, off + d_state * head_dim * n_head * n_slots());
+ ggml_tensor * dt_all = ggml_new_tensor_1d(ctx, type, off + n_head * n_seq_tokens * n_seqs);
+ ggml_tensor * A_all = ggml_new_tensor_1d(ctx, type, off + A_ne0 * n_head);
+ ggml_tensor * ids_all = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, off + n_seqs);
+ ggml_set_name(A_all, "A");
+ ggml_tensor * s = ggml_view_4d(ctx, s_all, d_state, head_dim, n_head, n_slots(),
+ d_state * f, d_state * head_dim * f, d_state * head_dim * n_head * f, off * f);
+ ggml_tensor * dt = ggml_view_3d(ctx, dt_all, n_head, n_seq_tokens, n_seqs, n_head * f, n_head * n_seq_tokens * f, off * f);
+ ggml_tensor * A = ggml_view_2d(ctx, A_all, A_ne0, n_head, A_ne0 * f, off * f);
+ ggml_tensor * ids = ggml_view_1d(ctx, ids_all, n_seqs, off * sizeof(int32_t));
+
ggml_tensor * out = ggml_ssm_scan(ctx, s, x, dt, A, B, C, ids, K);
return out;
}
@@ -5747,21 +5785,23 @@ struct test_ssm_scan : public test_case {
std::random_device rd;
std::default_random_engine rng(rd());
for (ggml_tensor * t = ggml_get_first_tensor(ctx); t != NULL; t = ggml_get_next_tensor(ctx, t)) {
+ if (ggml_is_view_op(t->op)) {
+ continue;
+ }
if (t->type == GGML_TYPE_I32) {
- if (ggml_is_view_op(t->op)) { continue; }
- // ids: permutation of [0..n_seqs)
- for (int64_t r = 0; r < ggml_nrows(t); r++) {
- std::vector<int32_t> data(t->ne[0]);
- for (int i = 0; i < t->ne[0]; i++) {
- data[i] = i;
- }
- std::shuffle(data.begin(), data.end(), rng);
- ggml_backend_tensor_set(t, data.data(), r * t->nb[1], t->ne[0] * sizeof(int32_t));
+ // ids: distinct random state slots
+ std::vector<int32_t> slots(n_slots());
+ for (size_t i = 0; i < slots.size(); i++) {
+ slots[i] = (int32_t) i;
}
- } else if (ggml_is_view_op(t->op)) {
- continue;
- } else if (t->ne[1] == n_head && t->ne[2] == 1) {
- // A {1 or d_state, n_head}: negative decay (2-D tensor, ne[2]==1 distinguishes from 3-D/4-D tensors)
+ std::shuffle(slots.begin(), slots.end(), rng);
+ std::vector<int32_t> data(ggml_nelements(t), 0);
+ for (int64_t i = 0; i < n_seqs; i++) {
+ data[off + i] = slots[i];
+ }
+ ggml_backend_tensor_set(t, data.data(), 0, ggml_nbytes(t));
+ } else if (strcmp(t->name, "A") == 0) {
+ // negative decay
init_tensor_uniform(t, weak_decay ? -0.02f : -1.0f, weak_decay ? -0.005f : -0.5f);
} else {
init_tensor_uniform(t);
@@ -13648,6 +13688,9 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_ssm_scan_rollback(GGML_TYPE_F32, 96, 64, 16, 8, 8, 2, /*K=*/3)); // d_state=96 rollback snapshots match prefix states
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, 32, 4)); // Mamba-2
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 256, 64, 8, 2, 32, 4)); // Falcon-H1
+ test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, 8, 2)); // Mamba-2
+ test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, 31, 2)); // Mamba-2
+ test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 256, 64, 8, 2, 9, 2)); // Falcon-H1
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 128, 4, 4, 16, 2, true)); // x/B/C overlap
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 80, 128, 1, 256, 1)); // Nemotron-9B SSD path
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 80, 128, 1, 512, 1)); // Nemotron-9B SSD multi-chunk (2 aligned chunks)
@@ -13659,6 +13702,25 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, 65, 2)); // SSD one chunk + 1-token sequential tail
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, 128, 2)); // SSD multi-chunk, no tail (exercises the chunk-to-chunk state handoff)
test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, 128, 2, false, /*K=*/1, /*weak_decay=*/true)); // SSD multi-chunk, carried state not numerically negligible
+ test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, 2048, 1)); // Mamba-2
+ test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 256, 64, 8, 2, 300, 2)); // Falcon-H1
+ test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 16, 16, 2, 64, 2)); // head_dim 16
+ test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 48, 16, 2, 64, 2)); // head_dim 48
+ test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 96, 64, 16, 8, 16, 2)); // Nemotron-3-Puzzle
+ test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 96, 48, 16, 8, 16, 2)); // head_dim 48
+ test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 96, 48, 16, 8, 64, 2)); // head_dim 48
+
+ // Mamba-2 with the inputs laid out like the model graph, then with unaligned offsets and strides.
+ for (int64_t n_tok : {4, 16, 100}) {
+ test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, n_tok, 2, false, 1, false, /*xbc_graph=*/true));
+ test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, n_tok, 2, false, 1, false, true, /*off=*/1)); // s, dt, A and ids
+ test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, n_tok, 2, false, 1, false, true, 0, /*xbc_off=*/1)); // x, B and C
+ test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, n_tok, 2, false, 1, false, true, 0, 0, /*pad=*/1)); // token stride
+ test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 64, 16, 2, n_tok, 3, false, 1, false, true, 0, 0, 0, /*seq_major=*/true));
+ }
+ test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 256, 64, 8, 2, 40, 2, false, 1, false, true, 1)); // Falcon-H1
+ test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 128, 80, 8, 1, 40, 2, false, 1, false, true, 1, 4, 4)); // Nemotron-9B
+ test_cases.emplace_back(new test_ssm_scan(GGML_TYPE_F32, 96, 64, 16, 8, 40, 2, false, 1, false, true, 1)); // Nemotron-3-Puzzle
// ssm_scan + cache cpy fusion
test_cases.emplace_back(new test_ssm_scan_cache_fusion(GGML_TYPE_F32, 128, 64, 16, 2, 4, 1, 4));