KV Cache Strategies for Long-Context Looped Decoding
Looped decoding reuses the same set of decoder layers multiple times in a single forward pass, trading limited parameters for deeper effective computation. It is especially attractive for long-context and multi-step reasoning, but the real difficulty is not running the layers again—it is how the attention state is stored. This article explains why naive looping roughly doubles the KV cache, examines a common compromise that splits attention into distant reuse and a near sliding window, and argues for a cleaner design where front layers own the global memory and back layers do the looping. It also covers the precision tradeoffs of a shared cache, the need for consistent training and inference semantics, and a checklist of questions to settle before fixing the loop count.
The goal of looped decoding is to execute the same set of decoder layers repeatedly within a single forward pass, trading limited parameters for deeper effective computation. It is especially attractive for long-context and multi-step reasoning scenarios: the prompt is long, and the truly time-consuming part is often the subsequent token-by-token generation. The difficulty is not “running the layers again,” but how the attention state is preserved. In a standard decoder-only structure, every layer must retain keys and values for every token seen so far. If you loop the entire network twice and write each pass to storage in the conventional way, the cache size grows roughly in proportion to the number of loops, and million-token contexts quickly become unmanageable.
Why Naive Looping Doubles the Cache
The self-attention in a decoder-only network is causal: the current position can only see the past. During inference, to avoid recomputing the keys and values of historical tokens, the system places them in a KV cache. The cache size is proportional to the number of layers, heads, head dimension, and sequence length, and it also scales with batch size.
If the loop happens on layers that write to the global cache, the second execution faces new hidden states, and the keys and values generally cannot simply overwrite the first pass’s results. Overwriting would discard the long-range information already encoded in the first pass; appending would create two histories for the same logical layer. So the sequence length stays the same, but the cache entries roughly double. When looping four or eight times, the problem shifts from “a bit expensive” to “won’t fit.” The prefill stage is affected too: a hundred-thousand-token prompt, if every layer of the whole network runs twice, has both computation and cache writes amplified during the prompt stage—the agent has not even started real decoding, yet the budget is already spent.
Therefore, the loop count, which layers participate in the loop, and whether those layers own independent global caches must be designed together, rather than mechanically repeated on an existing stack.
A Compromise: Distant Reuse and Near Separate Storage
A common engineering compromise is to split attention into distant and near segments. The distant part does not rewrite the full cache every round; instead it reuses the sparse keys and values built in the first pass, combined with a sparse index that fetches only the historical positions relevant to the current token. The near part opens a separate sliding window that stores only the local keys and values produced in the second pass. This way the global cache does not need to be fully duplicated per loop, and near tokens can still see the fine-grained representation updated in the current round.
This approach works, but the complexity concentrates on index consistency. The sparse index is selected based on the first pass’s hidden states; the second pass’s hidden states have already changed, so the selected historical positions may no longer be optimal. If you reselect every round, you pay extra scoring and data movement. The window length, the sparse retention ratio, and how the two caches are concatenated in attention all affect numerical stability and kernel implementation. Positional encoding must also be spelled out: the relative distance within the window and the original positions of the reused distant tokens must not be incorrectly renumbered in the second loop, otherwise the model will mix “the neighboring token just generated” and “a fact far away in the prompt” on the same distance scale.
Engineering must also handle lifecycle: how long the first-pass cache is retained, when the window cache slides and evicts, and how different sequence lengths within a batch are aligned. These are correctness and bandwidth issues, not just adding one more loop variable.
A Cleaner Structure: Front Segment for Memory, Back Segment for Looping
A more favorable division is to split layers by responsibility rather than looping evenly across all layers. The front half of the layers is dedicated to digesting the input and building and preserving the global keys and values—effectively the memory interface for the entire context. The back half no longer each maintains a cache covering the full sequence; the keys and values their attention needs are mapped or shared from the front segment’s output. The back segment can have local state, but it does not bear the responsibility of storing a million tokens all over again.
Putting the loop only in the back segment decouples global cache usage from the loop count. Whether the back segment runs twice, four times, or eight times, the front segment’s single global key-value set remains just one copy. Memory pressure returns to “sequence length × the number of front-segment layers that must be written to storage,” rather than “sequence length × all layers × loop count.” Whether a million tokens can be handled still depends on implementation, precision, and hardware, but the growth curve is no longer dominated by the loop count.
This division also better fits the compute shape of long-context agents. The prompt is often far longer than a single generation. If the whole network loops, every prompt token must repeatedly execute the loop body during prefill. By restricting the loop to the back segment that does not write the global cache, prefill only needs to feed the context into the front segment and build the shared memory, without rerunning the prompt multiple times just to deepen reasoning. The extra loop depth is mainly reserved for decoding: for each new token generated, the back segment does a few more refinement rounds, while the historical global cache stays unchanged. For agentic tasks that read long, write relatively short, and need multi-step verification along the way, this is a more reasonable budget.
A Shared Cache Is Not Free Precision
The back segment not storing global keys and values means the history it sees is constrained by the quality of the front segment’s representation. If the front segment is too shallow, distant facts are lost before entering the loop, and no amount of back-segment looping can recover them out of nothing. If the front segment is too deep, fewer parameters and compute remain for the loop to use. The layer split ratio should be considered together with the task: retrieval-heavy, reference-heavy scenarios need a more complete memory interface; local-reasoning-heavy, format-constraint-heavy scenarios can put more depth into the loopable back segment.
The mapping must preserve causality. The back segment can only use keys and values at the current position and earlier that have already been written by the front segment; it cannot read future layers or not-yet-committed positions inside the loop. Between multiple loop rounds, if the back segment produces intermediate vectors used only for the next refinement step, they should be placed in a temporary buffer or a limited window and explicitly discarded or written back at the end of the step, to avoid mixing with global memory. Otherwise, memory usage appears not to grow, but the actual activation peak still rises with the loop count.
If a sparse index is still used, it should be defined which state it belongs to. A safer approach: distant candidates are determined once by the front segment and the index is cached; the back-segment loop only recomputes attention weights over these candidates, supplemented if necessary with a short window for the current round’s local keys and values. This way index reuse is read-only, local updates are bounded, and the lifecycles of both paths are clear.
Training and Inference Need the Same Semantics
Turning on layer looping only at inference while training still uses a single stack causes the model to encounter distribution shift. The loop count, whether the cache is shared, and the window length should be part of the training configuration, at least covering the range of counts used at inference. The count can be sampled—it need not be maxed out every time—but the cache layout at the maximum count must appear in validation.
Positional encoding, normalization, and residual scaling must also be set for the same layer being executed multiple times. Adding residuals multiple times easily makes the activation magnitude drift with the round count; in practice, round-dependent scaling is often used, or the normalization inside the loop body absorbs the increment. These are general stability measures; the specific coefficients must be determined experimentally and cannot be converted directly from the layer count into a performance promise.
On the decoding kernel side, a shared global cache helps improve read-bandwidth reuse: multiple loop steps read the same block of historical keys and values. The short window is better placed in faster on-chip storage or a separate ring buffer. The scheduler should distinguish the two memory-access paths by global read-only and local writable, avoiding expanding the window into a full-sequence buffer for the sake of implementation simplicity and writing the structural advantage back in.
Questions to Check During Implementation
Design reviews can converge with the following questions rather than fixing the loop count first.
- Which layers have global key-value write access? Does the loop strictly avoid these layers?
- As the loop count increases, does the global cache byte count stay unchanged? Do temporary activations have an upper bound?
- Does prefill repeatedly execute the loop body for long prompts? If so, is the budget still worthwhile?
- Is the distant index reused read-only? Are the near window’s length, precision, and eviction rules clearly specified?
- Is positional numbering consistent between reused tokens and window tokens?
- Does the maximum loop count seen in training cover the online configuration?
An illustrative structure can be written as two clear segments, without binding to any specific implementation:
for layer in memory_layers: # write global cache, run onceh = layer(h, kv_global)for step in range(loop_steps): # only loop layers without global write accessfor layer in refine_layers:h = layer(h, kv_global_readonly, kv_window)commit_or_drop(kv_window)
This pseudocode only expresses the data flow: global memory is built once, the loop body reads it multiple times, and the local window is updated within a bound. It does not represent any fixed layer count, window size, or throughput.
How to Make the Tradeoff
If the parameters and layer count are already fixed and you must loop across all layers, sparse reuse plus a sliding window is a realistic compromise, but the index, positions, and the concatenation of the two caches will keep generating engineering cost. If the architecture can still be adjusted, splitting “ingesting context and saving keys and values” from “repeatedly refining on existing memory” into front and back segments better controls both memory and prefill computation. Loop depth serves multi-step reasoning in the decoding stage, rather than making every prompt token pay the same repeated cost.
The selection criterion should be measurable: at the target context length, does the global cache stay flat as the loop count increases, is long-prompt prefill time acceptable, and does adding loops genuinely improve the recall of distant facts and local consistency? If these three cannot be improved together, you are just piling computation deeper and have not solved the caching problem of long-context looping.
