# LLM Architecture Evolution: Shrinking the KV Cache to Cut Long-Context Costs

    Long-context inference is expensive because the KV cache grows with sequence length. This article explains why long contexts drive up serving costs, shows how to estimate KV cache memory with a simple formula, reviews five common architectural approaches to shrinking the cache—reducing KV heads, cross-layer KV sharing, compression, limited attention ranges, and hybrid efficient layers—and covers comparison trade-offs, deployment-side techniques like paged memory management and prefix caching, and a practical checklist for choosing an approach.

    1. Why Long Contexts Are Getting More Expensive

    What users experience as “running out of tokens” is fundamentally a matter of server-side resource consumption. Every time the model generates a new token, it must read the Keys and Values of the entire preceding history. The longer the context, the more data must be stored and read.

    Inference costs can be broken into two parts.

    The first is the prefill stage, where the model processes the input prompt. In standard self-attention, computation scales quadratically with sequence length: double the input, and attention computation roughly quadruples.

    The second is the decode stage, where the model outputs tokens one at a time. Each generated token requires accessing the full historical KV cache, so memory bandwidth—not raw compute—is often the bottleneck.

    Reasoning models and Agent scenarios amplify this problem further. Models produce lengthy intermediate reasoning chains, and tool call results keep getting appended to the context, so history length grows continuously. This is why shrinking the KV cache has become one of the central goals of recent architecture design.

    2. Do the Math First: How Big Is the KV Cache?

    Before designing optimizations, you need to be able to estimate memory. KV cache size in bytes can be computed as:

    Memory = 2 × num_layers × num_kv_heads × head_dim × seq_len × batch_size × bytes_per_element

    The factor of 2 accounts for the separate K and V tensors. The following function provides a general-purpose estimate:

    1. def kv_cache_bytes(num_layers, num_kv_heads, head_dim, seq_len,
    2. batch_size=1, bytes_per_elem=2):
    3. # 2 accounts for the separate K and V tensors
    4. return (2 * num_layers * num_kv_heads * head_dim
    5. * seq_len * batch_size * bytes_per_elem)
    6. gib = kv_cache_bytes(32, 8, 128, 128 * 1024) / 1024**3
    7. print(f"{gib:.1f} GiB") # 16.0 GiB

    This is an illustrative configuration, not the parameters of any specific model. It shows that with 32 layers, 8 KV heads, a head dimension of 128, 16-bit floating point, and a 128K context, a single request’s KV cache requires roughly 16 GiB.

    If the same configuration increases the number of KV heads from 8 to 64, the cache grows to 128 GiB. Clearly, KV head count, layer count, and context length all directly determine memory usage—optimizing any one of them yields significant savings.

    3. Five Common Approaches to Shrinking the KV Cache

    1. Reducing the Number of KV Heads

    In multi-head attention, every query head has its own key-value heads. Grouped-Query Attention (GQA) and Multi-Query Attention (MQA) let multiple query heads share a smaller set of key-value heads, directly shrinking the KV cache proportionally.

    The trade-off is some loss in expressiveness. As a result, this approach usually needs to be adopted during training; retrofitting it afterwards has limited effect.

    2. Sharing KV States Across Layers

    This is currently one of the most watched directions. Instead of each layer computing and storing its own KV, later layers reuse the Keys and Values already computed by an earlier layer. Only a subset of layers keeps KV in the cache; the rest simply reference it.

    In implementation, each layer can be assigned a KV source layer:

    1. class DecoderStack:
    2. def __init__(self, layers, share_map):
    3. # share_map[i] = j means layer i reuses the KV of layer j
    4. # Layers not in share_map compute their own KV
    5. self.layers = layers
    6. self.share_map = share_map
    7. def forward(self, x, cache):
    8. shared_kv = {}
    9. for i, layer in enumerate(self.layers):
    10. src = self.share_map.get(i)
    11. if src is None:
    12. k, v = layer.compute_kv(x)
    13. shared_kv[i] = (k, v)
    14. cache.append(i, k, v) # only source layers write to the cache
    15. else:
    16. k, v = shared_kv[src] # reuse the source layer's result, no new cache entries
    17. x = layer.attend_and_ffn(x, k, v)
    18. return x

    The benefit is straightforward: cache size scales with the number of source layers rather than the total layer count. The research community proposed similar cross-layer attention designs years ago; recently, some models have applied this idea to mainstream open-source architectures. The structure must be learned during training—it cannot be bolted on at deployment time the way quantization can.

    3. Compressing the Numerical Representation of KV

    These methods keep the attention structure unchanged and only change how KV is stored:

    • Quantization: Reduce the KV cache from 16-bit floats to 8-bit floats or 8-bit integers, roughly halving memory. Precision loss is usually small, but it should be validated on your target tasks.
    • Low-rank compression: Project high-dimensional KV into a lower-dimensional latent space for storage, then restore it—or compute attention directly in the projected domain—when running attention. This requires architectural design, not simple post-processing.

    4. Limiting the Attention Receptive Field

    Sliding-window attention lets each token attend only to the most recent few tokens. KV outside the window is not retained, so that layer’s cache size stays constant regardless of sequence length.

    Real models often use hybrid strategies: most layers use a local window, while a few layers retain global attention so information can still travel across long distances. This design balances efficiency and long-range dependency in long-context scenarios.

    5. Replacing or Mixing Attention Layers

    Linear attention and state-space models replace the per-token-growing KV cache with a fixed-size recurrent state. Their inference memory is largely independent of sequence length, but on tasks requiring precise retrieval of historical details, they typically underperform full attention. Hence the common practice today: stack a small number of full-attention layers interleaved with many efficient layers.

    One important distinction: sparse expert architectures (MoE). Their main role is reducing each token’s feedforward computation—they do not directly shrink the KV cache. Understanding this is essential to correctly judging where a given model’s cost savings actually come from.

    4. Comparing the Options and Their Trade-offs

    Approach Memory savings Compute savings Quality risk Retraining required
    Fewer KV heads High Medium Medium Usually
    Cross-layer KV sharing High Medium Medium Yes
    KV quantization Medium Low Low to medium Usually not
    Low-rank compression High Medium Medium Yes
    Sliding-window hybrid High High Medium Yes
    State-based efficient layers High High Higher Yes

    When choosing an approach, answer three questions in order: Is the bottleneck memory or compute? Does the target task depend on precisely recalling long-range details? Can you accept training-time changes? If you can only adjust at deployment time, prioritize KV quantization and inference-engine-level optimizations.

    5. Engineering in Practice: Serving-Side Techniques

    Beyond architecture, the inference service itself significantly affects long-context costs. The following are common practices:

    • Paged memory management: Split the KV cache into fixed-size blocks allocated on demand, reducing memory fragmentation and over-reservation waste.
    • Prefix caching: Reuse already-computed KV for requests sharing the same system prompt or document prefix, cutting repeated prefill overhead.
    • Continuous batching: Dynamically merge requests of different lengths to improve memory and compute utilization.
    • Concurrency budgeting: Limit the number of simultaneously processed sessions based on remaining memory, preventing out-of-memory failures.

    The concurrency budget can be written as a simple function:

    1. def max_concurrent_sessions(total_mem_gib, weight_gib,
    2. per_session_kv_gib, reserve_ratio=0.1):
    3. # Reserve some memory for activations and runtime overhead
    4. usable = total_mem_gib * (1 - reserve_ratio) - weight_gib
    5. return max(0, int(usable // per_session_kv_gib))
    6. # Example: 80 GiB memory, 30 GiB model weights, 2.5 GiB KV per session
    7. print(max_concurrent_sessions(80, 30, 2.5)) # 16

    In real deployments, you still need to calibrate through load testing with actual activation memory and fragmentation—don’t rely on theoretical estimates alone.

    6. Selection and Implementation Checklist

    1. Define your target context length range. Designs for 8K and for 128K+ differ significantly.
    2. Estimate per-session KV cache size with the formula, multiply by target concurrency, and confirm memory feasibility.
    3. Identify the bottleneck type. If memory-bound, prioritize KV-related design; if compute-bound, focus on feedforward and attention compute structure.
    4. Evaluate quality risk. Run regression tests on long-document retrieval, multi-hop reasoning, and code editing tasks—not just average benchmarks.
    5. Confirm the deployment path. Whether you can change the training pipeline determines which options are available.
    6. Set up monitoring. Continuously track memory usage, queue time, and per-request token consumption to catch abnormal growth early.

    7. Summary

    The cost problem of long contexts fundamentally comes down to KV cache size and attention computation growing with sequence length. Recent architectural evolution largely revolves around reducing the KV that must be stored, compressing its representation, limiting attention ranges, and mixing different layer types. Once you understand these mechanisms, your team can more accurately assess the relationship between model capability and resource cost, and make verifiable selection decisions in real business scenarios.