KV Cache Design for Long-Context Recurrent Decoding

    Recurrent decoding reuses decoder layers, but shared weights do not automatically reduce KV cache requirements. This article compares per-round caching, near–far cache partitioning, and shared context memory, explains their memory and latency trade-offs, and outlines how to evaluate quality, serving performance, and cache lifecycle behavior before choosing a design.

    1. Shared Weights Are Not Shared Historical States

    Recurrent decoding feeds the output of a group of decoder layers back into the same layers for multiple rounds of updates, then uses the final state to predict the next token. This is distinct from ordinary autoregressive generation. Autoregressive generation advances through the sequence one token at a time; recurrence repeats computation along the depth dimension before predicting the same token.

    Reusing layers saves the parameters that would otherwise be needed to stack additional modules. It does not automatically save inference cache memory. In standard self-attention, keys and values are projected from the hidden states received by the current layer. Even when two rounds use identical projection weights, different input states generally produce different keys and values. The historical KV states from the first round cannot simply replace those from the second round without changing the computation’s semantics.

    If every round requires exact attention over its own complete history, the inference system generally must retain separate historical KV states for each round or recompute them when needed. With per-round caching, two rounds require roughly twice as many cache entries for the recurrent layers as one round. This does not mean the entire model’s cache doubles: layers outside the recurrent block do not incur this increase.

    Before evaluating a recurrent architecture, map its data flow. Identify which states change in each round, which must persist across generation steps, and which are only temporary within the current computation.

    2. Near–Far Partitioning: Preserve Per-Round Detail for Recent History

    One compromise that retains the standard decoder structure is to assign different cache budgets to tokens based on their distance from the current position. For distant history, later rounds read the KV states stored during the first round, with sparse selection limiting the positions accessed. For recent history, later rounds maintain their own fixed-capacity sliding windows containing local KV states produced from that round’s hidden states.

    This confines the additional per-round cache to the window rather than allowing it to grow with the full context.

    A critical distinction is that sparse reads do not imply sparse storage. If the next step may select any historical position, and the system has no on-demand recomputation or other retrieval mechanism, usable KV states must still be retained for those candidate positions. Sparse selection primarily reduces the amount of data read and processed at each step. To determine the actual memory savings, specify which states are no longer stored and how selected states are retrieved.

    Selection indices can also be reused across rounds, but this should be treated as an approximation that requires quality validation. As hidden states evolve, later rounds may need different evidence. Reusing first-round indices reduces selection work, but it may also prevent later rounds from seeing passages missed by the first round.

    Sliding-window boundaries introduce another trade-off. Information that has just left the local window may remain accessible, but later rounds can access it only through the shared distant-history representation. Implementations also need explicit overlap and deduplication rules for the near and far regions, causal constraints on every read, and correct cache management during batching, request completion, and window advancement.

    Near–far partitioning is practical, but its memory savings must be weighed against the additional indexing, scheduling, and validation costs.

    3. Shared Context Memory: Repeated Queries Instead of Per-Round Storage

    When model design and training can be changed, a more direct approach is to separate responsibilities. An earlier stage processes the input causally and produces shared KV memory for a later stage to read. The later stage iteratively updates the current token’s representation. At each round, it generates queries from the updated hidden state and applies cross-attention to the same historical memory.

    Different rounds can attend to different positions without storing a new full set of historical keys and values for each round.

    In autoregressive serving, “shared” does not mean that the entire memory remains permanently frozen. As new tokens enter the context, the earlier stage still computes and appends their historical representations. What remains fixed is the visible memory that the later stage reads across rounds within a single decoding step.

    Both training and inference must restrict access according to the current position so that shared memory cannot expose future tokens. Some designs may also add local self-attention to the later stage to preserve recent per-round information, but that cache must be accounted for separately.

    The central benefit is that if the recurrent layers do not materialize per-round global KV states, adding recurrence rounds does not increase the number of copies of that global cache.

    This conclusion has clear limits. If each round still generates and persistently stores its own KV copy covering the full history, round-dependent memory costs return. If the later stage shares historical representations but stores separately projected keys and values for different reading modules, cache size still depends on the number of projected copies actually retained. Measure runtime tensors rather than counting modules labeled “shared” in an architecture diagram.

    Shared memory also changes the model’s representational capabilities. The later stage can ask new questions, but unlike per-round global self-attention, it cannot directly read a complete historical state produced by deep computation in the same round. If the earlier stage does not preserve sufficiently clear evidence in memory, additional iterations may not compensate.

    Switching from a conventional decoder to shared context memory should therefore not be treated as a cache configuration change that requires no training validation.

    4. Calculate Capacity and Speed Separately

    Let the history length be (T). At each position, suppose keys and values each contain (H) KV heads, each head has dimension (D), and each element occupies (S) bytes. The effective data size of one global KV cache is approximately:

    [
    2THDS \text{ bytes}
    ]

    The factor of 2 accounts for keys and values. This estimate covers one request and one cache copy. It excludes allocation granularity, index metadata, temporary tensors, and copies between devices. If head counts, dimensions, or precision differ between layers, calculate each layer separately and sum the results.

    These scaling relationships provide a useful basis for choosing a design:

    • Per-round global caching: Additional memory grows with both history length and the number of rounds.
    • Near–far partitioning: Additional per-round memory depends primarily on sliding-window capacity.
    • Shared context memory: Global cache memory depends on history length and the number of shared cache copies actually stored, rather than the number of recurrence rounds.

    If the later stage also retains per-round local states, adding rounds can still increase local cache requirements and peak memory usage.

    More importantly, storing fewer copies does not mean reading them fewer times. Multiple rounds may repeatedly read the same long history and add serial computation. Even when model weights and caches fit in GPU memory, attention data movement, operator scheduling, and per-token latency may prevent the service from meeting its targets.

    A successful model load is not enough to establish that an extremely long context is usable. On the intended hardware and at the intended concurrency, time to first token, sustained generation speed, and peak memory must all meet requirements.

    5. For Long-Context Agents, Validate the Benefit Before Choosing the Round Count

    Long-context agents often reread lengthy documents, interaction histories, or tool outputs. Shared memory is most suitable when the historical prefix is relatively stable and expensive to retain, and each generation step genuinely benefits from repeated queries and state updates.

    Additional recurrence may be less worthwhile when requests are mostly short interactions, old prefixes are frequently rewritten, or users are highly sensitive to per-step latency. For cross-request prefix reuse, verify that prefix content, positional handling, and model configuration match. Similar content alone does not justify direct cache reuse.

    Evaluation can proceed in three steps.

    1. Measure Quality First, Then Find the Compute Trade-Off

    Within the round-count configurations each model supports, compare single-round and multi-round performance on distant-evidence retrieval, cross-passage attribution, conflicts between recent and distant information, and multistep tasks.

    When comparing architectures, make training and inference budgets explicit. Otherwise, differences in training may be mistaken for effects of the cache strategy.

    For near–far partitioning, include cases where evidence crosses the sliding-window boundary and where later rounds need evidence that the first round did not select.

    2. Benchmark Prefill and Token Generation Separately

    During prefill, record input processing time and peak memory. During generation, record per-token latency, tail latency, and throughput.

    Test both individual long requests and concurrent workloads mixing long and short requests. Determine whether memory savings translate into higher effective concurrency or are offset by the bandwidth cost of repeatedly reading history.

    3. Test the Cache Lifecycle

    Cover window advancement, prefix appends, request interruption, and resource reclamation. Check whether memory grows with history length and round count as expected.

    For the same model configuration, use a recomputation path without cache reuse as a reference on small inputs to verify that the cached implementation preserves the expected outputs. For approximate designs that intentionally change attention semantics, evaluate quality differences separately rather than requiring exact agreement with full attention.

    Choose a design only after identifying the actual bottleneck. If implementation cost is the main constraint, near–far partitioning offers a way to control additional cache usage within an existing decoder structure. If per-round duplication of long history is the bottleneck, and retraining and redeployment are feasible, shared context memory deserves priority in evaluation. If per-token latency is already the limiting factor, use a single-round design as the baseline rather than assuming more recurrence is better.

    Ultimately, recurrent layers are valuable only when their additional computation delivers measurable task-quality gains at an acceptable serving cost.