Optimizing KV Cache for Large Language Models in Loop-Based Architectures
This article explores how loop-based model architectures cause KV cache memory to grow with each loop iteration, and presents practical optimization strategies. It covers three failure modes of naive looping, a design principle that decouples caching from loop count, a YOCO-style split between front and back network segments, memory budgeting for capacity planning, and a tuning checklist for deployment.
1. Where the Problem Starts: Why Loop Stacking Amplifies Memory
A common trend has emerged in recent large model architecture design: trading fewer physical parameters for more repeated computation to preserve quality. A typical approach extracts several layers from a fully pretrained large base model to build a smaller “loop core,” then executes the same set of parameters two or more times during inference. The benefit is direct—a smaller parameter footprint and reduced memory bandwidth pressure—but the cost is equally clear: each loop iteration produces new intermediate states, and without special handling, the key-value cache (KV Cache) grows roughly linearly with the number of loop iterations.
To understand this, first review the memory composition of a standard Decoder-only structure during autoregressive decoding. Each layer needs to cache the Keys and Values of historical tokens, and the total can be approximated as:
KV_bytes ≈ 2 × layers × kv_heads × head_dim × seq_len × batch × dtype_bytes
The factor of 2 corresponds to the two tensors for Key and Value. This equation shows that memory usage is linear in both the number of layers and the sequence length. When a loop core turns 28 “logical layers” into 56 (two iterations), and each layer independently holds a global cache, memory usage doubles immediately. Stretch the context to the million-token level, and the problem quickly shifts from “can it run” to “it simply won’t fit.”
2. Three Failure Modes of Naive Looping
Before optimizing, it is important to understand how failures occur; otherwise, optimization efforts may be ineffective.
- Memory overflow: The global KV multiplies with the number of iterations, long-context requests trigger OOM directly, and batch concurrency is forced down to 1.
- Bandwidth bottleneck: During decoding, every generated token requires reading the entire KV cache. Looping multiplies the number of reads, and single-request latency rises significantly.
- Prefix cache invalidation: Multi-turn conversations and agents repeatedly reuse the same system prompt and tool descriptions. If the cache key is bound to the loop iteration, the prefix reuse rate drops sharply, and the cost of repeated prefilling is passed on to every request.
3. Design Principle: Decouple “Storage” from “Computation”
The core idea of the optimization is a single sentence: make cache ownership independent of the number of loop iterations. Around this principle, the work can be broken into three independently implementable strategies.
3.1 Long-Range Context: Reuse One Sparse KV Across Iterations
For tokens far from the current decoding position, their semantics are highly stable across loop iterations, and recomputing them in the second iteration yields minimal benefit. Therefore, the global cache written in the first iteration can be reused read-only by all subsequent iterations, combined with sparsification to keep only selected channels or positions. The logic is illustrated below:
# Pseudocode: read-only cross-iteration reuse for the long-range portionkv_global = kv_round0 if step >= 0 else None # written in round 0, read-only afterwardidx = sparse_index.select(kv_global, top_k=512) # sparse index selects pointsk_far, v_far = kv_global.k[idx], kv_global.v[idx]
The engineering point here is that the cost of the sparse index itself must be controllable: the index structure should support incremental updates to avoid the extra overhead of rebuilding it at every step.
3.2 Short-Range Context: A Dedicated Sliding Window for the Second Iteration
Nearby tokens have the greatest influence on the next prediction, and cross-iteration reuse would lose precision. A more robust approach is to allocate a separate fixed-length sliding window cache for the second iteration of the loop. The window size is decoupled from the number of loop iterations, so memory grows as a constant rather than linearly.
window = SlidingWindowCache(capacity=4096) # fixed capacity, independent of loop countwindow.append(k_roundN, v_roundN)k_near, v_near = window.get()
3.3 Attention Concatenation: Merging the Two Caches
The final attention needs to see both the “sparse far field + dense near field” at once. In implementation, consistency of masks and position encoding must be ensured to avoid misalignment of the position baseline between the two caches:
k = concat([k_far, k_near], dim=seq)v = concat([v_far, v_near], dim=seq)mask = build_mask(len(k_far), len(k_near), sliding=window.capacity)out = attention(q, k, v, mask=mask)
4. A Better Fit for Loops: A YOCO-Style Split Between Front and Back Halves
The divide-and-conquer scheme above is effective, but its engineering implementation chain is long: sparse indexing, dual caches, mask concatenation, and position baseline calibration—each link is a potential defect point. The industry has another general approach that fits loop semantics more naturally, a “You Only Cache Once” (YOCO)-style division of labor between layers: split the network into a front and a back segment, where the front layers consume the input and write the global KV, while the Key/Value of the back layers are generated from the front segment’s output through a lightweight mapping, and the back layers no longer maintain a global cache of their own.
Placing the loop core in the back segment yields structural benefits:
- Constant memory: Regardless of whether the back segment loops 2, 4, or 8 times, the global KV footprint is determined only by the number of front-segment layers and is independent of the loop count, making million-token contexts feasible.
- Simpler implementation: No coordination between dual caches and a sparse index is needed; the code path is short and the regression testing surface is small.
- Scheduling-friendly: The front segment can perform prefilling only once and persist it, while the back-segment loop is easier to quantize and offload under memory constraints.
- Scenario fit: Long-context agents need to repeatedly review tool outputs and historical trajectories, and constant memory translates directly into higher concurrency.
The costs must also be stated honestly: the back-segment layers cannot see the original token representations and can only rely on the mapped representations, so the design quality of the mapping module directly affects quality; meanwhile, the boundary point between the front and back segments becomes a hyperparameter that needs tuning.
5. Memory Budget and Capacity Planning
Before going live, it is recommended to do an explicit budget and lay out the variables for evaluation:
Total memory ≈ weights + front-segment global KV + back-segment window KV + activations + framework reserveConcurrency limit ≈ (available memory - weights - reserve) / per-request KV
The recommended practical order is: first fix the context length and concurrency target, then work backward to the allowed number of logical layers; if the number of loop iterations must be increased, prefer the “back-segment loop + single front-segment cache” division of labor rather than continuing to stack cache optimization techniques. When deploying on the cloud, container platforms can host the inference service, object storage can hold model and cache snapshots, and logging services and monitoring alerts can track memory watermarks and time-to-first-token, forming a closed loop.
6. Tuning Checklist
- Boundary point position: too few front-segment layers weaken representational capacity, while too many bring cache costs back up; it is recommended to start from a 1:1 ratio and do a small-scale sweep.
- Sliding window capacity: based on the effective receptive field of the near field, usually a few thousand is enough to cover local dependencies.
- Sparse budget: adjust the far-field retention according to the task’s sensitivity to long-range dependencies; summarization tasks can be more aggressive.
- Precision alignment: compare layer-by-layer outputs before and after the loop to locate deviations introduced by cache reuse.
- Benchmarking metrics: separately record prefill time, per-token decoding time, and peak memory, avoiding looking only at averages.
7. Conclusion
Loop-based structures and long contexts are not inherently in conflict; the conflict is concentrated in the ownership design of the KV Cache. Decoupling the cache from the loop count is a more fundamental solution than stacking techniques: read-only cross-iteration reuse for the far field plus a fixed sliding window for the near field is a progressive transformation path; the front/back split, where the back segment loops while the global cache is written only once, is a more thorough and more maintainable target form. Which path to choose depends on how modifiable the existing code is and the memory budget, rather than the quality of a single iteration.
