Skip to content

Fix KV cache quantization: cache updates lost due to value-type propagation - #358

Closed
somegeekintn wants to merge 2 commits into
ml-explore:mainfrom
somegeekintn:fix/kvcache-quantization
Closed

somegeekintn wants to merge 2 commits into
ml-explore:mainfrom
somegeekintn:fix/kvcache-quantization

Conversation

@somegeekintn

Copy link
Copy Markdown
Contributor

Background

maybeQuantizeKVCache takes cache: inout [KVCache] and replaces array elements with new QuantizedKVCache instances when the quantization threshold is crossed. Because Swift arrays are value types, this replacement was only visible inside TokenIterator's local copy — the caller's array continued holding the original KVCacheSimple references. The quantized caches were deallocated at the end of generation, silently discarding all context generated after the quantization threshold. See issue #312 for additional details and reproduction steps.

What this PR does

Introduces KVCacheContainer, a reference-type (class) wrapper that owns the [KVCache] array. TokenIterator now holds a KVCacheContainer rather than a bare array, so element replacements during quantization are visible to any holder of the same container. KVCacheContainer.maybeQuantize also uses the new Bool return value from maybeQuantizeKVCache to set a canQuantize flag to false after the first successful quantization pass, eliminating the redundant per-step scan of all cache layers that occurred in the original code.

The QuantizableKVCache protocol is introduced to formalize which cache types support conversion to quantized form. KVCacheSimple conforms to it. RotatingKVCache is not yet supported (matching the Python implementation) with a TODO stub in place. Several quantization helpers (asQuantizableWithGroupSize, canQuantize(at:groupSize:), isValidQuantizedGroupSize, resolvedKVQuantizationGroupSize) are moved from a private free function into a KVCache extension, making them accessible for reuse and testing. The dead-code !(firstQuantizable is QuantizedKVCache) check noted in the original issue is removed.

maybeQuantizeKVCache gains @discardableResult and now returns Bool to indicate whether quantization occurred.

TokenIterator's multiple init paths are consolidated to funnel through a single canonical initializer, reducing duplication. The previously-fixed inits also pick up optional processor and sampler override parameters for consistency. tokenCount is tightened to private(set) public.

Out of scope

This PR does not address the ChatSession side of cache ownership, SpeculativeTokenIterator, or RotatingKVCache quantization support. Those are candidates for follow-up work.

Unrelated changes

Two minor compiler warning fixes are included: removal of an unused hasExplicitCache variable in Gemma4.swift, and a var → let correction for freqsT in Qwen25VL.swift.

PR description crafted with assist from Claude since I'm a bad explainer

Checklist

Put an x in the boxes that apply.

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

Replaces TokenIterator's bare [KVCache] array with a KVCacheContainer class so quantization replacements are visible to callers. Adds QuantizableKVCache protocol, moves quantization helpers into KVCache extension, and consolidates TokenIterator inits. Includes two minor unrelated compiler warning fixes.
@fdagostino

Copy link
Copy Markdown
Contributor

We validated this approach downstream (cherry-picked onto our fork after hitting #312 in production — a multi-turn voice app with kvBits set, where the session went amnesic about its own replies): KVCacheContainer fixes the direct TokenIterator path as advertised.

One gap worth flagging for the next step: ChatSession is still affected. It stores its own [KVCache] array and passes it to TokenIterator, so the element replacements the iterator makes through its container (KVCacheSimple → QuantizedKVCache) never reach the session's storage — every token generated after the quantization swap is lost, and the next turn continues from a stale prefix. Downstream we fixed it by having the session create the KVCacheContainer, pass it via the container-based init, and adopt container.cache back into its stored state after each generation pass — plus a regression test that fails without the sync-back, reproducing the #312 symptom exactly (the session ends up holding the stale KVCacheSimple while the iterator's QuantizedKVCache is dropped).

Happy to submit that as a follow-up PR once this one merges (one step at a time, as discussed). The SpeculativeTokenIterator/MTP paths hold plain [KVCache] arrays too and would lose replacements the same way — probably further steps down the same road.

@davidkoski

Copy link
Copy Markdown
Member

Sorry for the delay getting to this -- a lot of PRs coming in! I like the shape of this but I think I am going to take #453 over this. It has the same approach but also covers the ChatSession side as well as dealing with a number of other KVCache issues.

Thank you for the contribution!

@davidkoski davidkoski closed this Aug 3, 2026
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
SDK main gained ml-explore#358: Package.swift pins Layr-Labs/mlx-swift eedca444
(was 6c31f9f1), which pins mlx ff4bb35b (Layr-Labs/mlx ekryski#43: a freed
compiled closure is erased from every thread compile cache; ekryski#40: float16
and bfloat16 floor divide in float32) and mlx-c 004c735f. Clean merge.
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
Merges origin/main aee6ebb into darkbloom/tp-engine 8411247. Main is 377
commits past the merge base 889fe3c: the upstream sync to ml-explore
d02948b (ml-explore#339), the mlx-swift pin eedca444 (ml-explore#358), the provider 0.10.2 set
(ml-explore#356, ml-explore#357, ml-explore#359, ml-explore#360), GLM long-context decode (ml-explore#362), balanced
checkpoints for GLM-5.3-Flash and Nemotron Super (ml-explore#363), GLM video at the
track's average rate (ml-explore#340) and the Flint decode work (ml-explore#336-ml-explore#338).

Package.swift keeps the cluster's mlx-swift pin 9fe34405; everything else
is main's (swift-tools 6.2, the swift-syntax 602 floor, the new targets).

Conflicts:
- GLM5NextMoEDecodeKernel.swift: the cluster's file (the dense-MLP
  two-launch path, the non-private header) in main's swift-format layout,
  with main's two changes: GLM5NextNVFP4Linear.weightScale2 (renamed
  because MLXNN QuantizedLinear now declares globalScale) and the copied
  MLX sigmoid with metal::precise::exp (main 1ba5e73).
- PagedSegmentAttention.swift: main's first-bucket scratch allocation and
  seqinfo cache, plus the cluster's multi-query verification kernel and
  the non-private merge kernel it uses.
- GatedDelta.swift: main moved it to MLXLMCommon and added useKernel. The
  cluster's fuseQwen35Gates stays; its compiled gates move beside
  gatedDeltaUpdate (qwen35GatedDeltaGates, package) because MLXLMCommon
  cannot reach MLXLLM's Qwen35DecodeFusions, which now forwards to it. The
  traced ops are the cluster's (sigmoid(b) to float32, then
  exp(-exp(float32(A_log)) * softplus(a + dt_bias))), so the decode gates
  keep their bits. Qwen35DecodeFusionsTests compares against the separate
  ops, since main made computeGatedDeltaG itself a compiled closure.
- GLM5NextProcessor.swift: main's image.source switch with the cluster's
  GLM5NextRGBDecoder; main's variable-frame-rate decoding auto-merged.
- Package.swift: see above.

Merged without textual conflict but adjusted:
- PagedLayerCache.writePromptKVWithoutAttention (main, Flint) advances
  the offsets through advancePositionOffsets, so the cluster's
  hostPositionOffsets stay in step with the device offsets.
- PagedAttentionKVTests: main's newCache throws.

Numerics: main changed every copied MLX sigmoid to metal::precise::exp
(1ba5e73, 3794edf) to follow MLX #4461: the GLM hyper-connection
coefficients, the GLM MoE decode and prefill clamped GLU, Nemotron Super
and MiMo. They follow the merged MLX core. The cluster core pinned here
still has metal::exp, so GLM on the pair changes bits when it runs with
these kernels; see the merge record.

Tests: swift build --build-tests against main's mlx-swift eedca444 with
two compile-only stand-ins for the cluster mlx-swift API
(MLXArray.sharingArray, metalKernel fencedInputs): complete. The CPU unit
group (^MLXLMTests.UnitTests/, no Metal library): 437 tests, one failure,
the pre-existing GLM5NextProcessorMediaTests Metal dependency. The tree
does not build at its own pin 9fe34405 (main needs mlx-swift API such as
MLXArray.maskFill); it builds once the pin moves to the merged mlx-swift.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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.

3 participants