KV Cache Compression and Layered Inference for Long-Input Workloads
This article explains why long-input LLM workloads are dominated by the read side of inference, how the KV cache is created during attention, and how a layered encoder-decoder design, cross-layer cache sharing, and lower storage precision can reduce total cache size to roughly one quarter. It also includes a practical engineering checklist covering staged scheduling, tiered cache storage, configurable precision, context governance, and observability. Readers will gain a clear capacity model and a verifiable optimization path, with the reminder that all gains must be validated by self-testing and business quality metrics.
1. The Problem: Why Reading Costs More Than Writing
In applications such as AI coding assistants, document Q&A, and log analysis, a typical turn often evolves like this: the tool modifies several files, then stuffs tens of thousands of characters of source snippets, test output, stack traces, and retrieval results back into the context, and the model ultimately produces only a few hundred characters for the next action. The input and output are severely asymmetric in magnitude, so inference resources are dominated by the “read” side.
To understand this, split a request into two phases:
- Prefill: processes all input tokens at once. It is compute-intensive and mainly consumes compute and memory bandwidth.
- Decode: generates new tokens one by one, looking back at the full history at every step. It mainly consumes memory capacity and bandwidth.
When the context is repeatedly extended and turns keep accumulating, every decode step has to read an increasingly large history cache. Capacity pressure grows linearly, while compute utilization stays low. This is the core tension of long-input workloads.
2. Where the Cache Comes From: Attention and the KV Cache
A language model first splits text into tokens. Each token passes through multiple Transformer layers, forming hidden vectors layer by layer. Attention is responsible for pulling information from historical positions, and the feed-forward network continues the processing. Three common symbols in attention are Q (the query at the current position), K (used to judge the relevance of historical positions), and V (carrying the information read back). The intuitive expression for single-query, single-head attention is:
o = softmax(q * K^T / sqrt(c)) * V# q: 1 x c current query# K: t x c keys for t visible historical positions# V: t x c corresponding values# o: 1 x c read-back result
When generating a new token, the K and V of historical positions do not become invalid and can be reused, so they are cached. This is the KV Cache. If one copy is stored per layer, the cache size is roughly:
bytes ≈ 2 * layers * t * c * dtype_bytes * batch# 2 means two copies, K and V; t is the sequence length
This formula points to three directions to act on: reduce the layer contribution (cross-layer sharing), lower the bytes per element (low-precision storage), and reduce the number of effective tokens (sequence-side compression). The layered design and cache sharing discussed later cut in from the first two directions at the same time.
3. Layered Architecture: Encoding in the First Half, Generation Across the Full Network
One feasible design is to split a deep network into two segments: the first several layers form a causal encoder, and the last several layers form a decoder. When processing long inputs, mainly the first half runs, compressing the long context into a more compact representation. When generating new tokens, the full network runs to ensure output quality does not degrade.
Illustrative pseudocode:
def forward(input_ids, state):if state.phase == "prefill":h = encoder(input_ids) # first half only; the long sequence is compressed herestate.kv = h.kv # compact cache persisted or kept residentreturn hh = decoder(state.last, state.kv) # full network, token-by-token generationstate.kv = h.kvreturn h
The benefit of this structure is “allocating compute by phase”: expensive full-network computation happens only on short-sequence generation steps, while long sequences take a lightweight path. The cost is higher engineering complexity, and representation alignment and state consistency between the two segments must be guaranteed.
4. Cross-Layer Sharing and Precision Reduction: Why the Cache Can Drop to One Quarter
Doing only light compression along the sequence direction while the global cache drops sharply usually comes from two effects stacking:
- Cross-layer sharing: multiple layers reuse the same global cache, and some layers even reuse retrieval results as well, significantly weakening the layer factor.
- Storage precision reduction: the cache is stored at a lower bit width, reducing bytes per element.
Only when the two are multiplied does the result appear: sequence compression is not aggressive, yet total cache drops to about one quarter. In engineering, a rough model can be used for capacity estimation:
def kv_bytes(layers, t, c, bits, batch=1, share=1.0):return 2 * (layers * share) * t * c * (bits / 8) * batch# Example: halving the layer factor and halving the bit width => roughly 1/4 overall
It must be emphasized that this is a general capacity modeling method. Specific numbers must be based on your own testing, and no unverified metric should be copied.
5. Engineering Implementation Checklist
- Staged scheduling: put prefill and decode in different resource pools to avoid long inputs blocking short requests.
- Tiered cache storage: keep hot cache resident in GPU memory, and push cold cache down to object storage or local disk, with monitoring and alerts to observe hit rates.
- Configurable precision: make the cache bit width a switch, and use business metrics for A/B validation.
- Context governance: truncate, deduplicate, and produce structured summaries of tool output to reduce t at the source.
- Observability: instrument cache hit rate, input-to-output token ratio per turn, and tail latency to form a capacity regression baseline.
6. Conclusion
The essence of long-input workloads is “read-heavy, write-light,” and optimization must act on three places at once: phase separation, cache reuse, and storage precision. Layered encoding-decoding plus cross-layer sharing is an explainable and verifiable path; but any gain should be judged by self-tested data and business quality, not by unverified claims.
