KV Cache Compression and Sharing for Long-Input Workloads
This article explains why KV cache becomes the dominant cost in long-input LLM workloads and examines three validated optimization paths: sequence-direction compression, cross-layer sharing, and lower storage precision. It also outlines a layered design that pairs a half-depth causal encoder with a full decoder, along with capacity estimation factors and a practical rollout checklist. Readers will learn how prefill and decode stages consume memory and bandwidth differently, and how to sequence these optimizations by benefit and risk.
1. The Starting Point: Why Reading Costs More Than Writing
In applications such as AI coding assistants, document question answering, and log analysis, a single interaction often looks like this: the tool modifies a few files, then feeds tens of thousands of characters of source code, test output, and stack traces back to the model, and the model finally produces only a few hundred characters describing the next action. Input and output are severely asymmetric in volume, so the center of gravity for compute and GPU memory shifts to the “read” side.
These workloads have a second characteristic: context must be continued frequently. Multiple appended turns within the same session, repeated retrieval over the same codebase, and retries after failures all make the prefix highly repetitive. If every turn recomputes from scratch, the redundant cost is multiplied several times over.
2. How the Cache Grows
A language model splits text into tokens. Each token passes through multiple Transformer layers and forms hidden vectors layer by layer: attention retrieves information from historical positions, and the feed-forward network processes it further. In attention, Q is the query issued by the current position, K determines the relevance of historical positions, and V carries the content that is actually read back. The intuitive single-head, single-query form is:
o = softmax(q * Kᵀ / sqrt(c)) * Vq: 1×c K,V: t×c o: 1×c
Here t is the visible history length and c is the number of channels. When a new token is generated, the K and V of historical positions do not become invalid, so they are cached for reuse. This is the KV cache. Its size is approximately:
bytes ≈ 2(层) × t × c × bytes_per_value × 层数
Wait — the code comment must be in English.
bytes ≈ 2 × t × c × bytes_per_value × num_layers
The conclusion is straightforward: the cache grows linearly with sequence length, linearly with the number of layers, and linearly with storage precision. A single request therefore splits into two phases — the Prefill phase processes the existing input and builds the state, and the Decode phase generates tokens one by one while continuously reading the cache back. The pain points of long-input workloads concentrate on the GPU memory peak of Prefill and the read bandwidth of Decode.
3. Three Validated Optimization Paths
The first is compression along the sequence dimension: keeping fewer representations per position, or aggregating adjacent positions. This reduces the t dimension.
The second is sharing along the layer dimension. If multiple layers share the same global cache, the layer-count factor is significantly weakened; going further, even retrieved results are reused across layers, avoiding repeated fetching and repeated storage.
The third is lowering storage precision. The cache is sensitive to numeric range but insensitive to the least significant bits, so carrying the same K and V in fewer bytes is one of the most certain wins.
It is worth noting that lighter sequence-direction compression can actually reduce the total cache substantially — because the savings come mainly from cross-layer sharing and lower precision, not from more aggressive sequence pruning. This explains the seemingly contradictory result of “the input only travels halfway, yet the cache drops to a quarter.”
4. Layered Execution: Half-Depth Encoder Plus Full Decoder
One workable structure splits the network into two segments: the first several layers form a causal encoder, and the later layers form a decoder. When processing long input, mainly the first half runs, compressing the long sequence into a state; when generating a new token, the full network runs to preserve expressive power.
long input sequence ──> [causal encoder, first N/2 layers] ──> global state│new token ─────────────────────────────> [full network, N layers] <┘
There are three engineering benefits: Prefill compute drops; the cache produced during the encoder stage is shared across layers; and the decode stage retains full capacity, so generation quality is not sacrificed. Two constraints need attention in practice: the encoder must be causal, otherwise future information leaks in; and the state interface between the two segments must be stable, to make batching and incremental continuation easier.
5. Capacity Estimation and a Practical Checklist
When estimating, break out the four factors t, c, layer count, and precision, then multiply by concurrency and average session length to obtain peak GPU memory and bandwidth requirements. If a container platform hosts the inference service, monitoring alerts and logging services can be used to observe cache hit rate, batch size, and queueing latency, while object storage can archive long-session prefixes for reuse.
Practical checklist: first prioritize prefix reuse and cache hit statistics; then evaluate the cost of cross-layer sharing changes; finally adjust storage precision and run a quality regression. The three paths can be stacked, but should be advanced in order of benefit/risk, with a rollback switch kept at every step.
