Long-Context Inference: Reducing Input Computation and KV Cache Footprint
This article explores optimization strategies for long-context LLM inference, addressing the distinct challenges of reducing input computation and managing key-value (KV) cache footprints. It details architectural approaches that allow inputs to bypass certain network layers, explains the mechanics of KV cache growth, and demonstrates how cross-layer sharing and low-precision storage can offset the memory costs of retaining more sequence positions. Finally, it provides a framework for evaluating these optimizations under real-world workloads, ensuring that architectural benefits translate into tangible improvements in latency, throughput, and model quality.
1. Long Input, Short Output: The Bottleneck Isn’t Always Generation
A typical programming task might involve multiple rounds of file reading, code modification, and testing. With each tool call, new source code snippets, diagnostic information, or runtime results are fed back to the model. The model may only need to generate a few dozen to a few hundred tokens to decide the next step, yet it must first process an input significantly longer than the output. In such cases, looking solely at tokens generated per second can lead to a misjudgment of interaction speed: the user’s waiting time might primarily be spent before the first token appears.
To analyze this type of workload, inference must first be broken down into two phases. Input prefill processes the prompt tokens that have not yet been computed in the current round, establishing the historical state that subsequent generation can read. Multiple input positions within the same request can usually be computed in batches, but long inputs still incur significant computation. Token-by-token decoding sequentially generates new tokens; at each step, it reads the existing context and writes the new position’s state into the cache. This phase can be either compute-bound or memory-bandwidth-bound, depending on the model architecture, batch size, and hardware implementation.
This allows us to distinguish between two seemingly similar but fundamentally independent problems: How can we make the model perform less input computation? And how can we make the model retain less state for the same history? The former is primarily determined by the computation path, while the latter is dictated by the cache layout. Both optimizations can be used simultaneously, but the benefits of one cannot be directly attributed to the other.
2. Why Input Can Traverse Only Part of the Network
In a standard layer-by-layer causal network, the hidden states of prompt tokens pass through each layer sequentially. As long as subsequent generation needs to read the historical key-values corresponding to a particular layer, the prefill phase must prepare these states for the prompt positions. During deployment, you cannot simply skip the latter half of the network, or the generation phase might not have access to the historical information it depends on.
An alternative architecture divides the network into a front-end causal encoding module and a back-end generation module. The front-end processes the long input, producing context representations that can be read later. The generation layers in the back-end read these representations through pre-designed attention connections, without requiring every prompt position to pass through all back-end layers. “Causal” here means that a position can only use its own information and prior information when forming its representation; it does not imply that the entire input is allowed to be read bidirectionally. When generating new tokens, the computation can still pass through the complete network to perform queries, integrate information, and predict the output.
The key to this optimization is changing where the back-end obtains historical information, rather than arbitrarily dropping layers during inference. The attention connection method, the production and consumption relationship of the cache, and the computation path used during training all need to match each other. For existing models, directly pruning layers from the prefill process is generally not equivalent to adopting this architecture.
It is also important to distinguish between “fewer layers traversed” and “reduced first-token latency.” Even if the input path is significantly shortened, the computational cost of each layer may not be identical, and prefill also involves cache writes, cross-device communication, and request scheduling. First-token latency may also include queuing time. Therefore, end-to-end speedup cannot be directly extrapolated proportionally to the number of layers skipped. When the output is very long, sequential generation can still occupy the majority of the time, making the overall benefit of this input optimization relatively smaller.
3. Why KV Cache Grows with Context
The attention mechanism can be understood as a weighted historical query. The current position generates a query vector (Q), which it uses to calculate relevance with the keys (K) of visible historical positions, and then reads the values (V) of those positions based on the resulting weights. When generating the next token, the query changes, but in standard causal inference, the keys and values of already processed historical positions do not need to be recalculated due to the new position. Retaining these keys and values constitutes the key-value cache, or KV cache.
While caching avoids repeatedly computing historical states, it shifts the overhead to memory capacity and read bandwidth. When estimating the global KV cache for a single request, you can start with the following simplified relationship:
Global KV cache bytes ≈ Number of independent cache groups × Positions retained per group × Bytes per KV position.
This formula assumes a consistent layout across all groups. If different groups have varying channel counts, retained positions, or storage formats, they must be calculated separately and then summed. “Bytes per KV position” should be based on the actual stored representation: some implementations store keys and values separately, while others store reusable compressed representations. This estimate only covers the main body of the global cache; local window states, quantization metadata, indices, alignment padding, and allocator reservations need to be accounted for separately.
The “number of independent cache groups” is particularly important. In a layout where each relevant layer independently stores historical states, this number can approach the number of layers requiring global cache. In a cross-layer shared layout, multiple layers can read the same group of states, making the number of cache groups significantly smaller than the number of layers reading from it.
4. Lighter Sequence Compression: Why Cache Can Still Shrink
Compressing along the sequence dimension reduces the number of historical positions in the cache. For example, aggregating several adjacent positions into a single representative state can reduce the entries required for long history. If this compression is lightened, it typically means retaining more positions in the cache for the same original input length. Looking solely at the sequence dimension, lighter compression does not save space.
However, the total cache size depends on multiple dimensions. The first compensation comes from cross-layer sharing: the same group of historical keys and values is read by multiple layers, eliminating the need to redundantly store them in memory for each layer. Sharing historical representations does not mean each layer produces the same output. As long as the queries from different layers originate from different hidden states or query mappings, they can still assign different weights to historical positions, even when facing the same set of keys and values. The second compensation comes from low-precision storage: using fewer bytes to store the key-value representation for each position. Actual gains must account for metadata like scaling factors, as well as the dequantization costs and numerical errors during reads.
Consider an illustrative example showing multiplicative relationships: suppose the number of retained historical positions doubles, the number of independent cache groups drops to a quarter, and the bytes stored per position are halved. The relative size of the main global cache would then be:
2 × 1/4 × 1/2 = 1/4.
This is not empirical data or a fixed architectural ratio. It demonstrates that as long as the number of cache groups and bytes per position decrease sufficiently, the main global cache can still shrink even if more positions are retained along the sequence dimension. Conversely, shrinking the main body to a quarter does not mean the total inference memory shrinks to a quarter: model weights, temporary activations, local states, and the overhead of concurrent requests will not change by the same proportion.
It is also crucial to distinguish between shared cache and reused retrieval results. The former addresses whether multiple layers need to each store a copy of the historical representation; the latter applies to attention with candidate filtering and addresses whether multiple layers must re-search candidate positions. Multiple layers sharing a single cache can still select candidates independently. Only when the architecture allows reusing the same batch of candidate indices is there an opportunity to save some filtering work; even if the candidates are identical, each layer can still compute attention weights independently. When evaluating this reuse, one should check whether the small amount of critical information required by deeper layers was omitted in the previous filtering round.
5. How to Ensure Architecture Benefits Translate to Real Services
First record real read/write ratios, then split cache hit scenarios. For each round of requests, separately track the total input length, new input length, output length, and reusable prefix length. Two requests might both carry a very long context, but if one starts prefilling from scratch and the other only processes newly added logs, their actual overheads will differ significantly. Stress testing should cover the first long input, continuation after a prefix hit, and cases where earlier content modifications prevent further reuse of subsequent prefixes. Cross-request prefix reuse saves redundant prefilling, while cross-layer cache sharing saves redundant storage within the same request; these should not be merged into a single metric.
Measure latency, footprint, and throughput simultaneously. On the latency side, record first-token latency, per-token time during the output phase, and high-percentile latencies. On the capacity side, separately log the main global cache, peak runtime memory, and the stable concurrent load. Compare at least two workload types—long input/short output and long input/long output—while keeping the input samples, output budgets, and concurrency conditions identical. Once memory is saved, the scheduler might accommodate more requests, thereby increasing throughput. However, if low-precision conversion or irregular memory access becomes a bottleneck, the decoding speed of a single request may not improve synchronously.
Use tasks dependent on long-range evidence to verify quality. You shouldn’t just test whether the model can recite a sentence from the context. A more discriminating test is to place interface constraints at the beginning of a long document, put failure logs at the end, and then ask the model to pinpoint the issue based on the modification records. You can change the position of key information, add seemingly relevant but actually outdated records, and check whether the model cites the correct evidence. For programming workloads, you should also observe the accuracy of modifications, test pass rates, and the number of interaction rounds required to complete the task. If cache optimizations make each round faster but cause the agent to execute more rounds due to missed constraints, the end-to-end benefits might be negated.
Ultimately, evaluating the value of such solutions comes down to answering three questions: How much computation does the new input actually go through? How many bytes does the historical state actually occupy? And can the model consistently retrieve the information needed to complete the task? Segmented computation, cache sharing, and low-precision storage affect different stages. Only by placing them into the same real-world workload test can you determine whether the saved memory and computation translate into shorter wait times, higher concurrency, or merely a better-looking cache metric.
