Skip to content

fast: spec 041 phase 1.1 + spec 040 — fused quantized SDPA + Mamba state-replay kernels - #30

Merged
ekryski merged 2 commits into
alphafrom
ek/spec-041-040-fused-kernels
May 14, 2026
Merged

ekryski merged 2 commits into
alphafrom
ek/spec-041-040-fused-kernels

Conversation

@ekryski

@ekryski ekryski commented May 13, 2026

Copy link
Copy Markdown
Owner

Two new Metal primitive families: FlashQuantizedSDPA (spec 041 phase 1.1) and SSMStepRecord/SSMReplay (spec 040). Both build cleanly and have round-trip tests in mlx-swift-lm. See companion PRs in mlx-c, mlx-swift, mlx-swift-lm.

…ate-replay kernels

Two new primitive families landing together:

## Spec 041 Phase 1.1 — FlashQuantizedSDPA

Tiled online-softmax SDPA kernel that consumes affine-quantized K and V
triples `(packed_indices, scales, biases)` and dequantises inline per
thread. Same shape/semantics as the unquantized SDPA: GQA / MQA,
causal mask, array mask, sinks fold all supported.

Replaces the discrete `quantizedMM → softmax → quantizedMM` shape at
affine call sites — never materialises the [B, H, L, T] score matrix.

Files:
- `mlx/backend/metal/kernels/flash_quantized_sdpa.h` — template kernel
  body, modelled on `sdpa_vector.h` with per-thread inline dequant.
- `mlx/backend/metal/kernels/flash_quantized_sdpa.metal` —
  instantiations: float / bfloat16_t / float16_t × {2,3,4,6,8}-bit ×
  groupSize 64 × head dims {64, 96, 128, 256, 512}.
- `mlx/backend/metal/flash_quantized_sdpa.cpp` — dispatch + function-
  constant setup (mask mode, sinks, causal, transposed queries).
- `mlx/fast.h` / `mlx/fast.cpp` — public `flash_quantized_sdpa(...)`
  entry point + `FlashQuantizedSDPA` Primitive.

## Spec 040 — SSMStepRecord + SSMReplay

Mamba / Mamba 2 selective-SSM step with per-step delta-log capture.

- `ssm_step_record`: sequential per-step recurrence. Emits per-step
  `(dA, dBx)` log alongside `(y, state_out)`. Masked timesteps fold
  `dA=1, dBx=0` so rollback past a masked t is identity-preserving.
- `ssm_replay`: re-folds first `k` log entries onto a snapshot.
  Linear in `k`, parallel over `(B, H, dh, ds)`.

Files:
- `mlx/backend/metal/kernels/ssm_replay.metal` — both kernels +
  instantiations for Nemotron/Jamba/Granite/FalconH1 shapes:
  Dh × Ds ∈ {64×64, 128×128}, H ∈ {16, 32, 48}, G ∈ {1, 2, 4, 8}.
- `mlx/backend/metal/ssm_replay.cpp` — dispatch.
- `mlx/fast.h` / `mlx/fast.cpp` — `ssm_step_record(...)` and
  `ssm_replay(...)` entry points.
- `mlx/fast_primitives.h` — Primitive declarations.

Both kernel families compile cleanly via `xcrun metal -c`; mlx library
builds cleanly with the new sources registered in
`backend/metal/CMakeLists.txt`.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…record/replay

Adds C++ unit tests for the spec 041 phase 1.1 + spec 040 primitives, plus
the missing build_kernel() registrations so the kernels end up in the
metallib.

- tests/flash_quantized_sdpa_tests.cpp: shape+finite, dequant-then-SDPA
  reference match (bits=4 and bits=8), causal-mask sanity.
- tests/ssm_replay_tests.cpp: output shapes, full-T record/replay round
  trip, partial-prefix replay differs from full.
- mlx/backend/metal/kernels/CMakeLists.txt: register flash_quantized_sdpa
  and ssm_replay so the .metal sources compile into mlx.metallib (the
  primitives can't be loaded at runtime without this).

Tolerances: flash quantized SDPA uses 5% relative + 5e-3 absolute on
fp16 4-bit affine vs dequanted-fp16 reference (2% / 2e-3 for 8-bit).
SSM replay round trip uses 5e-3 to cover fp16 accumulation noise over
T sequential dA updates.
@ekryski

ekryski commented May 14, 2026

Copy link
Copy Markdown
Owner Author

⚠️ Important finding from test-coverage addition

While writing C++ doctest unit tests for the new primitives, we discovered that flash_quantized_sdpa.metal and ssm_replay.metal were never registered in mlx/backend/metal/kernels/CMakeLists.txt. The original commit (8915d2b) added the .metal sources but never wired them into the kernel build, so they would never have ended up in mlx.metallib and every runtime call would have failed with "function not found in library."

Caught by the new tests in commit a7574fb3 failing with that exact error, and fixed in the same commit alongside the test additions:

```cmake
build_kernel(flash_quantized_sdpa flash_quantized_sdpa.h)
build_kernel(ssm_replay)
```

This is the single biggest justification for the "tests before merge" discipline — the kernels build fine, the C++ Primitive compiles fine, but the Metal library is missing them. Tests caught it.

New test files

  • tests/flash_quantized_sdpa_tests.cpp — 4 cases: shape+finite, dequant-then-SDPA reference match at bits=4, causal mask sanity, bits=8 reference match.
  • tests/ssm_replay_tests.cpp — 3 cases: record returns 4 arrays with correct shapes, full-T record/replay round trip matches state_out, partial-prefix replay diverges from both snapshot and full-T.

All 7 cases pass on M1 Max via ./build/tests/tests --test-case="*flash quantized sdpa*" and --test-case="*ssm*". Tolerances documented inline.

@ekryski ekryski added feature New feature (auto-applied from feat: prefix) performance Performance improvement (auto-applied from perf: prefix) labels May 14, 2026
@ekryski
ekryski merged commit 947a440 into alpha May 14, 2026
11 checks passed
ekryski added a commit to ekryski/mlx-swift that referenced this pull request May 14, 2026
After ekryski/mlx#30 and ekryski/mlx-c#16 squash-merged into alpha, the
pre-merge feature-branch SHAs the PR pinned at (8915d2b6 / daa5d99) are
orphaned. Repin to the actual alpha tips so fresh CI clones resolve
the submodules cleanly:

  Source/Cmlx/mlx   → 947a440e (alpha)
  Source/Cmlx/mlx-c → bb40025b (alpha)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@ekryski
ekryski deleted the ek/spec-041-040-fused-kernels branch May 15, 2026 03:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature New feature (auto-applied from feat: prefix) performance Performance improvement (auto-applied from perf: prefix)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant