Skip to content

Add variance-normalized KV cache - #329

Merged
davidkoski merged 5 commits into
ml-explore:mainfrom
aleroot:kvarn-inspired-kv-cache
Aug 25, 2026
Merged

davidkoski merged 5 commits into
ml-explore:mainfrom
aleroot:kvarn-inspired-kv-cache

Conversation

@aleroot

@aleroot aleroot commented Jun 5, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • Hadamard rotation before tile compression
  • log-domain dual-axis variance normalization with clipped scale updates
  • best-imbalance scale tracking
  • asymmetric K/V quantization, e.g. 4-bit K with 2-bit V
  • compact completed-tile storage with fused quantization and variance scales
  • cache-native attention over completed quantized tiles

Benefits

  • Reduces KV cache memory pressure for long-context generation.
  • Avoids materializing completed compressed tiles on the decode hot path.

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)

Notes

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

@aleroot
aleroot force-pushed the kvarn-inspired-kv-cache branch 2 times, most recently from c8c0b5a to 14be156 Compare June 6, 2026 15:29
@aleroot
aleroot force-pushed the kvarn-inspired-kv-cache branch 2 times, most recently from dcc6aa3 to 266ca80 Compare June 19, 2026 16:19
@GoodOlClint GoodOlClint mentioned this pull request Jul 16, 2026
3 of 4 tasks
@aleroot
aleroot force-pushed the kvarn-inspired-kv-cache branch from 266ca80 to e5a3a39 Compare August 7, 2026 15:41
Comment on lines +619 to +622
public override func update(keys: MLXArray, values: MLXArray) -> (MLXArray, MLXArray) {
append(keys: keys, values: values)

guard let state = materializedState() else {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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
@aleroot
aleroot force-pushed the kvarn-inspired-kv-cache branch from e5a3a39 to 1fdf65f Compare August 21, 2026 19:14
@aleroot

aleroot commented Aug 22, 2026

Copy link
Copy Markdown
Contributor Author

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:

  • Compression still processes up to 32 tiles together, preserving its batching efficiency.
  • Attention slabs are formed every 4 tiles and compacted hierarchically.
  • The quantization algorithm, cached representation, and attention calculation are unchanged.

This is therefore a scheduling optimization rather than a numerical or format change.

Decode benchmark

Apple M2, Q8/KV4, head dimension 128, K4/V2, 128-token tiles. Times are median one-token decode latency(lower is better).

Context Previous partitions New partitions Previous New Improvement
512 4 1 1.926 ms 1.198 ms 37.8%
1,024 8 2 2.967 ms 1.512 ms 49.0%
2,048 16 4 5.114 ms 2.211 ms 56.8%
3,968 31 10 8.971 ms 4.052 ms 54.8%
4,096 1 1 1.364 ms 1.290 ms 5.4%
8,192 2 2 2.124 ms 1.991 ms 6.3%
32,768 1 1 2.089 ms 2.017 ms 3.4%

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 benchmark

Model: mlx-community/Qwen3-4B-4bit
Workload: 3,968-token natural-language prompt followed by 64 greedy decode tokens.

VarN K4/V2 implementation Prefill Decode Peak memory delta
Previous 32-tile base slab 108.19 tok/s 10.96 tok/s 1,347.19 MiB
New 4-tile base slab 148.41 tok/s 12.95 tok/s 1,347.19 MiB
Improvement +37.2% +18.2% Unchanged

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:

KV-cache backend Prefill Decode Token agreement vs FP16
FP16 183.22 tok/s 20.74 tok/s Reference
Affine 4-bit 171.35 tok/s 18.93 tok/s 100%
TurboQuant K4/V2 174.53 tok/s 17.96 tok/s 43.75%
VarN K4/V2 149.76 tok/s 12.90 tok/s 100%

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.

@aleroot

aleroot commented Aug 22, 2026

Copy link
Copy Markdown
Contributor Author

Memory consumption

Two different memory measurements should be distinguished:

  1. Persistent KV-cache storage: memory retained for cached keys and values.
  2. Peak process memory: includes model weights, MLX allocator reservations, temporary normalization buffers, attention workspaces, and the KV cache.

In the isolated 32K, one-layer storage test:

Representation KV storage
Raw FP16 keys and values 64.00 MiB
VarN K4/V2 compact storage 13.50 MiB
Reduction 78.9% / 4.74× smaller

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:

KV-cache backend Peak memory delta Difference vs FP16
FP16 1,067.30 MiB Reference
Affine 4-bit 1,067.30 MiB No measurable change
TurboQuant K4/V2 1,067.30 MiB No measurable change
VarN K4/V2 1,347.19 MiB +279.89 MiB / +26.2%

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:

  • VarN substantially reduces persistent KV-cache storage.
  • It does not yet reduce end-to-end peak process memory on Qwen3-4B.
  • Reducing temporary compression and materialization buffers remains a separate optimization opportunity.

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.

This implementation still has clear opportunities for further optimization, particularly around temporary workspace and peak memory usage. I believe it is a good foundation to merge in its current opt-in form and optimize incrementally in follow-up PRs.

@aleroot

aleroot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor Author

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 VarN algorithm or Sinkhorn iteration count.
  • Quantized values or cache format.
  • Attention behavior.
  • Prompt-cache compatibility.
  • The path used by models with four or fewer KV heads.

The compact results from each head batch are concatenated into the same final cache representation.

Real-model test

Hardware: Apple M2
Model: mlx-community/Qwen3-4B-4bit
Prompt: 3,968 natural-language tokens
Generation: 64 greedy tokens

Configuration Prefill Decode Peak memory delta Agreement vs FP16
FP16 KV 146.38 tok/s 18.22 tok/s 1,067.30 MiB Reference
VarN K4/V2 121.86 tok/s 10.87 tok/s 1,067.30 MiB 100%

Before bounded-head normalization, the same VarN configuration reached a peak delta of 1,347.19 MiB.

The change therefore removes:

  • 279.89 MiB of peak process memory.
  • The previous 26.2% peak overhead relative to FP16.
  • 20.8% of VarN’s previous measured peak.

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/B

A Qwen3-4B-like synthetic configuration was used:

  • 32 query heads.
  • 8 KV heads.
  • Head dimension 128.
  • 32,768 cached tokens.
  • K4/V2 compression.
Measurement All 8 heads together 4-head batches Change
Peak normalization workspace 946.7 MiB 558.9 MiB −41.0%
32K ingest 1.286 s 1.321 s approximately +2.7%
Raw FP16 KV storage 128.0 MiB 128.0 MiB —
Compact VarN storage 27.0 MiB 27.0 MiB 78.9% smaller than raw

The previous unbounded implementation fails the 768 MiB workspace regression guard at this shape. The bounded implementation passes with substantial margin.

Correctness evidence

The head batching is valid because variance normalization operates independently for each KV head. This is now enforced by a test comparing:

  • One eight-head cache using bounded batches.
  • Eight independently compressed one-head caches.

The reconstructed keys and values match with relative RMSE below 1e-6.

Additional quality results:

  • Qwen3-4B greedy agreement with FP16: 64/64 tokens.
  • Deterministic model test agreement: 100/100 tokens.
  • FP16 perplexity: 5.768397.
  • VarN K4/V2 perplexity: 5.744203.
  • Long-decode, GQA, masked-attention, trimming, serialization, dtype and prompt-cache tests pass.

Performance work included in the latest commits

The preceding slab-scheduling change also removed the dispatch cliff immediately before 4,096 tokens:

Context Previous decode Current decode Improvement
512 1.926 ms 1.198 ms 37.8%
1,024 2.967 ms 1.512 ms 49.0%
2,048 5.114 ms 2.211 ms 56.8%
3,968 8.971 ms 4.052 ms 54.8%
4,096 1.364 ms 1.290 ms 5.4%
8,192 2.124 ms 1.991 ms 6.3%
32,768 2.089 ms 2.017 ms 3.4%

Memory-footprint summary

The memory results measure two different things:

Measurement FP16 / previous VarN Current VarN K4/V2 Result
Qwen3-4B peak process delta at 3,968 tokens FP16: 1,067.30 MiB 1,067.30 MiB No measurable peak overhead vs FP16
VarN peak process delta before head batching 1,347.19 MiB 1,067.30 MiB −279.89 MiB / −20.8%
32K normalization workspace 946.7 MiB 558.9 MiB −41.0%
32K retained KV storage, keys and values FP16: 128.0 MiB 27.0 MiB −78.9% / 4.74× smaller

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.

With these changes, I think I will start to really use VarN for my local coding-agent.
@davidkoski I think now it is ready for another review. Thanks.

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The change looks good to me. Thank you for all the followup here!

@davidkoski
davidkoski merged commit 6745899 into ml-explore:main Aug 25, 2026
2 of 3 checks passed
ronaldmannak pushed a commit to ronaldmannak/mlx-swift-lm that referenced this pull request Aug 29, 2026
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
djandrewgibbons pushed a commit to djandrewgibbons/mlx-swift-lm that referenced this pull request Sep 1, 2026
* 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
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
…-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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants