Repository navigation
feat(turboquant): add runtime softmax-attention KV-cache quantization - #6603
Merged
Merged
Conversation
Add a clean-room TurboQuant runtime cache for standard softmax attention. Keys use TurboQuant-prod (MSE stage plus a one-bit QJL residual) and values use TurboQuant-mse; both are bit-packed behind a DynamicCache layer. The policy is runtime-only and never changes weights, checkpoints or quant_method. Expose GPTQModel.load(..., kv_quant=...) and enable_kv_quant(), wire the cache into every GPTQModel.generate branch, and fail closed for runtime generation, static/compiled caches, assistant/prompt-lookup decoding, unsupported attention layouts, and combined LeapQuant use. Add CPU oracle tests, CUDA/ROCm parity tests, a tiny-model generate test, a WikiText-2 benchmark, and the mechanism documentation.
Add probes for torch.bucketize, the bitwise code packers, the cumulative_trapezoid/trapezoid/searchsorted codebook solver, the Hadamard butterfly, and the packed cache. All passed three independent 8-thread x 4-iteration processes per backend with PYTHON_GIL=0. Record the measured rows and the cache ownership rule: the primitives are concurrent-safe, but one TurboQuant cache belongs to one generation stream.
ZX-ModelCloud
commented
Dec 1, 2026
ZX-ModelCloud
left a comment
Collaborator
Author
There was a problem hiding this comment.
Reviewed the TurboQuant KV-cache paths. Follow-up #6612 carries the fixes after this PR merged.
- Honor effective generation settings and reject incompatible cache layouts and decoding modes before writing cache data.
- Preserve batch metadata and roll back failed readouts. Store FP32 RMS scales to keep large and small finite KV values in range.
- Synchronize both boundaries of the decode benchmark timer.
The CPU TurboQuant suite passed 94 tests. Seven device cases were skipped. Formatting passed.
This was referenced Dec 1, 2026
Qubitium
added a commit
that referenced
this pull request
Dec 1, 2026
#6670) #6603 added BaseQModel._prepare_kv_quant_cache and generate() now calls it unconditionally. The _Harness double in the #4669 policy tests binds only the three policy methods, so the five generate() tests raised AttributeError before reaching their assertions. Bind the real method (the harness has no kv_quant, so it returns the kwargs unchanged) instead of duplicating a stub. Co-authored-by: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds a clean-room TurboQuant runtime quantizer for the softmax-attention KV
cache. It is not a weight format: weights, checkpoints and
quant_methodare unchanged. Keys use TurboQuant-prod (
key_bits - 1bit MSE plus a one-bitQJL residual); values use TurboQuant-mse. The packed cache sits behind a
DynamicCachelayer and is selected throughGPTQModel.load(..., kv_quant=...)or
enable_kv_quant().TurboQuant complements LeapQuant: LeapQuant covers the fixed-size recurrent
state of linear attention, TurboQuant covers the growing KV cache of softmax
attention. Enabling both on one cache is rejected for now.
Reference: TurboQuant: Online Vector Quantization with Near-optimal Distortion
Rate, Zandieh, Daliri, Hadian and Mirrokni, arXiv:2504.19874
(ICLR 2026). The implementation is clean-room from the paper; no code was
copied from public implementations. The paper's dense Gaussian rotation is
replaced by a randomized Walsh-Hadamard transform (orthogonal after the
documented
1 / sqrt(d)scale) with the samesqrt(pi / 2) / dQJL replay.Measured impact
WikiText-2, Llama-3.1-8B-Instruct, dense weights, FP16, 32768 evaluation tokens
in 16 x 2048 windows.
Prefill PPLuses a fresh cache per window;Decode PPLscores 64 continuation tokens after a 2048-token prompt. Lower is better.
CUDA:
ROCm:
The uniform 3.5-bit point (4/3) costs 3.8% prefill perplexity and 7.2% on the
short continuation while cutting the persistent cache by 4.34x. The 2.5-bit
point (3/2) costs 18.6% and 21.3%. The paper's absolute neutrality at 3.5 bits
also uses per-channel outlier splitting; that allocation is not part of this
phase. The packed cache is a Torch reference path and is not fused into the
attention kernel, so decode is slower than dense (about 12 versus 47 tokens/s
on CUDA and 5.9-8.5 versus 29.5 tokens/s on ROCm). No throughput gain is
claimed; the measured win is persistent cache memory and quality.
Small models without QK normalization are more sensitive: Qwen2.5-0.5B showed
a large perplexity increase at 4/3, while Llama-3.1-8B stayed within the table
above. The docs record that limitation.
Control flow
flowchart TD A["GPTQModel.generate"] --> B{"kv_quant set"} B -->|no| C["model.generate with caller kwargs"] B -->|yes| D{"supported path"} D -->|no| E["raise ValueError"] D -->|yes| F{"past_key_values supplied"} F -->|no| G["build TurboQuantDynamicCache"] F -->|yes| H{"TurboQuantDynamicCache"} H -->|no| E H -->|yes| I["keep caller cache"] G --> J["model.generate"] I --> Jflowchart LR A["key/value update"] --> B["normalize by vector norm"] B --> C["Hadamard rotation"] C --> D{"keys and use_qjl"} D -->|yes| E["b-bit MSE indices<br/>plus one-bit QJL sketch"] D -->|no| F["b-bit MSE indices"] E --> G["packed chunks<br/>indices, norms, sketch"] F --> G G --> H["materialize on attention call"] H --> I["inverse rotation and norm"]DynamicCache.TurboQuantDynamicCacheis built unless the caller supplied one.kv_quant=None.Validation
The CUDA and ROCm device-parity suites both pass. The CPU unit suite covers
the paper's closed-form codebooks and an independent quadrature fixed point, a
dense Hadamard oracle, exact pack/unpack for 1-4 bits, MSE nearest-centroid
selection, QJL inner-product bias, cache prefill/decode/batch/reorder/reset,
dtype/shape contracts and every rejection path. The model test loads a tiny
Llama port through
GPTQModel.loadand checks dense/quantized logits andgreedy generation. A smoke run on a GPTQ-quantized checkpoint with
kv_quantgenerated the same prefix as the dense cache and differed only after the
expected quantization drift.
GIL0: the TurboQuant primitives (
torch.bucketize, the bitwise packers, thecumulative_trapezoid/trapezoid/searchsortedcodebook solver and theHadamard butterfly) passed three independent 8-thread x 4-iteration probe
processes per backend with
PYTHON_GIL=0. The cache object itself issingle-threaded (one cache per generation stream), matching
DynamicCache;the ledger records both the concurrent primitive results and that ownership
rule.
Notes and limits
quant_methodchanges.reduced until the fused kernel reads packed chunks directly.
encoder-decoder, static/compiled caches, assistant/prompt-lookup decoding,
crop/rollback, offload and live batch expansion are rejected.
Credit
Method and algorithms come from the TurboQuant paper. Attribution is recorded
in
README.md,docs/citations.md,docs/turboquant.md, and thegptqmodel/utils/turboquant.pyandTurboQuantConfigdocstrings.