GO TO A SECTION

↑ ↓ to navigate · Enter to openExplore all sections →
FDEInterviews logo

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:

python
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

Choose the part of the budget you can changeMQA / GQA: Share KV heads. Example: MHA 64 GiB, GQA 16 GiB, MQA 2 GiB.. MLA: Store compressed latent state and positional key information. Use model-specific accounting.. Sliding window: Keep recent tokens in local layers. Test evidence outside the window.. Attention sinks: Keep initial + recent tokens. Discarded middle history is not durable memory.. PagedAttention: Allocate blocks on demand; reduce fragmentation. Same bytes per value.. Prefix reuse: Skip repeated prefill. Retained prefixes still consume cache space.. KV quantization: Example GQA: 16 GiB at 16-bit, 8 GiB at FP8. Recheck quality.. This is a classification, not a sequence of cumulative savings. Architecture, history retention and serving controls affect different terms. MQA and GQA count as two techniques; the other six are MLA, sliding window, attention sinks, paging, prefix reuse and quantization. Choose the part of the budget you can change Eight techniques address different costs. Validate model compatibility before combining them. CHECKPOINT AND ARCHITECTURE MQA / GQA Share KV heads. Example: MHA 64 GiB, GQA 16 GiB, MQA 2 GiB. MLA Store compressed latent state and positional key information. Use model-specific accounting. HISTORY YOU RETAIN Sliding window Keep recent tokens in local layers. Test evidence outside the window. Attention sinks Keep initial + recent tokens. Discarded middle history is not durable memory. COMPATIBLE SERVING CONTROLS PagedAttention Allocate blocks on demand; reduce fragmentation. Same bytes per value. Prefix reuse Skip repeated prefill. Retained prefixes still consume cache space. KV quantization Example GQA: 16 GiB at 16-bit, 8 GiB at FP8. Recheck quality. Raw KV storage only; weights, workspaces and allocation overhead excluded.

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.

TechniqueWhat changesFDE check before choosing it
1. Multi-query attention (MQA)All query heads share one key/value headCompare the actual checkpoint's task quality; head sharing changes the learned architecture.
2. Grouped-query attention (GQA)Groups of query heads share KV headsRead 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 vectorsUse architecture-specific memory accounting and a compatible inference backend.
4. Sliding-window attentionLocal-attention layers retain a bounded recent windowCheck for global layers and test evidence beyond the window.
5. Attention sinksPreserve initial tokens plus a recent windowStable streaming does not mean arbitrary earlier facts remain accessible.
6. PagedAttentionAllocate fixed-size blocks on demandMeasure fragmentation, active blocks and admitted work; raw bytes per KV value stay the same.
7. Prefix cachingReuse an identical previously computed prefixMeasure reused tokens, eviction and tenant isolation, alongside first-token latency.
8. KV quantizationStore cache values at lower precisionCheck 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.

RecordWhat a passing result must demonstrate
Peak memory on every deviceFits with agreed operating reserve, including runtime allocations
p50/p95 first-token and completion latencyMeets each target under the intended arrival pattern
Good tasks per secondCounts only correct, completed tasks that meet the latency target
Failures and preemptionsNo hidden improvement from dropping or repeatedly restarting hard requests
Quality by slicePreserves long-range evidence, exact identifiers and required citations
Reuse by tenantNo 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.

PRACTICE THIS

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.

Discussion (3)

Lukas HoffmannEditor

The allocation distinction matters: fewer reserved blocks and fewer bytes per value are different experiments. Record both live tokens and allocated cache blocks.

Emily CarterEditor

A cache-hit metric needs its denominator. Request hit rate and the fraction of prompt tokens reused answer different questions.

Arjun MehtaEditor

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.