diff --git a/mlx/backend/metal/CMakeLists.txt b/mlx/backend/metal/CMakeLists.txt index 00ad494030..4d27191bf1 100644 --- a/mlx/backend/metal/CMakeLists.txt +++ b/mlx/backend/metal/CMakeLists.txt @@ -133,6 +133,8 @@ target_sources( ${CMAKE_CURRENT_SOURCE_DIR}/softmax.cpp ${CMAKE_CURRENT_SOURCE_DIR}/sort.cpp ${CMAKE_CURRENT_SOURCE_DIR}/ssm.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/ssm_replay.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/flash_quantized_sdpa.cpp ${CMAKE_CURRENT_SOURCE_DIR}/reduce.cpp ${CMAKE_CURRENT_SOURCE_DIR}/ternary.cpp ${CMAKE_CURRENT_SOURCE_DIR}/turbo_quant.cpp diff --git a/mlx/backend/metal/flash_quantized_sdpa.cpp b/mlx/backend/metal/flash_quantized_sdpa.cpp new file mode 100644 index 0000000000..ef9339d1da --- /dev/null +++ b/mlx/backend/metal/flash_quantized_sdpa.cpp @@ -0,0 +1,170 @@ +// Copyright © 2026 Eric Kryski. Flash quantized SDPA — spec 041 phase 1.1. +// +// Dispatch for `FlashQuantizedSDPA::eval_gpu`. The kernel lives in +// `kernels/flash_quantized_sdpa.h` (template) + +// `kernels/flash_quantized_sdpa.metal` (instantiations). +// +// Inputs order matches `fast.cpp::flash_quantized_sdpa(...)`: +// 0: queries +// 1: k_packed 2: k_scales 3: k_biases +// 4: v_packed 5: v_scales 6: v_biases +// [7]: mask (optional, present iff !do_causal && has_arr_mask) +// [next]: sinks (optional) + +#include "mlx/backend/common/compiled.h" +#include "mlx/backend/metal/device.h" +#include "mlx/backend/metal/utils.h" +#include "mlx/fast_primitives.h" + +namespace mlx::core::fast { + +void FlashQuantizedSDPA::eval_gpu( + const std::vector& inputs, + std::vector& outputs) { + auto& s = stream(); + auto& d = metal::device(s.device); + + auto& out = outputs[0]; + out.set_data(allocator::malloc(out.nbytes())); + + const array& q = inputs[0]; + const array& k_packed = inputs[1]; + const array& k_scales = inputs[2]; + const array& k_biases = inputs[3]; + const array& v_packed = inputs[4]; + const array& v_scales = inputs[5]; + const array& v_biases = inputs[6]; + + int input_cursor = 7; + const array* mask_arr = nullptr; + // The fast.cpp wrapper appends mask only when has_arr_mask == true, so any + // input past `v_biases` that exists before sinks is the mask. We can detect + // it by checking remaining input count vs `has_sinks_`. + int remaining = static_cast(inputs.size()) - input_cursor; + bool has_array_mask = (remaining > (has_sinks_ ? 1 : 0)); + if (has_array_mask) { + mask_arr = &inputs[input_cursor++]; + } + const array* sinks_arr = nullptr; + if (has_sinks_) { + sinks_arr = &inputs[input_cursor++]; + } + + int D = q.shape(-1); + int V = out.shape(-1); + int gqa_factor = n_q_heads_ / n_kv_heads_; + int N = k_packed.shape(-2); + + // Stride helpers (in elements). After `ensureRowContiguous`, strides + // follow the canonical [B, n_kv_heads, T, *] layout, so head_stride is + // T * row_size and seq_stride is row_size. + int packed_per_token = D / (32 / bits_); + int v_packed_per_token = V / (32 / bits_); + int scale_per_token = D / group_size_; + int v_scale_per_token = V / group_size_; + + size_t k_head_stride_packed = static_cast(N) * packed_per_token; + size_t k_seq_stride_packed = packed_per_token; + size_t k_head_stride_scale = static_cast(N) * scale_per_token; + size_t k_seq_stride_scale = scale_per_token; + size_t v_head_stride_packed = static_cast(N) * v_packed_per_token; + size_t v_seq_stride_packed = v_packed_per_token; + size_t v_head_stride_scale = static_cast(N) * v_scale_per_token; + size_t v_seq_stride_scale = v_scale_per_token; + + // Function constants — match kernel-side IDs (40-45). + bool has_mask_b = has_array_mask; + bool query_transposed_b = !q.flags().row_contiguous; + bool do_causal_b = do_causal_; + bool bool_mask_b = has_array_mask && mask_arr->dtype() == bool_; + bool float_mask_b = has_array_mask && !bool_mask_b; + bool has_sinks_b = has_sinks_; + + metal::MTLFCList func_consts = { + {&has_mask_b, MTL::DataType::DataTypeBool, 40}, + {&query_transposed_b, MTL::DataType::DataTypeBool, 41}, + {&do_causal_b, MTL::DataType::DataTypeBool, 42}, + {&bool_mask_b, MTL::DataType::DataTypeBool, 43}, + {&float_mask_b, MTL::DataType::DataTypeBool, 44}, + {&has_sinks_b, MTL::DataType::DataTypeBool, 45}, + }; + + // Kernel name: flash_quantized_sdpa_{type}_{D}_{V}_{bits}_{group_size}. + // Use `get_type_string` (returns "float" / "float16_t" / "bfloat16_t") + // to match the Metal-side instantiations in `flash_quantized_sdpa.metal`. + std::string tname = mlx::core::get_type_string(q.dtype()); + std::string kname = "flash_quantized_sdpa_" + tname + "_" + + std::to_string(D) + "_" + std::to_string(V) + "_" + + std::to_string(bits_) + "_" + std::to_string(group_size_); + std::string hash_name = kname + + (has_array_mask ? (bool_mask_b ? "_boolmask" : "_floatmask") + : "_nomask") + + (query_transposed_b ? "_qt" : "_qnt") + (do_causal_b ? "_c" : "_nc") + + (has_sinks_b ? "_sinks" : "_nosinks"); + + auto& compute_encoder = metal::get_command_encoder(s); + auto kernel = d.get_kernel(kname, hash_name, func_consts); + compute_encoder.set_compute_pipeline_state(kernel); + + // Bind buffers + compute_encoder.set_input_array(q, 0); + compute_encoder.set_input_array(k_packed, 1); + compute_encoder.set_input_array(k_scales, 2); + compute_encoder.set_input_array(k_biases, 3); + compute_encoder.set_input_array(v_packed, 4); + compute_encoder.set_input_array(v_scales, 5); + compute_encoder.set_input_array(v_biases, 6); + compute_encoder.set_output_array(out, 7); + compute_encoder.set_bytes(gqa_factor, 8); + compute_encoder.set_bytes(N, 9); + compute_encoder.set_bytes(k_head_stride_packed, 10); + compute_encoder.set_bytes(k_seq_stride_packed, 11); + compute_encoder.set_bytes(k_head_stride_scale, 12); + compute_encoder.set_bytes(k_seq_stride_scale, 13); + compute_encoder.set_bytes(v_head_stride_packed, 14); + compute_encoder.set_bytes(v_seq_stride_packed, 15); + compute_encoder.set_bytes(v_head_stride_scale, 16); + compute_encoder.set_bytes(v_seq_stride_scale, 17); + compute_encoder.set_bytes(scale_, 18); + + if (has_array_mask) { + compute_encoder.set_input_array(*mask_arr, 19 + (float_mask_b ? 1 : 0)); + int32_t mask_kv_seq_stride = + mask_arr->shape(3) > 1 ? mask_arr->strides(3) : 0; + int32_t mask_q_seq_stride = + mask_arr->shape(2) > 1 ? mask_arr->strides(2) : 0; + int32_t mask_head_stride = mask_arr->shape(1) > 1 + ? mask_arr->strides(1) + : (mask_arr->shape(0) > 1 ? mask_arr->strides(0) : 0); + compute_encoder.set_bytes(mask_kv_seq_stride, 21); + compute_encoder.set_bytes(mask_q_seq_stride, 22); + compute_encoder.set_bytes(mask_head_stride, 23); + } + if (has_sinks_b) { + compute_encoder.set_input_array(*sinks_arr, 24); + compute_encoder.set_bytes(n_q_heads_, 25); + } + + // Grid: (B * n_q_heads, T_q, 1). Threadgroup: (1024, 1, 1) = 32 simdgroups. + MTL::Size group_dims(1024, 1, 1); + MTL::Size grid_dims(q.shape(0) * q.shape(1), q.shape(2), 1); + compute_encoder.dispatch_threadgroups(grid_dims, group_dims); +} + +bool FlashQuantizedSDPA::is_equivalent(const Primitive& other) const { + const FlashQuantizedSDPA& o = static_cast(other); + return scale_ == o.scale_ && do_causal_ == o.do_causal_ && + has_sinks_ == o.has_sinks_ && bits_ == o.bits_ && + group_size_ == o.group_size_ && n_q_heads_ == o.n_q_heads_ && + n_kv_heads_ == o.n_kv_heads_; +} + +std::vector FlashQuantizedSDPA::output_shapes( + const std::vector& inputs) { + const array& q = inputs[0]; + const array& v_scales = inputs[5]; + int V = v_scales.shape(-1) * group_size_; + return {{q.shape(0), q.shape(1), q.shape(2), V}}; +} + +} // namespace mlx::core::fast diff --git a/mlx/backend/metal/kernels/CMakeLists.txt b/mlx/backend/metal/kernels/CMakeLists.txt index dfa1ebc978..eb1d1c819f 100644 --- a/mlx/backend/metal/kernels/CMakeLists.txt +++ b/mlx/backend/metal/kernels/CMakeLists.txt @@ -56,6 +56,8 @@ build_kernel(random) build_kernel(rms_norm) build_kernel(rope) build_kernel(scaled_dot_product_attention sdpa_vector.h) +build_kernel(flash_quantized_sdpa flash_quantized_sdpa.h) +build_kernel(ssm_replay) if(MLX_METAL_VERSION GREATER_EQUAL 320) build_kernel(fence) endif() diff --git a/mlx/backend/metal/kernels/flash_quantized_sdpa.h b/mlx/backend/metal/kernels/flash_quantized_sdpa.h new file mode 100644 index 0000000000..aa4dfa77f0 --- /dev/null +++ b/mlx/backend/metal/kernels/flash_quantized_sdpa.h @@ -0,0 +1,234 @@ +// Copyright © 2026 Eric Kryski. Flash quantized SDPA — spec 041 phase 1.1. +// +// Affine-quantized variant of `sdpa_vector`. Same online-softmax loop, but +// K and V are dequantised inline per-thread from packed-indices + scale + +// bias triples (the same layout `quantizedMM` consumes). +// +// Layout assumptions (row-contiguous; passed through `ensureRowContiguous`): +// - queries: [B, n_q_heads, T_q, D] T +// - k_packed: [B, n_kv_heads, T_kv, D / (32/Bits)] uint32 +// - k_scales: [B, n_kv_heads, T_kv, D / GroupSize] T +// - k_biases: [B, n_kv_heads, T_kv, D / GroupSize] T (affine has bias; +// mxfp4 sets bias=0) +// - v_packed: [B, n_kv_heads, T_kv, V / (32/Bits)] uint32 +// - v_scales / v_biases: same shape rule as k. +// - out: [B, n_q_heads, T_q, V] T +// +// Threadgroup geometry: same as sdpa_vector (BN=BD=32, one threadgroup per +// (batch*query_head, query_pos), 32 simdgroups distributing K positions). + +#include + +using namespace metal; + +constant bool has_mask_fq [[function_constant(40)]]; +constant bool query_transposed_fq [[function_constant(41)]]; +constant bool do_causal_fq [[function_constant(42)]]; +constant bool bool_mask_fq [[function_constant(43)]]; +constant bool float_mask_fq [[function_constant(44)]]; +constant bool has_sinks_fq [[function_constant(45)]]; + +template +[[kernel]] void flash_quantized_sdpa( + const device T* queries [[buffer(0)]], + const device uint32_t* k_packed [[buffer(1)]], + const device T* k_scales [[buffer(2)]], + const device T* k_biases [[buffer(3)]], + const device uint32_t* v_packed [[buffer(4)]], + const device T* v_scales [[buffer(5)]], + const device T* v_biases [[buffer(6)]], + device T* out [[buffer(7)]], + const constant int& gqa_factor [[buffer(8)]], + const constant int& N [[buffer(9)]], + const constant size_t& k_head_stride_packed [[buffer(10)]], + const constant size_t& k_seq_stride_packed [[buffer(11)]], + const constant size_t& k_head_stride_scale [[buffer(12)]], + const constant size_t& k_seq_stride_scale [[buffer(13)]], + const constant size_t& v_head_stride_packed [[buffer(14)]], + const constant size_t& v_seq_stride_packed [[buffer(15)]], + const constant size_t& v_head_stride_scale [[buffer(16)]], + const constant size_t& v_seq_stride_scale [[buffer(17)]], + const constant float& scale [[buffer(18)]], + const device bool* bmask [[buffer(19), function_constant(bool_mask_fq)]], + const device T* fmask [[buffer(20), function_constant(float_mask_fq)]], + const constant int& mask_kv_seq_stride + [[buffer(21), function_constant(has_mask_fq)]], + const constant int& mask_q_seq_stride + [[buffer(22), function_constant(has_mask_fq)]], + const constant int& mask_head_stride + [[buffer(23), function_constant(has_mask_fq)]], + const device T* sinks [[buffer(24), function_constant(has_sinks_fq)]], + const constant int& num_q_heads + [[buffer(25), function_constant(has_sinks_fq)]], + uint3 tid [[threadgroup_position_in_grid]], + uint3 tpg [[threadgroups_per_grid]], + uint simd_gid [[simdgroup_index_in_threadgroup]], + uint simd_lid [[thread_index_in_simdgroup]]) { + constexpr int BN = 32; + constexpr int BD = 32; + constexpr int qk_per_thread = D / BD; + constexpr int v_per_thread = V / BD; + constexpr int pack_factor = 32 / Bits; + constexpr uint mask_bits = (1u << Bits) - 1u; + + typedef float U; + + thread U q[qk_per_thread]; + thread U k[qk_per_thread]; + thread U v[v_per_thread]; + thread U o[v_per_thread]; + + threadgroup U outputs[BN * BD]; + threadgroup U max_scores[BN]; + threadgroup U sum_exp_scores[BN]; + + // Position calc — matches sdpa_vector exactly. + const int q_batch_head_idx = tid.x; + const int q_seq_idx = tid.y; + const int kv_head_idx = q_batch_head_idx / gqa_factor; + const int o_offset = q_batch_head_idx * tpg.y + q_seq_idx; + const int q_offset = + query_transposed_fq ? tpg.x * q_seq_idx + q_batch_head_idx : o_offset; + + // Query slice: each thread reads `qk_per_thread` consecutive dims. + const device T* queries_thread = + queries + q_offset * D + simd_lid * qk_per_thread; + + // Mask offsets (same pattern as sdpa_vector). + if (bool_mask_fq) { + bmask += q_batch_head_idx * mask_head_stride + + simd_gid * mask_kv_seq_stride + q_seq_idx * mask_q_seq_stride; + } + if (float_mask_fq) { + fmask += q_batch_head_idx * mask_head_stride + + simd_gid * mask_kv_seq_stride + q_seq_idx * mask_q_seq_stride; + } + + // K base pointers for this kv_head, this simdgroup's first key position. + const device uint32_t* k_packed_head = + k_packed + kv_head_idx * k_head_stride_packed; + const device T* k_scales_head = k_scales + kv_head_idx * k_head_stride_scale; + const device T* k_biases_head = k_biases + kv_head_idx * k_head_stride_scale; + + const device uint32_t* v_packed_head = + v_packed + kv_head_idx * v_head_stride_packed; + const device T* v_scales_head = v_scales + kv_head_idx * v_head_stride_scale; + const device T* v_biases_head = v_biases + kv_head_idx * v_head_stride_scale; + + // Pre-load query (apply scale). + for (int i = 0; i < qk_per_thread; i++) { + q[i] = static_cast(scale) * static_cast(queries_thread[i]); + } + for (int i = 0; i < v_per_thread; i++) { + o[i] = 0; + } + + U max_score = -INFINITY; + U sum_exp_score = 0; + if (has_sinks_fq && simd_gid == 0) { + max_score = static_cast(sinks[q_batch_head_idx % num_q_heads]); + sum_exp_score = 1; + } + + // Iterate K positions in chunks of BN across simdgroups. + for (int i = simd_gid; i < N; i += BN) { + bool use_key = true; + if (do_causal_fq) { + use_key = i <= (N - int(tpg.y) + int(q_seq_idx)); + } else if (bool_mask_fq) { + use_key = bmask[0]; + } else if (float_mask_fq) { + use_key = (fmask[0] >= -INFINITY); + } + + if (use_key) { + // Inline dequant K[i] for this thread's qk_per_thread dim slice. + const device uint32_t* k_packed_t = + k_packed_head + i * k_seq_stride_packed; + const device T* k_scales_t = k_scales_head + i * k_seq_stride_scale; + const device T* k_biases_t = k_biases_head + i * k_seq_stride_scale; + + for (int j = 0; j < qk_per_thread; j++) { + int d = simd_lid * qk_per_thread + j; + int word_idx = d / pack_factor; + int shift = (d % pack_factor) * Bits; + int group_idx = d / GroupSize; + uint val = (k_packed_t[word_idx] >> shift) & mask_bits; + k[j] = static_cast(k_scales_t[group_idx]) * U(val) + + static_cast(k_biases_t[group_idx]); + } + + // Compute the i-th score across qk_per_thread dims, then simd_sum. + U score = 0; + for (int j = 0; j < qk_per_thread; j++) { + score += q[j] * k[j]; + } + score = simd_sum(score); + if (float_mask_fq) { + score += static_cast(fmask[0]); + } + + // Online softmax update. + U new_max = max(max_score, score); + U factor = fast::exp(max_score - new_max); + U exp_score = fast::exp(score - new_max); + max_score = new_max; + sum_exp_score = sum_exp_score * factor + exp_score; + + // Inline dequant V[i] for this thread's v_per_thread slice. + const device uint32_t* v_packed_t = + v_packed_head + i * v_seq_stride_packed; + const device T* v_scales_t = v_scales_head + i * v_seq_stride_scale; + const device T* v_biases_t = v_biases_head + i * v_seq_stride_scale; + + for (int j = 0; j < v_per_thread; j++) { + int d = simd_lid * v_per_thread + j; + int word_idx = d / pack_factor; + int shift = (d % pack_factor) * Bits; + int group_idx = d / GroupSize; + uint val = (v_packed_t[word_idx] >> shift) & mask_bits; + v[j] = static_cast(v_scales_t[group_idx]) * U(val) + + static_cast(v_biases_t[group_idx]); + } + + // Output accumulator update. + for (int j = 0; j < v_per_thread; j++) { + o[j] = o[j] * factor + exp_score * v[j]; + } + } + + if (bool_mask_fq) { + bmask += BN * mask_kv_seq_stride; + } + if (float_mask_fq) { + fmask += BN * mask_kv_seq_stride; + } + } + + // Cross-simdgroup max + sum_exp reduction (same shape as sdpa_vector). + if (simd_lid == 0) { + max_scores[simd_gid] = max_score; + sum_exp_scores[simd_gid] = sum_exp_score; + } + threadgroup_barrier(mem_flags::mem_threadgroup); + max_score = max_scores[simd_lid]; + U new_max = simd_max(max_score); + U factor = fast::exp(max_score - new_max); + sum_exp_score = simd_sum(sum_exp_scores[simd_lid] * factor); + + // Aggregate outputs across simdgroups. + for (int i = 0; i < v_per_thread; i++) { + outputs[simd_lid * BD + simd_gid] = o[i]; + threadgroup_barrier(mem_flags::mem_threadgroup); + o[i] = simd_sum(outputs[simd_gid * BD + simd_lid] * factor); + o[i] = sum_exp_score == 0 ? o[i] : (o[i] / sum_exp_score); + threadgroup_barrier(mem_flags::mem_threadgroup); + } + + // Write output. + if (simd_lid == 0) { + for (int i = 0; i < v_per_thread; i++) { + out[o_offset * V + simd_gid * v_per_thread + i] = static_cast(o[i]); + } + } +} diff --git a/mlx/backend/metal/kernels/flash_quantized_sdpa.metal b/mlx/backend/metal/kernels/flash_quantized_sdpa.metal new file mode 100644 index 0000000000..9938bd2235 --- /dev/null +++ b/mlx/backend/metal/kernels/flash_quantized_sdpa.metal @@ -0,0 +1,42 @@ +// Copyright © 2026 Eric Kryski. Flash quantized SDPA — spec 041 phase 1.1. + +#include + +// clang-format off +#include "mlx/backend/metal/kernels/utils.h" +#include "mlx/backend/metal/kernels/flash_quantized_sdpa.h" + +using namespace metal; + +#define instantiate_flash_quantized_sdpa(type, head_dim, value_dim, bits, group_size) \ + instantiate_kernel( \ + "flash_quantized_sdpa_" #type "_" #head_dim "_" #value_dim "_" #bits "_" #group_size, \ + flash_quantized_sdpa, \ + type, \ + head_dim, \ + value_dim, \ + bits, \ + group_size) + +// Phase 1: bits ∈ {4, 8}, groupSize = 64. Head dims cover common shapes: +// D=64 (Qwen 3.5-0.8B), D=128 (Qwen / Gemma 4 E2B / E4B), D=256 (Gemma 4 31B sliding), +// D=512 (Gemma 4 31B global, GPT-OSS-20B). +#define instantiate_flash_quantized_sdpa_for_head_dim(type, bits, group_size) \ + instantiate_flash_quantized_sdpa(type, 64, 64, bits, group_size) \ + instantiate_flash_quantized_sdpa(type, 96, 96, bits, group_size) \ + instantiate_flash_quantized_sdpa(type, 128, 128, bits, group_size) \ + instantiate_flash_quantized_sdpa(type, 256, 256, bits, group_size) \ + instantiate_flash_quantized_sdpa(type, 512, 512, bits, group_size) + +// Phase 2 bit-widths added alongside Phase 1 — MLX dequantize supports them all. +#define instantiate_flash_quantized_sdpa_for_type(type, group_size) \ + instantiate_flash_quantized_sdpa_for_head_dim(type, 2, group_size) \ + instantiate_flash_quantized_sdpa_for_head_dim(type, 3, group_size) \ + instantiate_flash_quantized_sdpa_for_head_dim(type, 4, group_size) \ + instantiate_flash_quantized_sdpa_for_head_dim(type, 6, group_size) \ + instantiate_flash_quantized_sdpa_for_head_dim(type, 8, group_size) + +instantiate_flash_quantized_sdpa_for_type(float, 64) +instantiate_flash_quantized_sdpa_for_type(bfloat16_t, 64) +instantiate_flash_quantized_sdpa_for_type(float16_t, 64) + // clang-format on diff --git a/mlx/backend/metal/kernels/ssm_replay.metal b/mlx/backend/metal/kernels/ssm_replay.metal new file mode 100644 index 0000000000..1f0b7a4d31 --- /dev/null +++ b/mlx/backend/metal/kernels/ssm_replay.metal @@ -0,0 +1,323 @@ +// Copyright © 2026 Eric Kryski. Spec 040 — Mamba / Mamba 2 state replay. +// +// Two kernels: +// 1. `ssm_step_record` — sequential forward over T steps capturing per-step +// `(dA, dBx)` into delta logs alongside the standard `(y, state_out)`. +// 2. `ssm_replay` — re-fold the first `k` log entries onto a recurrent +// state snapshot to recover state-after-k. +// +// Both kernels share the threadgroup shape from `ssm.metal`: +// Grid: (32, Dh, H * batch) ThreadGroup: (32, 8, 1) +// - thread_position_in_grid.x → ds_lane (0..31) +// - thread_position_in_grid.y → dh +// - thread_position_in_grid.z → batch * H + h +// Each simdgroup cooperatively reduces over the Ds state dimension. + +#include +#include +#include + +#include "utils.h" + +using namespace metal; + +constant bool ssm_record_has_mask [[function_constant(50)]]; +constant bool ssm_replay_has_mask [[function_constant(51)]]; + +// ============================================================================ +// SSM step record — sequential T-loop with delta capture. +// ============================================================================ +template +[[kernel]] void ssm_step_record( + const device T* x [[buffer(0)]], // [B, T, H, Dh] + const device T* A_log [[buffer(1)]], // [H] + const device T* B [[buffer(2)]], // [B, T, G, Ds] + const device T* C [[buffer(3)]], // [B, T, G, Ds] + const device T* D [[buffer(4)]], // [H] + const device T* dt [[buffer(5)]], // [B, T, H] + const device T* state_in [[buffer(6)]], // [B, H, Dh, Ds] + device T* y [[buffer(7)]], // [B, T, H, Dh] + device T* state_out [[buffer(8)]], // [B, H, Dh, Ds] + device T* dA_log [[buffer(9)]], // [B, T, H, Ds] + device T* dBx_log [[buffer(10)]], // [B, T, H, Dh, Ds] + const device bool* mask + [[buffer(11), + function_constant(ssm_record_has_mask)]], // [B, T] + const constant int& T_total [[buffer(12)]], + uint3 thread_position_in_grid [[thread_position_in_grid]], + uint3 thread_position_in_threadgroup [[thread_position_in_threadgroup]], + uint thread_index_in_simdgroup [[thread_index_in_simdgroup]]) { + constexpr int n_per_t = Ds / 32; + + auto n = thread_position_in_grid.z; // batch * H + h + auto h_idx = n % H; + auto b_idx = n / H; + // Group routing mirrors ssm.metal: g_idx = n / G. Kept for consistency + // with the existing dispatch but functionally we re-derive via b_idx + h_idx + // below for the per-step pointer math (B/C are [B, T, G, Ds]). + uint repeats = H / G; + uint g_idx_in_batch = h_idx / repeats; + + auto d_idx = thread_position_in_grid.y; // dh + auto ds_lane = thread_position_in_threadgroup.x; // 0..31 + + // Pre-load state into registers (per-(dh, ds_lane) slice of n_per_t entries). + float local_state[n_per_t]; + auto i_state_base = state_in + n * Dh * Ds + d_idx * Ds; + auto o_state_base = state_out + n * Dh * Ds + d_idx * Ds; + for (int i = 0; i < n_per_t; ++i) { + int s_idx = n_per_t * ds_lane + i; + local_state[i] = static_cast(i_state_base[s_idx]); + } + + float A = -fast::exp(static_cast(A_log[h_idx])); + + // Sequential T loop. + for (int t = 0; t < T_total; ++t) { + // Per-(b, t, h) indices + uint bt_h = (b_idx * uint(T_total) + uint(t)) * H + h_idx; + uint bt_g = (b_idx * uint(T_total) + uint(t)) * G + g_idx_in_batch; + uint bt = b_idx * uint(T_total) + uint(t); + + // Mask check: skip recurrence (dA=1, dBx=0) on masked timesteps so + // rollback past a masked t is identity-preserving. + bool active = true; + if (ssm_record_has_mask) { + active = mask[bt]; + } + + auto dt_v = static_cast(dt[bt_h]); + float dA; + if (active) { + dA = fast::exp(A * dt_v); + } else { + dA = 1.0f; + dt_v = 0.0f; // zeros the innovation contribution + } + + // Capture dA (per-Ds-lane redundant scalar; written once per ds slot). + // Layout dA_log[B, T, H, Ds]; each ds slot gets the same scalar dA so + // the replay kernel can read element-wise without a broadcast. + device T* dA_log_t = dA_log + bt_h * Ds; + for (int i = 0; i < n_per_t; ++i) { + int s_idx = n_per_t * ds_lane + i; + dA_log_t[s_idx] = static_cast(dA); + } + + auto x_v = static_cast(x[bt_h * Dh + d_idx]); + auto B_ = B + bt_g * Ds; + auto C_ = C + bt_g * Ds; + + device T* dBx_log_t = dBx_log + (((bt_h * Dh) + d_idx) * Ds); + + float y_acc = 0.0f; + for (int i = 0; i < n_per_t; ++i) { + int s_idx = n_per_t * ds_lane + i; + float B_v = static_cast(B_[s_idx]); + float dBx = active ? (x_v * dt_v * B_v) : 0.0f; + dBx_log_t[s_idx] = static_cast(dBx); + + // Update register state + local_state[i] = dA * local_state[i] + dBx; + + // y_t = C · state + D · x + y_acc += local_state[i] * static_cast(C_[s_idx]); + } + float y_sum = simd_sum(y_acc); + if (thread_index_in_simdgroup == 0) { + y[bt_h * Dh + d_idx] = + static_cast(y_sum + x_v * static_cast(D[h_idx])); + } + } + + // Final state write-back. + for (int i = 0; i < n_per_t; ++i) { + int s_idx = n_per_t * ds_lane + i; + o_state_base[s_idx] = static_cast(local_state[i]); + } +} + +// ============================================================================ +// SSM replay — re-fold first `k` log entries onto state snapshot. +// ============================================================================ +template +[[kernel]] void ssm_replay( + const device T* state_snapshot [[buffer(0)]], // [B, H, Dh, Ds] + const device T* dA_log [[buffer(1)]], // [B, T, H, Ds] + const device T* dBx_log [[buffer(2)]], // [B, T, H, Dh, Ds] + device T* state_after_k [[buffer(3)]], // [B, H, Dh, Ds] + const device bool* mask + [[buffer(4), + function_constant(ssm_replay_has_mask)]], // [B, T] + const constant int& k [[buffer(5)]], + const constant int& T_total [[buffer(6)]], + uint3 thread_position_in_grid [[thread_position_in_grid]], + uint3 thread_position_in_threadgroup [[thread_position_in_threadgroup]]) { + constexpr int n_per_t = Ds / 32; + + auto n = thread_position_in_grid.z; + auto h_idx = n % H; + auto b_idx = n / H; + + auto d_idx = thread_position_in_grid.y; + auto ds_lane = thread_position_in_threadgroup.x; + + // Load snapshot into registers. + float local_state[n_per_t]; + auto src_base = state_snapshot + n * Dh * Ds + d_idx * Ds; + for (int i = 0; i < n_per_t; ++i) { + int s_idx = n_per_t * ds_lane + i; + local_state[i] = static_cast(src_base[s_idx]); + } + + // Replay first k entries. + for (int t = 0; t < k; ++t) { + uint bt = b_idx * uint(T_total) + uint(t); + uint bt_h = bt * H + h_idx; + + bool active = true; + if (ssm_replay_has_mask) { + active = mask[bt]; + } + if (!active) { + // dA=1, dBx=0 — state unchanged. + continue; + } + + auto dA_t = dA_log + bt_h * Ds; + auto dBx_t = dBx_log + (((bt_h * Dh) + d_idx) * Ds); + + for (int i = 0; i < n_per_t; ++i) { + int s_idx = n_per_t * ds_lane + i; + local_state[i] = static_cast(dA_t[s_idx]) * local_state[i] + + static_cast(dBx_t[s_idx]); + } + } + + // Write result. + auto dst_base = state_after_k + n * Dh * Ds + d_idx * Ds; + for (int i = 0; i < n_per_t; ++i) { + int s_idx = n_per_t * ds_lane + i; + dst_base[s_idx] = static_cast(local_state[i]); + } +} + +// ============================================================================ +// Instantiations for Nemotron / Jamba / Granite / FalconH1 shapes. +// Matches ssm.metal's coverage. (Dh, Ds, H, G) combinations. +// ============================================================================ +#define instantiate_ssm_step_record(type, tname, dh, ds, h, g) \ + template [[host_name( \ + "ssm_step_record_" #tname "_" #dh "_" #ds "_" #h \ + "_" #g)]] [[kernel]] void \ + ssm_step_record( \ + const device type*, \ + const device type*, \ + const device type*, \ + const device type*, \ + const device type*, \ + const device type*, \ + const device type*, \ + device type*, \ + device type*, \ + device type*, \ + device type*, \ + const device bool*, \ + const constant int&, \ + uint3, \ + uint3, \ + uint); + +#define instantiate_ssm_replay(type, tname, dh, ds, h) \ + template [[host_name( \ + "ssm_replay_" #tname "_" #dh "_" #ds "_" #h)]] [[kernel]] void \ + ssm_replay( \ + const device type*, \ + const device type*, \ + const device type*, \ + device type*, \ + const device bool*, \ + const constant int&, \ + const constant int&, \ + uint3, \ + uint3); + +// Nemotron + family: Dh=64, Ds=64; common H=16/32/48, G=1/2/4/8. +#define instantiate_ssm_record_dh64_ds64_for(type, tname) \ + instantiate_ssm_step_record( \ + type, \ + tname, \ + 64, \ + 64, \ + 16, \ + 1) instantiate_ssm_step_record(type, tname, 64, 64, 16, 2) \ + instantiate_ssm_step_record(type, tname, 64, 64, 16, 4) \ + instantiate_ssm_step_record(type, tname, 64, 64, 16, 8) \ + instantiate_ssm_step_record(type, tname, 64, 64, 32, 1) \ + instantiate_ssm_step_record(type, tname, 64, 64, 32, 2) \ + instantiate_ssm_step_record(type, tname, 64, 64, 32, 4) \ + instantiate_ssm_step_record( \ + type, tname, 64, 64, 32, 8) \ + instantiate_ssm_step_record( \ + type, tname, 64, 64, 48, 1) \ + instantiate_ssm_step_record( \ + type, tname, 64, 64, 48, 2) \ + instantiate_ssm_step_record( \ + type, tname, 64, 64, 48, 4) \ + instantiate_ssm_step_record( \ + type, tname, 64, 64, 48, 8) \ + instantiate_ssm_replay( \ + type, tname, 64, 64, 16) \ + instantiate_ssm_replay( \ + type, tname, 64, 64, 32) \ + instantiate_ssm_replay( \ + type, \ + tname, \ + 64, \ + 64, \ + 48) + +// Mamba 2 wider state: Dh=128, Ds=128. +#define instantiate_ssm_record_dh128_ds128_for(type, tname) \ + instantiate_ssm_step_record( \ + type, \ + tname, \ + 128, \ + 128, \ + 16, \ + 1) instantiate_ssm_step_record(type, tname, 128, 128, 16, 2) \ + instantiate_ssm_step_record(type, tname, 128, 128, 16, 4) \ + instantiate_ssm_step_record(type, tname, 128, 128, 16, 8) \ + instantiate_ssm_step_record(type, tname, 128, 128, 32, 1) \ + instantiate_ssm_step_record(type, tname, 128, 128, 32, 2) \ + instantiate_ssm_step_record( \ + type, tname, 128, 128, 32, 4) \ + instantiate_ssm_step_record( \ + type, tname, 128, 128, 32, 8) \ + instantiate_ssm_step_record( \ + type, tname, 128, 128, 48, 1) \ + instantiate_ssm_step_record( \ + type, tname, 128, 128, 48, 2) \ + instantiate_ssm_step_record( \ + type, tname, 128, 128, 48, 4) \ + instantiate_ssm_step_record( \ + type, tname, 128, 128, 48, 8) \ + instantiate_ssm_replay( \ + type, tname, 128, 128, 16) \ + instantiate_ssm_replay( \ + type, \ + tname, \ + 128, \ + 128, \ + 32) \ + instantiate_ssm_replay( \ + type, \ + tname, \ + 128, \ + 128, \ + 48) + +instantiate_ssm_record_dh64_ds64_for(half, float16) + instantiate_ssm_record_dh64_ds64_for(bfloat16_t, bfloat16) + instantiate_ssm_record_dh128_ds128_for(half, float16) + instantiate_ssm_record_dh128_ds128_for(bfloat16_t, bfloat16) diff --git a/mlx/backend/metal/ssm_replay.cpp b/mlx/backend/metal/ssm_replay.cpp new file mode 100644 index 0000000000..933e5f085d --- /dev/null +++ b/mlx/backend/metal/ssm_replay.cpp @@ -0,0 +1,156 @@ +// Copyright © 2026 Eric Kryski. Spec 040 — Mamba state-replay dispatch. + +#include "mlx/backend/metal/device.h" +#include "mlx/backend/metal/utils.h" +#include "mlx/fast_primitives.h" + +namespace mlx::core::fast { + +// ============================================================================ +// SSMStepRecord: sequential T-loop with delta capture. +// ============================================================================ +void SSMStepRecord::eval_gpu( + const std::vector& inputs, + std::vector& outputs) { + auto& s = stream(); + auto& d = metal::device(s.device); + + auto& y_out = outputs[0]; + auto& state_out = outputs[1]; + auto& dA_log_out = outputs[2]; + auto& dBx_log_out = outputs[3]; + y_out.set_data(allocator::malloc(y_out.nbytes())); + state_out.set_data(allocator::malloc(state_out.nbytes())); + dA_log_out.set_data(allocator::malloc(dA_log_out.nbytes())); + dBx_log_out.set_data(allocator::malloc(dBx_log_out.nbytes())); + + const array& x = inputs[0]; + const array& A_log = inputs[1]; + const array& B = inputs[2]; + const array& C = inputs[3]; + const array& D_arr = inputs[4]; + const array& dt = inputs[5]; + const array& state_in = inputs[6]; + const array* mask = has_mask_ ? &inputs[7] : nullptr; + + int B_dim = x.shape(0); + int T_total = x.shape(1); + + std::string tname = type_to_name(y_out.dtype()); + std::string kname = "ssm_step_record_" + tname + "_" + std::to_string(Dh_) + + "_" + std::to_string(Ds_) + "_" + std::to_string(H_) + "_" + + std::to_string(G_); + + metal::MTLFCList func_consts = { + {&has_mask_, MTL::DataType::DataTypeBool, 50}, + }; + std::string hash_name = kname + (has_mask_ ? "_mask" : "_nomask"); + + auto& compute_encoder = metal::get_command_encoder(s); + auto kernel = d.get_kernel(kname, hash_name, func_consts); + compute_encoder.set_compute_pipeline_state(kernel); + + compute_encoder.set_input_array(x, 0); + compute_encoder.set_input_array(A_log, 1); + compute_encoder.set_input_array(B, 2); + compute_encoder.set_input_array(C, 3); + compute_encoder.set_input_array(D_arr, 4); + compute_encoder.set_input_array(dt, 5); + compute_encoder.set_input_array(state_in, 6); + compute_encoder.set_output_array(y_out, 7); + compute_encoder.set_output_array(state_out, 8); + compute_encoder.set_output_array(dA_log_out, 9); + compute_encoder.set_output_array(dBx_log_out, 10); + if (has_mask_) { + compute_encoder.set_input_array(*mask, 11); + } + compute_encoder.set_bytes(T_total, 12); + + // Grid: (32, Dh, B * H). ThreadGroup: (32, 8, 1). One simdgroup per (b, h, + // dh). + compute_encoder.dispatch_threadgroups( + MTL::Size(1, Dh_ / 8, H_ * B_dim), MTL::Size(32, 8, 1)); +} + +bool SSMStepRecord::is_equivalent(const Primitive& other) const { + const SSMStepRecord& o = static_cast(other); + return Dh_ == o.Dh_ && Ds_ == o.Ds_ && H_ == o.H_ && G_ == o.G_ && + has_mask_ == o.has_mask_; +} + +std::vector SSMStepRecord::output_shapes( + const std::vector& inputs) { + const array& x = inputs[0]; + const array& B = inputs[2]; + const array& state_in = inputs[6]; + int B_dim = x.shape(0); + int T = x.shape(1); + int H = x.shape(2); + int dh = x.shape(3); + int ds = B.shape(3); + return { + {B_dim, T, H, dh}, // y + state_in.shape(), // state_out + {B_dim, T, H, ds}, // dA_log + {B_dim, T, H, dh, ds} // dBx_log + }; +} + +// ============================================================================ +// SSMReplay: replay first k log entries onto state snapshot. +// ============================================================================ +void SSMReplay::eval_gpu( + const std::vector& inputs, + std::vector& outputs) { + auto& s = stream(); + auto& d = metal::device(s.device); + + auto& out = outputs[0]; + out.set_data(allocator::malloc(out.nbytes())); + + const array& state_snapshot = inputs[0]; + const array& dA_log = inputs[1]; + const array& dBx_log = inputs[2]; + const array* mask = has_mask_ ? &inputs[3] : nullptr; + + int B_dim = state_snapshot.shape(0); + int T_total = dA_log.shape(1); + + std::string tname = type_to_name(out.dtype()); + std::string kname = "ssm_replay_" + tname + "_" + std::to_string(Dh_) + "_" + + std::to_string(Ds_) + "_" + std::to_string(H_); + + metal::MTLFCList func_consts = { + {&has_mask_, MTL::DataType::DataTypeBool, 51}, + }; + std::string hash_name = kname + (has_mask_ ? "_mask" : "_nomask"); + + auto& compute_encoder = metal::get_command_encoder(s); + auto kernel = d.get_kernel(kname, hash_name, func_consts); + compute_encoder.set_compute_pipeline_state(kernel); + + compute_encoder.set_input_array(state_snapshot, 0); + compute_encoder.set_input_array(dA_log, 1); + compute_encoder.set_input_array(dBx_log, 2); + compute_encoder.set_output_array(out, 3); + if (has_mask_) { + compute_encoder.set_input_array(*mask, 4); + } + compute_encoder.set_bytes(accepted_prefix_, 5); + compute_encoder.set_bytes(T_total, 6); + + compute_encoder.dispatch_threadgroups( + MTL::Size(1, Dh_ / 8, H_ * B_dim), MTL::Size(32, 8, 1)); +} + +bool SSMReplay::is_equivalent(const Primitive& other) const { + const SSMReplay& o = static_cast(other); + return Dh_ == o.Dh_ && Ds_ == o.Ds_ && H_ == o.H_ && + accepted_prefix_ == o.accepted_prefix_ && has_mask_ == o.has_mask_; +} + +std::vector SSMReplay::output_shapes(const std::vector& inputs) { + return {inputs[0].shape()}; +} + +} // namespace mlx::core::fast diff --git a/mlx/fast.cpp b/mlx/fast.cpp index 28577ee337..8ed498f5d3 100644 --- a/mlx/fast.cpp +++ b/mlx/fast.cpp @@ -2090,4 +2090,179 @@ std::vector ssm_step( return outputs; } +// ============================================================================ +// Spec 041 phase 1.1: flash quantized SDPA +// ============================================================================ +array flash_quantized_sdpa( + const array& queries, + const array& k_packed, + const array& k_scales, + const array& k_biases, + const array& v_packed, + const array& v_scales, + const array& v_biases, + const float scale, + int bits, + int group_size, + const std::string& mask_mode /* = "" */, + std::optional mask_arr /* = {} */, + const std::optional& sinks /* = {} */, + StreamOrDevice s_ /* = {} */) { + auto s = to_stream(s_); + + if (queries.ndim() != 4) { + throw std::invalid_argument( + "[flash_quantized_sdpa] queries must be rank 4 [B, n_q, T_q, D]"); + } + bool do_causal = (mask_mode == "causal"); + bool has_arr_mask = mask_arr.has_value() && !do_causal; + if (!mask_mode.empty() && mask_mode != "causal" && mask_mode != "array") { + throw std::invalid_argument( + "[flash_quantized_sdpa] mask_mode must be 'causal', 'array', or ''"); + } + + int B = queries.shape(0); + int n_q_heads = queries.shape(1); + int T_q = queries.shape(2); + int D = queries.shape(3); + int n_kv_heads = k_packed.shape(1); + int T_kv = k_packed.shape(2); + int V = v_scales.shape(-1) * group_size; + if (V == 0) + V = D; + + Shape out_shape = {B, n_q_heads, T_q, V}; + + auto fallback = [](const std::vector&) -> std::vector { + throw std::runtime_error("[flash_quantized_sdpa] Only runs on GPU"); + }; + + std::vector inputs = { + queries, + k_packed, + astype(k_scales, queries.dtype(), s), + astype(k_biases, queries.dtype(), s), + v_packed, + astype(v_scales, queries.dtype(), s), + astype(v_biases, queries.dtype(), s)}; + + if (has_arr_mask) { + inputs.push_back(*mask_arr); + } + bool has_sinks = sinks.has_value(); + if (has_sinks) { + inputs.push_back(astype(*sinks, queries.dtype(), s)); + } + + return array( + std::move(out_shape), + queries.dtype(), + std::make_shared( + s, + fallback, + scale, + do_causal, + has_sinks, + bits, + group_size, + n_q_heads, + n_kv_heads), + std::move(inputs)); +} + +// ============================================================================ +// Spec 040: Mamba state replay +// ============================================================================ +std::vector ssm_step_record( + const array& x, + const array& A_log, + const array& B, + const array& C, + const array& D, + const array& dt, + const array& state, + const std::optional& mask /* = {} */, + StreamOrDevice s_ /* = {} */) { + auto s = to_stream(s_); + auto out_type = x.dtype(); + + int B_dim = x.shape(0); + int T = x.shape(1); + int H = x.shape(2); + int dh = x.shape(3); + int G = B.shape(2); + int ds = B.shape(3); + + Shape y_shape = {B_dim, T, H, dh}; + Shape state_shape = state.shape(); + Shape dA_log_shape = {B_dim, T, H, ds}; + Shape dBx_log_shape = {B_dim, T, H, dh, ds}; + + auto fallback = [](const std::vector&) -> std::vector { + throw std::runtime_error("[ssm_step_record] Only runs on GPU"); + }; + + std::vector inputs = { + astype(x, out_type, s), + astype(A_log, out_type, s), + astype(B, out_type, s), + astype(C, out_type, s), + astype(D, out_type, s), + astype(dt, out_type, s), + astype(state, out_type, s)}; + bool has_mask = mask.has_value(); + if (has_mask) { + inputs.push_back(astype(*mask, out_type, s)); + } + + auto outputs = array::make_arrays( + {std::move(y_shape), + std::move(state_shape), + std::move(dA_log_shape), + std::move(dBx_log_shape)}, + {out_type, out_type, out_type, out_type}, + std::make_shared(s, fallback, dh, ds, H, G, has_mask), + std::move(inputs)); + async_eval(outputs); + return outputs; +} + +array ssm_replay( + const array& state_snapshot, + const array& dA_log, + const array& dBx_log, + int accepted_prefix, + const std::optional& mask /* = {} */, + StreamOrDevice s_ /* = {} */) { + auto s = to_stream(s_); + auto out_type = state_snapshot.dtype(); + + int B_dim = state_snapshot.shape(0); + int H = state_snapshot.shape(1); + int dh = state_snapshot.shape(2); + int ds = state_snapshot.shape(3); + + Shape out_shape = {B_dim, H, dh, ds}; + + auto fallback = [](const std::vector&) -> std::vector { + throw std::runtime_error("[ssm_replay] Only runs on GPU"); + }; + + std::vector inputs = { + astype(state_snapshot, out_type, s), + astype(dA_log, out_type, s), + astype(dBx_log, out_type, s)}; + bool has_mask = mask.has_value(); + if (has_mask) { + inputs.push_back(astype(*mask, out_type, s)); + } + + return array( + std::move(out_shape), + out_type, + std::make_shared( + s, fallback, dh, ds, H, accepted_prefix, has_mask), + std::move(inputs)); +} + } // namespace mlx::core::fast diff --git a/mlx/fast.h b/mlx/fast.h index 0d5f104ecb..4479cfe046 100644 --- a/mlx/fast.h +++ b/mlx/fast.h @@ -440,4 +440,63 @@ MLX_API std::vector ssm_step( int G, StreamOrDevice s = {}); +/// Flash quantized SDPA — spec 041 phase 1.1. +/// +/// Mirrors `scaled_dot_product_attention` but consumes affine-quantized K and +/// V (each as a triple `(packed_indices, scales, biases)`) and dequantises +/// inline inside the tiled online-softmax loop. Output shape and semantics +/// match the unquantized path. +/// +/// `mask_mode` accepts `""`, `"causal"`. Array masks pass through `mask_arr`. +/// `sinks` is an optional `[n_q_heads]` tensor of per-head sink logits folded +/// into the softmax denominator. +MLX_API array flash_quantized_sdpa( + const array& queries, + const array& k_packed, + const array& k_scales, + const array& k_biases, + const array& v_packed, + const array& v_scales, + const array& v_biases, + const float scale, + int bits, + int group_size, + const std::string& mask_mode = "", + std::optional mask_arr = {}, + const std::optional& sinks = {}, + StreamOrDevice s = {}); + +/// Mamba state-replay primitive — sequential SSM step with per-step delta-log +/// capture. Drop-in replacement for the L>1 forward path during a recording +/// session; emits a per-step `(dA, dBx)` log alongside the standard +/// `(y, state_out)` outputs. +/// +/// Returns `{y, state_out, dA_log, dBx_log}`: +/// - y [B, T, H, dh] +/// - state_out [B, H, dh, ds] +/// - dA_log [B, T, H, ds] +/// - dBx_log [B, T, H, dh, ds] +MLX_API std::vector ssm_step_record( + const array& x, + const array& A_log, + const array& B, + const array& C, + const array& D, + const array& dt, + const array& state, + const std::optional& mask = {}, + StreamOrDevice s = {}); + +/// Replay the first `accepted_prefix` entries of a delta log produced by +/// `ssm_step_record` onto a state snapshot, returning the post-replay state. +/// +/// Output: [B, H, dh, ds] +MLX_API array ssm_replay( + const array& state_snapshot, + const array& dA_log, + const array& dBx_log, + int accepted_prefix, + const std::optional& mask = {}, + StreamOrDevice s = {}); + } // namespace mlx::core::fast diff --git a/mlx/fast_primitives.h b/mlx/fast_primitives.h index 48ea7da128..e7e3c36f50 100644 --- a/mlx/fast_primitives.h +++ b/mlx/fast_primitives.h @@ -1104,4 +1104,183 @@ class SSMStep : public Custom { int G_; }; +// Spec 041 Phase 1.1: fused flash-quantized SDPA — affine-quantized K and V +// are dequantised inline inside a tiled online-softmax loop. Same shape and +// semantics as MLXFast's `scaled_dot_product_attention`; replaces the +// discrete `quantizedMM → softmax → quantizedMM` triple at affine call sites. +// +// Inputs (in order): +// queries — [B, n_q_heads, T_q, D] +// k_packed — [B, n_kv_heads, T_kv, D / (32/bits)] uint32 +// k_scales — [B, n_kv_heads, T_kv, D / group_size] T +// k_biases — [B, n_kv_heads, T_kv, D / group_size] T +// v_packed — [B, n_kv_heads, T_kv, V / (32/bits)] uint32 +// v_scales / v_biases — same shape rule as K. +// mask — optional bool / float mask [..., T_q, T_kv]. +// sinks — optional [n_q_heads] per-Q-head sink logits. +// +// Output: [B, n_q_heads, T_q, V] in queries' dtype. +class FlashQuantizedSDPA : public Custom { + public: + FlashQuantizedSDPA( + Stream stream, + std::function(std::vector)> fallback, + float scale, + bool do_causal, + bool has_sinks, + int bits, + int group_size, + int n_q_heads, + int n_kv_heads) + : Custom(stream, std::move(fallback)), + scale_(scale), + do_causal_(do_causal), + has_sinks_(has_sinks), + bits_(bits), + group_size_(group_size), + n_q_heads_(n_q_heads), + n_kv_heads_(n_kv_heads) {} + + void eval_cpu(const std::vector& inputs, std::vector& outputs) + override { + throw std::runtime_error("FlashQuantizedSDPA only runs on GPU"); + } + void eval_gpu(const std::vector& inputs, std::vector& outputs) + override; + + DEFINE_NAME(FlashQuantizedSDPA) + bool is_equivalent(const Primitive& other) const override; + std::vector output_shapes(const std::vector& inputs) override; + auto state() const { + return std::make_tuple( + nullptr, + scale_, + do_causal_, + has_sinks_, + bits_, + group_size_, + n_q_heads_, + n_kv_heads_); + } + + private: + float scale_; + bool do_causal_; + bool has_sinks_; + int bits_; + int group_size_; + int n_q_heads_; + int n_kv_heads_; +}; + +// Spec 040: Mamba / Mamba 2 selective-SSM step + delta-log capture for +// state-replay rollback. Sequential per-step recurrence — written this way +// (instead of leveraging ssmAttn's parallel scan) so we can materialise the +// per-step `(dA_t, dBx_t)` pair into a delta log that `SSMReplay` re-folds +// during n-gram speculative rollback. +// +// Inputs: +// x — [B, T, H, dh] hidden state input +// ALog — [H] state-decay log +// B — [B, T, G, ds] per-step input gate (G ≤ H, GQA-expanded) +// C — [B, T, G, ds] per-step output gate +// D — [H] skip +// dt — [B, T, H] per-step time-step +// state_in — [B, H, dh, ds] recurrent state at t=0 +// mask? — [B, T] (optional, branchless-masked timesteps zero dA/dBx) +// +// Outputs: +// y — [B, T, H, dh] +// state_out — [B, H, dh, ds] +// dA_log — [B, T, H, ds] per-step decay (for SSMReplay) +// dBx_log — [B, T, H, dh, ds] per-step innovation (for SSMReplay) +class SSMStepRecord : public Custom { + public: + SSMStepRecord( + Stream stream, + std::function(std::vector)> fallback, + int Dh, + int Ds, + int H, + int G, + bool has_mask) + : Custom(stream, std::move(fallback)), + Dh_(Dh), + Ds_(Ds), + H_(H), + G_(G), + has_mask_(has_mask) {} + + void eval_cpu(const std::vector& inputs, std::vector& outputs) + override { + throw std::runtime_error("SSMStepRecord only runs on GPU"); + } + void eval_gpu(const std::vector& inputs, std::vector& outputs) + override; + + DEFINE_NAME(SSMStepRecord) + bool is_equivalent(const Primitive& other) const override; + std::vector output_shapes(const std::vector& inputs) override; + auto state() const { + return std::make_tuple(nullptr, Dh_, Ds_, H_, G_, has_mask_); + } + + private: + int Dh_; + int Ds_; + int H_; + int G_; + bool has_mask_; +}; + +// Rollback step for Mamba state replay. Re-folds the first `k` entries of +// the delta log produced by `SSMStepRecord` onto a recurrent-state snapshot. +// +// Inputs: +// state_snapshot — [B, H, dh, ds] pre-record recurrent state +// dA_log — [B, T, H, ds] +// dBx_log — [B, T, H, dh, ds] +// mask? — [B, T] (optional — masked steps skip replay) +// +// Output: +// state_after_k — [B, H, dh, ds] state after folding entries [0, k). +class SSMReplay : public Custom { + public: + SSMReplay( + Stream stream, + std::function(std::vector)> fallback, + int Dh, + int Ds, + int H, + int accepted_prefix, + bool has_mask) + : Custom(stream, std::move(fallback)), + Dh_(Dh), + Ds_(Ds), + H_(H), + accepted_prefix_(accepted_prefix), + has_mask_(has_mask) {} + + void eval_cpu(const std::vector& inputs, std::vector& outputs) + override { + throw std::runtime_error("SSMReplay only runs on GPU"); + } + void eval_gpu(const std::vector& inputs, std::vector& outputs) + override; + + DEFINE_NAME(SSMReplay) + bool is_equivalent(const Primitive& other) const override; + std::vector output_shapes(const std::vector& inputs) override; + auto state() const { + return std::make_tuple(nullptr, Dh_, Ds_, H_, accepted_prefix_, has_mask_); + } + + private: + int Dh_; + int Ds_; + int H_; + int accepted_prefix_; + bool has_mask_; +}; + } // namespace mlx::core::fast diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index f3b05c7b4c..221d3a057c 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -10,6 +10,11 @@ if(MLX_BUILD_METAL OR MLX_BUILD_CUDA) set(METAL_TEST_SOURCES gpu_tests.cpp) endif() +if(MLX_BUILD_METAL) + list(APPEND METAL_TEST_SOURCES flash_quantized_sdpa_tests.cpp + ssm_replay_tests.cpp) +endif() + include(${doctest_SOURCE_DIR}/scripts/cmake/doctest.cmake) target_sources( diff --git a/tests/flash_quantized_sdpa_tests.cpp b/tests/flash_quantized_sdpa_tests.cpp new file mode 100644 index 0000000000..274a46535f --- /dev/null +++ b/tests/flash_quantized_sdpa_tests.cpp @@ -0,0 +1,261 @@ +// Copyright (c) 2026 Eric Kryski. Spec 041 phase 1.1 — C++ doctest coverage +// for the fused flash quantized SDPA primitive. + +#include + +#include "doctest/doctest.h" +#include "mlx/mlx.h" + +using namespace mlx::core; + +namespace { + +// Affine-quantize the last dim of `x` at the given bits / group_size and +// return {packed, scales, biases} matching the layout `flash_quantized_sdpa` +// expects on its k_* / v_* inputs. +struct Quantized { + array packed; + array scales; + array biases; +}; + +Quantized affine_quant(const array& x, int bits, int group_size) { + auto qout = quantize(x, group_size, bits, "affine"); + return {qout[0], qout[1], qout[2]}; +} + +// Convenience: max(abs(a - b)) reduced to a scalar float on CPU. +float max_abs_diff(const array& a, const array& b) { + auto diff = abs(subtract(a, b)); + auto m = max(diff, /*keepdims=*/false); + // Cast through float32 in case inputs are fp16/bf16. + return astype(m, float32, Device::cpu).item(); +} + +float max_abs(const array& a) { + auto m = max(abs(a), /*keepdims=*/false); + return astype(m, float32, Device::cpu).item(); +} + +} // namespace + +TEST_CASE("flash quantized sdpa output shape and finite") { + // Q [B=1, n_q=4, T_q=1, D=128], K/V [B=1, n_kv=4, T_kv=256, D=128]. + const int B = 1, n_h = 4, T_q = 1, T_kv = 256, D = 128; + const int bits = 4, group_size = 64; + const float scale = 1.0f / std::sqrt(static_cast(D)); + + auto q = random::normal({B, n_h, T_q, D}, float16, std::nullopt, Device::gpu); + auto k = + random::normal({B, n_h, T_kv, D}, float16, std::nullopt, Device::gpu); + auto v = + random::normal({B, n_h, T_kv, D}, float16, std::nullopt, Device::gpu); + + auto kq = affine_quant(k, bits, group_size); + auto vq = affine_quant(v, bits, group_size); + + auto out = fast::flash_quantized_sdpa( + q, + kq.packed, + kq.scales, + kq.biases, + vq.packed, + vq.scales, + vq.biases, + scale, + bits, + group_size, + /*mask_mode=*/"", + /*mask_arr=*/std::nullopt, + /*sinks=*/std::nullopt, + Device::gpu); + eval(out); + + CHECK_EQ(out.shape(), Shape{B, n_h, T_q, D}); + CHECK(all(isfinite(out)).item()); +} + +TEST_CASE("flash quantized sdpa matches dequant then sdpa reference") { + // Same layout as the shape test. Reference: dequantize K/V then call the + // unquantized `fast::scaled_dot_product_attention`. + const int B = 1, n_h = 4, T_q = 1, T_kv = 256, D = 128; + const int bits = 4, group_size = 64; + const float scale = 1.0f / std::sqrt(static_cast(D)); + + auto q = random::normal({B, n_h, T_q, D}, float16, std::nullopt, Device::gpu); + auto k = + random::normal({B, n_h, T_kv, D}, float16, std::nullopt, Device::gpu); + auto v = + random::normal({B, n_h, T_kv, D}, float16, std::nullopt, Device::gpu); + + auto kq = affine_quant(k, bits, group_size); + auto vq = affine_quant(v, bits, group_size); + + auto out_flash = fast::flash_quantized_sdpa( + q, + kq.packed, + kq.scales, + kq.biases, + vq.packed, + vq.scales, + vq.biases, + scale, + bits, + group_size, + /*mask_mode=*/"", + /*mask_arr=*/std::nullopt, + /*sinks=*/std::nullopt, + Device::gpu); + + // Reference: dequantize then run the standard fast SDPA. + auto k_dq = dequantize( + kq.packed, + kq.scales, + kq.biases, + group_size, + bits, + "affine", + std::nullopt, + float16, + Device::gpu); + auto v_dq = dequantize( + vq.packed, + vq.scales, + vq.biases, + group_size, + bits, + "affine", + std::nullopt, + float16, + Device::gpu); + auto out_ref = fast::scaled_dot_product_attention( + q, k_dq, v_dq, scale, "", std::nullopt, std::nullopt, Device::gpu); + eval(out_flash, out_ref); + + // Tolerance: affine 4-bit quant + tiled online-softmax adds noise that is + // both relative (per-element magnitude) and absolute (small drift on + // near-zero outputs). 5% relative + 5e-3 absolute is well above what we've + // observed in practice (~1-2%) but tight enough to catch real bugs. + float ref_max = max_abs(out_ref); + float tol = 0.05f * ref_max + 5e-3f; + float diff = max_abs_diff(out_flash, out_ref); + CHECK(diff < tol); +} + +TEST_CASE("flash quantized sdpa with causal mask") { + // Square prefill: T_q == T_kv == 8 so causal masking is observable. The + // no-mask output should differ from the causal output because the + // upper-triangular K positions get masked out for early Q tokens. + const int B = 1, n_h = 4, T = 8, D = 128; + const int bits = 4, group_size = 64; + const float scale = 1.0f / std::sqrt(static_cast(D)); + + auto q = random::normal({B, n_h, T, D}, float16, std::nullopt, Device::gpu); + auto k = random::normal({B, n_h, T, D}, float16, std::nullopt, Device::gpu); + auto v = random::normal({B, n_h, T, D}, float16, std::nullopt, Device::gpu); + + auto kq = affine_quant(k, bits, group_size); + auto vq = affine_quant(v, bits, group_size); + + auto out_causal = fast::flash_quantized_sdpa( + q, + kq.packed, + kq.scales, + kq.biases, + vq.packed, + vq.scales, + vq.biases, + scale, + bits, + group_size, + /*mask_mode=*/"causal", + /*mask_arr=*/std::nullopt, + /*sinks=*/std::nullopt, + Device::gpu); + auto out_nomask = fast::flash_quantized_sdpa( + q, + kq.packed, + kq.scales, + kq.biases, + vq.packed, + vq.scales, + vq.biases, + scale, + bits, + group_size, + /*mask_mode=*/"", + /*mask_arr=*/std::nullopt, + /*sinks=*/std::nullopt, + Device::gpu); + eval(out_causal, out_nomask); + + CHECK_EQ(out_causal.shape(), Shape{B, n_h, T, D}); + CHECK(all(isfinite(out_causal)).item()); + // Sanity: causal mask must change the output (otherwise the mask flag + // wasn't honoured). + CHECK(max_abs_diff(out_causal, out_nomask) > 1e-3f); +} + +TEST_CASE("flash quantized sdpa bits 8") { + // 8-bit affine quant: tighter agreement with the dequant-then-SDPA + // reference than the 4-bit test. + const int B = 1, n_h = 4, T_q = 1, T_kv = 256, D = 128; + const int bits = 8, group_size = 64; + const float scale = 1.0f / std::sqrt(static_cast(D)); + + auto q = random::normal({B, n_h, T_q, D}, float16, std::nullopt, Device::gpu); + auto k = + random::normal({B, n_h, T_kv, D}, float16, std::nullopt, Device::gpu); + auto v = + random::normal({B, n_h, T_kv, D}, float16, std::nullopt, Device::gpu); + + auto kq = affine_quant(k, bits, group_size); + auto vq = affine_quant(v, bits, group_size); + + auto out_flash = fast::flash_quantized_sdpa( + q, + kq.packed, + kq.scales, + kq.biases, + vq.packed, + vq.scales, + vq.biases, + scale, + bits, + group_size, + /*mask_mode=*/"", + /*mask_arr=*/std::nullopt, + /*sinks=*/std::nullopt, + Device::gpu); + + auto k_dq = dequantize( + kq.packed, + kq.scales, + kq.biases, + group_size, + bits, + "affine", + std::nullopt, + float16, + Device::gpu); + auto v_dq = dequantize( + vq.packed, + vq.scales, + vq.biases, + group_size, + bits, + "affine", + std::nullopt, + float16, + Device::gpu); + auto out_ref = fast::scaled_dot_product_attention( + q, k_dq, v_dq, scale, "", std::nullopt, std::nullopt, Device::gpu); + eval(out_flash, out_ref); + + // 8-bit affine quant noise is ~1/16 of 4-bit. Use a tighter (still + // generous) 2% relative + 2e-3 absolute envelope. + float ref_max = max_abs(out_ref); + float tol = 0.02f * ref_max + 2e-3f; + float diff = max_abs_diff(out_flash, out_ref); + CHECK(diff < tol); +} diff --git a/tests/ssm_replay_tests.cpp b/tests/ssm_replay_tests.cpp new file mode 100644 index 0000000000..47b1d987ab --- /dev/null +++ b/tests/ssm_replay_tests.cpp @@ -0,0 +1,146 @@ +// Copyright (c) 2026 Eric Kryski. Spec 040 — C++ doctest coverage for the +// Mamba state-replay primitives: `ssm_step_record` and `ssm_replay`. + +#include + +#include "doctest/doctest.h" +#include "mlx/mlx.h" + +using namespace mlx::core; + +namespace { + +float max_abs_diff(const array& a, const array& b) { + auto diff = abs(subtract(a, b)); + auto m = max(diff, /*keepdims=*/false); + return astype(m, float32, Device::cpu).item(); +} + +} // namespace + +// Note on shapes (cf. mlx/backend/metal/kernels/ssm_replay.metal): +// x: [B, T, H, Dh] +// A_log: [H] +// B, C: [B, T, G, Ds] (G = key/value groups; H is a multiple of G) +// D: [H] +// dt: [B, T, H] +// state: [B, H, Dh, Ds] +// Available kernel instantiations cover H in {16, 32, 48}, G in {1, 2, 4, 8}, +// and (Dh, Ds) in {(64, 64), (128, 128)}. H=4 is not instantiated, so these +// tests use H=16, G=1 (the smallest available shape) instead. + +TEST_CASE("ssm step record returns four arrays") { + const int B = 1, T = 4, H = 16, G = 1, Dh = 64, Ds = 64; + + auto x = random::normal({B, T, H, Dh}, float16, std::nullopt, Device::gpu); + auto A_log = random::normal({H}, float16, std::nullopt, Device::gpu); + auto B_arr = + random::normal({B, T, G, Ds}, float16, std::nullopt, Device::gpu); + auto C_arr = + random::normal({B, T, G, Ds}, float16, std::nullopt, Device::gpu); + auto D_arr = random::normal({H}, float16, std::nullopt, Device::gpu); + // Small dt magnitudes keep dA = exp(-exp(A_log)*dt) bounded — otherwise + // negative-tailed random dt with positive A_log overflows to inf/nan. + auto dt = multiply( + random::normal({B, T, H}, float16, std::nullopt, Device::gpu), + array(0.1f, float16), + Device::gpu); + auto state = zeros({B, H, Dh, Ds}, float16, Device::gpu); + + auto outs = fast::ssm_step_record( + x, A_log, B_arr, C_arr, D_arr, dt, state, std::nullopt, Device::gpu); + eval(outs); + + CHECK_EQ(outs.size(), size_t{4}); + // y: [B, T, H, Dh] + CHECK_EQ(outs[0].shape(), Shape{B, T, H, Dh}); + // state_out: [B, H, Dh, Ds] + CHECK_EQ(outs[1].shape(), Shape{B, H, Dh, Ds}); + // dA_log: [B, T, H, Ds] + CHECK_EQ(outs[2].shape(), Shape{B, T, H, Ds}); + // dBx_log: [B, T, H, Dh, Ds] + CHECK_EQ(outs[3].shape(), Shape{B, T, H, Dh, Ds}); + CHECK(all(isfinite(outs[0])).item()); + CHECK(all(isfinite(outs[1])).item()); +} + +TEST_CASE("ssm replay round trip") { + // Record a forward pass, then replay the FULL log onto the initial + // snapshot. The replayed state should match `state_out` from the record + // call within tight tolerance (fp16 accumulation noise only). + const int B = 1, T = 4, H = 16, G = 1, Dh = 64, Ds = 64; + + auto x = random::normal({B, T, H, Dh}, float16, std::nullopt, Device::gpu); + auto A_log = random::normal({H}, float16, std::nullopt, Device::gpu); + auto B_arr = + random::normal({B, T, G, Ds}, float16, std::nullopt, Device::gpu); + auto C_arr = + random::normal({B, T, G, Ds}, float16, std::nullopt, Device::gpu); + auto D_arr = random::normal({H}, float16, std::nullopt, Device::gpu); + // Small dt magnitudes keep dA = exp(-exp(A_log) * dt) numerically tame and + // bounded away from underflow over T steps. + auto dt = multiply( + random::normal({B, T, H}, float16, std::nullopt, Device::gpu), + array(0.1f, float16), + Device::gpu); + auto initial = zeros({B, H, Dh, Ds}, float16, Device::gpu); + + auto outs = fast::ssm_step_record( + x, A_log, B_arr, C_arr, D_arr, dt, initial, std::nullopt, Device::gpu); + auto& state_out = outs[1]; + auto& dA_log = outs[2]; + auto& dBx_log = outs[3]; + + auto replayed = fast::ssm_replay( + initial, + dA_log, + dBx_log, + /*accepted_prefix=*/T, + std::nullopt, + Device::gpu); + eval(state_out, replayed); + + CHECK_EQ(replayed.shape(), state_out.shape()); + // Tolerance: 5e-3 covers fp16 mantissa noise (~1e-3 per step) accumulated + // over T=4 sequential dA-scaled updates. Empirically ~2e-3 in practice. + CHECK(max_abs_diff(replayed, state_out) < 5e-3f); +} + +TEST_CASE("ssm replay partial accept differs from full") { + // Record T=8 steps, then replay only the first 4. The partial-replay state + // should differ from BOTH the initial snapshot AND the full-T state_out: + // proving the kernel is honouring `accepted_prefix` rather than always + // replaying the entire log. + const int B = 1, T = 8, H = 16, G = 1, Dh = 64, Ds = 64; + + auto x = random::normal({B, T, H, Dh}, float16, std::nullopt, Device::gpu); + auto A_log = random::normal({H}, float16, std::nullopt, Device::gpu); + auto B_arr = + random::normal({B, T, G, Ds}, float16, std::nullopt, Device::gpu); + auto C_arr = + random::normal({B, T, G, Ds}, float16, std::nullopt, Device::gpu); + auto D_arr = random::normal({H}, float16, std::nullopt, Device::gpu); + auto dt = multiply( + random::normal({B, T, H}, float16, std::nullopt, Device::gpu), + array(0.1f, float16), + Device::gpu); + auto initial = zeros({B, H, Dh, Ds}, float16, Device::gpu); + + auto outs = fast::ssm_step_record( + x, A_log, B_arr, C_arr, D_arr, dt, initial, std::nullopt, Device::gpu); + auto& state_full = outs[1]; + auto& dA_log = outs[2]; + auto& dBx_log = outs[3]; + + auto state_partial = fast::ssm_replay( + initial, + dA_log, + dBx_log, + /*accepted_prefix=*/4, + std::nullopt, + Device::gpu); + eval(state_full, state_partial); + + CHECK(max_abs_diff(state_partial, initial) > 1e-4f); + CHECK(max_abs_diff(state_partial, state_full) > 1e-4f); +}