Repository navigation
Add variance-normalized KV cache - #329
Conversation
c8c0b5a to
14be156
Compare
dcc6aa3 to
266ca80
Compare
266ca80 to
e5a3a39
Compare
| public override func update(keys: MLXArray, values: MLXArray) -> (MLXArray, MLXArray) { | ||
| append(keys: keys, values: values) | ||
|
|
||
| guard let state = materializedState() else { |
There was a problem hiding this comment.
Is there a case where we want to allow callers to use this? If this is accidentally called does it signal a bug?
This looks like an expensive call: it dequantizes and combines all the tiles.
There was a problem hiding this comment.
Callers do need this compatibility path because several specialized attention implementations invoke KVCache.update directly. It is intentionally expensive as the standard attention path dispatches to updateAndAttend and keeps completed tiles quantised.
Integrate a KVarN-inspired variance-normalized KV cache into the typed KVCacheConfiguration / KVCachePlan system introduced on main. - Hadamard rotation, dual-axis log-domain variance normalization, and asymmetric K/V quantization for completed tiles - Cache-native attention via KVCacheAttentionProtocol with stacked multi-tile quantized matmul for score and value projection - Typed strategy VarianceNormalizedKVCacheConfiguration plus legacy schemes (varn / varn4v2 / varn4v2t32, ...) - Dynamic conversion through applyKVCacheConfiguration; prompt-cache serialization for VarianceNormalizedKVCache - Unit, attention parity, memory, and quality-gate coverage Memory-bound long-context use case; slower than the default cache on the decode path by design. Reference: https://arxiv.org/abs/2606.03458
e5a3a39 to
1fdf65f
Compare
|
Today I had the opportunity to work on this and I have added a new optimisation commit: "bounded attention slab scheduling", which addresses a performance cliff found while benchmarking the variance-normalized KV cache across different context lengths. Previously, cache compression and attention slab formation both used 32-tile batches. Until the cache accumulated all 32 tiles, attention could require up to 31 separate GPU dispatches. This produced a noticeable slowdown immediately before the 4,096-token boundary. The implementation now separates these concerns:
This is therefore a scheduling optimization rather than a numerical or format change. Decode benchmarkApple M2, Q8/KV4, head dimension 128, K4/V2, 128-token tiles. Times are median one-token decode latency(lower is better).
The important result is that the worst pre-boundary case becomes approximately 2.2× faster, while the already-efficient 4K, 8K, and 32K boundaries do not regress. Real-model A/B benchmarkModel:
The generated-token sequence had 100% agreement with the FP16 KV-cache reference for all 64 decode tokens in this test. For context, the complete backend comparison on the same workload was:
These results do not claim that VarN is faster than every existing backend. They show that this change removes a substantial internal dispatch bottleneck without changing its output quality, cache format, or peak working memory. |
Memory consumptionTwo different memory measurements should be distinguished:
In the isolated 32K, one-layer storage test:
VarN therefore delivers the expected reduction in persistent KV-cache storage. This becomes increasingly relevant for long contexts and models with many global-attention layers. However, the full Qwen3-4B benchmark showed a different result for peak process memory:
This means the compact VarN representation is substantially smaller once stored, but the current implementation uses enough temporary workspace during normalization and compression to produce a higher process high-water mark on this workload. The slab-scheduling optimization in this update improves prefill and decode performance but does not reduce that peak workspace: both the previous and new versions measured approximately 1,347 MiB. Consequently, the memory claim for this PR should be precise:
This does not block merging the scheduling improvement because it introduces no memory regression relative to the previous VarN implementation. It does, however, mean VarN should remain opt-in until its transient workspace behavior has been improved and evaluated at longer full-model context lengths.
|
|
Following the earlier review, I investigated the temporary-memory peak rather than treating compact KV storage as equivalent to low process memory. The peak came from variance-normalizing all eight KV heads in one lazy FP32 graph. The cache now normalizes at most four KV heads at a time while retaining the existing 32-tile compression batching. This does not change:
The compact results from each head batch are concatenated into the same final cache representation. Real-model testHardware: Apple M2
Before bounded-head normalization, the same VarN configuration reached a peak delta of 1,347.19 MiB. The change therefore removes:
The objective here is memory-constrained long-context operation rather than outperforming FP16 latency. VarN remains slower, but its measured process peak is no longer higher than FP16 for this workload. Direct 32K workspace A/BA Qwen3-4B-like synthetic configuration was used:
The previous unbounded implementation fails the 768 MiB workspace regression guard at this shape. The bounded implementation passes with substantial margin. Correctness evidenceThe head batching is valid because variance normalization operates independently for each KV head. This is now enforced by a test comparing:
The reconstructed keys and values match with relative RMSE below Additional quality results:
Performance work included in the latest commitsThe preceding slab-scheduling change also removed the dispatch cliff immediately before 4,096 tokens:
Memory-footprint summaryThe memory results measure two different things:
The full-model peak includes model weights, activations, allocator reservations, attention workspaces, and temporary compression buffers. The retained-storage measurement isolates the memory occupied by the KV representation itself. The important result is that the current implementation preserves VarN’s approximately 4.74× reduction in retained KV storage while eliminating the previously measured full-process peak overhead for this Qwen3-4B workload.
|
davidkoski
left a comment
There was a problem hiding this comment.
The change looks good to me. Thank you for all the followup here!
26 upstream commits since the last sync. The branch touches ten files; exactly one of them, Libraries/MLXLMCommon/KVCache.swift, was also changed on main -- by 6745899 "Add variance-normalized KV cache" (ml-explore#329), +217 lines against this branch's +39. Both are additions in separate regions and git resolved them without conflict; `git merge-tree` was clean before the merge was run. A merge rather than a rebase, deliberately: PicoCore pins this branch by revision, and a rebase would rewrite 8a1aa5a -- the revision main pins today -- into a commit reachable from no branch. Merging keeps every previously pinned revision an ancestor, and needs no force-push over the 31 commits here that predate this run. Carrying the merge does NOT advance PicoCore's pin. That is a separate change with its own CI run: 26 upstream commits can drift signatures the batched caches call, and a clean textual merge is not evidence that the result compiles. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RT2yoDKAz695YTHR6hDuoC
* Add variance-normalized KV cache Integrate a KVarN-inspired variance-normalized KV cache into the typed KVCacheConfiguration / KVCachePlan system introduced on main. - Hadamard rotation, dual-axis log-domain variance normalization, and asymmetric K/V quantization for completed tiles - Cache-native attention via KVCacheAttentionProtocol with stacked multi-tile quantized matmul for score and value projection - Typed strategy VarianceNormalizedKVCacheConfiguration plus legacy schemes (varn / varn4v2 / varn4v2t32, ...) - Dynamic conversion through applyKVCacheConfiguration; prompt-cache serialization for VarianceNormalizedKVCache - Unit, attention parity, memory, and quality-gate coverage Memory-bound long-context use case; slower than the default cache on the decode path by design. Reference: https://arxiv.org/abs/2606.03458
…-explore#329) * fix(cbv2): charge first-token deadline decode once per batch step A per-request decode rate prices one row's cadence, but the first-token projection summed every decode row's tokens against it, about B times too much at batch width B. It also charged every MTP row its configured 1+k width at any batch size, although the live planner speculates only inside its batch gate and automatic verification envelope. - Record projected decode steps by shape (decode rows, widest assignment). When the caller passes the measured decode-rate shape (CBv2DecodeRateShape: rows, confirmed tokens and assigned width per decode step), price each step as one measured step, scaled linearly for extra rows or width. A caller that passes no shape keeps the per-row charge. - Mirror the live MTP plan's pure depth gates through CBv2MTPRoundDriver.speculationDepthCeiling (zero beyond maxSpeculativeBatch, otherwise the automatic envelope), and project a full-slot MTP stretch with no live depth in one jump, like plain decode. Any media row keeps the configured 1+k charge, and a reviewed calibration keeps the configured 1+k work vector its error envelope was measured against. The unit suite CBv2PerBatchDecodeChargeTests covers per-step accounting, the mirrored gates (with a driver check that the ceiling bounds every live plan depth), the full-slot stretch and the shape conversion; the integration suite CBv2PerBatchDecodeConversionTests covers the engine's conversion. Neither needs the Metal library. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(cbv2): tidy per-batch decode comments and test fixtures Behavior-preserving follow-up from the independent refactor pass: - CBv2FirstTokenScheduledWork: put the serial-envelope bound ("This is deliberately conservative for one asyncEval") directly after its formula again, as on main, and state the per-batch replacement after it. The sentence inserted before it made that bound read as a claim about per-batch charging. - firstTokenWorkProjection: a mirrored row is charged at most 1 + ceiling, not only one token where the ceiling is zero. - CBv2PerBatchDecodeChargeTests: mint requests with CBv2SchedFixtures.request, as the integration suite does, instead of a private lock-guarded ID counter. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Proposed changes
This PR adds an opt-in, KVarN-inspired variance-normalized KV for reducing KV-cache memory pressure during long-context generation.
This introduces
kvQuantizationStrategy: .varianceNormalized, which keeps completed KV tiles compressed and uses cache-native attention over quantized rotated tiles instead of repeatedly materializing full K/V tensors.The cache applies:
Benefits
Checklist
Put an
xin the boxes that apply.pre-commit run --all-filesto format my code / installed pre-commit prior to committing changesNotes
The current implementation is slower than the default cache, so the intended use case is memory-constrained long-context decoding, not latency-sensitive generation.
Reference: https://arxiv.org/abs/2606.03458