Skip to content

add kvScheme parameter for extensible KV cache compression - #230

Merged
davidkoski merged 1 commit into
ml-explore:mainfrom
TheTom:pr/upstream-kv-scheme
Jun 22, 2026
Merged

davidkoski merged 1 commit into
ml-explore:mainfrom
TheTom:pr/upstream-kv-scheme

Conversation

@TheTom

@TheTom TheTom commented Apr 21, 2026 •

Copy link
Copy Markdown
Contributor

Proposed changes

Adds kvScheme to GenerateParameters alongside existing kvBits. Provides
a string-based scheme selector for KV cache compression strategies.

Built-in: "affine4", "affine8" (equivalent to kvBits 4/8).
kvScheme overrides kvBits when set. Unrecognized schemes pass through
for custom KVCache implementations.

Fully backward compatible. kvScheme defaults to nil, existing kvBits
behavior unchanged.

Plumbing only, no new compression algorithms. Prepares the API for
WHT-based and other non-affine KV compression schemes.

Checklist

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

Comment on lines +1779 to +1781
/// Resolve a kvScheme string to (bits, groupSize) for affine quantization.
/// Returns nil for unrecognized schemes (custom schemes handle their own caches).
public func resolveAffineScheme(_ scheme: String?) -> (bits: Int, groupSize: Int)? {

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.

I think this is getting concatenated with the docs for the maybeQuantizeKVCache below (the docs checker is failing). Also need kvScheme added to the docs.

@davidkoski

Copy link
Copy Markdown
Member

When you get a chance please rebase -- this will fix the merge conflict and fix the CI issue so tests can run. Thank you!

Adds kvScheme to GenerateParameters alongside existing kvBits. Provides
a string-based scheme selector for KV cache compression strategies.

Built-in: "affine4", "affine8" (equivalent to kvBits 4/8).
kvScheme overrides kvBits when set. Unrecognized schemes pass through
for custom KVCache implementations.

Plumbing only, no new compression algorithms. Prepares the API for
WHT-based and other non-affine KV compression schemes.
@TheTom
TheTom force-pushed the pr/upstream-kv-scheme branch from 122300d to 4e799a4 Compare June 11, 2026 20:57
@TheTom

TheTom commented Jun 11, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto main and pushed — the doc-comment concatenation is fixed (resolveAffineScheme moved above the maybeQuantizeKVCache docs) and kvScheme is now documented in the parameter list. CI is green.

@TheTom TheTom mentioned this pull request Jun 11, 2026
4 tasks done

@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.

Thank you for the contribution!

@davidkoski
davidkoski merged commit d1d9a09 into ml-explore:main Jun 22, 2026
2 checks passed
somegeekintn added a commit to somegeekintn/mlx-swift-lm that referenced this pull request Jun 28, 2026
TheTom added a commit to TheTom/mlx-swift-lm that referenced this pull request Jul 16, 2026
Walsh-Hadamard rotation + Lloyd-Max codebook KV compression behind the
kvScheme parameter (ml-explore#230), with JIT Metal kernels: fused encode, a
SIMD-parallel two-pass online-softmax flash decode (packed-K, raw-fp16-K,
and 8-bit-affine-K score variants), and an inline sparse value kernel.

Schemes are asymmetric because keys are far more quality-sensitive than
values (softmax amplifies key error, value error averages out): the
recommended tiers keep K at fp16 (turbo0v4/v3/v2) or 8-bit affine
(turbo8v4/v3/v2) while V takes the compression; symmetric turbo4/3/2 are
available for validated use. Boundary-layer protection converts the first
and last attention layers to 8-bit affine for fragile schemes.

Per-call kernel values travel in a parameter buffer rather than template
arguments, so each shape compiles once. Caches stay raw fp16 through
prefill, compress on the first decode step, and encode incrementally;
state round-trips through prompt cache save/restore, and speculative
decoding routes through the compressed path. Generation settles cache
state with the token eval and drains autoreleased temporaries per step so
long generations hold steady memory.
TheTom added a commit to TheTom/mlx-swift-lm that referenced this pull request Jul 16, 2026
Walsh-Hadamard rotation + Lloyd-Max codebook KV compression behind the
kvScheme parameter (ml-explore#230), with JIT Metal kernels: fused encode, a
SIMD-parallel two-pass online-softmax flash decode (packed-K, raw-fp16-K,
and 8-bit-affine-K score variants), and an inline sparse value kernel.

Schemes are asymmetric because keys are far more quality-sensitive than
values (softmax amplifies key error, value error averages out): the
recommended tiers keep K at fp16 (turbo0v4/v3/v2) or 8-bit affine
(turbo8v4/v3/v2) while V takes the compression; symmetric turbo4/3/2
compress both sides. Symmetric key quality rides on per-dimension key
calibration: at compression time the cache derives a per-dimension scale
from the post-rotation key variance of the prefill cache and folds it
into the query side, leaving the score kernels untouched; the calibrated
encode rotates through the codec's MLX ops so kernel and reference
quantize identical values. Boundary-layer protection converts the first
and last attention layers to 8-bit affine for fragile schemes. Rotating
(sliding-window) cache layers stay fp16 with a one-time notice; global
layers on mixed models compress normally.

Per-call kernel values travel in a parameter buffer rather than template
arguments, so each shape compiles once. Caches stay raw fp16 through
prefill, compress on the first decode step, and encode incrementally;
state round-trips through prompt cache save/restore, and speculative
decoding routes through the compressed path. Generation settles cache
state with the token eval and drains autoreleased temporaries per step so
long generations hold steady memory.
TheTom added a commit to TheTom/mlx-swift-lm that referenced this pull request Jul 16, 2026
Walsh-Hadamard rotation + Lloyd-Max codebook KV compression behind the
kvScheme parameter (ml-explore#230), with JIT Metal kernels: fused encode, a
SIMD-parallel two-pass online-softmax flash decode (packed-K, raw-fp16-K,
and 8-bit-affine-K score variants), and an inline sparse value kernel.

Schemes are asymmetric because keys are far more quality-sensitive than
values (softmax amplifies key error, value error averages out): the
recommended tiers keep K at fp16 (turbo0v4/v3/v2) or 8-bit affine
(turbo8v4/v3/v2) while V takes the compression; symmetric turbo4/3/2
compress both sides. Symmetric key quality rides on per-dimension key
calibration: at compression time the cache derives a per-dimension scale
from the post-rotation key variance of the prefill cache and folds it
into the query side, leaving the score kernels untouched; the calibrated
encode rotates through the codec's MLX ops so kernel and reference
quantize identical values. Boundary-layer protection converts the first
and last attention layers to 8-bit affine for fragile schemes. Rotating
(sliding-window) cache layers stay fp16 with a one-time notice; global
layers on mixed models compress normally.

Per-call kernel values travel in a parameter buffer rather than template
arguments, so each shape compiles once. Caches stay raw fp16 through
prefill, compress on the first decode step, and encode incrementally;
state round-trips through prompt cache save/restore, and speculative
decoding routes through the compressed path. Generation settles cache
state with the token eval and drains autoreleased temporaries per step so
long generations hold steady memory.
davidkoski pushed a commit that referenced this pull request Jul 20, 2026
* Add TurboQuant KV cache compression

Walsh-Hadamard rotation + Lloyd-Max codebook KV compression behind the
kvScheme parameter (#230), with JIT Metal kernels: fused encode, a
SIMD-parallel two-pass online-softmax flash decode (packed-K, raw-fp16-K,
and 8-bit-affine-K score variants), and an inline sparse value kernel.

Schemes are asymmetric because keys are far more quality-sensitive than
values (softmax amplifies key error, value error averages out): the
recommended tiers keep K at fp16 (turbo0v4/v3/v2) or 8-bit affine
(turbo8v4/v3/v2) while V takes the compression; symmetric turbo4/3/2
compress both sides. Symmetric key quality rides on per-dimension key
calibration: at compression time the cache derives a per-dimension scale
from the post-rotation key variance of the prefill cache and folds it
into the query side, leaving the score kernels untouched; the calibrated
encode rotates through the codec's MLX ops so kernel and reference
quantize identical values. Boundary-layer protection converts the first
and last attention layers to 8-bit affine for fragile schemes. Rotating
(sliding-window) cache layers stay fp16 with a one-time notice; global
layers on mixed models compress normally.

Per-call kernel values travel in a parameter buffer rather than template
arguments, so each shape compiles once. Caches stay raw fp16 through
prefill, compress on the first decode step, and encode incrementally;
state round-trips through prompt cache save/restore, and speculative
decoding routes through the compressed path. Generation settles cache
state with the token eval and drains autoreleased temporaries per step so
long generations hold steady memory.

* Add TurboQuant tests

Codec round trips and pinned codebooks, rotation orthogonality, packing, kernel-vs-reference attention parity (GQA repeat factors 1/2/3, non-power-of-two head dims), calibrated-encode kernel exact index parity, prompt-cache round trips for all state layouts including calibration state, compressed partial trim with continued decode, speculative decoding with a turbo scheme, allocation-boundary growth, boundary-protection gating, mixed rotating/standard cache conversion, and end-to-end generation on tiny random-weight models. CI-runnable, no checkpoint downloads.

* Add KV cache quantization documentation

Scheme reference table, the asymmetric-first selection ladder, measured family sensitivity and calibration notes, performance guidance, and limitations.
dkgv pushed a commit to dkgv/mlx-swift-lm that referenced this pull request Jul 30, 2026
…e#230)

Adds kvScheme to GenerateParameters alongside existing kvBits. Provides
a string-based scheme selector for KV cache compression strategies.

Built-in: "affine4", "affine8" (equivalent to kvBits 4/8).
kvScheme overrides kvBits when set. Unrecognized schemes pass through
for custom KVCache implementations.

Plumbing only, no new compression algorithms. Prepares the API for
WHT-based and other non-affine KV compression schemes.
dkgv pushed a commit to dkgv/mlx-swift-lm that referenced this pull request Jul 30, 2026
* Add TurboQuant KV cache compression

Walsh-Hadamard rotation + Lloyd-Max codebook KV compression behind the
kvScheme parameter (ml-explore#230), with JIT Metal kernels: fused encode, a
SIMD-parallel two-pass online-softmax flash decode (packed-K, raw-fp16-K,
and 8-bit-affine-K score variants), and an inline sparse value kernel.

Schemes are asymmetric because keys are far more quality-sensitive than
values (softmax amplifies key error, value error averages out): the
recommended tiers keep K at fp16 (turbo0v4/v3/v2) or 8-bit affine
(turbo8v4/v3/v2) while V takes the compression; symmetric turbo4/3/2
compress both sides. Symmetric key quality rides on per-dimension key
calibration: at compression time the cache derives a per-dimension scale
from the post-rotation key variance of the prefill cache and folds it
into the query side, leaving the score kernels untouched; the calibrated
encode rotates through the codec's MLX ops so kernel and reference
quantize identical values. Boundary-layer protection converts the first
and last attention layers to 8-bit affine for fragile schemes. Rotating
(sliding-window) cache layers stay fp16 with a one-time notice; global
layers on mixed models compress normally.

Per-call kernel values travel in a parameter buffer rather than template
arguments, so each shape compiles once. Caches stay raw fp16 through
prefill, compress on the first decode step, and encode incrementally;
state round-trips through prompt cache save/restore, and speculative
decoding routes through the compressed path. Generation settles cache
state with the token eval and drains autoreleased temporaries per step so
long generations hold steady memory.

* Add TurboQuant tests

Codec round trips and pinned codebooks, rotation orthogonality, packing, kernel-vs-reference attention parity (GQA repeat factors 1/2/3, non-power-of-two head dims), calibrated-encode kernel exact index parity, prompt-cache round trips for all state layouts including calibration state, compressed partial trim with continued decode, speculative decoding with a turbo scheme, allocation-boundary growth, boundary-protection gating, mixed rotating/standard cache conversion, and end-to-end generation on tiny random-weight models. CI-runnable, no checkpoint downloads.

* Add KV cache quantization documentation

Scheme reference table, the asymmetric-first selection ladder, measured family sensitivity and calibration notes, performance guidance, and limitations.
davidtai added a commit to davidtai/mlx-swift-lm that referenced this pull request Oct 6, 2026
…l-explore#230)

Integrate Deepseek V4 fp8 scale-key cleanup and enable strict checkpoint-loading regression assertions without reducing coverage.
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.

2 participants