KV Cache Quantization and Compression: Solving Long-Context Memory Bottlenecks
Long-context inference on local devices often fails not because the model is not smart enough, but because memory is not enough. This article explains why KV cache grows linearly with context length and becomes the dominant memory cost in unified-memory deployments. It covers the basic principles of KV cache quantization and compression, including low-bit quantization, random orthogonal rotation, polar-coordinate quantization, and 1-bit random projection. It also provides practical guidance for enabling KV cache quantization in local inference frameworks, validating outputs and performance, evaluating trade-offs, and deciding when it is worth using.
Introduction: Ask the Right Question Before Tuning
When running large models locally, many people focus first on parameter size. But when deploying long-context applications, the first bottleneck is often not whether the model is smart enough, but whether memory is enough. This is especially true for models that natively support very long contexts. When the context is expanded to 32K, 64K, or 128K, unified-memory devices can easily report out-of-memory errors.
The problem is not mysterious. Model weights are a relatively fixed cost. The additional overhead introduced by long contexts mainly comes from the KV cache. The size of the KV cache grows linearly with context length. On unified-memory devices where the CPU and GPU share memory, weights, KV cache, and system usage all compete for the same memory pool. Once the required memory exceeds the available memory, inference fails.
This article focuses on four questions:
- Why does the KV cache become the main memory overhead in long-context inference?
- What are the basic principles and benefits of KV cache quantization and compression?
- How can it be enabled, validated, and rolled back in local inference frameworks?
- When is it worth enabling, and when are the benefits limited?
One point needs to be clarified upfront: the value of KV cache quantization and compression is not to make the model smarter. It makes a long-context workload that previously could not fit into memory runnable. Its benefits depend heavily on context length, framework implementation, and inference workload, so they cannot be generalized into a universal conclusion.
1. KV Cache: The Primary Memory Overhead in Long-Context Inference
1.1 What Is KV Cache, and Why Does It Grow Linearly?
During autoregressive generation, the model produces tokens one by one. Generating the current token depends not only on the input but also on the tokens already generated. If the model recomputed the Key and Value representations for all historical tokens at every step, the computational cost would increase sharply. Therefore, mainstream inference frameworks cache the Key and Value vectors generated by each token at each layer. This is the KV cache.
The size of the KV cache can be approximated as:
KV cache size ≈ 2 × number of layers × number of KV heads × head_dim × context length × bytes per element
The factor of 2 corresponds to the two datasets: Key and Value. Context length usually includes both the prompt length and the generated length. As long as the context becomes longer, the KV cache grows linearly.
1.2 Memory Pressure on Unified-Memory Devices
On unified-memory devices, model weights and the KV cache directly share the same physical memory. For a model with 32 layers, 8 KV heads, and a head dimension of 128, storing the KV cache in FP16 uses about 128 KiB per token. If 3-bit quantization is used, the KV cache usage per token can drop to about 24 KiB.
The table below is used to show the scale. Actual values may vary slightly depending on the number of layers, number of KV heads, head dimension, tokenizer, and framework implementation.
| Attention structure | KV precision | 8K context | 32K context | 128K context |
|---|---|---|---|---|
| 8 KV heads (GQA) | FP16 | about 1.1 GB | about 4.3 GB | about 17.2 GB |
| 8 KV heads (GQA) | 3-bit | about 0.20 GB | about 0.81 GB | about 3.2 GB |
| 1 KV head (MQA) | FP16 | about 0.13 GB | about 0.54 GB | about 2.1 GB |
| 1 KV head (MQA) | 3-bit | about 0.025 GB | about 0.10 GB | about 0.40 GB |
Assume a 32 GB unified-memory device has about 24 GB available for model inference after system overhead, and the model weights are about 15.5 GB after 4-bit quantization. In this case:
- With 8 KV heads, FP16, and 128K context: weights are about 15.5 GB and KV cache is about 17.2 GB, for a total of about 32.7 GB. This inevitably exceeds the available memory.
- With 8 KV heads, 3-bit KV, and 128K context: weights are about 15.5 GB and KV cache is about 3.2 GB, for a total of about 18.7 GB. This can run.
- If the context is extended further to 256K, 3-bit KV cache is about 6.4 GB, and the total is about 21.9 GB. It may still run, but the remaining memory margin is much smaller.
Therefore, the essence of many local long-context failures is that this inequality is broken:
weight size + KV cache size + runtime overhead > available memory
It is worth noting that grouped-query attention (GQA) and multi-query attention (MQA) have already greatly reduced KV cache size. If a model already has little KV pressure, introducing additional compression usually brings limited benefits.
2. Three Technical Routes for KV Compression
There are three common approaches to mitigating KV cache expansion:
- Sparsification: Keep the KV of only part of the tokens. Common strategies include evicting tokens based on accumulated attention scores and keeping the first few tokens plus a recent window. These methods usually do not impose a hard upper limit on context length, but once information is discarded, it cannot be recovered. This can be risky for precise retrieval and multi-hop reasoning tasks.
- Low-precision quantization: Represent each KV element with fewer bits. It does not change the content of the KV cache, but reduces storage precision. It is simple to implement, broadly applicable, and currently the most widely adopted approach.
- Transformation-based encoding: Apply a linear transformation to the KV vectors first, then perform low-bit quantization. For example, a random orthogonal rotation can make the distribution of dimensions more uniform and reduce quantization error.
These three routes are not mutually exclusive, and real systems may combine them. This article focuses on the second route, as well as the combination of “rotation plus quantization.”
3. How KV Cache Quantization and Compression Work
The conclusion first: these methods usually do not compress model weights. Instead, they compress the KV cache at runtime using low-bit representations. Different papers and frameworks may use different names, parameters, and pipelines. The breakdown below is conceptual and is meant to help explain common practices.
3.1 Random Orthogonal Rotation: Making Distributions More Uniform
Ordinary block quantization needs to store separate scale factors and zero points for each data block. The smaller the block, the higher the precision, but the greater the metadata overhead. To reduce extra metadata, one approach is to apply a random orthogonal rotation to the KV vectors.
A random orthogonal matrix has a key property: it preserves vector inner products and norms. Therefore, in theory, it does not break the vector geometry that attention computation relies on. After rotation, the distribution of dimensions is usually more uniform, and extreme values are spread out. This makes low-bit quantization easier to cover the real value range.
The key to this method is that it is data-independent: the rotation matrix can be generated once in advance and reused during inference. It does not need to compute scaling parameters dynamically based on current KV data, which helps reduce metadata overhead.
3.2 Polar-Coordinate Quantization: Separating Radius and Direction
In the rotated space, vectors can be converted into polar-coordinate representation, which separates a vector into “radius” and “direction.” Different dimensions have different sensitivities to reconstruction error. Therefore, a higher precision can be assigned to the radius, while the direction can use a lower precision.
This “radius plus direction” separation is closer to real reconstruction error than simple direct quantization. In essence, it allocates bits under a limited bit budget to the components that are more sensitive.
3.3 1-bit Random Projection: Reducing Residual Bias
After low-bit quantization, KV vectors may still have reconstruction bias. A 1-bit Johnson-Lindenstrauss projection, or 1-bit JL projection, can be added on top. The JL lemma states that an appropriate random projection can map high-dimensional vectors to a lower-dimensional space while approximately preserving distances between vectors.
The 1-bit projection can store some distance-structure information at very low cost. In effect, it uses a small number of extra bits to correct geometric bias introduced after quantization.
3.4 Why Such Large Compression Is Possible
In theory, if each element stores only 3 bits, the theoretical compression limit relative to FP16 is approximately:
16 / 3 ≈ 5.33x
In practice, implementations usually add rotation, polar-coordinate quantization, 1-bit JL projection, necessary metadata, or correction bits. Therefore, the actual compression ratio is often lower than the theoretical upper limit. In an illustrative implementation, 3-bit KV cache may achieve about 4x to 5x compression, but the exact result depends on the framework, model architecture, and context distribution.
For comparison, ordinary block quantization may store one 16-bit scale factor for every 8 elements, while the data itself uses 4 bits. The effective bit rate is then:
(8 × 4 + 16) / 8 = 6 bits per element
The compression ratio relative to FP16 is:
16 / 6 ≈ 2.67x
For 128K context, a difference of a few times or more than ten times may be the difference between “cannot run” and “can run.”
It should be emphasized that “lower precision loss” usually refers to overall language-modeling metrics such as perplexity. It does not mean that all tasks are lossless. For long-distance precise retrieval, contract comparison, code localization, and similar tasks, compression error may be amplified.
3.5 General Engineering Flow
The code below is only used to illustrate the general flow. Parameter names and interfaces should follow the actual framework or implementation.
# Illustrative code: this only shows the general workflow; real parameter names depend on the framework.def compress_kv(k, v, cfg):# 1. Rotation: multiply k and v by the same random orthogonal matrix.k_rot = rotate(k, cfg.rotation_matrix)v_rot = rotate(v, cfg.rotation_matrix)# 2. Polar-coordinate quantization: decompose each vector into radius and direction, then encode them with the configured bits.k_code = polar_quantize(k_rot, bits=cfg.kv_bits)v_code = polar_quantize(v_rot, bits=cfg.kv_bits)# 3. 1-bit random projection: store additional correction information to reduce quantization bias.k_code = project_1bit(k_code, cfg.jl_seed)v_code = project_1bit(v_code, cfg.jl_seed)return k_code, v_codedef decompress_kv(code, cfg):k = dequantize_polar(code, cfg)v = dequantize_polar(code, cfg)k = project_1bit_inverse(k, cfg.jl_seed)v = project_1bit_inverse(v, cfg.jl_seed)k = rotate_inverse(k, cfg.rotation_matrix)v = rotate_inverse(v, cfg.rotation_matrix)return k, v
There are two important engineering points:
- The rotation matrix usually only needs to be generated once and reused. Otherwise, it adds extra initialization overhead.
- Compression mainly happens at the storage layer. Before attention computation, dequantization is required. Therefore, it solves the “cannot fit” problem, but it does not necessarily speed up attention computation itself.
4. Enabling and Validating Locally
4.1 Three Checks Before Enabling
1. Confirm framework support.
KV cache quantization is an inference-framework-level capability. Support varies across frameworks and versions. For example, newer llama.cpp builds usually provide --cache-type-k and --cache-type-v. If these options are not available in your version, the version may be too old.
Example:
# Requires a newer llama.cpp build that supports --cache-type-k and --cache-type-vllama-cli \-m model.gguf \-p "Please summarize the following text:" \-n 128 \-c 32768 \--cache-type-k q8_0 \--cache-type-v q8_0
If the build supports 4-bit KV, you can try:
# If the parameter or type is not supported, the command will fail or have no effectllama-cli \-m model.gguf \-p "Please summarize the following text:" \-n 128 \-c 32768 \--cache-type-k q4_0 \--cache-type-v q4_0
For tools such as mlx-lm, newer versions may also provide similar options, for example:
# Follow the actually installed mlx-lm version and its help outputmlx_lm.generate \--model /path/to/model \--prompt "Please summarize the following text:" \--max-tokens 128 \--kv-bits 4
Different frameworks may use different parameter names. Common examples include kv-cache-dtype, cache-type-k, cache-type-v, and kv-bits. Before enabling, it is best to check the help output first:
llama-cli --help# orpython -m mlx_lm.generate --help
2. Confirm model and quantization compatibility.
Models that use attention structures such as GQA or MQA are usually more suitable for KV quantization. Some models use special attention structures, custom positional encodings, or unusual implementations. Enabling KV quantization may cause abnormal outputs. It is best to compare results case by case.
3. Do not stack too many optimizations at once.
When KV quantization is combined with features such as speculative decoding, paged cache, sliding window, or thread-count tuning, compatibility issues may appear. It is best to change only one variable at a time and confirm the effect step by step.
For risk control, test first on a test project or a copy of the model. Do not overwrite the original configuration in production directly. If crashes, garbled output, or obvious quality degradation occur after enabling, roll back to the default FP16 KV cache first, and keep logs and parameter records.
4.2 Recommended Validation Flow
A recommended validation order is: short context first, long context later; comparison first, tuning later.
1. Short-context comparison.
First test with short conversations of 1K to 8K and compare whether outputs before and after enabling are consistent. A simple prompt can be prepared, for example:
Please find the meeting time in the text below and quote it verbatim:...
2. Gradually increase context length.
Increase context from 8K to 32K, 64K, and 128K, and observe whether out-of-memory errors, interrupted generation, or obvious slowdowns occur.
3. Record peak memory usage.
Different systems have different methods:
- macOS: use Activity Monitor, or check memory and KV size statistics printed by llama.cpp.
- Linux: use tools such as
time -vorvalgrind --tool=massif. - llama.cpp logs: they usually print model size, KV cache size, and context length, which can serve as a basic reference.
4. Test with real workloads.
Do not only test whether the model can start. Also test whether it can be used well. For example, long-document question answering, multi-turn conversations, long-text summarization, and contract-clause retrieval.
5. Evaluation Methodology: How to Judge Whether the Benefits Are Reasonable
The benefits of KV cache quantization and compression are highly workload-dependent. The following steps are recommended.
5.1 Keep Variables Fixed and Control Precision
Keep the following fixed:
- Model weight quantization precision, for example 4-bit.
- Inference framework version.
- Sampling parameters, such as temperature, top_p, and top_k.
- Prompt templates and evaluation tasks.
Then use KV quantization precision as the only variable, for example:
FP16 / 8-bit / 4-bit / 3-bit
5.2 Track Five Core Metrics
| Metric | Meaning | What to focus on |
|---|---|---|
| Peak memory | Highest physical memory usage during inference | Determines how long a context can be supported |
| Time to first token (TTFT) | Time from submitting the request to producing the first token | Prefill overhead from quantization is concentrated here |
| Generation throughput | Number of tokens generated per second | Dequantization during decoding may add extra computation |
| Task accuracy | Scores on long-text retrieval, multi-hop QA, summarization, etc. | Determines whether precision is acceptable |
| Perplexity (PPL) | Model prediction uncertainty on test text | A proxy metric for overall language-modeling quality |
5.3 Practical Rules for Interpreting Results
- Memory usage and context length are roughly linearly related. When the number of bits decreases, KV cache size decreases approximately proportionally. This is the most certain benefit of compression.
- TTFT is usually affected most. During the prefill stage, the KV cache for the entire prompt must be written, and quantization/dequantization can increase time to first token.
- Changes in decoding throughput depend on the balance between extra dequantization overhead and weight-access overhead. It may decrease slightly, or it may stay roughly the same.
- Task accuracy must be judged according to the business scenario. Tasks with higher tolerance, such as summarization, rewriting, and open-ended QA, may be fine with 3-bit. Precise-retrieval tasks such as contract-clause verification and code localization should prefer 4-bit and then undergo thorough evaluation.
For example, assume a device has 24 GB of available memory, the model weights are about 15.5 GB after 4-bit quantization, and the model uses 8 KV heads. With 3-bit KV, 128K context requires about 3.2 GB of KV cache, for a total of about 18.7 GB, leaving a relatively comfortable margin. With 4-bit KV, 128K context requires about 4.3 GB to 5.0 GB of KV cache, for a total of about 20 GB. It may still run, but the remaining margin is clearly smaller. If the context is extended to 256K, 3-bit KV cache is about 6.4 GB, and total memory is about 21.9 GB, which is close to the available limit and requires careful testing.
6. Capability Boundaries and Best Practices
6.1 What It Does Not Do
- It does not make the model smarter. It only changes how KV cache is stored. It does not change the model parameter size or the model’s capability ceiling.
- It is not necessarily faster. TTFT may increase, and decoding throughput improvements may be limited, because dequantization adds extra computation.
- It cannot replace weight quantization. Weights and KV cache are two independent memory costs and need to be planned separately.
- It cannot solve all long-context problems. Even if memory is sufficient, attention computation still grows with context length, and long-distance retrieval capability may degrade as length increases. Being able to fit does not mean being able to perform well.
6.2 When It Is Worth Enabling
- The context requirement is above 32K, and the model supports it.
- Weights plus KV cache already exceed available memory, and the workload cannot run without KV compression.
- Long conversations or long documents are high-frequency use cases.
- The task has moderate precision requirements, such as summarization, rewriting, or open-ended QA.
6.3 When It Is Not Necessary
- The context is usually within 8K, and KV cache accounts for a very small share of memory.
- The model already uses a low-KV structure such as MQA, so KV pressure is already small.
- Inference speed is the current main bottleneck. In this case, check memory bandwidth, thread configuration, and quantization kernels first.
- The task has extremely high requirements for precise retrieval, and precision loss caused by compression is unacceptable.
6.4 Combined Tuning Checklist
| Check item | Yes / No |
|---|---|
| Can the model fit into the target context after weight quantization? | |
| Has KV cache become a major memory cost? | |
| Is the target context above 32K? | |
| Is the task extremely sensitive to precise retrieval? | |
| Have before-and-after output comparisons been completed? |
Recommended tuning order:
- Choose the right weight quantization first: with the goal of fitting the target context, prefer a scheme with low quality loss.
- Then enable KV quantization: start with 4-bit or 8-bit, and consider 3-bit only if memory is still tight.
- Then optimize context management: for long conversations, use summarization to compress history; for long documents, use retrieval to assemble prompts on demand.
- Finally, add monitoring and alerts: set memory-usage threshold alerts to detect overflow risk early.
7. Frequently Asked Questions (FAQ)
Q: Why is there no visible effect in short conversations?
A: KV cache grows linearly with context length. At 8K context, KV cache may only take up a few hundred MB to about 1 GB. At 128K, it may expand to more than ten GB and often becomes the main memory cost. Therefore, the relative benefit of compression naturally increases with context length.
Q: What should I do if output quality becomes worse after enabling?
A: First check where the difference appears. If the model answers incorrectly when key information is placed in the middle of a long text, but answers correctly when the information is at the beginning or end, this is likely accumulated error from low-bit compression. Increase the precision to 4-bit or 8-bit and compare outputs again.
Q: What should I do if it becomes slower after enabling?
A: First check whether dequantization overhead has increased. Compare TTFT and generation throughput under short and long contexts. If performance clearly drops even at short context, the quantization operator may be inefficient or the framework implementation may be immature. If slowdown only happens at long context, it is more likely caused by KV writing and memory pressure.
Q: Which frameworks support KV cache quantization?
A: Common local inference tools such as llama.cpp, mlx-lm, and vLLM may provide different forms of KV quantization support in different versions. Available parameters and precision types should follow the help information of the version you use. Compatibility can vary significantly across hardware and model architectures, so test in a test environment first.
Q: Is more unified memory always better?
A: Unified memory determines how much can fit, but it does not solve bandwidth or compute bottlenecks. After context exceeds 32K, attention computation and KV writing overhead during the prefill stage increase significantly. Memory, speed, and precision need to be evaluated together.
Conclusion: Measure First, Then Decide
The key to local long-context inference is not to pursue a larger model or a longer context window at all costs, but to find the balance among memory, speed, and quality. KV cache quantization and compression provides unified-memory devices with a path that trades a small amount of precision for several times more context space.
It is best to validate in this order: short context first, long context later; comparison first, tuning later. First confirm whether the weights can fit. Then enable 4-bit or 8-bit KV quantization. Finally, use real business data to judge whether precision, latency, and memory usage meet requirements.
If you are worried about memory limitations at 128K context, you can start by upgrading the framework and enabling KV cache quantization, then run a small-scale real-world test.
