Skip to content

feat(turboquant): add runtime softmax-attention KV-cache quantization - #6603

Merged
Qubitium merged 2 commits into
mainfrom
feat/turboquant-kv-cache
Dec 1, 2026
Merged

Qubitium merged 2 commits into
mainfrom
feat/turboquant-kv-cache

Conversation

@ZX-ModelCloud

Copy link
Copy Markdown
Collaborator

Summary

Adds a clean-room TurboQuant runtime quantizer for the softmax-attention KV
cache. It is not a weight format: weights, checkpoints and quant_method
are unchanged. Keys use TurboQuant-prod (key_bits - 1 bit MSE plus a one-bit
QJL residual); values use TurboQuant-mse. The packed cache sits behind a
DynamicCache layer and is selected through GPTQModel.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 same sqrt(pi / 2) / d QJL replay.

Measured impact

WikiText-2, Llama-3.1-8B-Instruct, dense weights, FP16, 32768 evaluation tokens
in 16 x 2048 windows. Prefill PPL uses a fresh cache per window; Decode PPL
scores 64 continuation tokens after a 2048-token prompt. Lower is better.

CUDA:

Config Prefill PPL Decode PPL 2K cache 4K cache 8K cache
dense 7.4254 14.0382 256 MiB 512 MiB 1024 MiB
4/4 7.6285 14.8193 67 MiB 134 MiB 268 MiB
4/3 7.7093 15.0497 59 MiB 118 MiB 236 MiB
3/2 8.8032 17.0343 43 MiB 86 MiB 172 MiB

ROCm:

Config Prefill PPL Decode PPL 2K cache 4K cache 8K cache
dense 7.4254 14.0372 256 MiB 512 MiB 1024 MiB
4/4 7.6349 15.0371 67 MiB 134 MiB 268 MiB
4/3 7.7050 14.7953 59 MiB 118 MiB 236 MiB
3/2 8.7814 17.9974 43 MiB 86 MiB 172 MiB

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 --> J
Loading
flowchart 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"]
Loading
Situation Before After
Generation cache Transformers builds a dense DynamicCache. A TurboQuantDynamicCache is built unless the caller supplied one.
Persistent cache Dense FP16/BF16 K/V. Packed codes, FP16 norms and a packed one-bit QJL sketch.
Attention read Reads the dense cache. Materializes the current dense K/V, then runs the same attention kernel.
Prefill and decode One dense path. Both paths quantize every appended token, including generated tokens.
Unsupported paths n/a Runtime generation, static/compiled caches, assistant/prompt-lookup decoding, sliding/hybrid/MLA layouts, encoder-decoder and combined LeapQuant fail closed.
Default Dense cache. Unchanged when kv_quant=None.

Validation

python -m pytest tests/test_turboquant.py tests/test_turboquant_gpu.py \
    tests/models/test_turboquant_kv_cache.py -q
# 76 passed

python -m pytest tests/test_docs_contract_refs.py -q
# passed

python -m pytest tests/test_backend_config.py tests/test_lazy_kernel_registry_import.py \
    tests/test_transformers_unpatched.py tests/test_model_port_policy.py \
    tests/test_leapquant_state.py tests/test_config_unapplied_options_5583.py -q
# 254 passed

PYTHON_GIL=0 python -m pytest tests/test_turboquant.py -q
# 60 passed

PYTHON_GIL=0 python -m pytest tests/test_turboquant_gpu.py -q
# 7 passed on each backend

PYTHON_GIL=0 python scripts/gil0_api_probe.py \
    --only 'torch.bucketize' \
    --only 'torch.bitwise_left_shift + torch.bitwise_right_shift' \
    --only 'torch.cumulative_trapezoid + torch.trapezoid' \
    --only 'torch.searchsorted' \
    --only 'TurboQuant Hadamard butterfly' \
    --only 'TurboQuant codebook solver' \
    --only 'TurboQuant packed cache'
# 7/7 PASS, three independent processes per backend

sh format/check.sh
# All checks passed

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.load and checks dense/quantized logits and
greedy generation. A smoke run on a GPTQ-quantized checkpoint with kv_quant
generated the same prefix as the dense cache and differed only after the
expected quantization drift.

GIL0: the TurboQuant primitives (torch.bucketize, the bitwise packers, the
cumulative_trapezoid/trapezoid/searchsorted codebook solver and the
Hadamard butterfly) passed three independent 8-thread x 4-iteration probe
processes per backend with PYTHON_GIL=0. The cache object itself is
single-threaded (one cache per generation stream), matching DynamicCache;
the ledger records both the concurrent primitive results and that ownership
rule.

Notes and limits

  • Runtime-only; no checkpoint or quant_method changes.
  • Uniform per-vector bits. The paper's per-channel outlier split is future work.
  • Torch reference path; fused attention kernels are future work.
  • The dense K/V materialization is transient, so peak attention memory is not
    reduced until the fused kernel reads packed chunks directly.
  • Sliding-window, chunked, hybrid, MLA, compressed/indexed attention,
    encoder-decoder, static/compiled caches, assistant/prompt-lookup decoding,
    crop/rollback, offload and live batch expansion are rejected.
  • Beam reorder and batch select/repeat are supported.
  • LeapQuant and TurboQuant cannot be enabled together yet.

Credit

Method and algorithms come from the TurboQuant paper. Attribution is recorded
in README.md, docs/citations.md, docs/turboquant.md, and the
gptqmodel/utils/turboquant.py and TurboQuantConfig docstrings.

@inproceedings{zandieh2026turboquant,
  title     = {TurboQuant: Online Vector Quantization with Near-optimal Distortion Rate},
  author    = {Zandieh, Amir and Daliri, Majid and Hadian, Majid and Mirrokni, Vahab},
  booktitle = {International Conference on Learning Representations (ICLR)},
  year      = {2026},
  eprint    = {2504.19874},
  archivePrefix = {arXiv}
}

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
ZX-ModelCloud marked this pull request as ready for review December 1, 2026 06:10
@Qubitium
Qubitium merged commit deab0f9 into main Dec 1, 2026
6 checks passed
@Qubitium
Qubitium deleted the feat/turboquant-kv-cache branch December 1, 2026 06:30

@ZX-ModelCloud ZX-ModelCloud left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

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]>
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