KV Cache Compression for Long-Input Workloads: Layering, Cross-Layer Sharing, and Low-Precision Storage
This article explains why long-input LLM workloads are dominated by KV cache cost rather than raw compute, and walks through three practical compression paths: splitting a model into a causal encoder and a decoder, sharing a global KV cache across layers, and lowering storage precision combined with sequence-side reduction. It includes the attention and cache cost model, pseudocode for each approach, the trade-offs of each, a capacity estimation formula, and a pre-launch checklist covering workload profiling, quantization regression, and scheduling between encoding and decoding states.}
1. The Problem: Why Reading Costs More Than Writing
In applications like AI coding assistants, document Q&A, and long-log analysis, a single interaction usually looks like this: a tool modifies a few files, then the model has to read back tens of thousands of characters of source code, test output, and stack traces, and finally produce only a few hundred characters describing the next action. Input and output are severely asymmetric in length, and inference resource consumption happens to be far more sensitive to input length than to output length.
Two consequences follow directly. First, the prefill stage must process all input tokens at once, so compute cost grows with sequence length. Second, to avoid recomputing history during decoding, the system must keep the key-value pairs of past tokens in GPU memory. This is the KV cache. The longer the sequence, the more layers, and the more concurrent sessions, the more likely the cache becomes the single largest consumer of memory, directly capping how many requests can be served.
So the optimization goal under long-input workloads is not simply “make the model compute faster.” It is to reduce the cache cost per token and to avoid paying the same price during generation that was already paid during prefill.
2. Background: Attention, the KV Cache, and a Cost Model
A language model splits text into tokens. Each token passes through multiple layers, producing a different hidden representation at each layer. Attention pulls information from historical positions; the feed-forward network continues processing it. The computation for a single query and a single attention head can be written as:
o = softmax( q * K^T / sqrt(c) ) * V
Here q is the current query with shape 1×c, K and V are the historical key and value matrices with shape t×c, c is the number of channels, and t is the visible history length. Softmax normalizes relevance scores into weighting coefficients, and V carries the content that is actually read back.
The key point: when decoding token t+1, the K and V of the previous t positions can be reused in full, with no recomputation. Systems cache them, trading memory for compute. If each layer stores its own copy, the cache size is on the order of:
cache_bytes ≈ 2 * L * t * c * bytes_per_element * batch
L is the number of layers, and the factor of 2 accounts for the two copies, K and V. This expression points to three viable reduction paths: cut the effective number of layers (cross-layer sharing), cut t (sequence compression or reuse), and cut bytes_per_element (lower-precision storage). The layering and sharing schemes discussed below essentially attack the first two, combined with the third.
3. Approach 1: Splitting a Causal Encoder from the Decoder
One structure that works well for long-input workloads splits the deep network into two parts by responsibility: the front section acts as a causal encoder that compresses long input into a more compact representation, and the back section acts as a decoder that generates autoregressively.
The engineering semantics look like this:
# Stage A: process the long input, run only the front sectionhidden = causal_encoder(input_tokens) # most compute and caching happens here# Stage B: generate new tokens, run the full networkfor step in range(max_new_tokens):hidden = decoder(causal_encoder_tail(hidden), hidden)token = sample(hidden)
There are three benefits. First, most of the compute for long input goes to the front section, while calls to the back section during prefill are significantly reduced. Second, each decoding step adds key-values for only one new position, so if only the back section participates in the autoregressive cache, fewer layers contribute new cache entries. Third, the encoder output can be reused as a “context summary,” so an unchanged input prefix does not need to be re-encoded across turns.
The costs need attention too. Layering introduces an information bottleneck, so the encoder must take on the compression burden; training objectives, distillation strategy, and capacity allocation all need rebalancing. At runtime, two execution paths must be distinguished, and the scheduler has to recognize whether a request is in the encoding state or the decoding state.
4. Approach 2: Sharing a Global KV Cache Across Layers
The second optimization comes from reuse between layers. If the key-value distributions of several adjacent layers are highly similar, there is no need to store a separate copy for each; multiple layers can read the same global cache, forming a “one store, many references” structure.
Pseudocode sketch:
# The global cache is allocated per "group", not per layerglobal_kv = allocate_kv_cache(num_groups, max_seq_len, head_dim)for layer in layers:if layer.kv_group is None:k, v = layer.compute_kv(hidden) # independent layer, stores for itselfelse:k, v = global_kv[layer.kv_group] # shared layer, reference directlyhidden = layer.attend(hidden, k, v)
Going further, some layers can also reuse intermediate results such as retrieval output or encoder output, avoiding repeated reads and transfers of the same context. The benefit of sharing is that memory usage drops roughly in proportion to “number of groups / number of layers,” and memory bandwidth pressure is reduced as well. The throughput gain during decoding is often more noticeable than during prefill.
The costs are equally clear: sharing weakens representational capacity across layers, and the grouping granularity becomes a critical hyperparameter. Groups that are too coarse lose accuracy; groups that are too fine save no memory. In practice, the common configuration is “dense sharing in the front section, progressively independent toward the back,” so that compression happens in the shallower layers where semantics are relatively redundant.
5. Approach 3: Lower Storage Precision and Sequence-Side Compression
The third path changes no structure, only “how things are stored.” The KV cache is sensitive to numeric range but relatively tolerant of low-order precision, so common practices include storing the cache at a bit width lower than the compute precision, applying scaling quantization per channel or per block, and keeping high precision for outlier channels. Halving the storage bit width roughly halves the cache footprint.
The effect is more pronounced when combined with sequence-side techniques: sliding windows that limit visible history, reuse of repeated prefixes, and decay or summarization of tool outputs that have served their purpose. These reduce the effective t, and they are orthogonal to cross-layer sharing and low-precision storage, so they can be combined.
Two things must accompany this in engineering. One is precision regression: use a long-input task set to verify output consistency before and after quantization. The other is overflow protection: set clipping and fallback policies for the quantization range, so quality does not collapse at the tail of long sequences.
6. Explaining Why Lighter Sequence Compression Still Yields a Much Smaller Cache
A common confusion: if sequence-side compression is the lighter change, why can the global cache drop to roughly a quarter of the previous generation? Substituting back into the cost model explains it. Cache size is determined jointly by effective layers × sequence length × channels × bit width. The sequence term is only moderately reduced, but the effective layer count falls by a multiple thanks to cross-layer sharing, and the bit width falls again with low-precision storage. The two multiplied together are more than enough to cover the smaller saving on the sequence side.
This suggests a general conclusion: the gains from capacity optimization are multiplicative, so any evaluation must look at the product rather than a single factor. Any conclusion that reports improvement in only one dimension is insufficient to support capacity planning.
7. Capacity Estimation and a Launch Checklist
Before going live, do a paper estimate first, then calibrate with load testing:
per-request cache ≈ 2 * L_eff * t_eff * c * bytes * batchL_eff = number of independent cache groups (shared layers not counted again)t_eff = effective length after window and summary policies take effect
Launch checklist:
- Define the workload profile: input-to-output length ratio, number of continuation turns, prefix reuse rate.
- Choose the layering and sharing granularity, and set up small-scale ablation experiments.
- Determine the cache bit width and quantization granularity, and prepare a precision regression set.
- Distinguish encoding and decoding states at the scheduling layer, so long inputs do not block short requests.
- Accept jointly on three metrics: memory hit rate, time to first token, and decoding throughput.
If you use a cloud inference service, you can rely on a container platform to host elastic replicas, object storage to keep session prefixes, and logging plus monitoring and alerting to track cache hit rate and memory watermarks, forming an observable, rollback-capable iteration loop. Baidu AI Cloud likewise emphasizes balancing capacity and precision through general engineering means in long-context inference scenarios.
8. Summary
The core tension in long-input workloads is the conflict between “read-heavy, write-light” traffic and a cache that grows linearly with layers and sequence length. Layered encoding, cross-layer sharing, and low-precision storage attack layer count, effective length, and bit width respectively, and their gains multiply rather than add. Understanding this is what makes it possible to make verifiable, rollback-capable trade-offs within a memory budget.
