Repository navigation
fix(Gemma4Text): dispatch QuantizedKVCache correctly in LLM attention (fixes SharpAI/SwiftLM#71) - #29
Conversation
There was a problem hiding this comment.
Pull request overview
Fixes Gemma 4 text-model decoding crashes when KV cache quantization is enabled (GenerateParameters.kvBits != nil) by correctly dispatching KV-cache updates and routing attention through the quantized SDPA implementation.
Changes:
- Introduces a file-private KV-state discriminated union to carry regular vs. quantized KV representations through the attention forward pass.
- Updates
Gemma4Attention.callAsFunctionto callupdateQuantized(keys:values:)when the cache conforms toQuantizedKVCacheProtocol. - Switches the attention implementation to use
quantizedScaledDotProductAttentionfor quantized KV state andMLXFast.scaledDotProductAttentionotherwise.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| let (retKeys, retValues): (MLXArray, MLXArray) = | ||
| switch kvState { | ||
| case .regular(let k, let v): (k, v) | ||
| case .quantized: (k, v) // raw k/v kept for the kvPair return (shared-layer consumers) | ||
| } |
There was a problem hiding this comment.
In the quantized-cache branch, the returned kvPair is set to the raw k/v for just the current step. Downstream KV-sharing layers (which consume sharedKV) need the full cached K/V over the entire context; returning only the new-token tensors will produce incorrect attention (and can also desync mask/key lengths). Consider returning a usable shared-KV representation for the quantized case as well—e.g., plumb a shared-KV enum that can carry quantized tuples (like the VLM implementation), or explicitly dequantize the quantized cache state once for sharing.
| var adjustedMask = mask | ||
| if case .array(let maskArray) = mask { | ||
| let keysSeqLen = kvState.seqLen | ||
| if maskArray.dim(-1) != keysSeqLen { |
There was a problem hiding this comment.
The mask adjustment slices to 0 ..< keysSeqLen whenever lengths differ. If maskArray.dim(-1) < keysSeqLen, this will index out of bounds at runtime. It should only slice when the mask is wider than the KV length (or otherwise handle the shorter-mask case explicitly), similar to the guarded logic used elsewhere for quantized KV attention.
| if maskArray.dim(-1) != keysSeqLen { | |
| if maskArray.dim(-1) > keysSeqLen { |
| // Dispatch to the correct KV-cache update based on concrete cache type. | ||
| // QuantizedKVCache traps on `.update(keys:values:)` — we must call | ||
| // `.updateQuantized(keys:values:)` and then route to | ||
| // `quantizedScaledDotProductAttention` below. | ||
| let kvState: Gemma4LLMKVState | ||
| if let quantizedCache = cache as? QuantizedKVCacheProtocol { | ||
| let (qKeys, qValues) = quantizedCache.updateQuantized(keys: k, values: v) | ||
| kvState = .quantized( | ||
| keys: qKeys, | ||
| values: qValues, | ||
| groupSize: quantizedCache.groupSize, | ||
| bits: quantizedCache.bits, | ||
| mode: quantizedCache.mode | ||
| ) |
There was a problem hiding this comment.
There are existing Gemma4Text tests, but none cover the new quantized-cache dispatch (the crash described in SharpAI/SwiftLM#71) or its interaction with KV-sharing layers. Adding a test that runs a small prefill+decode step using a QuantizedKVCache (or GenerateParameters.kvBits) would prevent regressions and validate both the updateQuantized path and shared-KV behavior.
…fixes #71) The attention forward in Gemma4Text.swift called unconditionally. QuantizedKVCache intentionally traps that call with: fatalError(" was called on . Use instead.") This caused a crash on the first decode token whenever was non-nil (i.e. TurboKV was enabled). Fix: mirror the dispatch already present in the VLM sibling (MLXVLM/Models/Gemma4.swift:690-706): - Cast to ; if it matches, call and carry the quantized tensors in a new local case. - Route the downstream attention call to for the quantized case and to for regular caches. - The sharedKV fast-path (KV-sharing layers) is unaffected; those layers receive pre-computed FP16 KV pairs from an earlier non-shared layer and continue to use . A local enum (private to the file) is introduced to carry the discriminated KV state through the attention forward; it mirrors the type in the VLM file.
f54dde8 to
cdc0a0c
Compare
|
Applied both actionable suggestions from the Copilot review:
For the test coverage suggestion: that is a valid long-term improvement, but requires wiring a full |
|
Re: integration test suggestion — integration test added in the SwiftLM server layer (not in this mlx-swift-lm PR, since it requires a running server):
All 4 sub-tests verify: server doesn't crash, response is non-empty coherent text, ≥3 generated tokens. |
Problem
Gemma 4 models loaded via
LLMModelFactorycrash on the first decode step wheneverGenerateParameters.kvBitsis non-nil:Root cause:
Gemma4TextAttention.callAsFunctioninLibraries/MLXLLM/Models/Gemma4Text.swiftcalledcache.update(keys:values:)unconditionally, whichQuantizedKVCacheintentionally traps.Fix
Mirrors the correct dispatch already present in the VLM sibling (
MLXVLM/Models/Gemma4.swift:690-706):Gemma4LLMKVStateenum (discriminated union of regular vs. quantized KV tensors), mirroringGemma4SharedKVStatein the VLM file.cachetoQuantizedKVCacheProtocol; if it matches, callsupdateQuantized(keys:values:)and carries the quantized tuples in the new enum case.quantizedScaledDotProductAttention(quantized) orMLXFast.scaledDotProductAttention(regular).Testing
swift build --target MLXLLMpasses cleanly.