Pidoku

More Than One Kind of Cache

Module 17 Lesson 17.i 45 min Difficulty 4/5

Prerequisites 12.g, 17.f, 17.g


Before you start: words you need#

WordPlain meaning
Sliding-window attentionA layer that looks only at the last w tokens, not the whole context.
State-space layer (Mamba)A layer that keeps one fixed-size running state instead of per-token keys and values.
Hybrid modelA model that mixes layer types, for example full attention with sliding windows or with Mamba.
KV cache specWhat a layer declares about its cache: what it stores and how big a page is.
KV cache groupA set of layers with the same spec, sharing one block table per request.
Hybrid KV cache manager (HMA)vLLM’s machinery for giving each group its own rules from one shared pool.
Padding layerAn empty slot added so every group has the same number of layers.

1. What is it?#

So far every layer needed the same thing from the cache: room for every token, forever. Many current models break that. Some layers look only at the most recent thousand tokens; some keep a fixed-size running state; some share another layer’s cache; some compress keys into latent vectors. Giving all of them a full-length cache wastes most of the memory.

vLLM’s answer is to split layers into KV cache groups, give each group its own block table per request and its own rule for how many blocks a sequence needs, and draw all of them from the one shared block pool (17.e). Prefix caching then has to find a prefix that is valid for every group at once.

Facts checked on 12 November 2026 against vLLM v0.32.0.


2. Why does it matter?#

Gemma-3-27B has 62 layers: 10 full attention and 52 with a sliding window of 1,024 tokens. For a 32,000-token prompt:

treat all 62 layers as full attention     62 × 32,000              = 1,984,000 layer-tokens
honour the window                         10 × 32,000 + 52 × 1,024 =   373,248 layer-tokens

                                                                     5.3 times less memory

That is the difference between fitting three such requests and fitting sixteen. For Mamba hybrids the gap is larger still, and without the hybrid manager some of them cannot run at all.


3. Simple analogy#

A school where some classes keep every exercise book all year (full attention), some keep only the last week’s (sliding window), and some keep a single summary sheet (state space). The school has one storeroom with identical shelves. Each class gets its own shelf list, and old books from the “last week only” classes go back on the free shelves as the week moves on. To make the shelves interchangeable, every class is given the same number of pupils, adding empty desks where needed.


4. Tiny example#

The example from vLLM’s design document: 10 full-attention layers, 20 sliding-window layers with a window of 32 tokens, block size 16. One 112-token request:

groups: 1 full group of 10 layers + 2 sliding-window groups of 10 layers each
full group:             all 112 tokens   → 7 blocks
each window group:      last 32 tokens   → 2 blocks  (older blocks freed)
total:                                     11 blocks, instead of 21 if every layer were full

5. Technical explanation#

Layers that need less#

Layer typeWhat it storesBlocks needed for n tokensExample models
Full attentionKeys and values for every tokenceil(n / block)Llama, Qwen, Mistral
Sliding-window attentionKeys and values for the last w tokensabout ceil(w / block), constantGemma 2 and 3, gpt-oss
Chunked local attentionThe current chunk onlyup to one chunk’s worthLlama 4
State space (Mamba)A fixed-size stateone, plus checkpoints for prefix cachingJamba, Nemotron-H, Granite 4.0 hybrids
Latent attention (MLA)One compressed vector per tokenceil(n / block), smaller pagesDeepSeek V3-class
Cross-attentionKeys and values of the encoder’s outputfixed by the encoder lengthWhisper

Each attention layer reports a spec (FullAttentionSpec, SlidingWindowSpec, MambaSpec, MLAAttentionSpec, ChunkedLocalAttentionSpec, CrossAttentionSpec, … in vllm/v1/kv_cache_interface.py). v0.32.0 also has specs for newer designs, such as attention sinks and sparse-attention host/hot pools. A registry in single_type_kv_cache_manager.py maps each spec to the manager class that implements its rules; MLA, for example, uses the full-attention manager with a smaller page. At startup the engine core collects the specs from the workers and decides how to group them.

The constraint: one page size#

The block pool hands out identical blocks. A group of 10 layers and a group of 52 layers would need pages of different sizes for the same number of tokens. So vLLM makes groups the same size (kv_cache_utils.py):

  • A regular ratio. With 20 sliding-window and 10 full layers, three groups of 10.
  • No regular ratio. Gemma-3-27B’s 52 and 10 do not divide evenly. The group size is the smallest layer count: one full group of 10, five sliding-window groups of 10, and a sixth sliding-window group with the 2 remaining layers and 8 layers of padding. The design document is frank: “The solution has some memory waste and is not perfect.” vLLM logs a warning with the padding cost.
  • Nearly equal counts. If the larger count is under 1.5 times the smaller, the larger count is used instead. The source’s example is gpt-oss-20b with an EAGLE drafter: 12 sliding-window and 13 full layers are padded to 13 and 13, rather than 12 and 24.
  • Different sizes per token (state-space layers, whose state is much larger than one token’s keys and values). The attention block_size is raised until one attention page is at least as large as the state, and the state is padded to match. This is why some hybrid models run with blocks of hundreds or a thousand tokens instead of 16, and why --prefix-match-unit exists (17.f). Newer layouts can also pack layers with different page sizes into one block-shaped region.

A request then has one block table per group. You can see it in the type of NewRequestData.block_ids: tuple[list[int], ...], one list per group.

Layers share buffers across groups#

Physical memory is not one tensor per group. For n groups of m layers each, vLLM allocates m buffers, and each buffer is shared by n layers, one from each group. So layer full.0, layer sw.0 and layer sw.10 all read and write the same tensor, at different block indices. Since the groups hold disjoint sets of block IDs, they never collide, and “block 37” means the same slice of memory for every layer.

Freeing blocks as the window moves#

A sliding-window layer does not use a ring buffer. A ring overwrites old tokens in place, and a block whose contents change cannot be shared or cached. Instead each token gets its own slot, as for full attention, and blocks are freed once they fall behind the window:

Python
# Free the blocks that are skipped during the attention computation
# (e.g., tokens outside the sliding window).
self.coordinator.remove_skipped_blocks(request.request_id, ...)

The freed positions in the table are replaced by the null block (block 0), so the table keeps its shape and indices still line up with token positions. Freed blocks go back to the pool with their hashes intact and may still serve another request’s cache hit.

(v0.32.0 does have a CircularBufferSpec, a one-block ring per request, but only for a narrow case: holding the raw keys of a token group still being compressed in a few compressed-attention models such as DeepSeek-V4.1. Prefix caching is off for that group.)

Prefix caching across groups#

A cache hit is usable only if every layer can resume from it. The rule differs by type:

TypeA prefix of length L is a valid hit if…Search
Full attentionevery block from 0 to L is cachedleft to right, stop at the first miss
Sliding windowthe blocks covering the last w − 1 tokens before L are cachedright to left, stop at the first run long enough
State spacea saved state exists exactly at Lat checkpoint positions

The design document describes a two-step combination for “exactly two” types: find the full attention hit, then search the other group within it. The v0.32.0 code generalises this (HybridKVCacheCoordinator.find_longest_cache_hit): an iterative fixed-point algorithm. “Each attention type either accepts the current candidate length or reduces it. If any type reduces the length, restart checks over all types.” It ends because the length only ever shrinks. For the common one-full-plus-one-other case, one pass suffices.

The cache key includes the group: the map is from (block hash, group id) to a block, so the same tokens are cached, and evicted, independently for each group.

Which coordinator you get#

get_kv_cache_coordinator chooses one at startup:

CoordinatorWhen
KVCacheCoordinatorNoPrefixCachePrefix caching disabled. Any number of groups; no lookups.
UnitaryKVCacheCoordinatorExactly one group. The common case.
HybridKVCacheCoordinatorSeveral groups with prefix caching on

note

The published design document still says the hybrid coordinator “Handles exactly two KV cache groups”. The v0.32.0 class handles more, plus Mamba checkpoints, EAGLE drafter groups and bounded replay for sliding windows. Treat the document as the explanation of the idea and the source as the truth about current limits.


6. Under the hood#

The picture#

flowchart LR
  REQ[":i-file-text: <b>One request</b><br/><small>112 tokens</small>"] --> CO[":i-split: <b>KVCacheCoordinator</b>"]
  CO --> G0[":i-layers: <b>Group 0: full attention</b><br/><small>10 layers · needs all 112 tokens<br/>7 blocks</small>"]
  CO --> G1[":i-layers: <b>Group 1: sliding window</b><br/><small>10 layers · last 32 tokens<br/>2 blocks</small>"]
  CO --> G2[":i-layers: <b>Group 2: sliding window</b><br/><small>10 layers · last 32 tokens<br/>2 blocks</small>"]
  G0 --> POOL[(":i-database: <b>One BlockPool</b><br/><small>one page size for everyone</small>")]
  G1 --> POOL
  G2 --> POOL
  class REQ neutral
  class CO queue
  class G0,G1,G2 compute
  class POOL memory

Bounded replay for sliding windows#

DeepSeek-V4.1 introduced a different trade: swa_bounded_replay (on by default where the model supports it, Model Runner V2 only) keeps sliding-window KV out of the prefix cache altogether. After a prefix hit on the full-attention layers, the sliding-window state is rebuilt by recomputing just the last window of the hit. That costs one window of compute per hit and saves keeping many sliding-window blocks cached.

When the hybrid manager is turned off#

--disable-hybrid-kv-cache-manager makes vLLM treat every attention layer as full attention for allocation, while the model still computes with its real window. It wastes memory (the first row of the arithmetic in section 2). In v0.32.0 vLLM also turns it off automatically when:

  • the platform does not support it (non-GPU platforms);
  • the model uses chunked local attention (Llama 4), because of a latency regression, unless VLLM_ALLOW_CHUNKED_LOCAL_ATTN_WITH_HYBRID_KV_CACHE=1, and always with EAGLE in that case;
  • a KV connector is configured that does not support it. The warning spells out the impact: Mamba hybrids “require HMA and will fail at startup without it; models with sliding window attention will run with reduced performance.”

If the startup log says the hybrid manager was disabled, your capacity is the full-attention figure.

KV sharing#

In some models a layer has no cache of its own and reads another layer’s (cross-layer KV sharing, as in Gemma 3n). vLLM allocates nothing for such layers and points them at the owner’s buffer. They add nothing to the per-token cost, so counting layers in config.json overestimates the cache for these architectures.

Group formation and memory in Go#

Go
package main

import "fmt"

const blockSize = 16

func ceilDiv(a, b int) int { return (a + b - 1) / b }

// blocksFull: every token keeps its slot.
func blocksFull(n int) int { return ceilDiv(n, blockSize) }

// blocksWindow: slots for the last w tokens; whole blocks behind the window are freed.
func blocksWindow(n, w int) int {
	skipped := n - w
	if skipped < 0 {
		skipped = 0
	}
	return ceilDiv(n, blockSize) - skipped/blockSize
}

type model struct {
	name          string
	fullLayers    int
	windowLayers  int
	window        int
	groupSize     int // layers per group = the smaller layer count
	windowGroups  int
	paddingLayers int
}

func newModel(name string, full, win, window int) model {
	m := model{name: name, fullLayers: full, windowLayers: win, window: window}
	m.groupSize = min(full, win)
	m.windowGroups = ceilDiv(win, m.groupSize)
	m.paddingLayers = m.windowGroups*m.groupSize - win
	return m
}

// cost returns layer-tokens of memory for one request of n tokens:
// blocks x block size x layers per group, summed over groups.
func (m model) cost(n int) (hybrid, allFull int) {
	page := blockSize * m.groupSize
	hybrid = blocksFull(n)*page*(m.fullLayers/m.groupSize) + blocksWindow(n, m.window)*page*m.windowGroups
	allFull = blocksFull(n) * blockSize * (m.fullLayers + m.windowLayers)
	return
}

func main() {
	// The example from vLLM's design document: 10 full + 20 window layers, window 32.
	toy := newModel("toy", 10, 20, 32)
	fmt.Printf("%s: %d groups of %d layers (1 full, %d window), padding %d layers\n",
		toy.name, 1+toy.windowGroups, toy.groupSize, toy.windowGroups, toy.paddingLayers)
	fmt.Printf("  112-token request: %d blocks for the full group, %d for each window group, %d in total\n\n",
		blocksFull(112), blocksWindow(112, 32), blocksFull(112)+toy.windowGroups*blocksWindow(112, 32))

	g := newModel("Gemma-3-27B", 10, 52, 1024)
	fmt.Printf("%s: %d full + %d window layers -> 1 full group + %d window groups of %d, padding %d layers\n\n",
		g.name, g.fullLayers, g.windowLayers, g.windowGroups, g.groupSize, g.paddingLayers)

	fmt.Printf("%10s %16s %16s %10s\n", "tokens", "hybrid manager", "all-full", "saving")
	for _, n := range []int{512, 2000, 8000, 32000, 128000} {
		h, f := g.cost(n)
		fmt.Printf("%10d %16d %16d %9.1fx\n", n, h, f, float64(f)/float64(h))
	}
	fmt.Println("\n(units: layer-tokens; multiply by bytes per token per layer for bytes)")
}

Output:

toy: 3 groups of 10 layers (1 full, 2 window), padding 0 layers
  112-token request: 7 blocks for the full group, 2 for each window group, 11 in total

Gemma-3-27B: 10 full + 52 window layers -> 1 full group + 6 window groups of 10, padding 8 layers

    tokens   hybrid manager         all-full     saving
       512            35840            31744       0.9x
      2000            81440           124000       1.5x
      8000           141440           496000       3.5x
     32000           381440          1984000       5.2x
    128000          1341440          7936000       5.9x

(units: layer-tokens; multiply by bytes per token per layer for bytes)

How to read it: for a 512-token request the hybrid manager is worse than treating every layer as full attention: the window is not full yet, so nothing is saved, and the eight padding layers cost extra. The saving appears once requests exceed the window and grows with length (5.2x at 32,000 tokens, a little under the ideal 5.3x because of padding and whole blocks). A model like this suits long-context work and is slightly worse for short chats, which is what its architecture was designed for.


7. Performance implications#

  • Long requests get much cheaper per token on sliding-window and Mamba hybrids; short ones may cost slightly more because of padding.
  • Large blocks on Mamba hybrids make prefix hits coarse unless --prefix-match-unit is set (17.f).
  • The fixed-point hit search runs per admission; with many groups it does more lookups, still small next to a prefill.
  • Disabling the hybrid manager (by flag, platform or connector) silently multiplies cache use for windowed models.

8. Production implications#

  • For Llama-style models, nothing changes: one group, one table, the arithmetic of 17.h.
  • For hybrid models, trust the startup log’s GPU KV cache size: N tokens. It is computed group-aware; blocks × 16 is wrong when a request occupies blocks in several groups.
  • Check the log for “hybrid kv cache manager” warnings after adding a KV connector or moving to a new platform.
  • New architectures arrive with new specs. When a freshly released model is slow or memory-hungry in vLLM, the usual cause is that its layers are treated as full attention until a dedicated spec lands.

9. Common mistakes#

  1. Computing hybrid-model capacity as num_blocks × block_size.
  2. Assuming the hybrid manager is always on. Connectors, platforms and Llama 4 can turn it off.
  3. Trusting the design document’s “exactly two groups” limit. The code is more general now.
  4. Expecting sliding-window savings on short prompts. They start beyond the window length.
  5. Counting shared-KV layers as if each had its own cache.

10. Hands-on exercise#

  1. Add a model with 30 full and 30 window layers and a window of 4,096. How many groups, how much padding, and what saving at 32,000 tokens? (Note that 30 is not above 1.5 × 30.)
  2. Add the 1.5x rule to newModel and try 12 window and 13 full layers. Compare the padding with and without the rule.
  3. For Gemma-3-27B, find the request length at which the hybrid manager breaks even with all-full. Why is it a little above the window size and not exactly at it?

11. Interview questions#

  1. Why must all KV cache groups have the same page size?
  2. Why does a sliding-window layer free old blocks instead of overwriting them in a ring?
  3. For a model with full and sliding-window layers, in which direction is each group searched for a cache hit, and why?
  4. How does vLLM choose the number of layers per group, and what does that cost Gemma-3-27B?
  5. Name two situations in which vLLM turns the hybrid KV cache manager off by itself.

12. Further reading#

Checked on 12 November 2026, against the v0.32.0 tag.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in