KV Cache Compression for Long-Context Inference: How to Choose
Long-context local inference often runs out of memory because the KV cache grows linearly with context length. This article explains how to estimate KV cache size, compares four compression approaches—quantization, eviction and sparse retention, low-rank decomposition and cross-layer sharing, and paging and offloading—and outlines a practical local deployment workflow covering baselines, monitoring, validation, evaluation metrics, and selection guidance.
1. Why Long Contexts Exhaust Memory
During local inference, memory usage mainly falls into two parts. The first is model weights, whose size is basically fixed after loading. The second is runtime cache. During text generation, each attention layer must store the Key and Value vectors of historical tokens. This cache is called the KV cache. KV cache size grows linearly with context length and is directly related to the number of conversation turns and the length of input documents.
KV cache usage can be estimated with the following formula:
KV cache bytes = 2 × layers × KV heads × head dimension × context length × bytes per element
The coefficient 2 corresponds to the two tensors, Key and Value. The code below uses a set of assumed parameters; these numbers do not correspond to measured values for any specific model.
def kv_cache_bytes(layers, kv_heads, head_dim, seq_len, bytes_per_elem):"""Estimate KV cache usage in bytes. Single sequence only, batch=1."""return 2 * layers * kv_heads * head_dim * seq_len * bytes_per_elem# Assumptions: 64 layers, 8 KV heads, head dimension 128, FP16 (2 bytes per element), batch=1per_token = kv_cache_bytes(64, 8, 128, 1, 2)print(f"Per token: {per_token / 1024:.0f} KiB") # 256 KiBtotal = kv_cache_bytes(64, 8, 128, 131072, 2)print(f"128K context: {total / 1024**3:.1f} GiB") # 32 GiB
Under these assumptions, cache usage at different context lengths is as follows:
| Context length | KV cache usage (single sequence, FP16) |
|---|---|
| 8K | 2 GiB |
| 32K | 8 GiB |
| 128K | 32 GiB |
These numbers cover only the cache. They do not include weights, intermediate tensors for attention computation, or framework overhead. In concurrent scenarios, this must also be multiplied by the concurrency level. For example, four simultaneous 8K sessions require about 8 GiB for cache alone. Each beam in beam search also keeps its own cache, so the same multiplication applies. Framework memory allocation may also cause fragmentation, making actual usage higher than the estimate.
Model architecture can amplify the problem. More KV heads and deeper layers increase the per-token cache cost. As a result, two models with similar parameter counts can differ significantly in memory behavior at the same context length. When selecting a model, parameter count alone is not enough.
2. Basic Approaches to KV Cache Compression
The goal of KV cache compression is to reduce the number of bytes per token or reduce the number of tokens that must be retained. Common methods fall into four categories, each with different applicable boundaries.
2.1 Quantization
Quantization reduces the numerical precision of the KV cache from FP16 to INT8, FP8, or INT4. Using the example above, INT8 is about half of FP16, and INT4 is theoretically about one quarter. Actual usage also includes metadata such as scaling factors, so savings are slightly lower than the theoretical value.
Quantization applies when the framework supports the precision and the model is not sensitive to lower precision. Precision degradation is more visible in long-context scenarios, so it should be validated with a test set. Quantization is usually the easiest method to try in local deployments.
2.2 Eviction and Sparse Retention
Eviction methods retain the cache for only a subset of historical tokens, such as a recent window or tokens with higher attention scores. These methods directly reduce the number of cached tokens.
They are suitable for tasks such as dialogue and summarization that mainly depend on recent content. They are not suitable for tasks that require precise localization of details across the full text, such as finding an exact sentence in a long document. Once a token is evicted, the model can no longer read it.
2.3 Low-Rank Decomposition and Cross-Layer Sharing
These methods reduce cost by reducing the dimension of KV vectors or by letting multiple layers share a cache. Grouped-query attention (GQA) and multi-query attention (MQA) in model architecture are design-stage approaches to reducing the number of KV heads. Low-rank and sharing schemes usually require support in model training or architecture, and generally cannot be directly applied to off-the-shelf models.
2.4 Paging and Offloading
Paged management, such as vLLM’s PagedAttention, divides the cache into fixed-size blocks and allocates them on demand. It can reduce fragmentation and wasted reserved space, but it cannot reduce the total amount required.
Offloading moves part of the cache to system memory or SSD so that a longer context can fit. The cost is that data movement adds latency, and movement bandwidth can become a bottleneck, potentially reducing generation speed noticeably.
3. Local Deployment Steps
3.1 Record Hardware and Headroom
First confirm the device’s available memory. Unified memory devices need to deduct usage by the system and other programs. How much headroom to keep should be based on actual system usage during runtime; it is not recommended to decide directly from rules of thumb.
3.2 Calculate Target Usage
Use the formula in Section 1 to calculate the KV cache for the target context, then add the size of model weights to get an estimated total. If the estimated total is already close to available memory, compression or a shorter context is needed.
3.3 Establish an Uncompressed Baseline
Without compression, run a fixed task at the target context and record peak memory, first-token latency, generation speed, and output. This data is the baseline for later comparison.
3.4 Enable Compression Parameters
Using llama.cpp as an example, you can quantize both K and V of the KV cache to q8_0 and specify the context length:
llama-cli -m model.gguf -c 131072 -fa on --cache-type-k q8_0 --cache-type-v q8_0
Parameter names and values may differ across versions; refer to the --help output of the version you use. Some backends require Flash Attention to be enabled at the same time before a quantized V cache can be used.
3.5 Monitor Memory
On macOS, you can run memory_pressure in the terminal or check memory pressure in Activity Monitor. On Linux, use free -h to check memory. For NVIDIA GPUs, the following command refreshes GPU memory usage once per second:
nvidia-smi --query-gpu=memory.used --format=csv -l 1
3.6 Validate and Roll Back
Compare outputs before and after compression on the same test set. Roll back if any of the following occurs: output quality drops noticeably, memory pressure remains high, or generation speed falls below an acceptable level. Rollback options include shortening the context, returning to FP16, or switching to paging or offloading.
4. Evaluation Metrics
At least the following five metrics should be recorded during evaluation:
- Peak memory: includes weights, KV cache, and runtime overhead. Looking only at the cache number is not enough.
- First-token latency (TTFT): reflects the time spent in the long-context prefill stage.
- Generation speed (tokens/s): reflects decoding efficiency after compression.
- Task quality: agreement rate with the uncompressed baseline, or manual scoring against fixed criteria.
- Long-context recall: insert known facts into a long text, ask questions, and count the hit rate. This metric is especially important for eviction methods.
Compression may reduce long-context recall or precision, so it must be compared with an uncompressed baseline, and rollback conditions should be set in advance. Conclusions from too small a sample are unreliable; it is recommended to repeat each test group multiple times and report the median.
5. Selection Guidance
When choosing a compression method, use the following order:
- Measure usage first, then decide whether to compress. If memory is sufficient without compression, compression brings limited benefit and adds risk.
- If memory is insufficient and the task is mainly dialogue, try quantization first.
- If precise retrieval of full-text details is required, prioritize quantization or paging, and use eviction cautiously.
- If the hardware cannot fit the target context and other methods do not work, then consider offloading and accept the speed reduction.
- Do not deploy a compression configuration without a test set or baseline data.
Compression is suitable when the context length exceeds what the device can handle, the task can tolerate slight precision loss, and before-and-after comparison is possible. Compression is not suitable when the task depends on precise full-text details and cannot accept quality degradation, when hardware headroom is sufficient, or when a reproducible test set is missing.
KV cache compression is not a one-click speedup. It is a trade-off that exchanges precision or speed for memory space. Measure first, then compress, and finally validate with the same data set to determine whether it fits your hardware and task.
