Skip to content

fix(Gemma4Text): dispatch QuantizedKVCache correctly in LLM attention (fixes SharpAI/SwiftLM#71) - #29

Merged
solderzzc merged 1 commit into
mainfrom
fix/gemma4-quantized-kv-cache-issue-71
Apr 22, 2026
Merged

solderzzc merged 1 commit into
mainfrom
fix/gemma4-quantized-kv-cache-issue-71

Conversation

@solderzzc

Copy link
Copy Markdown
Member

Problem

Gemma 4 models loaded via LLMModelFactory crash on the first decode step whenever GenerateParameters.kvBits is non-nil:

MLXLMCommon/KVCache.swift:1063: Fatal error: `update` was called on `QuantizedKVCache`. Use `updateQuantized` instead.

Root cause: Gemma4TextAttention.callAsFunction in Libraries/MLXLLM/Models/Gemma4Text.swift called cache.update(keys:values:) unconditionally, which QuantizedKVCache intentionally traps.

Fix

Mirrors the correct dispatch already present in the VLM sibling (MLXVLM/Models/Gemma4.swift:690-706):

  1. Adds a file-private Gemma4LLMKVState enum (discriminated union of regular vs. quantized KV tensors), mirroring Gemma4SharedKVState in the VLM file.
  2. Casts cache to QuantizedKVCacheProtocol; if it matches, calls updateQuantized(keys:values:) and carries the quantized tuples in the new enum case.
  3. Switches on the KV state to route downstream attention to quantizedScaledDotProductAttention (quantized) or MLXFast.scaledDotProductAttention (regular).
  4. The sharedKV fast-path (KV-sharing layers) is unaffected.

Testing

Copilot AI review requested due to automatic review settings April 22, 2026 17:29

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.callAsFunction to call updateQuantized(keys:values:) when the cache conforms to QuantizedKVCacheProtocol.
  • Switches the attention implementation to use quantizedScaledDotProductAttention for quantized KV state and MLXFast.scaledDotProductAttention otherwise.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +414 to +418
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)
}

Copilot AI Apr 22, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.
var adjustedMask = mask
if case .array(let maskArray) = mask {
let keysSeqLen = kvState.seqLen
if maskArray.dim(-1) != keysSeqLen {

Copilot AI Apr 22, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
if maskArray.dim(-1) != keysSeqLen {
if maskArray.dim(-1) > keysSeqLen {

Copilot uses AI. Check for mistakes.
Comment on lines +358 to +371
// 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
)

Copilot AI Apr 22, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.
…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.
@solderzzc
solderzzc force-pushed the fix/gemma4-quantized-kv-cache-issue-71 branch from f54dde8 to cdc0a0c Compare April 22, 2026 17:58
@solderzzc

Copy link
Copy Markdown
Member Author

Applied both actionable suggestions from the Copilot review:

  1. Mask guard (line 386 + sharedKV path): Changed != keysSeqLen → > keysSeqLen on both mask-adjustment sites. A shorter mask is left alone; we only slice when the mask is wider than the KV sequence.

  2. kvPair return for quantized cache (line 418): Replaced the incorrect raw-k/v return with a proper dequantization of the full accumulated cache state via getQuantizedState() (which snapshots the whole context window post-updateQuantized), falling back to dequantizing the just-updated tuples only on the first decode step (when the cache holds exactly the current step). This ensures KV-sharing layers receive the complete context, not just the new tokens.

For the test coverage suggestion: that is a valid long-term improvement, but requires wiring a full LLMModelFactory + GenerateParameters integration harness into the SwiftBuddy test suite (tracked in the SwiftLM test harness). Out of scope for this targeted bug-fix PR.

@solderzzc

Copy link
Copy Markdown
Member Author

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):

  • Added kv_bits as a per-request field to ChatCompletionRequest in Server.swift, threaded into GenerateParameters.kvBits. This enables the QuantizedKVCache path to be exercised via the API without a new CLI flag.
  • Added Test 9: QuantizedKVCache Regression to run_benchmark.sh:
    • [1/4] kv_bits=4, short prompt — exercises the basic quantized decode path
    • [2/4] kv_bits=8, short prompt — verifies 8-bit quantization also works
    • [3/4] kv_bits=4, longer prompt — exercises the KV-sharing layers (last 20 layers of Gemma-4 that share KV from an earlier layer, where the dequantized kvPair return is critical)
    • [4/4] Baseline without kv_bits — regression guard that the regular path is not broken

All 4 sub-tests verify: server doesn't crash, response is non-empty coherent text, ≥3 generated tokens.

@solderzzc
solderzzc merged commit 63707c0 into main Apr 22, 2026
6 checks passed
@solderzzc
solderzzc deleted the fix/gemma4-quantized-kv-cache-issue-71 branch April 22, 2026 18:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: MLXLLM Gemma 4 attention crashes when kvBits is set

2 participants