KV Cache Compression and Reuse in Long-Context Inference
Long-context workloads such as coding assistants spend most of their compute on reading history rather than generating new content, which makes KV cache management critical. This article explains how attention and KV caching work, provides a formula and worked example for estimating cache size, and compares five practical optimization strategies: reducing KV heads, lowering storage precision, sharing KV across layers, compressing the sequence dimension, and reusing prefix caches.
Why Long Inputs Unbalance Inference Costs
In scenarios such as intelligent coding assistants, a single task typically involves multiple rounds of interaction. After the model modifies a file, the system feeds source code snippets, test logs, and command outputs back into the context, while the model may ultimately generate only a few hundred words describing the next step. As a result, most of the compute in each round goes toward “reading historical information” rather than “generating new content.”
This type of workload has two defining characteristics: the input is long, and the input is frequently extended. The former determines the compute cost of the initial processing, while the latter determines how often historical information is re-read. Understanding these two points is a prerequisite for choosing the right optimization direction.
Attention and the Basics of KV Caching
Language models split text into tokens, and each token forms a hidden vector at every layer. The attention layer is responsible for reading relevant information from the context. Taking a single query and a single attention head as an example, the computation can be written as:
o = softmax(q K^T / √c) V
Here, q is the query vector at the current position with shape 1×c; K and V store the keys and values of t historical positions, each with shape t×c; and c is the number of channels per vector. The softmax converts relevance scores into weighting coefficients, and the output o is the historical information aggregated according to those weights.
When generating the next token, the K and V of historical positions do not change, so the system saves them to avoid redundant computation. These saved tensors are the KV cache.
The example code looks like this:
import numpy as npdef attention_decode_step(q, k_cache, v_cache):"""q: (1, c); k_cache, v_cache: (t, c)"""c = q.shape[-1]scores = q @ k_cache.T / np.sqrt(c) # (1, t)scores = scores - scores.max() # numerical stabilityweights = np.exp(scores)weights = weights / weights.sum() # softmaxreturn weights @ v_cache # (1, c)
This code only demonstrates a single read step. Real inference frameworks also handle multiple heads, batching, and positional encodings, merging them into batched tensor operations.
Estimating Cache Size
The footprint of the KV cache can be roughly estimated with one formula:
Cache bytes ≈ 2 × L × H_kv × d_h × T × B × s
The symbols mean the following:
- 2: storing K and V separately;
- L: number of layers;
- H_kv: number of KV heads per layer;
- d_h: dimension of each head;
- T: sequence length;
- B: concurrent batch size;
- s: bytes per element — 2 for FP16, 1 for INT8.
Consider an example configuration: L = 32, H_kv = 8, d_h = 128, T = 128K (131,072), B = 1, using FP16. Substituting these values gives 2 × 32 × 8 × 128 × 131,072 × 2 bytes, or roughly 16 GiB. This is the estimate for a single request; concurrent requests scale the footprint linearly with batch size.
This example illustrates two things. First, sequence length and layer count jointly determine cache size, which is where the GPU memory pressure of long-context scenarios mainly comes from. Second, every coefficient in the formula is a potential starting point for optimization.
Common Compression and Reuse Strategies
1. Reducing the Number of KV Heads
Having multiple query heads share the same set of K and V directly shrinks the cache. Grouped-query attention follows this idea. The trade-off is that each query group can read less information, so memory savings must be balanced against quality.
2. Lowering Storage Precision
Reducing the cache from FP16 to FP8 or INT8 can halve its size. The precision loss is usually small, but layers that are sensitive to numeric ranges may need to retain higher precision, combined with per-channel or per-block quantization scales.
3. Sharing KV Across Layers
Adjacent layers or specific layer groups can reuse the same KV, so multiple layers share a single cache. The space saved is proportional to the number of shared layers. The risk is that different layers attend to different information, and sharing too much weakens the model’s expressiveness, so layer-by-layer validation is necessary.
4. Compressing the Sequence Dimension
Sliding windows, sparse selection, or summarizing historical segments can reduce the number of entries each position needs to retain. These methods suit tasks where historical information has clear locality. Tasks that require precise recall of early content should use them cautiously.
5. Prefix Cache Reuse
When prefixes such as system prompts, tool definitions, and fixed documents remain unchanged across multiple rounds of requests, their KV can be cached and directly reused by subsequent requests. The key is keeping the prefix stable — for example, avoid inserting timestamps at the beginning, which change every time.
The table below compares these methods:
| Method | Primary Source of Savings | Primary Cost |
|---|---|---|
| Reducing KV heads | Fewer entries stored per layer | Reduced attention expressiveness |
| Lowering precision | Fewer bytes per element | Quantization error; requires calibration |
| Cross-layer sharing | Eliminates redundant storage between layers | Information from different layers gets mixed |
| Sequence compression or sparsity | Fewer retained entries | Precise long-range recall may degrade |
| Prefix reuse | No recomputation for repeated prefixes | Prefix must remain stable to hit the cache |
These methods can be combined. Using the earlier example, switching from FP16 to INT8 reduces the cache to about 8 GiB; if two layers then share one KV cache, the footprint drops to roughly 4 GiB. The actual effect of stacking must be validated by measurement, because the impact of different combinations on quality is not independent.
Understanding “Reads” and “Writes” in Inference
Inference is divided into two phases. The prefill phase processes the entire input at once; it is compute-intensive and well suited to parallel execution. The decode phase generates tokens one at a time, and each step must read the entire cache, so it is typically limited by memory bandwidth.
In the loop of a coding agent, these two phases alternate. After each round of tool output is appended to the end of the context, the system re-enters prefill for the newly added portion and then resumes decoding. Because historical KV is already cached, only the incremental tokens need to be prefilled — which is exactly why keeping prefixes stable and reusing cached KV has such a large impact on end-to-end latency and cost in multi-round workloads.
