Hierarchical KV Cache Optimization for Long-Input, Short-Output LLM Workloads
This article explains why the KV cache becomes a bottleneck when an LLM reads long inputs and generates short outputs, as coding agents often do. It covers split-depth execution, cross-layer KV sharing, and low-precision storage, along with their trade-offs and deployment considerations.
In LLM inference, a long context does not always mean long generation. Take an intelligent coding agent. After it modifies a file, it often has to read back tens of thousands of characters of source code, test logs, tool output, and error stacks, then generate only a few hundred characters for its next action. Over multiple runs, the resources spent on reading can easily exceed those spent on writing. At that point, the bottleneck is no longer only generation speed. It shifts to long-input prefill, context continuation, and KV cache occupancy. For workloads that read far more than they write and continue context frequently, layered execution, cross-layer sharing, and low-precision storage are worth exploring.
1. Problem Background: Why Long Inputs Make the Cache a Bottleneck
A language model first splits text into tokens. Each token passes through the Transformer and forms a hidden vector at each layer. The attention mechanism reads information from the historical context, and the feed-forward network processes that information further. When generating the next token, the keys and values of earlier positions can be reused, so the system caches them. This is the KV cache.
For a single attention layer, Q can be understood as the query issued by the current position, K determines which historical positions are relevant, and V carries the information to be read back. A simplified calculation is:
o = softmax(qK^T / sqrt(c)) V
Here, q is the current query vector. K and V contain the keys and values of t visible historical positions, and c is the number of channels in each vector. Softmax turns the relevance scores into weighting coefficients. Real systems also involve multi-head attention, grouped-query attention, paged caches, and quantized storage. Even so, the formula builds the core intuition: the longer the sequence, the more layers, and the wider the channels, the more K and V must be stored.
In traditional designs, each layer maintains its own K/V cache. The cache size grows roughly with the number of layers, the sequence length, the number of heads, and the channel count. For long-input, short-output workloads, the input phase writes a large cache, while the output phase consumes only a few new tokens. If the cache cannot be shared or compressed, the read path consumes both memory capacity and bandwidth.
2. Split-Depth Execution: Long Inputs Use the First Half, Generation Uses the Full Network
One approach splits the network into two segments. The first half acts as a causal encoder for long inputs. The second half, together with the first, forms the full network used for step-by-step generation. In one publicly documented configuration, a network of about 40 layers can be split into a 20-layer encoding segment and a 20-layer decoding segment. When processing a long input, the system mainly runs the first half and encodes the long context into intermediate representations and reusable caches. When generating new tokens, it still runs the full network to preserve step-by-step reasoning ability.
The value of this asymmetric computation is that long-input prefill runs only part of the layers, which reduces both computation and cache writes during the input phase. The generation phase still runs the full network, but it produces few tokens, so the total cost remains manageable. This approach suits workloads with very long inputs and short outputs. It does not suit long-form generation or complex reasoning that needs full interaction at every layer.
The first half cannot fully replace the full network without consequences. If the input encoding is insufficient, deep semantic interactions may be lost. Therefore, this kind of approach usually needs compensation through training objectives, distillation, adapter layers, or cache projections. Quality evaluation should focus on tasks such as long-document question answering, code localization, and log diagnosis.
3. Cross-Layer Sharing and Low-Precision Storage: Why the Cache Can Shrink Significantly
A large reduction in KV cache usually comes from combining several techniques, not from a single trick. First, multiple layers share a global KV cache. In traditional designs, each layer stores its own K/V. With sharing, several layers can read the same cache or the same group of caches, which removes repeated storage along the layer dimension. Some layers can also reuse encodings of retrieval results, so external context does not get written repeatedly.
Second, the storage precision is reduced. Common methods such as 8-bit floating point, integer quantization, and grouped scaling lower the bit width of each cache element. These methods must handle outliers, numerical stability, and per-layer sensitivity.
One publicly documented approach reduces the global KV cache to about one quarter of the baseline, even though it compresses the sequence direction only lightly. The key is not aggressive sequence truncation. The savings come from reducing cross-layer redundancy and lowering storage precision. Light sequence compression keeps more token-level detail, which matters for code, logs, and tool output. The memory savings come mainly from sharing and quantization.
Pseudocode illustrates the idea:
def prefill(tokens):h = embed(tokens)for layer in encoder_layers: # First half processes the long inputh = layer(h, kv_store=shared_kv)return h, shared_kvdef decode_step(h, shared_kv):for layer in full_layers: # Generation runs the full networkkv = shared_kv.get(layer.group) if layer.share else layer.kvh = layer(h, kv)return h
In engineering practice, teams must also manage cache lifecycle, concurrency safety, paged allocation, and eviction policies. The more the cache is shared, the more carefully the expressiveness and numerical accuracy need to be validated. The more aggressive the quantization, the more it needs per-layer calibration and output quality comparison.
4. Applicable Scenarios and Deployment Recommendations
This optimization suits workloads that read far more than they write, involve multi-turn context continuation, produce long tool output, and generate short responses. Examples include intelligent coding agents, log diagnosis, retrieval-augmented generation over long documents, and test failure analysis. It is not suitable for long-form generation, tasks that require strictly independent attention at every layer, or tasks with very high precision sensitivity.
For deployment, monitor cache reuse rate, per-layer cache footprint, prefill and decoding latency, quantization error, and output quality metrics. Start with sharing in some layers and mild quantization, then expand the scope gradually. When deploying on a cloud platform, teams can use general-purpose container platforms, monitoring and alerting, and log services to track these metrics. This helps ensure that the optimization does not come at the cost of system stability.
