KV Cache Compression and Sharing for Long-Context Inference
Long-context inference in coding agents is often read-heavy and write-light: the model reads large amounts of source code, logs, and tool output across turns, while generating only a small amount of new text. This article explains why KV cache becomes a bottleneck, reviews the basic attention and cache-size formulas, and examines three practical optimization approaches: allocating computation by phase, sharing KV cache across layers, and reducing storage precision. It also provides a capacity-estimation code example and deployment guidance for monitoring prefill and decode separately, validating quality, and scaling optimizations under real workloads.
1. Problem Background: Read-Heavy, Write-Light Workloads
In a typical coding-agent loop, the model first modifies a file, then reads back related source code, test logs, and tool output. Together, this content may add up to tens of thousands of words, while the model usually generates only a few hundred words per turn, such as the next action description or a small patch.
This workload has two characteristics. First, the input is much longer than the output, and inference is clearly split into two stages: the prefill stage, which processes the input, and the decode stage, which generates new tokens one by one. Second, the task frequently continues the context, so the same historical content is read repeatedly across multiple turns.
As a result, the bottleneck of the inference system is not only compute volume but also GPU memory and memory bandwidth. Understanding how cache occupancy behaves is a prerequisite for optimizing this type of scenario.
2. Attention and KV Cache Basics
For a single query and a single attention head, attention can be written as:
o = softmax(qKᵀ / √c) V
Here, q is the query vector at the current position, with shape 1×c; K and V contain the keys and values of t historical positions, with shape t×c; and c is the number of channels per vector. Softmax converts relevance scores into weighting coefficients, and the final output o is a weighted read of historical information.
When generating the next token, the K and V of historical positions remain unchanged, so the system can cache them to avoid recomputation. This cache is called the KV cache. If every layer stores its own copy, cache size grows linearly with sequence length, layer count, and precision. A common estimation formula is:
Cache bytes = 2 × stored layers × KV heads × head dimension × sequence length × batch size × bytes per element
The coefficient 2 means that both K and V are stored. This formula shows that cache occupancy is determined by four factors: layer count, sequence length, storage precision per element, and the organization of KV heads. Optimization directions therefore fall into several categories: reducing the number of layers that need storage, reducing bytes per element, or reducing the number of KV heads.
3. Method 1: Allocate Computation by Phase
Encoding long inputs and generating short outputs have different computational requirements. One feasible design is to split the network into two segments: the first half specializes in encoding the input, and generating new tokens runs the full network.
The benefit of this split is that prefill for long inputs only needs to pass through the first half, nearly halving the computation. The cost is that the generation stage still passes through the full network, so single-step decode latency is not reduced. Engineering teams need to accept this trade-off: if the workload is dominated by long inputs, the benefit is clear; if outputs are long, the benefit is diluted.
Implementation must ensure that the intermediate representation produced by the first half is correctly used by the second half, and training must learn under this structure rather than simply truncating the network at inference time.
4. Method 2: Share KV Cache Across Layers
The idea of cross-layer sharing is to let multiple adjacent layers reuse the same KV cache. This reduces the number of stored copies from the number of layers to the number of sharing groups. For example, if every four layers share one cache, cache occupancy is about one quarter of the original.
Sharing also has a cost. Different layers focus on different types of information, and forced sharing loses some expressiveness. Therefore, the sharing structure usually needs to be considered during training, and evaluation must confirm whether the quality loss is acceptable.
A related approach is to reuse retrieval results. When multiple layers need to read the retrieval results for the same set of historical positions, the results can be computed once and reused across the relevant layers. This reduces both duplicate computation and intermediate data movement.
5. Method 3: Lower Storage Precision
KV cache can be stored at lower precision than regular floating point, such as 8-bit floating point or 8-bit integer. With lower precision, bytes per element are halved, and cache occupancy is also halved.
Lower precision requires a supporting evaluation process. Common validation methods include:
- Benchmark task accuracy: compare results before and after on tasks such as code generation and question answering.
- Long-context retrieval tests: check whether distant information can still be read back accurately.
- Perplexity comparison: observe changes in language-modeling metrics as an auxiliary signal.
- Online canary rollout: ramp traffic by percentage and monitor error rates and user feedback.
Lower precision should not be applied uniformly. Critical layers can keep higher precision, while insensitive layers can use lower precision.
6. Capacity Estimation Example
The following code estimates cache occupancy under different configurations. All parameters are hypothetical and are used only to demonstrate the calculation method; they do not represent the specifications of any specific model.
def kv_cache_bytes(stored_layers, kv_heads, head_dim,seq_len, batch, bytes_per_elem):"""Estimate KV cache occupancy in bytes. The coefficient 2 means one copy each for K and V."""return (2 * stored_layers * kv_heads * head_dim* seq_len * batch * bytes_per_elem)GiB = 1024 ** 3# Baseline: 40 layers stored separately, 16-bit floating point, sequence length 128Kbaseline = kv_cache_bytes(40, 8, 128, 128_000, 1, 2)# Optimized: one shared copy per four layers, only 10 stored layers, 8-bit storageoptimized = kv_cache_bytes(10, 8, 128, 128_000, 1, 1)print(f"Baseline: {baseline / GiB:.2f} GiB")print(f"Optimized: {optimized / GiB:.2f} GiB")print(f"Ratio: {optimized / baseline:.3f}")
After running it, the baseline is about 19.5 GiB, and the optimized version is about 2.4 GiB, with a ratio of 0.125. With both optimizations combined, the cache drops to one eighth of the baseline. Actual benefits depend on model architecture and precision loss, and must be confirmed with real evaluation results.
7. Deployment Recommendations
When planning deployment, proceed with the following steps.
- Estimate capacity: concurrency × average context length × cache bytes per token gives peak GPU memory demand. Then reserve space for model weights and intermediate activations.
- Define metrics: monitor time to first token, output tokens per second, GPU memory usage, and cache hit behavior, observing prefill and decode separately.
- Validate in stages: first compare quality on offline datasets, then observe online behavior in a small-traffic environment, and finally expand gradually.
- Coordinate with infrastructure: when deploying on cloud platforms such as Baidu AI Cloud, you can use general-purpose compute instances, container platforms, logging services, and monitoring and alerting capabilities to establish resource thresholds and alert rules.
For scenarios such as coding agents, the most important focus is input-side cost. Reducing the amount of data repeatedly read each turn is often more effective than simply increasing decode speed.
8. Conclusion
The cost of long-context inference mainly comes from cache storage and reads. Allocating computation by phase, sharing cache across layers, and lowering storage precision are three methods that can be combined, and each involves a trade-off between quality and efficiency. Engineering teams should first use capacity formulas to estimate the scale of the problem, then validate solutions with task metrics to ensure that optimizations hold under real workloads.
