KV Cache optimization compresses the K/V tensors cached per layer during autoregressive inference to break the memory wall of long contexts and large batches. Memory formula:
2×2×L×H×d×s×b bytes (K and V per token × 2 bytes for FP16 × layers × heads × head dim × sequence length × batch size). Four main lines: ① structural compression — GQA shares one KV head group across multiple Q heads (e.g. 64 → 8, memory /8); MLA (DeepSeek-V2) compresses each layer's K/V into a low-rank latent vector
ctKV=WDKVht, and at inference the
WUK projection is absorbed into
WQ and the output projection, caching only the latent — vs MHA's 86GB, KV memory drops to 5.1GB (−93.3%); ② KV quantization — storing K/V in INT8/FP8 halves memory with little accuracy loss; ③ StreamingLLM — keeping only the "attention sink" (first 4 tokens) plus a sliding window, so long-session memory drops from
O(s) to
O(window); ④ H2O sparsity — retaining only heavy-hitter tokens by cumulative attention score, with dynamic replacement.