8 KV Cache Optimization Techniques: What an FDE Can Actually Change
Compare MQA, GQA, MLA, sliding windows, attention sinks, PagedAttention, prefix caching and FP8 KV caches. Work through memory math and a customer acceptance test.
BY LUKAS HOFFMANN · FDEINTERVIEWS EDITORIAL · UPDATED NOVEMBER 24, 2026 · 5 MIN READ
PRACTICE THIS:Practice KV-cache memory math ·Diagnose a long-context OOM ·Learn hardware-constrained deployment
KV-cache optimization starts by identifying which memory cost you can change. MQA, GQA and MLA change the model's representation. Sliding windows and attention sinks limit retained history. PagedAttention improves allocation. Prefix caching reuses work. KV quantization reduces precision. They solve different problems and have different failure modes.
For a forward deployed engineer, the decision starts with the customer's hardware, request lengths and required behavior. A contract assistant that must cite an exception on page two has different constraints from a streaming assistant answering questions about the latest event. Calculate the budget first, then test the smallest compatible change.
Start with bytes per live token
For conventional full-attention MHA, MQA or GQA layers, the raw cache estimate is:
bytes = 2 × layers × KV heads × head dimension × bytes per element × resident tokens
The factor two counts keys and values. Resident tokens include prompt and generated tokens across active sequences. Use KV heads, which can differ from query heads. This simplified calculation excludes allocator overhead, scales, workspaces and cross-request sharing; hybrid and MLA models need their actual layer layouts.
Run this dependency-free Python example:
def kv_gib(kv_heads, bytes_per_element, tokens, batch):
raw = 2 * 32 * kv_heads * 128 * bytes_per_element * tokens * batch
return raw / 2**30
for name, heads, size in [("MHA", 32, 2), ("GQA", 8, 2),
("MQA", 1, 2), ("GQA FP8", 8, 1)]:
print(name, kv_gib(heads, size, tokens=8192, batch=16))
The illustrative outputs are 64, 16, 2 and 8 GiB. These compare storage shapes, not measured quality or speed. Switching from the first row to the second requires suitable model weights. The KV-cache concept explains how those tensors are created during decoding.
Eight techniques, different costs
The diagram separates controls you can test on a compatible deployment from changes that require a different checkpoint. Its memory numbers are the synthetic calculation above.
| Technique | What changes | FDE check before choosing it |
|---|---|---|
| 1. Multi-query attention (MQA) | All query heads share one key/value head | Compare the actual checkpoint's task quality; head sharing changes the learned architecture. |
| 2. Grouped-query attention (GQA) | Groups of query heads share KV heads | Read num_key_value_heads; do not budget using query-head count. |
| 3. Multi-head latent attention (MLA) | Cache a compressed representation instead of all expanded K/V vectors | Use architecture-specific memory accounting and a compatible inference backend. |
| 4. Sliding-window attention | Local-attention layers retain a bounded recent window | Check for global layers and test evidence beyond the window. |
| 5. Attention sinks | Preserve initial tokens plus a recent window | Stable streaming does not mean arbitrary earlier facts remain accessible. |
| 6. PagedAttention | Allocate fixed-size blocks on demand | Measure fragmentation, active blocks and admitted work; raw bytes per KV value stay the same. |
| 7. Prefix caching | Reuse an identical previously computed prefix | Measure reused tokens, eviction and tenant isolation, alongside first-token latency. |
| 8. KV quantization | Store cache values at lower precision | Check supported hardware, scales, backend and task regressions. |
The MQA paper motivates reducing memory-bandwidth traffic during incremental decoding. GQA offers an intermediate sharing choice and describes checkpoint adaptation with additional training. Neither is a universal inference-time switch.
DeepSeek-V2's MLA needs another distinction: its compressed KV state is accompanied by positional key information. Optimized implementations can absorb projections into attention computation; budgeting a fully reconstructed K/V cache misses the design's purpose. Use the runtime's measured allocation for the model you actually deploy.
History removal changes the question you can answer
Mistral 7B describes an architecture trained with sliding-window attention. Arbitrarily evicting old tokens from a full-attention model is a different intervention. Hybrid models may combine local and global layers, so a window size alone does not determine total cache usage.
StreamingLLM retains initial attention-sink tokens along with recent tokens to stabilize streaming inference. Those initial tokens need not carry useful facts. Retaining them does not preserve the contents of every discarded middle turn.
For a maintenance assistant, plant an equipment revision in the first exchange and ask about it after enough turns to exceed the window. Then change that revision. Test whether the system uses current evidence, retrieves an authorized durable record or abstains. The agent-memory reference covers that application-level responsibility.
Allocation, reuse and precision need separate experiments
PagedAttention attacks fragmented allocation and redundant duplication. Its benefit depends on the workload and existing allocator. A server already using paged allocation cannot claim the same saving again by renaming the feature.
vLLM's prefix-caching documentation identifies repeated long documents and multi-turn chats as useful cases. Keep stable instructions and documents before the varying question. Reuse must respect the model, adapter, tokenization and security scope. A retained prefix also occupies memory: a high hit rate is not proof that the memory budget shrank.
For quantized KV caches, record the runtime version, attention backend and scale-calibration method. FP8 can increase token capacity, but actual latency depends on the supported kernels. Do not treat weight quantization as evidence that KV quantization is already enabled. The two have separate configurations and quality effects.
A customer acceptance test you can defend
Suppose a synthetic deployment reserves 12 GiB for KV state after weights, workspaces and operating reserve. The 16-sequence GQA workload above needs 16 GiB of raw cache, so it fails the budget even before allocation overhead. FP8's 8 GiB estimate makes it a candidate. It does not prove that the service is ready.
Freeze the request corpus, model revision and generation settings. Replay short and long prompts, short and long answers, repeated prefixes and unique prompts. Include the customer's concurrency pattern and a burst of unusually long requests. Change one supported setting at a time.
| Record | What a passing result must demonstrate |
|---|---|
| Peak memory on every device | Fits with agreed operating reserve, including runtime allocations |
| p50/p95 first-token and completion latency | Meets each target under the intended arrival pattern |
| Good tasks per second | Counts only correct, completed tasks that meet the latency target |
| Failures and preemptions | No hidden improvement from dropping or repeatedly restarting hard requests |
| Quality by slice | Preserves long-range evidence, exact identifiers and required citations |
| Reuse by tenant | No unauthorized shared state; measure cold and warm behavior separately |
Practice: FP8 improves average latency, but long-contract answers miss exception clauses. Would you ship? Hold the rollout. Compare identical cases at higher precision and inspect truncation, retrieval and cache configuration before assigning the cause to quantization. If a longer safe context or fallback is required, include its cost in the final capacity test.
Continue with long-context OOM triage and measuring the serving capacity knee. Bring a capacity table, a quality diff and a rollback configuration to the deployment review.
Turn it into offers. Work the real questions and concepts this maps to:
FAQ
It reduces allocation waste by managing KV state in blocks and can support sharing. It does not reduce the bytes needed to represent each stored key or value. Quantization and architectural changes address different parts of the memory budget.
GQA changes how query heads share key and value heads. Use a checkpoint trained or adapted for that architecture and a compatible runtime. Changing a serving configuration field does not convert arbitrary weights correctly.
A matching cached prefix saves repeated prefill work. It does not remove the attention reads and computation needed for each newly generated token. Measure first-token latency and generation speed separately.
FP8 halves raw key/value storage relative to 16-bit storage. Total GPU usage also includes weights, scales, runtime workspaces and other allocations. Test the supported backend and quality on your workload before increasing concurrency.
Discussion (3)
The allocation distinction matters: fewer reserved blocks and fewer bytes per value are different experiments. Record both live tokens and allocated cache blocks.
A cache-hit metric needs its denominator. Request hit rate and the fraction of prompt tokens reused answer different questions.
For a document assistant, include an early-page exception clause in the quality set. A short window can look excellent on recent-message questions and still fail that requirement.
