# Deep Dive into KV Cache Engineering for Large Language Models

> This comprehensive guide explains why the KV cache grows during LLM inference and details 12 key optimization techniques including GQA, MQA, cross-layer attention, quantization, MLA, and more. Each method includes its core principle for saving memory or compute, practical trade-offs, and code examples to help you choose the best approach for your specific workload.

- Source: https://www.waytoagi.com/en/kb/learning-path/llm-kv-cache-engineering
- Original (Feishu, Chinese): https://waytoagi.feishu.cn/wiki/KjKIwbuVJiPbSgk3S5xcZCRonIc
- Updated: 2026-10-23

---

**English Translation:**

> 🔗 Original link: [KV Cache Engineering for LLM Serving, clearly explained](https://x.com/_avichawla/status/2096491130489872479)

> Avi Chawla · X · @_avichawla · 2026-09-06 14:50

> 📌 This article is reprinted. All copyrights belong to the original author. The full text is subject to the original link.

![](https://www.waytoagi.com/api/kb-media/Bjb1bf3xko3do3x162VctRz5nWd)

Everything you need to know: why the KV cache grows, 12 ways models and inference engines reduce it, what each technique actually saves, and the trade-offs for deciding which is right for your workload.

---

Loading an LLM is only the first part of GPU memory planning.

Model weights remain roughly fixed during inference. The KV cache does not. It grows with every token in the sequence, and by default, each active sequence needs its own cache.

For Llama 3.1 70B, a 128K-token sequence requires approximately 40 GB of BF16 KV cache. Four full-length sequences add an extra 160 GB — not including model weights or inference overhead.

![](https://www.waytoagi.com/api/kb-media/T3dhbytTLo97hPx44f3cRz2qnCb)

This creates two distinct costs. The cache occupies GPU memory, while the attention layers must repeatedly read it every time a new token is generated.

Techniques described as KV cache optimizations target different parts of this problem. Some change what the model stores. Some keep fewer tokens or use fewer bits. Others leave the logical cache unchanged and improve how the inference engine reads, allocates, shares, or moves it.

This article organizes the twelve techniques by what they reduce, when they can be applied, and the trade-offs they leave behind. Each section includes a runnable mini-example that explains the core idea.

---

# The Cache Formula

Each attention layer stores one key and one value for every token it retains.

The raw cache size for a sequence is:

![](https://www.waytoagi.com/api/kb-media/Wh0RbHGwVotILgx89NicXrksnrH)

The leading 2 accounts for keys and values. BF16 uses two bytes per value, while FP8 uses one.

This formula also gives us a clear way to group the techniques:

- GQA and MQA reduce the number of KV heads.
- Cross-layer attention reduces the number of unique cached layers.
- Sliding window and eviction reduce the number of tokens retained.
- MLA reduces the width of the stored representation.
- Quantization reduces the number of bytes per value.
- Hybrid recurrent layers replace the ever-growing cache with a fixed-size state.
- Paging and prefix reuse reduce allocation waste and duplicate blocks.

Sparse attention deserves a separate note. It may read fewer tokens without removing them from memory, so it can reduce attention computation without changing cache capacity.

This distinction matters when the GPU is full. A faster attention kernel does not free space for another sequence unless it also stores fewer bytes.

---

# Technique Map

The chart below brings all 12 techniques together, showing what each one changes and whether its primary savings come from fewer heads, layers, tokens, dimensions, bits, or duplicate memory.

The table above represents the problem each technique is trying to solve.

The quadrant diagram below selects six representative techniques and reorganizes them by whether they reduce cache memory, attention computation, or both. The full set remains in the table above.

![](https://www.waytoagi.com/api/kb-media/Yp8pbLNzOoMERWxFoC2cMyoDnj1)

The rest of this article walks through the complete table in order.

---

**1. GQA and MQA (Grouped Query Attention and Multi-Query Attention): Caching Fewer Heads**

The cache formula above includes a term for the number of KV heads. Reducing this term is one of the largest architectural savings available.

Inside each transformer layer, every token produces three representations:

![](https://www.waytoagi.com/api/kb-media/D1HVbPCHkoYx4oxgwmTcVqTznFf)

- The **Query** represents what the current token is looking for.
- The **Key** describes what each earlier token has to offer for matching.
- The **Value** carries the information that is returned when a match receives attention.

During generation, the current token’s query is compared against the cached keys.

Attention splits these representations into smaller pieces called **heads**.

A query head is a slice of the token’s query representation. It is not the user’s prompt or an individual model request. Different heads can learn to attend to different relationships within the same sequence.

![](https://www.waytoagi.com/api/kb-media/IDHtboe4PofNVSxeqArcpMhbnAb)

- **Standard Multi-Head Attention (MHA)** provides each query head with its own matching key head and value head. Therefore, a layer with eight query heads produces eight key heads and eight value heads. Each attention layer performs this projection independently and maintains its own KV cache.
- **Multi-Query Attention (MQA)** keeps all eight query heads but produces only one key head and one value head. Every query head reads from this single shared KV pair. This sharing does not extend across transformer layers.
- **Grouped Query Attention (GQA)** sits between these two layouts. It divides the query heads into groups and assigns one KV pair to each group. With eight query heads and two KV heads, four query heads share each KV pair.

All three approaches operate entirely within each individual attention layer. They differ only in the number of KV heads stored by that layer. Cross-layer attention, which will be introduced next, is a separate concept that shares cache information *between* layers.

The GQA paper describes it as a sweet spot between MHA and MQA.

The authors converted existing MHA checkpoints and performed recovery training using only 5% of the original pre-training compute. The resulting GQA models came very close to MHA in quality while approaching the speed of MQA.

The following example uses eight query heads and shows which KV head each query head reads from, along with the total number of cached scalar values for six tokens:

```python
query_heads = 8
tokens = 6
head_size = 8

for name, kv_heads in [("MHA", 8), ("GQA", 2), ("MQA", 1)]:
    queries_per_kv_head = query_heads // kv_heads
    mapping = [head // queries_per_kv_head for head in range(query_heads)]
    cached_scalars = 2 * kv_heads * tokens * head_size

    print(name, "mapping:", mapping)
    print(name, "cached scalars:", cached_scalars)


# Output:
"""
MHA mapping: [0, 1, 2, 3, 4, 5, 6, 7]
MHA cached scalars: 768
GQA mapping: [0, 0, 0, 0, 1, 1, 1, 1]
GQA cached scalars: 192
MQA mapping: [0, 0, 0, 0, 0, 0, 0, 0]
MQA cached scalars: 96
"""
```

The mapping table lists a KV head index for each query head. MHA uses a different KV head every time. GQA makes query heads 0–3 share KV head 0, and query heads 4–7 share KV head 1. MQA maps every query head to KV head 0.

The cache count includes both keys and values, then multiplies by the number of tokens (six) and the number of scalars per head (eight).

Llama 3.1 70B uses 64 query heads and 8 KV heads. At a 128K context length, this results in a 40GB BF16 cache, whereas the same shape with 64 KV heads would require 320GB.

This code demonstrates the storage scaling. It does not test quality, because head sharing changes what the model learns and must be evaluated after training.

## 2. Cross-layer Attention (Cross-layer Attention)

GQA shares keys and values across heads within a single layer. Cross-layer attention, on the other hand, shares them between adjacent layers.

![](https://www.waytoagi.com/api/kb-media/Z2nHbCjtko1AFlxSqbAcMUp1n3r)

Therefore, a sharing factor of 2 means that two attention layers use a single set of shared cache keys and values. The model now stores only half as many independent per-layer caches.

The Cross-Layer Attention (CLA) paper trained 1B and 3B models and reported an additional 2× reduction in KV cache size while maintaining accuracy close to the MQA baseline.

The following script demonstrates two layers sharing one cache allocation:

```python
tokens = 32
kv_heads = 2
head_size = 8

one_layer_cache = 2 * tokens * kv_heads * head_size
shared_cache = {"stored_scalars": one_layer_cache}
layer_caches = [shared_cache, shared_cache]

separate_total = 2 * one_layer_cache
shared_total = shared_cache["stored_scalars"]

print("layers point to same cache:", layer_caches[0] is layer_caches[1])
print("two separate layer caches:", separate_total, "scalars")
print("one shared layer cache:", shared_total, "scalars")


# Output:
"""
layers point to same cache: True
two separate layer caches: 2048 scalars
one shared layer cache: 1024 scalars
"""
```

Here, one layer stores 1024 scalars. The leading factor of 2 accounts for keys and values. Two separate layers would therefore store 2048 scalars.

The two elements in `layer_caches` point to the exact same Python object. Even though two logical layers are using it, the physical storage remains only 1024 scalars.

Cross-layer sharing is orthogonal to GQA because they reduce different dimensions. GQA reduces the number of KV heads stored per layer. CLA reduces the number of distinct layer caches stored across the entire model.

Standard checkpoints learn independent KV projections for each layer. Each layer expects to use a cache created by its own weights. Redirecting it to another layer’s cache would alter the model’s computation.

CLA models are trained with the sharing pattern from the start. Training allows every dependent layer to adapt to the shared cache. The serving engine must then reproduce the exact same ownership pattern.

The checkpoint and the engine must agree on which layer owns which cache. This is why CLA cannot be enabled as a generic runtime flag.

## 3. Sliding Windows (Sliding Windows)

CLA reduces the amount of cache required in the storage layer. Sliding window attention further reduces the number of tokens that need to be stored within selected layers.

In full self-attention, every new token can attend to all earlier tokens. Therefore, each attention layer must retain the keys and values for the entire sequence. As the sequence grows, the KV cache in every layer grows accordingly.

![](https://www.waytoagi.com/api/kb-media/ENocbliCnoMB9FxhN1QcW1PmnId)

Sliding window attention restricts a layer to only attend to the most recent tokens. Suppose the window contains 1024 positions. This layer only stores KV entries for the most recent 1024 tokens. Once the window is full, each new entry removes the oldest one. Its cache then remains fixed at 1024 positions.

We call these **local layers** because they only see nearby context. **Global layers** can still attend to all earlier tokens. Their cache continues to grow until the end of the sequence.

Many models mix both types of layers. The local layers provide the majority of the memory savings. The occasional global layers preserve access to distant parts of the prompt. The total cache still grows, but much more slowly than if full attention were used everywhere.

For example, Gemma 3 uses a repeating pattern of five local layers followed by one global layer. Its local window is 1024 tokens, while the global layers support the full 128K context:

![](https://www.waytoagi.com/api/kb-media/EKLibXm88ormBIxhGaDclftyn5c)

The following example tracks the positions retained by a four-token window:

```python
window_size = 4
retained_positions = []

for position in range(10):
    retained_positions.append(position)

    if len(retained_positions) > window_size:
        retained_positions.pop(0)

    print(f"after token {position}: {retained_positions}")

print("maximum retained positions:", window_size)


# Output:
"""
after token 0: [0]
after token 1: [0, 1]
after token 2: [0, 1, 2]
after token 3: [0, 1, 2, 3]
after token 4: [1, 2, 3, 4]
after token 5: [2, 3, 4, 5]
after token 6: [3, 4, 5, 6]
after token 7: [4, 5, 6, 7]
after token 8: [5, 6, 7, 8]
after token 9: [6, 7, 8, 9]
maximum retained positions: 4
"""
```

The list is sequentially filled with positions 0 through 3. When position 4 arrives, the list becomes too long. Removing the first element discards position 0.

The same steps repeat for every subsequent token. Production inference engines typically use a circular buffer, which overwrites old slots without moving the remaining entries.

The first four tokens fill all available slots. Token 4 then evicts token 0, and the window slides to positions 1–4. Each subsequent token shifts this range forward by one. After token 9, only positions 6–9 remain. The allocated memory stays fixed at four slots throughout the entire process.

The savings also scale with context length. Below 1024 tokens, both layouts retain the same number of positions. Savings only appear once the sequence exceeds the local window size.

## 4. Multi-head Latent Attention (MLA)

Multi-head Latent Attention, or MLA, does not cache the full key and value vectors for each head. Instead, it compresses the hidden states into a much smaller latent representation and stores only that representation.

During decoding, the model uses learned projections to recover the information needed for attention.

The implementation can fold portions of these projections into the query and output pathways, avoiding the need to reconstruct the full KV tensors in memory.

DeepSeek-V2 introduced this design. The paper reports that, compared with the DeepSeek 67B model, the KV cache is reduced by 93.3% and the maximum generation throughput is improved by 5.76×:

![](https://www.waytoagi.com/api/kb-media/KIL5bUKVroRvllxsZj2cgkL0nlc)

In a real MLA layer, learned matrices are used to create and consume the latent representations. These matrix operations obscure the underlying memory difference in small examples.

The following example calculates storage for a single token. The dimensions are deliberately kept very small so the difference between the two layouts is clearly visible.

```python
kv_heads = 4
head_size = 8

standard_keys = kv_heads * head_size
standard_values = kv_heads * head_size
standard_total = standard_keys + standard_values

mla_latent = 8
mla_rotary_key = 4
mla_total = mla_latent + mla_rotary_key

print("standard cache:", standard_keys, "key +", standard_values, "value")
print("MLA cache:", mla_latent, "latent +", mla_rotary_key, "rotary key")
print("stored scalars per token:", standard_total, "->", mla_total)
print(f"example reduction: {standard_total / mla_total:.2f}x")


# Output:
"""
standard cache: 32 key + 32 value
MLA cache: 8 latent + 4 rotary key
stored scalars per token: 64 -> 12
example reduction: 5.33x
"""
```

Four KV heads, each with eight scalars, produce 32 key scalars. Values require another 32. Therefore, standard attention stores 64 scalars per token.

The illustrative MLA layout stores eight latent scalars and four positional (rotary) scalars, for a total of 12. Dividing 64 by 12 yields the example reduction ratio.

The 5.33× figure applies only to this toy example. A real MLA model chooses different latent and positional dimensions.

MLA is not an inference-time flag that can be applied to standard checkpoints. Its projection weights and cache layout are part of the trained model. Converting other models still requires training.

---

**5. Replace growing cache with fixed state using Hybrid models（Using Hybrid Models to Replace Growing Cache with Fixed State）**

Mamba and recurrent linear attention layers do not store a key and value for every previous token. Instead, they update a fixed-size state as the sequence grows.

![](https://www.waytoagi.com/api/kb-media/OgK3bRU4Eo1PR7xa1Sbc7vFUnfN)

Pure recurrent models keep memory almost constant as context grows, but full attention still performs better at precise retrieval in many scenarios. Recent models combine both approaches.

Qwen3-Next has 48 layers, arranged as 12 repeated blocks. Each block contains three Gated DeltaNet layers and one full attention layer. Only these 12 full attention layers create the standard growing KV cache.

The model card reports that these attention layers have 16 query heads, 2 KV heads, and a head dimension of 256.

The following example compares their memory growth. The attention layers store a 64-value key and value per token. The recurrent layers maintain a fixed 64×64 state.

```python
width = 64
bytes_per_value = 4

attention_values_per_token = 2 * width
recurrent_state_values = width * width

for tokens in [128, 4096]:
    attention_kb = tokens * attention_values_per_token * bytes_per_value // 1024
    recurrent_kb = recurrent_state_values * bytes_per_value // 1024

    print(f"{tokens} tokens")
    print("  attention KV:", attention_kb, "KB")
    print("  recurrent state:", recurrent_kb, "KB")


# Output:
"""
128 tokens
  attention KV: 64 KB
  recurrent state: 16 KB
4096 tokens
  attention KV: 2048 KB
  recurrent state: 16 KB
"""
```

Attention computation multiplies the per-token storage by the sequence length. Recurrent computation has nothing to do with individual tokens — its state size remains the same in both cases.

This example only tracks memory. It does not implement Mamba or Gated DeltaNet. Those architectures use learned update rules to decide what information the fixed state should retain.

The attention cache grows 32× between the two sequence lengths, while the recurrent state stays at 16 KB. Hybrid models only incur linear cache growth in their full attention layers.

For Qwen3-Next’s attention configuration, the 12 full attention layers require 3 GB of BF16 KV cache at 128K context.

If all 48 layers were full attention, the growing portion would increase to 12 GB.

Jamba follows the same design philosophy with different ratios. It interleaves one attention layer with seven Mamba layers. In the Jamba paper, at 256K context the KV cache is reported as 4 GB, compared to 32 GB for Mixtral.

![](https://www.waytoagi.com/api/kb-media/JiUFbVRwYolYkCxbGUzcx4dvnxh)

This layout is baked into the trained model. A serving engine cannot arbitrarily replace any attention layer with a recurrent layer at runtime.

**6. Compressed Sparse Attention (Compressed Sparse Attention)**

Full attention performs two very expensive operations. It stores a separate KV entry for every earlier token, and then reads all stored entries when generating the next token.

Sparse attention only changes the second part.

It reads fewer entries for each new token, but may still keep the full cache in memory. This can accelerate generation without reducing the resident KV cache size.

**Compressed sparse attention** optimizes both parts simultaneously.

![](https://www.waytoagi.com/api/kb-media/NpT6bzgWcof73xxSjjBc6M6Xnec)

- First, it merges several adjacent token entries into one compressed entry. Instead of storing a long-distance entry for every token, it stores this much shorter sequence.

- Then, for each new token, a selector picks only the compressed entries that appear most relevant. Attention is performed only on this selected subset.

DeepSeek V4 adopts this design.

If the compression factor is *m*, every *m* token entries are merged into one stored entry. Thus, a context of *n* tokens produces roughly *n / m* compressed entries.

The model then selects *k* of these entries for attention. A small sliding window is kept for the most recent tokens to preserve fine-grained local details.

At one million tokens, DeepSeek reports that V4-Pro uses only **10%** of the KV cache and **27%** of the per-token inference FLOPs required by DeepSeek V3.2. V4-Flash goes even further, reducing the cache to **7%** and FLOPs to **10%**.

These figures are for the overall model. They incorporate V4’s hybrid attention layout and precision choices, and should not be interpreted as the gains produced by the compression technique alone.

The next module separates the two reductions. It compresses 32 long-range entries by grouping every four together, leaving 8 stored entries. If attention selects 2 out of these 8, it only reads 2 compressed entries in this step.

```python
full_token_entries = 32
tokens_per_group = 4
selected_entries = 2

compressed_entries = full_token_entries // tokens_per_group

print("full token entries:", full_token_entries)
print("compressed entries stored:", compressed_entries)
print("compressed entries read:", selected_entries)
print("storage reduction:", f"{full_token_entries / compressed_entries:.0f}x")


# Output:
"""
full token entries: 32
compressed entries stored: 8
compressed entries read: 2
storage reduction: 4x
"""
```

Dividing 32 tokens into groups of four produces 8 compressed entries. This is the storage reduction. Selecting 2 out of those 8 is a separate reduction in attention work.

The cache now holds 8 long-range entries instead of 32. Attention reads only 2 of them. A small local window separately preserves fine details for the most recent tokens.

This technique must be built into the model and the training process. A serving engine cannot turn an existing full-attention model into compressed sparse attention simply by changing cache settings.

## 7. Query-aware Sparse Reads (Query-Aware Sparse Reads)

The previous techniques reduce both storage and attention work at the same time.

Sometimes, changing the model architecture is not an option. We may still want to reduce the amount of cache read during each decoding step.

Recall what happens when the model generates a token. A new token produces a query, which acts like a search signal. Full attention compares it with every stored key. As a result, long prompts force the GPU to repeatedly load a large amount of cache.

Quest is a technique that reduces these reads without deleting any KV entries.

- It divides the cache into pages.
- A page is a small group of adjacent token entries.
- Each page also stores the minimum and maximum key values it contains.

For each new query, Quest first scores these short page summaries. It then loads only the highest-scoring pages. The complete cache is still retained, because pages that are currently ignored may become important in later steps.

![](https://www.waytoagi.com/api/kb-media/Qt1HbY49eouay1xFH4ocTzrTnbc)

The Quest paper reports that its self-attention latency is reduced by up to 7.03×. Its full inference system achieves up to 2.23× speedup.

The example below uses four pages. Each page contains two keys. Here each key consists of only two numbers to make the scoring process clearly visible.

```python
import numpy as np

pages = np.array([
    [[1, 0], [2, 1]],
    [[5, 1], [4, 2]],
    [[0, 6], [1, 5]],
    [[-2, -1], [-1, 0]],
])
query = np.array([1.0, 0.5])

page_min = pages.min(axis=1)
page_max = pages.max(axis=1)
page_scores = np.maximum(query * page_min, query * page_max).sum(axis=1)
selected_pages = np.argsort(page_scores)[-2:]

for page, score in enumerate(page_scores):
    print(f"page {page} score: {score:.1f}")

print("selected pages:", np.sort(selected_pages).tolist())
print("KV entries read:", len(selected_pages) * 2, "of", pages.size // 2)
print("KV entries still stored:", pages.size // 2)


# Output:
"""
page 0 score: 2.5
page 1 score: 6.0
page 2 score: 4.0
page 3 score: -1.0
selected pages: [1, 2]
KV entries read: 4 of 8
KV entries still stored: 8
"""
```

The `pages` array contains a total of eight keys. The next two lines of code create a minimum summary and a maximum summary for each page. Quest uses similar summaries to estimate the best possible attention score a page might achieve.

This query prefers larger values in both key dimensions. Pages 1 and 2 receive the highest scores, so the example reads their four keys. In this step, the other four keys remain untouched.

If you look at the last line, this step reads four entries, but all eight entries still reside in memory. Quest reduces cache traffic and attention computation, but it does not reduce the memory required to hold the full cache.

In real applications, Quest uses multi-dimensional keys and specialized GPU code. It also repeats the selection process for every query.

---

**8. Quantization**

Quest retains every KV entry but skips some of the reads. Quantization takes a different path: it keeps all entries but stores each number with fewer bits.

Keys and values are typically stored as floating-point numbers. BF16 uses 16 bits per number. FP8 uses 8 bits, so its raw data size is roughly half that of BF16. A 4-bit format reduces the data size to 25% of the original.

Quantization maps a large set of original numbers onto a much smaller set of allowed values. A scaling factor controls the spacing between these values. The engine stores compact integer codes along with enough scaling information to interpret them later.

The choice of scaling factor directly affects precision. An extreme value can make the shared scaling factor too wide, causing most normal values to be excessively rounded.

KIVI handles keys and values differently. It groups keys by channel (i.e., grouping the same feature across tokens) and groups values by token. The KIVI paper reports that its 2-bit cache reduces peak memory usage by 2.6× while supporting up to 4× larger batch sizes.

![](https://www.waytoagi.com/api/kb-media/JxDxb48gioiqyBxKNS4cZds8nVa)

The small example below demonstrates the basic mapping process. It converts six BF16-style values into signed 4-bit codes, then converts those codes back into approximate values.

```python
import numpy as np

values = np.array([-1.0, -0.55, -0.10, 0.25, 0.60, 1.0])
bits = 4
largest_code = 2 ** (bits - 1) - 1
scale = np.max(np.abs(values)) / largest_code

codes = np.rint(values / scale)
codes = np.clip(codes, -largest_code, largest_code).astype(np.int8)
restored = codes * scale

print("original values:", values.tolist())
print("4-bit codes:", codes.tolist())
print("restored values:", np.round(restored, 3).tolist())
print("raw payload:", len(values) * 16, "bits ->", len(values) * 4, "bits")


# Output:
"""
original values: [-1.0, -0.55, -0.1, 0.25, 0.6, 1.0]
4-bit codes: [-7, -4, -1, 2, 4, 7]
restored values: [-1.0, -0.571, -0.143, 0.286, 0.571, 1.0]
raw payload: 96 bits -> 24 bits
"""
```

In this example, signed 4-bit storage provides a code range from -7 to 7. Each original value is divided by the scaling factor to map it to a code. Multiplying by the same scaling factor yields the approximate value used in attention computation.

You may have noticed that the restored values are close but not identical. These rounding differences are quantization error. The last line only counts the six stored values. A real cache would also store scaling metadata.

This example uses a single scaling factor for all six values. KIVI uses smaller groups because each group can adapt to its own numerical range. This typically reduces rounding error, although it requires more scaling metadata.

If you are using vLLM, it can directly expose FP8 KV cache storage:

```bash
MODEL_ID=Qwen/Qwen2.5-7B-Instruct
vllm serve "$MODEL_ID" --kv-cache-dtype fp8
```

The first line defines the model name. The second line starts a vLLM server and instructs it to store the KV cache in FP8 format. This command will keep running because it launches an inference server.

Newer versions of vLLM also allow selected layers to retain their native data types. This is useful when sliding window layers are shown to be more sensitive:

```bash
MODEL_ID=google/gemma-3-4b-it
vllm serve "$MODEL_ID" \
  --kv-cache-dtype fp8 \
  --kv-cache-dtype-skip-layers sliding_window
```

This version keeps the sliding window layers in their original format and quantizes the remaining cache layers. The option is helpful when those local attention layers lose too much precision under FP8.

Quantization preserves every token position. The next technique reduces memory by removing positions entirely.

---

## 9. Eviction

Quantization retains all token positions. For long contexts, this may still be too large. Eviction strategies set a fixed position budget and discard entries that exceed that budget.

The hard question is which positions should not be evicted. Recent tokens are usually important because they contain the current conversation. Older tokens may still carry instructions, facts, or tool results needed later.

H2O is a technique that retains both the most recent positions and earlier heavy hitters. Heavy hitters are tokens that have accumulated high attention scores in earlier steps. Once H2O evicts another token, its KV entry is no longer available.

![](https://www.waytoagi.com/api/kb-media/EVvfbQdsSoUxkcxGLMUcGAeOnGh)

Other methods estimate importance in different ways. SnapKV examines the attention near the end of the input prompt. It uses this observation window to select prompt positions before generation begins.

![](https://www.waytoagi.com/api/kb-media/YCisbxAoOo0ckPx11KVcAX7JnWf)

Based on the attention patterns reported by its authors, PyramidKV allocates larger budgets to lower layers and smaller budgets to higher layers.

![](https://www.waytoagi.com/api/kb-media/PK4zbeAEro6STNxx5pJcwP5HnJ5)

According to its authors, SnapKV achieves 8.2× higher memory efficiency and 3.6× faster generation with 16K token inputs. PyramidKV reports that retaining just 12% of the cache is sufficient to match full-cache performance on its LongBench experiments.

The example below takes a snapshot after ten tokens. Their scores represent the attention accumulated during the early decoding steps. The cache can only keep six positions, including the two most recent ones.

```python
scores = [9.0, 0.2, 4.0, 0.1, 0.3, 6.0, 0.2, 0.4, 0.1, 0.2]
budget = 6
recent_count = 2

positions = list(range(len(scores)))
recent = positions[-recent_count:]
older = positions[:-recent_count]

heavy_hitter_count = budget - recent_count
heavy_hitters = sorted(
    older,
    key=lambda position: scores[position],
    reverse=True,
)[:heavy_hitter_count]

retained = sorted(heavy_hitters + recent)

print("heavy hitters:", sorted(heavy_hitters))
print("recent positions:", recent)
print("retained positions:", retained)
print("cache entries:", len(retained), "of", len(scores))


# Output:
"""
heavy hitters: [0, 2, 5, 7]
recent positions: [8, 9]
retained positions: [0, 2, 5, 7, 8, 9]
cache entries: 6 of 10
"""
```

Positions 8 and 9 are kept because they are the most recent. There are four remaining slots. Sorting selects positions 0, 2, 5, and 7 because they have the largest scores among the older tokens.

The union of these two sets forms the final six-position cache. Positions 1, 3, 4, and 6 are discarded.

Real H2O implementations update their heavy-hitter statistics throughout the generation process. This smaller example starts from already-accumulated scores so that the selection rule remains clearly visible.

That said, eviction strategies require careful evaluation. Importance can shift across conversation turns. A tool result that receives little attention now may become essential after multiple calls. System instructions and delimiters can also carry disproportionate importance.

![](https://www.waytoagi.com/api/kb-media/M1dUb5Qazoq4L0xuFnBcMb30nNe)

Therefore, evaluation of eviction strategies should use complete AI agent trajectories and delayed references. They should also include structured prompts. A good “needle-in-a-haystack” score does not cover these scenarios.

---

## 10. Paging

So far, we have explored what a single request stores or reads. Paging solves a different problem: how the serving engine allocates cache memory across multiple requests.

A simple allocator might reserve one contiguous memory region for each request. It typically reserves enough space for the request’s maximum possible length. Shorter requests leave part of the region unused. As requests complete, the free space also becomes fragmented.

![](https://www.waytoagi.com/api/kb-media/M48zbC3rlodpj4x2moocP0ucnBg)

PagedAttention divides GPU cache memory into blocks of equal size. Each block holds KV entries for a fixed number of tokens. A request can use blocks from anywhere in the shared pool, so its blocks do not need to be adjacent to each other.

When a request finishes, the allocator returns its blocks to the pool. Another request can reuse them immediately. The PagedAttention paper reports that, compared with the systems they tested, KV cache waste is close to zero and throughput improves by 2 to 4 times.

![](https://www.waytoagi.com/api/kb-media/WvjFb5IVUoiQEQx4MmHcplCinOd)

A fixed-size pool can mask the effects of quantization. The engine may reserve the same 8 GB of memory both before and after enabling FP8. Smaller entries simply allow more tokens to fit inside that pool. The allocated memory shown by nvidia-smi may remain unchanged.

The example below starts with six free blocks. Request A takes three blocks, and Request B takes two blocks. Then A completes and returns its blocks, after which Request C arrives.

```python
free_blocks = [0, 1, 2, 3, 4, 5]

request_a = free_blocks[:3]
free_blocks = free_blocks[3:]

request_b = free_blocks[:2]
free_blocks = free_blocks[2:]

free_blocks.extend(request_a)
free_after_a = free_blocks.copy()
request_c = free_blocks[:2]
free_blocks = free_blocks[2:]

print("request A blocks:", request_a)
print("request B blocks:", request_b)
print("free after A finishes:", free_after_a)
print("request C blocks:", request_c)


# Output:
"""
request A blocks: [0, 1, 2]
request B blocks: [3, 4]
free after A finishes: [5, 0, 1, 2]
request C blocks: [5, 0]
"""
```

After A finishes, the free pool contains block 5 and the blocks returned by A. Request C takes block 5 and block 0. These block numbers are not contiguous, but the block table records the order in which they belong to C.

This is the core idea of paging. The allocator reuses whatever blocks are available instead of searching for one large contiguous region.

vLLM also tracks which blocks each request owns. Its attention code can read non-contiguous blocks in logical order. This short example isolates the allocation and reuse logic.

Quantization still changes the capacity inside that pool. An 8 GB pool can hold 26,214 tokens at 320 KB per token, compared with 52,428 tokens at 160 KB per token. In both cases, the total allocated GPU memory remains 8 GB.

---

**11. Prefix Reuse (Prefix Reuse)**

After a request completes, paging reuses its blocks. Prefix caching allows blocks to be shared while multiple requests are still active. It works when these requests begin with exactly the same tokens.

This is very common with system prompts and tool definitions. Without prefix caching, the engine computes and stores another copy of the KV cache for every request. Repeated prefixes waste memory and redundantly repeat the prefill work required to produce them.

![](https://www.waytoagi.com/api/kb-media/XJ1Bb6FEjoL9K3xCOSPc8ynqn1d)

Automatic prefix caching stores each completed prefix block under a lookup key. When another request arrives with the same token prefix, it points to the existing KV blocks. New computation only begins after the point where the request diverges.

vLLM builds each lookup key from the current block and all blocks preceding it. When details such as adapter IDs affect compatibility, they are also included. The structure is documented in vLLM’s prefix caching design document.

The example below uses blocks of four tokens. Each lookup key contains the entire prefix up to that block. It serves as a readable alternative to vLLM’s chained hashing approach.

```python
def prefix_keys(tokens, block_size):
    block_ends = range(block_size, len(tokens) + 1, block_size)
    return [tuple(tokens[:end]) for end in block_ends]

first = [10, 11, 12, 13, 20, 21, 22, 23, 30, 31, 32, 33]
second = [10, 11, 12, 13, 20, 21, 22, 23, 40, 41, 42, 43]

cache = set()
first_keys = prefix_keys(first, block_size=4)
first_hits = sum(key in cache for key in first_keys)
cache.update(first_keys)

second_keys = prefix_keys(second, block_size=4)
second_hits = sum(key in cache for key in second_keys)

print("first request reused:", first_hits, "of", len(first_keys), "blocks")
print("second request reused:", second_hits, "of", len(second_keys), "blocks")
print("second request computes:", len(second_keys) - second_hits, "new block")


# Output:
"""
first request reused: 0 of 3 blocks
second request reused: 2 of 3 blocks
second request computes: 1 new block
"""
```

The first request has no cache entries to reuse. It adds keys for the first four, eight, and twelve tokens. The second request shares the same first eight tokens, so its first two keys match.

The final four tokens differ. This changes the last prefix key, so the second request must compute one new block.

Using the full prefix prevents false matches. Two requests cannot reuse the same block simply because four tokens match somewhere in the middle. The preceding context must also match.

Prefix reuse depends on an exact tokenized prefix. Timestamps in system prompts, reordered JSON keys in tool schemas, or different whitespace from chat templates can all break the match.

Therefore, using stable prompt templates can significantly improve hit rates. The model and cache format remain unchanged, while duplicate storage is reduced.

## 12. Cache Offloading from GPU

Prefix reuse helps when another request starts with tokens the engine has already processed. Offloading addresses a different problem. It moves KV blocks that are not currently needed from GPU memory to a larger but slower memory tier, typically CPU memory.

These blocks may belong to sequences paused by the scheduler, or they may be retained cache prefixes reserved for future reuse. When the engine needs them again, it copies them back to the GPU.

![](https://www.waytoagi.com/api/kb-media/KyZAbk7zgomqcHxbljBc4PcNnof)

There is an important limitation. New OpenAI-compatible API requests do **not** automatically restore KV caches from earlier requests. Reuse only occurs if the engine is still tracking the sequence, can identify an exact prefix cache match, or restores the cache through an external storage system.

Offloading frees up GPU memory without deleting the stored KV data. It does not reduce the total number of bytes held across GPU and CPU memory. The trade-off appears when the engine must transfer these blocks back before computation can continue.

The example below gives the GPU space for two sessions. Adding session C moves the oldest session A to CPU memory. Restoring A brings it back and evicts B.

```python
gpu_cache = ["cache-a", "cache-b"]
cpu_cache = []


# Cache C needs GPU space, so cache A moves to CPU memory.
cpu_cache.append(gpu_cache.pop(0))
gpu_cache.append("cache-c")

print("GPU after cache C arrives:", gpu_cache)
print("CPU after cache C arrives:", cpu_cache)


# Cache A is needed again, so it returns to the GPU.
cpu_cache.remove("cache-a")
cpu_cache.append(gpu_cache.pop(0))
gpu_cache.append("cache-a")

print("GPU after cache A returns:", gpu_cache)
print("CPU after cache A returns:", cpu_cache)


# Output:
"""
GPU after cache C arrives: ['cache-b', 'cache-c']
CPU after cache C arrives: ['cache-a']
GPU after cache A returns: ['cache-c', 'cache-a']
CPU after cache A returns: ['cache-b']
"""
```

The first move keeps caches B and C on the GPU while cache A remains available in CPU memory. When cache A is needed again, the example brings it back and evicts cache B.

The lists contain cache names rather than tensors. A real engine performs this operation on KV blocks and tracks which request or reusable prefix each block belongs to.

The example assumes the engine has retained enough information to recognize cache A later. Sending an unrelated API request with the same label will not automatically restore it.

vLLM can directly enable a 16 GB CPU offloading buffer with the following command:

```bash
MODEL_ID=Qwen/Qwen2.5-7B-Instruct

vllm serve "$MODEL_ID" \
  --kv-offloading-size 16 \
  --kv-offloading-backend native
```

The first option sets the CPU buffer size in GB. The second selects vLLM’s native CPU backend. Like the previous serve commands, this process remains running after startup.

Offloading trades GPU capacity for transfer time. Before enabling a large offload layer, measure recovery latency and CPU bandwidth.

# How to Use Them Together

Some of these methods can be combined because they reduce different factors. Architecture-level approaches still depend on how the checkpoint was trained.

For example, take the 40 GB GQA cache from the first example.

![](https://www.waytoagi.com/api/kb-media/QMmzbQPszok0x4xHr6Jc8y5GnWg)

- CLA2 can halve the number of unique layers, reducing it to 20 GB.
- FP8 can halve the number of bytes per value, bringing it down to approximately 10 GB.
- A 50% token budget can further reduce the resident cache to about 5 GB.

This multiplication is useful for capacity planning, but it obscures the impact on model quality and kernel support.

- CLA requires training.
- FP8 introduces quantization error.
- Eviction discards context.
- And the serving engine must also support the resulting layout.

Here are some situations you may encounter along with recommended solutions:

- When choosing a model → Check the number of KV heads, the ratio of local to global layers, the potential attention dimension, and the recurrent layers. These determine the starting cache size before deployment.
- When serving an existing model → Test FP8 first, then standardize prefixes. Both preserve the token set unchanged. Only add eviction policies after thorough quality testing on your specific workload.
- When memory usage appears unchanged → Check the cache capacity and number of blocks. A fixed pool may absorb the memory savings while the total allocated GPU memory stays the same.
- When latency becomes an issue → Measure cache read time and attention time. Quest-style sparse reads can still help even if they don’t free up capacity.
- When inactive sessions occupy GPU memory → Test offloading and scheduling. Moving cold blocks may be more important than further compressing active blocks.

---

Once each technique has a clear objective, KV cache reduction becomes much easier to understand.

The table below summarizes all the techniques we covered, what they change, the key takeaways, and what they do not address:

Start from the constraint you need to resolve, then choose the technique that targets that constraint.

👉 Your turn: How do you reduce KV cache in production?
