New Tool Radar

AI Concepts

How to Quantize the KV Cache to Fit Longer Contexts in Memory

Enable a quantized KV cache, pick the backend and bit width, and check the quality loss is acceptable for your context length.

Schematic with three steps: Enable the quantized cache; Run the long prompt and check memory; Check the answer quality.

The KV cache stores the key and value vectors computed for past tokens, so the model does not recompute them at every step. For long contexts it can occupy a significant portion of memory and become the bottleneck. A QuantizedCache reduces memory by quantizing the KV values to a lower precision: it supports int1, int2, int3, int4 and int8 with the hqq backend, int2 and int4 with quanto, and 8-bit floating point with fp8. Quantizing the cache is a memory trade, not a free win, so measure it at your context length.

What you need

  • A model and a long-context task that runs out of GPU memory
  • The Transformers library with a quantization backend installed
  • A test prompt at the context length you need

Step 1: Enable the quantized cache

Set cache_implementation to quantized in generate or GenerationConfig, and pass the backend and bit width in cache_config, for example nbits 4 with the hqq backend and axis_key and axis_value set to 1.

Step 2: Run the long prompt and check memory

Run the test prompt at your target context length and confirm the memory use drops enough to fit. If it still does not fit, decrease the residual length or drop to fewer bits.

Step 3: Check the answer quality

Compare the answer with the unquantized cache on the same prompt. Quantizing the cache can harm latency if the context is short and memory is plentiful, so only use it when memory is actually the constraint.

Worked example: synthetic quantized KV cache check

The table below is a synthetic example. It shows the expected result of quantizing the KV cache; no model was run.

Cache Memory at 32k tokens Answer quality
Full precision Out of memory Not run
Quantized 4-bit hqq Fits Same answer
Quantized 2-bit quanto Fits easily Slightly worse
Decision 4-bit hqq chosen Fits, quality kept

Expected result (UNTESTED). the 4-bit quantized cache fits the 32k-token prompt and keeps the answer, while full precision runs out of memory. This check was not run live; the table shows the expected result for the synthetic example.

Limits

  • Use the default quantization parameters unless you are running out of memory; then consider decreasing the residual length.
  • For the hqq backend, set axis_key and axis_value to 1; for quanto, set them to 0.
  • The fp8 backend stores KV values in float8 and rejects nbits and group-size options, since it quantizes per tensor.
  • Quantized caches do not support sliding layers or offloading in the same way as the dynamic cache.

Sources

See all