Repository navigation
feat(affine-sdpa): spec 041 phases 1+2+4 — flash quantized SDPA via dequant-then-SDPA - #212
Merged
Merged
Conversation
This was referenced May 13, 2026
…ttention
GPT-OSS-20B and MiMo (when attentionSinkBias is non-zero) under
`--kv affine*` previously hit `fatalError("Affine quantized attention
does not support non-zero sinks.")` and crashed the bench. The affine
SDPA now folds sinks into its softmax denominator via a fused
softmax-of-augmented-scores:
M = max(max_t s_t, sink_h)
p_t = exp(s_t - M) / (Σ_t exp(s_t - M) + exp(sink_h - M))
output_h = Σ_t p_t · V_t
Implementation: append the per-head sink as a (T+1)th score column,
run MLX's fused `softmax` over T+1, slice off the sink column on the
way to the V matmul. The sink's V is implicit zero, so its softmax
mass simply absorbs probability from the real-token columns and
doesn't contribute to the output.
Why softmax-of-augmented-scores instead of an explicit manual softmax
(max → subtract → exp → sum-with-sink → divide): MLX's softmax is a
single fused Metal op that doesn't materialize per-token exp / running
sum intermediates. The naive manual version peaks at ~3 copies of the
score tensor.
Sink broadcasting:
- GQA: scores [B, nKVH, nRep, L, T], sinks [nQH=nKVH·nRep]
→ reshape sinks to [1, nKVH, nRep, 1, 1]; broadcast to
[B, nKVH, nRep, L, 1] for concat along T.
- MHA: scores [B, nQH, L, T], sinks [nQH]
→ reshape sinks to [1, nQH, 1, 1]; broadcast to [B, nQH, L, 1].
Sinks are cast to `scores.dtype` before subtraction — bf16/fp16
end-to-end, matching the negative-infinity sentinel fix above.
Plumbed through:
- `quantizedScaledDotProductAttention` new optional `sinks:` parameter
- `attentionWithCacheUpdate` removes the affine fatalError, passes
`sinks` through.
- `MiMoV2Flash`'s private `attentionWithCacheUpdateAndSinks` drops
its matching precondition for the affine path.
Four new regression tests cover:
- sinks=-INF reduces to no-sinks output
- finite sinks shrink output magnitude (sanity)
- GQA broadcast (8Q × 2KV) with mixed -INF / finite sinks per-head
- 8-bit affine SDPA-with-sinks tracks unquantized `MLXFast.scaledDotProductAttention(...sinks:)`
within affine-quantization noise
Verified end-to-end on GPT-OSS-20B 4bit at ctx=4096 simple and ctx=8192
summarization: coherent output, decode 60-72 tok/s vs 63.6 tok/s
no-quant baseline. Peak GPU 20 GB at ctx=8192 reflects the affine
path's intrinsic score-matrix materialisation cost, not the sinks fold
(no-sinks affine on Qwen3.5-0.8B 8k = 2.71 GB; matches expected
scaling).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…ow correctness The α (dequant-first) rotating-buffer branch of `updateAndDequant` silently corrupted output on GPT-OSS-20B `--kv turbo4v2`. Two bugs in the same code path: 1. **Buffer size mismatch with `update()`.** Prefill goes through `update()`, which (post-PR #209) sizes the raw FP16 buffer at `bufferTokens + S` via retain-and-append. `updateAndDequant`'s rotating branch assumed the buffer was pre-allocated to `maxSz` and wrote at `[writePos:writePos+S]` where `writePos = rotatingIdx`. On the first decode call with `prevOffset=101`, `maxSz=128`, `rotatingIdx=101`, the slice assignment indexed past the end of the 101-token buffer. 2. **Slot-order vs time-order.** Even after fixing the size, the modular-rotation layout returned the buffer in slot-position order, not time order: after wrap, slot 0 holds the *newest* token and the oldest tokens trail at the higher slot indices. RoPE-encoded keys read in scrambled positional order produce garbage attention scores and the model collapses into repetition (the smoke-test signature was `<|channel|>analysis<|message|>commentaryanalysis<|message|>…?`). Replaced with retain-and-append matching `update()` and `StandardKVCache.updateConcat`: drop only enough oldest tokens to leave room for the append, keep the rest in time order. The returned slice is always chronologically sorted, so RoPE positions and SDPA (with sliding-window or causal mask) attend correctly. Verified end-to-end: - GPT-OSS-20B 4bit turbo4v2 ctx=128 (sliding window wraps repeatedly): no longer gibberish, decode 71.9 tok/s. - ctx=4096 simple: coherent. - ctx=8192 summarization: coherent, decode 59.8 tok/s, peak GPU 11.94 GB, KV cache 46 MB. - ctx=32768 summarization: coherent, decode 29.8 tok/s, peak GPU 12.5 GB. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…reader quantised path Closes the `--kv affine*` `StandardKVCache` fallback that Gemma 4 LLM (E2B / E4B) was routing through on KV-sharing donor layers. Donors now stay `AffineQuantizedKVCache` and their readers consume the donor's quantised `(packed, scales, biases)` tuple via `quantizedScaledDotProductAttention` — the discrete-path qSDPA that already supports sinks (PR #210). Trade-off: discrete path materialises the [B, nKVH, nRep, L, T] score matrix during the second matmul. Spec 041 phase 1 (the flash quantised SDPA kernel) will swap the call out without changing the reader API, recovering the score-tensor memory the same way `MLXFast.scaledDotProductAttention` does for FP16 K/V today. ## Changes - `Gemma4TextAttention.callAsFunction(useSharedKV:...)` gains `quantizedSharedKVArrays` / `quantizedSharedKVConfig` parameters. When set, takes precedence over the existing FP16 `sharedKVArrays` branch and routes through `quantizedScaledDotProductAttention`. - `Gemma4ModelInner.callAsFunction` populates a parallel `intermediateQuantizedKVs` array — when the donor cache is `AffineQuantizedKVCache`, we grab `getQuantizedState()` after the donor's `attentionWithCacheUpdate` runs and hand it to the reader. - `Gemma4Model.newCache(...)` flips its callers' `forceRawKV` flag to `false` — the donor path no longer needs the `StandardKVCache` fallback under affine. - `makeAttentionCache(...)`'s `forceRawKV` flag is now a "caller's contract": "my reader can / cannot consume quantised donor state." Gemma 4 LLM (this PR) sets `false`; Gemma 3n and Gemma 4 VLM still set `true` until their reader paths are similarly extended. ## Verification (M1 Max 64GB) Gemma 4 E2B affine4 summarization @ ctx=8192: | Metric | pass1 (alpha, pre-fixes) | this PR | |---|---:|---:| | Decode tok/s | 44.0 (gibberish) | 87.3 (coherent) | | Peak GPU | 9.62 GB | 5.47 GB | | KV cache | 48 MB | 26 MB | | Output | garbage | "This is a fascinating collection of excerpts, clearly drawn from Nick Carraway's perspective..." | Gemma 4 E4B affine4 + turbo4v2 summarization @ ctx=4096 — both coherent. Spec 041 doc updated: Phase 5 marked as shipped for Gemma 4 LLM; Gemma 3n / Gemma 4 VLM extension is a mechanical follow-up tracked alongside Phase 1. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 session evaluating a one-shot spec 040 implementation: - Couldn't ship Option 1 (kernel pair) without the Metal toolchain installed on this dev machine (`xcodebuild -downloadComponent MetalToolchain` required). - Sketched Option 2 in detail enough to surface a design tension: Mamba state replay needs both recurrent-state capture AND conv-state capture (`applyConv` cache slot 0) to support mid-window rollback; that's the part that pushes Option 2 past the spec's "cheap fallback" estimate. Both blockers captured at the top of the spec so the next attempt can plan around them. No code change. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…equant-then-SDPA
Closes the `--kv affine*` peak-GPU gap that the discrete
`quantizedMM → softmax → quantizedMM` path was causing — the [B, H, L, T]
score matrix is the dominant contributor at long context (~1 GiB per
layer at L=2048, T=32k on Qwen 3.5-0.8B). The new flash path dequantises
K and V to FP16 once per call and routes through
`MLXFast.scaledDotProductAttention`, which tiles K/V internally and runs
an online softmax — never materialising the score matrix.
Why "phases 1+2+4 all at once": MLX's `dequantized()` op already supports
`bits ∈ {2,3,4,5,6,8}` and mxfp4 — Phase 2's broader bit-widths come for
free. `MLXFast.scaledDotProductAttention(... sinks:)` natively folds
sinks — Phase 4 is also free under this strategy. The single
implementation path covers all three phases that spec 041 originally
scoped as separate kernel work.
**Auto-strategy selection** (`MLX_AFFINE_SDPA=auto`, default):
- **L > 1 (prefill)**: flash path. Big peak-GPU win.
- **L = 1 (decode)**: discrete path. Small score matrix; dequanting
K/V per step is ~15% decode tok/s regression at long context.
Override via env: `MLX_AFFINE_SDPA={auto,flash,discrete}`.
**Phase 1 acceptance gate measurements** (M1 Max 64 GB):
| Model | ctx | no-quant | affine4 (before) | affine4 (after) |
|---|---:|---:|---:|---:|
| Qwen 3.5-0.8B | 32k | 1.97 GiB | 4.03 GiB | **1.68 GiB** |
| Qwen 3.5-9B | 32k | 6.91 GiB | 8.81 GiB | **6.21 GiB** |
| GPT-OSS-20B | 8k | 11.94 GiB | 20.41 GiB | **11.85 GiB** |
| Gemma 4-31B | 8k | 28.10 GiB | 33.43 GiB (gibberish) | **27.52 GiB coherent** |
All five rows close the spec's acceptance gate ("peak GPU within 200 MiB
of `--kv none`"). Three rows go FURTHER and drop peak BELOW no-quant
(the 4-bit K/V cache is 4× smaller than the FP16 cache that no-quant
allocates, so the smaller stored cache offsets the dequant transient).
Decode (auto picks discrete for L=1):
- GPT-OSS-20B 8k: 60.7 → 62.2 tok/s (improvement, not regression)
- Gemma 4-31B 8k: 7.0 → 12.9 tok/s (+85% — yesterday's gibberish
output was running the broken sinks path; the kv=none and turbo4v2
baselines were ~14 tok/s, so we're now in striking distance)
Two new regression tests:
- `testFlashQuantizedSDPAMatchesDiscreteAtPrefillLength` — flash vs
discrete on L=16 (no sinks): max-diff < 5e-2.
- `testFlashQuantizedSDPASinksMatchesDiscreteSinks` — flash vs
discrete with sinks: same tolerance.
Spec 041 updated: Phase 1 marked shipped (stop-gap via dequant-then-SDPA);
Phase 1.1 fused-kernel optimisation deferred (saves the per-call K_fp +
V_fp transient at long ctx, all kernel-level optimisations in the
original Phase 1 design still apply to that follow-up).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
… on spec 039 Updates phase statuses to reflect what landed in `feat(affine-sdpa): spec 041 phases 1+2+4`: - Phase 1: stop-gap shipped (dequant-then-MLXFastSDPA). Fused-kernel optimisation deferred to Phase 1.1. - Phase 2: shipped for free — `dequantized()` already covers 2/3/4/5/6/8 bit + mxfp4. - Phase 3: deferred. `compressedAttention(L>1)` never fires today (`attentionWithCacheUpdate` routes L>1 through raw FP16 prefix prefill); spec 039's compressed-prefix hydration is the gating piece. - Phase 4: shipped for free — MLXFast SDPA folds sinks natively in the flash path. Discrete path's explicit fold (PR #210) is retained as the L=1 fallback. - Phase 5: shipped via PR #211 (Gemma 4 LLM affine donor compression). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski
force-pushed
the
ek/041-phase1-dequant-then-sdpa
branch
from
May 14, 2026 22:11
38c67b1 to
e74f6bb
Compare
Add the MLX_AFFINE_SDPA={auto,flash,discrete} env var to the
kv-cache.md env-var table. Documents the auto-strategy selection
(flash for L>1 prefill, discrete for L=1 decode) introduced by the
spec 041 phases 1+2+4 work in this PR, the override modes, and the
empirical peak-GPU savings on long-context prefill.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…rameter Promote the SDPA strategy selector from a global env-var-only override to a first-class per-cache constructor parameter. Callers that want to pin a strategy on a specific cache instance no longer need to mutate process env. API additions: * `AffineSDPAStrategy` enum (`.auto`, `.flash`, `.discrete`) promoted from private file-scope to a public top-level type. * `AffineQuantizedKVCache.sdpaStrategy: AffineSDPAStrategy` public property + `sdpaStrategy: AffineSDPAStrategy = .auto` constructor parameter. * `quantizedScaledDotProductAttention(..., strategy:)` parameter threads the per-cache strategy through the free function. Default `.auto` preserves backward compatibility for direct callers. * `AttentionUtils.attentionWithCacheUpdate` reads `quantizedKVCache.sdpaStrategy` and forwards it to the SDPA call. Precedence (matches the `TurboQuantizedKVCache.useDequantSDPA` / `TURBO_DEQUANT_SDPA` pattern): env var when set ▶ per-cache `sdpaStrategy` ▶ `.auto` default Env var stays the diagnostic global override (set once, applies to every cache in the process). Constructor parameter is the per-call opt-in (no env mutation required). Tests in `KVCacheTests.swift`: * `testAffineQuantizedKVCacheSDPAStrategyDefaultIsAuto` — default is `.auto` as documented. * `testAffineQuantizedKVCacheSDPAStrategyConstructorOverride` — `.flash` and `.discrete` round-trip through the property. * `testAffineSDPAStrategiesProduceEquivalentOutput` — both strategies produce non-NaN equivalent output (within 15% relative on 8-bit affine; tile-summation differences + quant noise compound). Seeded for determinism. Docs (`documentation/kv-cache.md`): * New behaviour-knob row for `AffineQuantizedKVCache.sdpaStrategy`. * `MLX_AFFINE_SDPA` env var row noted as overriding the per-cache constructor parameter. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski
commented
May 14, 2026
| // that consumes the donor's `getQuantizedState()` tuple directly | ||
| // via `quantizedScaledDotProductAttention`. That callsite passes | ||
| // `forceRawKV: false` so its donors stay compressed under affine. | ||
| // Other KV-sharing callers (Gemma 3n, Gemma 4 VLM — both still |
Owner
Author
There was a problem hiding this comment.
We'll follow up on support for VLM and other models that do KV sharing in a separate PR.
`make build-tests` going through `xcrun metal` was a temporary build-env issue on one dev machine, not a spec-level concern. Reduce the "session blockers" section to just the SSMStateCache layout tension which is a real ongoing design decision. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
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>
4 tasks done
div0-space
pushed a commit
to LibraxisAI/mlx-swift-lm
that referenced
this pull request
Nov 29, 2026
Apply the isolated FalconH1 causal-mask correction and retain the corresponding regression assertions. FalconH1 is outside the current Darkbloom serving set; shared runtime code is unchanged.
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
Consolidates four pieces of spec 041 work that landed in stacked branches but never merged individually (predecessor PRs #210 and #211 closed; their content rebased into this PR). Now based directly on
alpha.Scope (6 commits):
Affine SDPA attention-sink support (
fbde1b8) — augmented-softmax sinks fold inquantizedScaledDotProductAttention. Closes the GPT-OSS-20B--kv affine*coherence gap.TurboQuant
updateAndDequantsliding-window correctness (8d46bca) — retain-and-append pattern replaces modular-slot writes that produced silent OOB at the prefill→decode boundary.Gemma 4 Phase 5 — affine donor compression (
eb4cad7) — KV-sharing donor layers under--kv affine*route throughGemma4TextAttention's new quantized shared-reader path (consumes the donor'sgetQuantizedState()triple directly). Closes theStandardKVCachefallback that was losing affine compression on Gemma 4 E2B/E4B donors.Spec 041 Phases 1 + 2 + 4 — flash quantized SDPA via dequant-then-MLXFastSDPA (
4b8bd65) — the load-bearing change.quantizedScaledDotProductAttentionauto-routes L>1 (prefill) throughdequantized(K) + dequantized(V) + MLXFast.scaledDotProductAttentionto avoid materialising the[B, H, L, T]score matrix that the discretequantizedMM → softmax → quantizedMMpath produces. Decode (L=1) stays on the discrete path because score materialisation is cheap there and dequanting K/V per step costs ~15% decode tok/s. Override viaMLX_AFFINE_SDPA={auto,flash,discrete}.Phase 2 (
bits ∈ {2,3,4,5,6,8}+ mxfp4) and Phase 4 (sinks) come for free under this strategy —dequantized()already supports the bit widths, andMLXFast.scaledDotProductAttention(... sinks:)folds sinks natively.Spec docs (
95c7176+e74f6bb) — spec 040 session-blocker notes; spec 041 Phases 1/2/4 marked shipped, Phase 3 (TurboQuant compressed-domain L>1) noted as deferred on spec 039.Phase 3 stays deferred — gated on spec 039 (compressed prefix-cache hydration). The Phase 1.1 fused-kernel optimisation (tile-wise dequant inside the SDPA loop, never materialising the FP16 K/V transient) has since shipped via the cross-repo chain (mlx#30/#31, mlx-c#16/#17, mlx-swift#31/#32 — all merged) and is consumed by the follow-on PR #215 in this chain.
Phase 1 acceptance gate (spec target: peak GPU within 200 MiB of
--kv none)Four out of five rows drop peak GPU below
--kv nonebecause the 4-bit cache is ~4× smaller than the FP16 cache that--kv noneallocates; the smaller stored bytes offset the dequant transient.Decode tok/s (auto picks discrete for L=1)
Test plan
swift buildcleanKVCacheTests.swiftpass (testFlashQuantizedSDPA*+testAffineSDPASinks*)Chain context
This is the first PR in the mlx-swift-lm chain (PR #212 → #213 → #214 → #215). Each subsequent PR builds on this one; #215 lands the spec 041 Phase 1.2 sliding-window + perf optimisations on top, after the spec 041 Phase 1.1 fused-kernel cross-repo chain landed in alpha (mlx#30/#31, mlx-c#16/#17, mlx-swift#31/#32 — all merged 2026-05-14).