Repository navigation
feat(kvcache): spec 041 phase 1.1 + spec 040 — fused kernel + Mamba state-replay end-to-end - #213
Merged
Merged
Conversation
This was referenced May 13, 2026
ekryski
force-pushed
the
ek/041-phase1-dequant-then-sdpa
branch
from
May 14, 2026 22:11
38c67b1 to
e74f6bb
Compare
8 tasks done
Three Swift-side integrations of the new Metal kernels landing in the
mlx / mlx-c / mlx-swift fork branches:
`quantizedScaledDotProductAttention`'s strategy-selection enum gains a
`.kernel` arm that routes through `MLXFast.flashQuantizedSDPA`. The
auto-strategy default keeps `.flash` (dequant-then-MLXFastSDPA) for
prefill since the fused kernel — while correct and passes round-trip
tests — is not yet matrix-engine-optimised (47% prefill / 18% decode
regression vs flash on Qwen 0.8B at ctx=8k, same peak GPU).
`MLX_AFFINE_SDPA=kernel` opts in for validation / future-perf-work.
The kernel handles `bits ∈ {2,3,4,6,8}` × `groupSize=64` × head dims
`{64, 96, 128, 256, 512}` × `{float, float16_t, bfloat16_t}`. Shapes
outside that grid auto-fall-back to `.flash`. Sliding-window mode
falls back too (kernel doesn't have a fused windowed path).
`SSMStateCache.recordStep` now accepts both GDN (`[delta, k, g]`) and
Mamba (`[dA_log, dBx_log]`) entries, dispatched by tensor count.
`rollback(acceptedPrefix:)` detects the Mamba flavour and re-folds via
`MLXFast.ssmReplay`. The replay slices `[..<k]` of the per-round
T-axis entry — matches GDN's per-round recording convention.
`NemotronH.mambaForward` routes `T > 1 && cache.isRecording` through
`MLXFast.ssmStepRecord`, capturing `(dA_log, dBx_log)` into the cache.
`canStateReplay = false` opt-outs removed for both NemotronH and Jamba
(NemotronH integrated end-to-end; Jamba inherits the cache changes but
its mamba forward still uses `ssmUpdate` — extending the conditional
forward is a mechanical follow-up).
- `testFusedFlashQuantizedSDPAMatchesDiscrete` — kernel output matches
discrete reference within affine-quantization noise (max diff < 5e-2).
- `testFusedFlashQuantizedSDPASinks` — sinks fold matches discrete.
- `testMambaStateReplayRoundTrip` — `ssmStepRecord` + `ssmReplay`
round-trip on 16-head × 8-step verify window: replay(k=T) = recorded
final state (diff < 5e-3); replay(k=0) = snapshot (diff < 1e-6);
partial replay(k=T/2) differs from both ends.
- `testSSMStateCacheMambaRollback` — end-to-end through the cache
dispatcher.
- swift build clean across all targets.
- Unit tests: 4 affine sinks + 2 fused kernel + 2 Mamba state-replay
all pass.
- Bench: Nemotron-30B-A3B autoregressive (no ngram) coherent at 4k
summarization — baseline non-speculative path unaffected by the
Mamba record/replay integration.
- Bench: Nemotron-30B-A3B with `--ngram 3` — speculative decoding
fires (7/25 draft tokens accepted, 28%), kernel paths exercised
end-to-end. **Known limitation**: conv-state mismatch on partial
accept causes mild output drift (same issue as spec 020's GDN path
per the comment in `KVCache.swift`'s replay block); the recurrent
state is replayed correctly but the conv state stays at its
pre-record value. Capturing per-step conv state is the obvious
follow-up.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…eplay live) - specs/041: Phase 1.1 fused Metal kernel shipped alongside Phase 1 stop-gap. Auto-strategy default still `.flash` until Phase 1.2 MMA optimisations close the 18-47% perf gap. - specs/040: Option 1 kernel pair + 4-repo plumbing live. NemotronH integrated end-to-end; round-trip tests pass. Known limitation: conv-state mismatch on partial accept (same as spec 020's GDN); follow-up tracked. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski
force-pushed
the
ek/spec-041-040-fused-kernels
branch
from
May 14, 2026 22:40
2c3ce66 to
6bcd631
Compare
ekryski
added a commit
that referenced
this pull request
May 14, 2026
…Mamba families + KV-shared models Closes the parity gaps identified in the post-#213 audit so every model that can benefit from KV compression / KV state replay gets the fused kernels under the hood without losing coherence. ## Spec 040 follow-up 1. **Conv-state capture for partial-accept rollback** (the load-bearing fix). `SSMStateCache` gains `recordMambaConvPadded(_:)` and `mambaConvPadded` storage; each Mamba mixer's `applyConv` pushes the full `[B, K-1 + T, conv_dim]` padded input when the cache is recording. `rollback(acceptedPrefix: k)` slices `padded[k : k + K - 1]` back into `cache[0]` — the conv state now advances by k accepted tokens instead of staying at the pre-record value. Without this slice the Nemotron-30B-A3B + `--ngram 3` smoke produced loop-pattern drift on partial accept; with it the same prompt produces fully coherent output at 21.4% draft-acceptance rate. Before: `"Hello! What is your and ( ( this this This is a large language model..."` After: `"We need to respond with name and capabilities, concise..."` 2. **GraniteMoeHybrid + FalconH1 integrated** alongside NemotronH — both already use the shared `ssmUpdate` Mamba 2 selective-state formulation, so the integration is the same conditional branch: `if T > 1, cache.isRecording { ssmStepRecord } else { ssmUpdate }`. Plus the `recordMambaConvPadded` call in their `applyConv` / `_applyConv`. Jamba's mamba mixer uses a 2D `A_log` shape that doesn't match the `ssm_step_record` kernel's `[H]` ALog signature; remains TODO. ## Spec 041 phase 5 extension 3. **Gemma 3n**: shared-layer fast path in `Gemma3nAttention.callAsFunction` detects `AffineQuantizedKVCache` donors and routes through `quantizedScaledDotProductAttention` on the donor's quantised tuple. `newCache` drops `forceRawKV: true` → donors stay compressed under `--kv affine*`. 4. **Gemma 4 VLM**: the `Gemma4SharedKVState.quantized` variant already existed in the VLM's `Gemma4TextAttention.callAsFunction`; just flipping `forceRawKV: false` in `newCache` activates it. ## Parity status (KV compression × KV state replay) | Family | Affine compression | TurboQuant compression | Mamba state replay | |---|---|---|---| | Qwen 3.5 (GDN) | ✓ | ✓ | ✓ (spec 020) | | GPT-OSS-20B (sinks) | ✓ (PR #210) | ✓ via α | n/a | | Gemma 4 LLM (KV-shared) | ✓ donor compressed (#211) | ✓ | n/a | | **Gemma 3n (KV-shared)** | **✓ donor compressed (this PR)** | ✓ | n/a | | **Gemma 4 VLM (KV-shared)** | **✓ donor compressed (this PR)** | ✓ | n/a | | Nemotron-30B-A3B (Mamba) | ✓ | ✓ | **✓ coherent on partial accept (this PR)** | | **GraniteMoeHybrid (Mamba)** | ✓ | ✓ | **✓ (this PR)** | | **FalconH1 (Mamba)** | ✓ | ✓ | **✓ (this PR)** | | Jamba (alt Mamba) | ✓ | ✓ | ⏸ (different ssmStep signature, separate kernel work) | ## Test plan - [x] `swift build` clean across all targets. - [x] Existing Mamba state-replay round-trip unit tests pass (no regression from the conv-state addition). - [x] Existing fused flash-quantized SDPA tests pass. - [x] Nemotron-30B-A3B + `--ngram 3` end-to-end: coherent output, 21.4% draft acceptance (was loop-pattern drift pre-fix). - [x] Nemotron-30B-A3B autoregressive baseline (no ngram) at 4k summarization: coherent — no regression on the baseline path. ## Out of scope (follow-ups) - Jamba mamba-mixer integration — 2D `A_log` kernel variant or Swift- side reformulation needed. - Sliding-window fused kernel path for Gemma 4 sliding layers + GPT-OSS sliding layers under affine (closes the `architecturalSlidingWindow` StandardKVCache fallback). - Spec 041 Phase 1.2 simdgroup_matrix_multiply_accumulate MMA + threadgroup codebook + INT8 score accumulator perf optimisations (closes the 18–47% gap vs the dequant-then-SDPA flash path). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski
added a commit
that referenced
this pull request
May 14, 2026
…Mamba families + KV-shared models (#214) * feat(kvcache): spec 041 phase 5 + spec 040 follow-up — parity across Mamba families + KV-shared models Closes the parity gaps identified in the post-#213 audit so every model that can benefit from KV compression / KV state replay gets the fused kernels under the hood without losing coherence. ## Spec 040 follow-up 1. **Conv-state capture for partial-accept rollback** (the load-bearing fix). `SSMStateCache` gains `recordMambaConvPadded(_:)` and `mambaConvPadded` storage; each Mamba mixer's `applyConv` pushes the full `[B, K-1 + T, conv_dim]` padded input when the cache is recording. `rollback(acceptedPrefix: k)` slices `padded[k : k + K - 1]` back into `cache[0]` — the conv state now advances by k accepted tokens instead of staying at the pre-record value. Without this slice the Nemotron-30B-A3B + `--ngram 3` smoke produced loop-pattern drift on partial accept; with it the same prompt produces fully coherent output at 21.4% draft-acceptance rate. Before: `"Hello! What is your and ( ( this this This is a large language model..."` After: `"We need to respond with name and capabilities, concise..."` 2. **GraniteMoeHybrid + FalconH1 integrated** alongside NemotronH — both already use the shared `ssmUpdate` Mamba 2 selective-state formulation, so the integration is the same conditional branch: `if T > 1, cache.isRecording { ssmStepRecord } else { ssmUpdate }`. Plus the `recordMambaConvPadded` call in their `applyConv` / `_applyConv`. Jamba's mamba mixer uses a 2D `A_log` shape that doesn't match the `ssm_step_record` kernel's `[H]` ALog signature; remains TODO. ## Spec 041 phase 5 extension 3. **Gemma 3n**: shared-layer fast path in `Gemma3nAttention.callAsFunction` detects `AffineQuantizedKVCache` donors and routes through `quantizedScaledDotProductAttention` on the donor's quantised tuple. `newCache` drops `forceRawKV: true` → donors stay compressed under `--kv affine*`. 4. **Gemma 4 VLM**: the `Gemma4SharedKVState.quantized` variant already existed in the VLM's `Gemma4TextAttention.callAsFunction`; just flipping `forceRawKV: false` in `newCache` activates it. ## Parity status (KV compression × KV state replay) | Family | Affine compression | TurboQuant compression | Mamba state replay | |---|---|---|---| | Qwen 3.5 (GDN) | ✓ | ✓ | ✓ (spec 020) | | GPT-OSS-20B (sinks) | ✓ (PR #210) | ✓ via α | n/a | | Gemma 4 LLM (KV-shared) | ✓ donor compressed (#211) | ✓ | n/a | | **Gemma 3n (KV-shared)** | **✓ donor compressed (this PR)** | ✓ | n/a | | **Gemma 4 VLM (KV-shared)** | **✓ donor compressed (this PR)** | ✓ | n/a | | Nemotron-30B-A3B (Mamba) | ✓ | ✓ | **✓ coherent on partial accept (this PR)** | | **GraniteMoeHybrid (Mamba)** | ✓ | ✓ | **✓ (this PR)** | | **FalconH1 (Mamba)** | ✓ | ✓ | **✓ (this PR)** | | Jamba (alt Mamba) | ✓ | ✓ | ⏸ (different ssmStep signature, separate kernel work) | ## Test plan - [x] `swift build` clean across all targets. - [x] Existing Mamba state-replay round-trip unit tests pass (no regression from the conv-state addition). - [x] Existing fused flash-quantized SDPA tests pass. - [x] Nemotron-30B-A3B + `--ngram 3` end-to-end: coherent output, 21.4% draft acceptance (was loop-pattern drift pre-fix). - [x] Nemotron-30B-A3B autoregressive baseline (no ngram) at 4k summarization: coherent — no regression on the baseline path. ## Out of scope (follow-ups) - Jamba mamba-mixer integration — 2D `A_log` kernel variant or Swift- side reformulation needed. - Sliding-window fused kernel path for Gemma 4 sliding layers + GPT-OSS sliding layers under affine (closes the `architecturalSlidingWindow` StandardKVCache fallback). - Spec 041 Phase 1.2 simdgroup_matrix_multiply_accumulate MMA + threadgroup codebook + INT8 score accumulator perf optimisations (closes the 18–47% gap vs the dequant-then-SDPA flash path). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs(spec-040 + kv-cache): clarify conv-state replay semantics The conv-state-on-partial-accept slice was implemented inline in the preceding commit (`fad50f1`'s `SSMStateCache.rollback` body) but the slot-assignment comment block at the top of the function still claimed "the conv state is re-initialised by the layer on the next forward" — which only holds for GDN. Tighten: * `SSMStateCache.rollback` comment now distinguishes GDN (no separate conv slot — conv update folds into the recurrent delta log) from Mamba (replays `state[0]` from the `mambaConvPadded` per-step capture introduced in this PR). * Spec 040 "Known limitations" section now reflects that the conv-state limitation is closed by this PR. Issue #218 (opened in error before grepping the rebased branch) closed with reference to the inline fix. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski
added a commit
that referenced
this pull request
May 14, 2026
…pped Five stale claims caught in an audit pass: * **TurboQuant row (line 14)**: dropped "sliding-window held back until #185" (#185 CLOSED, codec rotating buffer works); replaced the old "A path (raw fp16) / B path (compressed, default)" framing with the post-rework naming (A = TurboFlash compressed default; B = dequant + SDPA opt-in). * **Spec 020 'what shipped' bullet (line 22)**: dropped "Mamba opt-out via canStateReplay=false on NemotronH / Jamba" (only Jamba is partial now; NemotronH / GraniteMoeHybrid / FalconH1 are integrated end-to-end via spec 040). Added a new bullet for spec 040 with the actual state-replay coverage. * **SSMStateCache mention (line 71)**: expanded "Qwen 3.5/3.6 GDN"-only framing to include Mamba families (NemotronH / GraniteMoeHybrid / FalconH1; Jamba partial). * **AffineQuantizedKVCache class row (line 130)**: previous note said "sliding-window + KV-shared donor layers automatically fall back to StandardKVCache under .affine(...)" and referenced open issue #202. All wrong now: #202 CLOSED, sliding-window keeps affine compression via the rotating-window cache (spec 041 phase 1.2), donors keep affine compression via spec 041 phase 5 (Gemma 4 LLM + VLM + Gemma 3n all integrated; no model still passes forceRawKV: true). Replaced with an accurate description of rotating eviction via the optional `maxSize` constructor parameter. No new content; just bringing the doc in line with what alpha now ships post #213/#214 and this PR. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
4 tasks done
ekryski
added a commit
that referenced
this pull request
May 15, 2026
…to Tier 2 (#222) * docs(specs + skills): refresh status against alpha (specs 040/041/043, spec 006/017/020/023 shipped; skills/kv-cache rewrite) Spec status headers: - 006: ✅ Shipped via PRs #163–#166 (KV cache type consolidation) - 014/015/016/019/021/022: 🚧 Phase 1 scaffolds landed; phase 2+ open - 017: ✅ All phases (1, 1B, 2, 3, 4, 5 Option A) shipped via #144 + #198 - 023: ✅ Phase 1 shipped via #154; Phase 3 subsumed by #153 - 041: ✅ Phases 1, 1.1, 1.2, 2, 4, 5 shipped via #212→#213→#214→#215; Phase 1.2 perf uplift moved to spec 042 Phase 1b; Phase 3 deferred to spec 039 IMPLEMENTATION-PLAN.md: - Last-updated bump 2026-05-13 → 2026-05-14 - New 2026-05-14 update note covering the spec 040/041/6c/043 ship wave - Row 6c (GPT-OSS sinks) rewritten with actual landing PRs (#213 + #215 chain — prior row cited fabricated commit SHAs) - Row 6d (spec 043) updated to "doc shipped via #219; impl not started" - Spec 041 promoted from Tier 4 row 25 to Tier 2 row 10g (landed early as a gate-keeper for spec 040, Tier 1 row 6c, Gemma 4 KV-sharing fallback retirement, spec 042/043 kernel-uplift wave) - Tier 4 renumbered: 042 is now row 25 (was row 26) - Status snapshot rewritten: Tier 2 row 10g spec 041 ship state, Tier 1 row 6b spec 040 ship state, Tier 1 row 6d spec 043 doc ship, expanded closed-issue list, new Kernel-uplift-wave priority bullet - Dependency graph: spec 040 reframed from "future work" to "shipped"; spec 017 phase 3 marked shipped - Issue #185 marked ✅ CLOSED (was 🟡 OPEN); resolution path cited - Issue #77 cross-linked to #160 + spec 043 Phase 1 - Issue #61 confirmed still relevant - Fixed stale "Tier 4 row 26 spec 042" refs across the doc to "Tier 4 row 25" Skills directory: - references/kv-cache.md: major rewrite. Old text had AffineQuantizedKVCache as "unbounded only" (now rotating-window via spec 041 phase 1.2), TurboQuantizedKVCache windowed eviction "until #185 is fixed" (#185 closed 2026-05-12), stale "Gemma 4 produces incoherent output under windowed turbo", wrong makeAttentionCache signature. Added sections for AffineSDPAStrategy + MLX_AFFINE_SDPA env var, useBias/DC-bias correction, TurboFlash A/B decode paths, state-replay rollback (specs 020 + 040), cross-request prefix cache (spec 017), prefillStep parameter threading. - references/supported-models.md: GPT-OSS row no longer claims supportsTurboQuantization: false; documents DC-bias + hybrid sliding-FP16 policy + turbo_flash_sdpa_v sinks kernel. - SKILL.md: GenerateParameters maxKVSize comment updated to reflect uniform rotating-eviction across .none/.affine/.turbo; added prefixCacheEnabled to example + Optional Configuration table. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs(specs): bulletize Status / Branch / Depends-on frontmatter blocks Convert the **Field:** paragraph blocks at the top of each spec to a bullet list (`- **Field:** ...`). Same content, easier to scan — fields render as a unified list instead of stacked bold-prefix lines. Sub-bullets under "Depends on:" indent under their parent. Wrapped continuation lines indent to align with the bullet body. Spec 040 also restructured: the multi-paragraph ship details that lived under the Status field moved to a new "## Ship details (2026-05-13)" section below the metadata bullets, so Status / Branch / Depends-on form a clean top-of-file block. Spec 020 closed the blank line that separated Status from Branch so the metadata renders as a single tight bullet list. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
div0-space
pushed a commit
to LibraxisAI/mlx-swift-lm
that referenced
this pull request
Nov 29, 2026
…a sanitize that removes per-expert tensors (ekryski#213) Integrate the Deepseek V3 cache and loader corrections and enable their existing regression assertions. Production edits are confined to the Deepseek V3 model implementation.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Wires the new Metal kernels from ekryski/mlx#30 / ekryski/mlx-c#16 / ekryski/mlx-swift#31 (all merged 2026-05-14) into mlx-swift-lm.
Two primitive families, one PR.
Spec 041 Phase 1.1 — fused flash quantized SDPA
quantizedScaledDotProductAttention's strategy enum gains a.kernelarm that routes throughMLXFast.flashQuantizedSDPA. The auto default keeps.flash(dequant-then-MLXFastSDPA) for prefill since the new kernel is correct but not yet matrix-engine-optimised — 47% prefill / 18% decode regression vs.flashon Qwen 0.8B 8k.MLX_AFFINE_SDPA=kernelopts in.Phase 1.2 (simdgroup_matrix_multiply_accumulate MMA + threadgroup codebook hoisting + INT8 score accumulator) is the remaining perf-uplift work. Moved to spec 042 as Phase 1b (subsumes the original spec 041 Phase 1.2) to consolidate the SIMD audit across turbo + affine kernels.
3-way comparison on Qwen 3.5-0.8B affine4 8k summarization (M1 Max 64GB):
All three produce coherent output.
This merges cleanly with the per-cache
AffineQuantizedKVCache.sdpaStrategyconstructor parameter from #212 (now in alpha):.auto/.kernel/.flash/.discreteMLX_AFFINE_SDPAenv var when set ▶ per-cachesdpaStrategy▶.auto.autoresolves toL > 1 ? .flash : .discrete(kernel is opt-in only)Spec 040 — Mamba state-replay (NemotronH integrated end-to-end)
SSMStateCache.recordStepnow accepts both GDN[delta, k, g]and Mamba[dA_log, dBx_log]entries (dispatched by tensor count).rollback(acceptedPrefix:)detects Mamba flavour and re-folds viaMLXFast.ssmReplay.NemotronH.mambaForwardroutesT > 1 && cache.isRecordingthroughMLXFast.ssmStepRecord.canStateReplay = falseopt-outs removed from NemotronH (integrated end-to-end). Jamba inherits the cache changes but its mamba forward extension is a follow-up (the 2D A_log shape vs the kernel's[H]ALog signature needs reconciliation).Bench on Nemotron-30B-A3B simple ctx=1024 with
--ngram 3: spec decode fires (7/25 draft tokens accepted, 28%), kernels exercised end-to-end.Conv-state on partial-accept rollback: at the time of this PR's bench, the recurrent state replayed correctly via
MLXFast.ssmReplaybut the depthwise-conv buffercache[0]stayed at its pre-record value — causing mild output drift on n-gram speculative decode rounds. Baseline non-speculative path was unaffected (coherent at 4k summarization). The conv-state slice is landing in the immediate follow-up PR #214 (fad50f1), which capturespadded = concat(pre_record_conv, conv_input)per record-mode forward and slicespadded[k : k + K - 1]back intocache[0]onrollback(acceptedPrefix: k). No new kernels.Tests
8 unit tests across both specs:
testAffineSDPASinks*(regression-protected through both flash + kernel paths)testFusedFlashQuantizedSDPA*(fused kernel vs discrete reference)testMambaStateReplay*(ssmStepRecord+ssmReplayround-trip, end-to-end throughSSMStateCache.rollback)All pass on M1 Max post-rebase.
Chain state
This PR is now based directly on
alpha. The four-repo dependency chain merged cleanly earlier today:947a440ebb40025b015b771eDownstream in the chain: PR #214 (spec 041 phase 5 + spec 040 parity follow-ups for KV-shared models / Mamba families) → PR #215 (spec 041 phase 1.2 sliding-window).