Repository navigation
Prefill over a quantized KV cache through the fused SDPA kernel - #703
davidkoski merged 1 commit into
Conversation
4507fd1 to
326a360
Compare
attentionWithCacheUpdate sent every query length to quantizedScaledDotProductAttention when the cache is quantized. That path materializes [B, H, L, N] scores through quantized matmuls, which is the right trade at decode (L = 1 reads a quarter of the key bytes) but loses to the fused kernel once the query block is long enough to be compute-bound. For L >= 64 and head dims the fused kernel handles on every GPU generation (64, 72, 80, 96, 128), dequantize the returned keys and values once and call MLXFast.scaledDotProductAttention. Head dims 192 and 256 stay on the quantized route because MLX runs them unfused outside NAX, where the quantized matmuls are within ~1.1x. MLA-style caches with narrower values than queries also stay on the quantized route. Measured on M4 Pro with Qwen3-14B-4bit, kvBits 4, step 512: - 16k prefill from an empty cache: 171 -> 199 tok/s (fp16 cache: 200), peak memory 11.3 -> 9.8 GB - 2k turn over 8k history: 170 -> 195 tok/s (8-bit cache: 173 -> 182) - decode at 8k unchanged (quantized route still used at L = 1) - SDPA microbenchmark, D = 128, L = 512: quantized path 1.45-1.7x slower than fused at N = 2.5k..33k, and 135 MB..1.4 GB of scores vs 24..99 MB
326a360 to
9241276
Compare
| /// Head dims whose fused SDPA kernel MLX compiles for every GPU generation | ||
| /// (`mlx/backend/metal/scaled_dot_product_attention.cpp`). MLX routes 192 and 256 to | ||
| /// its unfused path, where the quantized matmuls are competitive, so they stay out. | ||
| package let dequantizedPrefillAttentionHeadDims: Set<Int> = [64, 72, 80, 96, 128] |
There was a problem hiding this comment.
This is a cool idea, but it is unfortunate that the layer that knows which ones are fused lives here (mlx-swift-lm). Maybe that is right though and this is application specific.
Anyway, I wonder if mlx could expose these cut points? If not, I wonder if the mlx-swift layer could (in the prepare-mlx.sh layer) extract these cut points and expose them. A caller might want to know about NAX and normal metal cut points.
Also the CUDA path. Or we need to represent the common fusings.
Actually this is complicated enough that maybe we wouldn't want a table, we want a function that answers the question. Or both.
Worth a thought for the future.
davidkoski
left a comment
There was a problem hiding this comment.
Change looks good, thank you!
Apply the upstream commits efcedcd..c8dabc6 (the 25 after 991266a) as cherry-picks. CLAUDE.md is untouched. Where a conflict was only a fork refactor, upstream's code is taken; the fork's MTP speed and prompt-cache behavior is kept. - efcedcd Gemma 4 VLM: expose hidden states for a prepared input (ml-explore#730) - 3d066d3 mlx-swift 0.33.0 (ml-explore#720) - 39b92df Read Gemma 3 RoPE scaling from rope_parameters (ml-explore#723) - c358cea Throw when Bert id2label keys share an integer id (ml-explore#736) - c3d3afe FastVLM: Keep image sentinels out of the repetition-penalty history (ml-explore#735) - 72a4673 Fix attention masks sized from the absolute cache offset (ml-explore#728) - cf9b7e9 Prefill over a quantized KV cache through the fused SDPA kernel (ml-explore#703) - ef36109 Add reasoning streaming events and support Gemma 4 channels (ml-explore#563) - 691a19a Support Nemotron 3.5 (Lightning, Bolt, Super) text models (ml-explore#712) - f5b0677 Expose Qwen 3.5 text geometry read-only (ml-explore#737) - c2f1073 Add GrammarConstraint.freshMatcher() (ml-explore#732) - 411d8e7 Feed the sampled token before its fast-forward tokens (ml-explore#731) - 71cc028 MLXFoundationModels: let MLXLanguageModel set the prefill step size (ml-explore#745) - 52e6001 Report model tensor buffer memory (ml-explore#746) - 128f49f Use the MLXFast gated delta kernel where mlx core supports it (ml-explore#740) - 35bd2c9 Add MiniCPM5 Tool Call Parser (ml-explore#637) - c611a3f integration tests to run using xcode 27 (now that it is released) (ml-explore#743) - bb36fc3 EmbeddingGemma 2: soft tokens for every row of a batch (ml-explore#729) - b8d4935 Show the response schema to the model during guided generation (ml-explore#715) - 2775ddd RotatingKVCache: keep the pinned prefix visible in multi-token masks (ml-explore#747) - eccf774 Fix EmbeddingGemma 2 image orientation and batch text embeddings (ml-explore#692) - ffe7647 Add resumable Qwen MTP speculative decoding to ChatSession (ml-explore#581) - 327d92d Put images before text in GLM-OCR prompts (ml-explore#765) - 2fdad9e Keep Nemotron-H Mamba activations in the input dtype (ml-explore#754) - c8dabc6 Fix the x86_64 build of the EmbeddingGemma 2 image processor (ml-explore#763) mlx-swift 0.33.0 (MLX core 0.32.4 line): - MultiRowQuantizedMatvec: widen each input before the 4-bit pack sum, as qmv_fast now does, so verify rows keep the bits of a decode step. - GatedDeltaDecodeKernel and the DeepSeek-V4 Sinkhorn kernel: the sigmoid reads metal::precise::exp, as MLX Sigmoid now does (mlx#4461). Conflicts and choices: - ml-explore#563: Generation.reasoning carries thinking apart from .chunk on every path (textToolHandler takes reasoningPrimedInside, read before the prefill). ChatSession records the content with the finished reasoning beside it, and prefilledReasoningStartDelimiter, as upstream does; ReasoningHistory keeps one fork rule: a protocol that replays reasoning also replays a turn cut off inside it, so the next render extends the cache. Upstream's Qwen3VL generator replaces separatingImportedReasoning; the fork's whole-text helpers (separating, staysInsidePrimedReasoning, the duplicate prompt probe) are gone. FM ports the thinking gate fix, routed reasoning on allowed-tool turns, and ReasoningTokenCollector. Benchmark transcripts count .reasoning. - ml-explore#581: the fork already holds the port of the PR and the MTP work on it. The later transcript rebuild after a target-only turn is not taken: the fork cold-starts the drafter at the cached position and keeps the target cache. Recorded as an empty pick. - ml-explore#740: MLXFast gated delta for prefill and fallbacks; decode and MTP verify keep the fork kernels. - ml-explore#745: same public API; the executor reads the step size from a task-local, as drainCoordinator, and makeParameters defaults to it. - ml-explore#715: the schema prompt is built after the fork's history replay. A session that changes schema between turns changes its system prompt. - ml-explore#703: quantizedCacheAttention carries the fork's attention sinks. - ml-explore#728, ml-explore#747, ml-explore#731, ml-explore#735: applied to the split files; ml-explore#747 and ml-explore#731 were already fixed in the fork. - ml-explore#732: the fork's xgrammar v0.1.34 keeps Fork(); the clone tests stay on. Tests: MLXLMTests 964 XCTest and 2278 Swift Testing tests pass. MLXGuidedGenerationTests 76, MLXFoundationModelsTests 493, CXGrammarTests 7, MLXHuggingFaceMacrosTests 7 pass. HybridRecurrentCacheOffsetTests pass; nemotron_h_puzzle reuses NemotronHModel. Release, M5 Ultra: Qwen35SessionPromptCacheTests, Qwen35AgenticPromptCacheAssessmentTests, PromptCacheSpoolCostAssessmentTests, qwen38FourBitMTPGeneration and qwen38FourBitMTPSystemPromptCache pass (each run alone). Default MTP math/code ~94-100 / 85 tok/s against plain ~57; edit turn reuses 2169 and prefills 123. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Proposed changes
Continuing my personal battle against prefill slowness, which is from my point of view the weakest link of the chain on Apple Silicon, I hope next hardware is going to do something about it...
Basically my finding is:
attentionWithCacheUpdaterouted every query length throughquantizedScaledDotProductAttentionwhenever the cache was quantized. That path computes scores with quantized matmuls and materializes a[B, H, L, N]fp16 score tensor before softmax. At decode this is the right trade (one query reads a quarter of the key bytes), but during prefill the block is compute-bound and the fused kernel wins while allocating no scores.These changes dequantizes the cached keys/values once per chunk and calls
MLXFast.scaledDotProductAttentionwhen the query block has ≥ 64 tokens and the head dim is one the fused kernel supports on every GPU generation (64/72/80/96/128). Head dims 192/256 stay on the quantized route: MLX runs them unfused outside NAX, where the quantized matmuls are within ~1.1×. MLA-style caches (values narrower than queries) also stay on the quantized route.Measurements
M4 Pro(24 GB - base model), Qwen3-14B-4bit,
kvBits: 4, prefill step 512:The crossover was swept at N≈8k: quantized/fused ratio 1.10× (L=1), 0.72× (L=8), 0.98× (L=16), 1.11× (L=32), 1.45× (L=64), 1.50× (L=128), which is why the threshold is 64.
Checklist
Put an
xin the boxes that apply.pre-commit run --all-filesto format my code / installed pre-commit prior to committing changesAI usage
accurately describes the code changes.