KV Cache Compression Explained: How Modern LLM Architectures Shrink Memory Use

    This article explains why KV Cache compression has become the main thread of recent LLM architecture evolution. It covers why KV Cache is the core constraint in autoregressive decoding — linear memory growth, the memory wall at long context, and the bandwidth bottleneck during the decode phase. It then takes a close look at cross-layer KV sharing (the progression from MHA to MQA to GQA to sharing across layers), including its motivation, three implementation patterns, and a minimal PyTorch implementation. You'll also find a comparison of quantization, sliding window attention, attention sparsification, low-rank KV, paged caching, eviction policies, and linear/SSM architectures, plus engineering notes on training-time design, cache management, and evaluation, and guidance on matching each architecture to on-device, local inference, and quality-first use cases.

    1. Introduction: Recent Architecture Changes Are All About Memory

    Recent changes to LLM architectures are not isolated technical tweaks. They follow one common thread: compressing the KV Cache.

    A typical example is a series of open-weight small models released around April. They came in three tiers:

    • Small models for on-device use on phones and embedded hardware.
    • Mid-size models with sparse experts (MoE), designed for efficient local inference.
    • Larger, dense flagship models that prioritize model quality and easier post-training.

    Put these models side by side on an architecture diagram, and you’ll notice that total parameter count is often not what determines whether a model can run, or for how long. What matters is how small the KV Cache can be made.

    If you build inference services, deploy on devices, or choose models, this thread directly determines your memory budget, maximum context length, and cost per token. This article starts from the problem and breaks down the mainstream solutions layer by layer.

    2. Why KV Cache Is the Core Problem

    2.1 The memory baggage of autoregressive decoding

    During autoregressive generation, each new token is attended against all historical tokens. To avoid recomputation, the standard engineering practice is to cache each layer’s Key and Value tensors for all historical tokens. This is the KV Cache: memory traded for compute. It is the standard approach for autoregressive decoding.

    The cost: the KV Cache grows linearly with sequence length. For a single layer, its memory footprint is approximately:

    1. bytes ≈ 2 (K and V) × num_layers × num_kv_heads × head_dim × seq_len × batch × bytes_per_value

    2.2 The memory wall at long context

    Here is a concrete estimate (illustrative parameters, to show the order of magnitude):

    • Model: 32 layers, hidden size 4096, 32 attention heads (head_dim = 128), 8 KV heads with GQA enabled
    • Precision: FP16
    • One sequence with 8K context

    Plugging into the formula:

    1. 2 × 32 × 8 × 128 × 8192 × 2 bytes = 1 GiB / sequence

    So a single 8K request consumes 1 GiB of GPU memory just for its KV Cache. If the server handles 128 concurrent requests, the KV Cache alone takes 128 GiB. That is far beyond the memory capacity of most single GPUs. Longer contexts (32K, 128K) amplify memory usage linearly.

    2.3 The bandwidth bottleneck: the decode phase

    Memory capacity is only the first constraint. The second is bandwidth. In the decode phase, each step processes just one new token, so compute density is extremely low (memory-bound). GPUs spend most of their time waiting for the KV Cache to be moved from memory. This means:

    • A larger KV Cache means higher latency per decoded token (degrading TPOT after TTFT).
    • The maximum batch size for concurrency is directly capped by memory capacity.
    • The longer the context, the higher the cost per token.

    So shrinking the KV Cache solves three problems at once: memory capacity, decode bandwidth, and long-context feasibility. That is why recent architecture changes keep circling back to it.

    3. Cross-Layer KV Sharing: The Key Lever for Small Models

    3.1 From MHA to GQA, and then to cross-layer sharing

    The evolution of attention structure follows a clear path:

    1. MHA (multi-head attention): Each head has its own K/V. It is the most expressive, but its KV Cache is the largest (num_kv_heads = num_attention_heads).
    2. MQA (multi-query attention): All query heads share one set of K/V. The KV Cache shrinks to 1/n, but quality loss is noticeable.
    3. GQA (grouped-query attention): A middle ground where several query heads share one set of K/V. It has been the de facto standard for the past two years.
    4. Cross-layer sharing: Instead of grouping only within a layer, adjacent layers reuse the same K/V. This is the focus of this article.

    3.2 The motivation: inter-layer representational redundancy

    Why can KV be shared across layers? The main reason is significant representational redundancy between Transformer layers:

    • The residual stream evolves gradually across layers. Adjacent layers often produce highly similar outputs, especially in the shallow layers.
    • After pre-training, some layers’ attention weight distributions are already “decided” by upstream layers. Recomputing K/V independently yields diminishing marginal benefit.
    • Existing research (such as analyses of cross-layer attention) has shown through ablation experiments that replacing some layers’ K/V with that of adjacent layers causes only limited degradation in model quality.

    In other words, most layers do not need to maintain their own independent K/V memory. Sharing is a reasonable compression direction.

    3.3 Three typical implementation patterns

    Pattern A: Pair-wise sharing between adjacent layers

    Pair up layers two at a time: the first layer computes K/V, and the second reuses it:

    1. Layer 0: compute K0, V0 → Layer 1: reuse K0, V0
    2. Layer 2: compute K2, V2 → Layer 3: reuse K2, V2
    3. ...

    The KV Cache is halved. On top of GQA, this is a “free” second layer of compression, and it usually has minimal impact on quality.

    Pattern B: Global sharing groups

    Divide all layers into several groups, with layers in the same group sharing one set of K/V. Fewer groups mean more aggressive compression. In the extreme case where all layers share one set of K/V, the compression ratio can reach a multiple of the number of layers, but the model must learn to adapt to this during training.

    Pattern C: Hybrid sharing with sliding window

    Combine cross-layer sharing with sliding window attention: most layers use local attention with a narrow window (e.g., 1K tokens), while only a few layers retain global attention. Local layers have naturally truncated KV Caches because of the limited window. Global layers handle long-range dependencies. This is the classic trade-off between long-context capability and controllable memory usage.

    3.4 Sample code

    Below is a minimal implementation of pair-wise adjacent-layer sharing in PyTorch style:

    1. import torch
    2. import torch.nn as nn
    3. import torch.nn.functional as F
    4. class SharedKVBlock(nn.Module):
    5. """Single forward step; when share_kv=True, reuse the previous layer's K/V"""
    6. def __init__(self, d_model, n_heads, n_kv_heads):
    7. super().__init__()
    8. self.n_heads = n_heads
    9. self.n_kv_heads = n_kv_heads
    10. self.head_dim = d_model // n_heads
    11. self.q_proj = nn.Linear(d_model, d_model, bias=False)
    12. self.kv_proj = nn.Linear(d_model, 2 * n_kv_heads * self.head_dim, bias=False)
    13. self.o_proj = nn.Linear(d_model, d_model, bias=False)
    14. def forward(self, x, past_kv=None, reuse_kv=False):
    15. B, T, D = x.shape
    16. q = self.q_proj(x).view(B, T, self.n_heads, self.head_dim).transpose(1, 2)
    17. if reuse_kv and past_kv is not None:
    18. # Reuse the previous layer's K/V; skip projection and write-back
    19. k, v = past_kv
    20. new_kv = past_kv
    21. else:
    22. kv = self.kv_proj(x).view(B, T, 2, self.n_kv_heads, self.head_dim)
    23. k, v = kv.unbind(dim=2) # (B, n_kv, T, d)
    24. k = k.transpose(1, 2)
    25. v = v.transpose(1, 2)
    26. new_kv = (k, v)
    27. # GQA: broadcast KV heads to query heads
    28. repeat = self.n_heads // self.n_kv_heads
    29. k = k.repeat_interleave(repeat, dim=1)
    30. v = v.repeat_interleave(repeat, dim=1)
    31. attn = F.scaled_dot_product_attention(q, k, v, is_causal=True)
    32. out = self.o_proj(attn.transpose(1, 2).reshape(B, T, D))
    33. return out, new_kv

    Key engineering details:

    • The reusing layer skips kv_proj, which saves both memory and one matrix multiplication.
    • Reuse must be coordinated with GQA’s repeat_interleave. Otherwise, the head dimensions won’t line up.
    • For variable-length sequences, a reusing layer’s past_kv length must match the current sequence length. It’s best to manage this centrally in the cache manager.

    4. Other Mainstream Compression Approaches: A Comparison

    Approach Core idea Compression ratio Quality impact Implementation difficulty Typical scenarios
    Cross-layer KV sharing Reuse K/V across adjacent or grouped layers 2×–N× Low–medium Medium (must be introduced during training) Small models, on-device
    KV quantization (INT8/FP8) Lower cache precision 2×–4× Low (requires calibration) Low General inference serving
    Sliding window attention Keep only the most recent W tokens Strongly context-dependent Medium (weak long-range) Low–medium Streaming, long-form generation
    Attention sparsification Compute only part of the KV (block/local + global) High (does not save memory) Medium High Ultra-long context
    Low-rank/compressed KV Replace with low-rank projections or summary vectors 3×–10× Medium High Extreme memory constraints
    Paged cache management Allocate in blocks to reduce fragmentation Improves effective utilization None Medium High-concurrency serving
    Eviction strategies (e.g., H2O) Evict historical KV based on attention scores High Medium–high Medium Very long conversations
    Linear/SSM architectures Fixed-size state instead of KV Constant size Medium (weak on recall tasks) High Ultra-long sequences, edge devices

    Selection guidance:

    • Memory is tight but model capability is sufficient → KV quantization + paged management offers the best cost-performance ratio.
    • Small on-device models → Cross-layer sharing + sliding window delivers the biggest architectural gains.
    • Ultra-long context (>100K) → Sparse attention + eviction, but evaluate the loss on recall-type tasks.

    5. Engineering Implementation Notes

    5.1 Introduce the sharing strategy during training

    Cross-layer sharing is an architecture-level change. Forcibly “turning off” some layers’ KV at inference time causes a cliff-like drop in quality. The right approach is to decide the sharing topology during pre-training so the model learns to adapt to it. Alternatively, initialize from a dense model and transfer through distillation fine-tuning.

    5.2 Coordination with positional encoding

    Cross-layer sharing requires all layers to use the same RoPE parameters and scaling strategy. Otherwise, the reused K/V will be misaligned in downstream layers. If you also use a sliding window, make sure to confirm how window boundaries align when KV is reused across layers.

    5.3 Cache management details

    • Paged/block allocation: Split the KV Cache into fixed-size blocks and allocate them on demand. This significantly reduces fragmentation and reserved-but-unused memory.
    • Prefix reuse: Share the prefix KV across requests with the same system prompt. It is one of the most cost-effective optimizations.
    • Combining quantization and sharing: Whether to quantize before sharing or share before quantizing depends on measured accuracy differences. Quantizing first is usually more stable.
    • Batch scheduling: With continuous batching, request lengths vary widely, so pair it with block-level release strategies.

    5.4 Evaluation must cover long context

    Compression solutions can’t be judged by perplexity alone. Your evaluation should cover at least:

    • Short-context quality: Regression tests on MMLU-style tasks to confirm there is no capability degradation.
    • Long-context recall: Needle-in-a-haystack, multi-hop retrieval.
    • System metrics: TTFT, TPOT, and GPU memory usage under different concurrency levels.
    • On-device metrics: Peak memory usage, time to first token, power consumption.

    6. Three Takeaways for Architecture Selection

    Reviewing how these recent small models are positioned, you can distill the selection logic:

    1. On-device/embedded → Small size + cross-layer KV sharing + sliding window. The goal is to “fit in a phone’s memory”, with quality yielding to usability.
    2. Efficient local inference (MoE) → Sparse activation reduces compute, but total parameter count stays the same, so memory pressure remains. It needs to be paired with KV compression.
    3. Quality first (Dense) → Dense structures offer more controllable post-training and a shorter tuning pipeline. They suit scenarios that need fine-grained alignment. The trade-off is higher inference cost.

    One point that is easy to overlook: MoE reduces compute, not memory usage. If your bottleneck is the KV Cache and weight loading, sparse experts won’t solve the problem automatically. You still need to work on KV compression.

    7. Summary

    The main thread of recent LLM architecture evolution is clear: use architecture-level techniques to make the KV Cache smaller. Cross-layer KV sharing is the most effective of these techniques for small models. It leverages the fact of inter-layer representational redundancy, trading minimal quality loss for multiples in memory savings.

    Actionable advice for developers:

    • Start with quantization and paged management. They are low-cost and deliver quick results.
    • For on-device models, prioritize the combination of cross-layer sharing + sliding window.
    • Decide the sharing topology during training. Don’t force architecture changes at inference time.
    • Evaluation must include long-context recall. Don’t draw wrong conclusions from perplexity alone.

    Memory is the hardest constraint in the era of long context. Whoever can compress the KV Cache further at the same quality level will have an advantage on the cost curve. This thread won’t change in the short term.