
25 November 2026 · Inference engine notes · 3/4
Inference Engines 03: Paged KV and Prefix Caching
Part 3 is the KV cache. When I got to RadixAttention, something didn't click: everyone asks different questions, so how can one request reuse KV that someone else computed? And isn't that just the ordinary KV cache, so what's the tree for? Part 1's KV cache section only listed the pieces; this one digs a level deeper: paging first, then prefix caching, then where it all lives in mini-sglang's code.
Three kinds of waste without paging
- The naive approach: give each request one contiguous region of GPU memory. You don't know how long it will write, so you reserve for the maximum
- Reserved but unused: reserve 4096 slots, write 200 tokens, and nobody else can use the rest
- The vLLM paper splits this into two: slots reserved for future tokens, which will be used eventually but sit empty now; and slots over-provisioned for the maximum length that are never used (internal fragmentation)
- External fragmentation: requests come and go and leave holes of different sizes; there's enough memory in total, but no single contiguous hole is big enough
- No sharing: the same system prompt is stored once per request
- The PagedAttention paper (Kwon et al., 2023) measured the systems of the time: only 20.4%–38.2% of KV memory actually held token state
- KV memory decides how big a batch can get, so using only a fifth to two fifths of it means serving far fewer requests at once
How paging works
- The vLLM team introduced PagedAttention in 2023; mainstream engines now basically all do it
- vLLM calls a page a block. That "block" has nothing to do with the chunks in chunked prefill
- How it works:
- At startup, allocate one big pool, cut it into numbered pages, and put them all on a free list
- A request takes a page only when it starts writing into a new one; pages don't need to be contiguous
- Each request has a page table: logical page 0 → physical page 3, page 1 → physical page 7…
- The attention kernel takes the page table and fetches K/V from the pool page by page. "PagedAttention" means this page-table-reading kernel plus the paging bookkeeping around it
- When the request finishes, its pages go back on the free list
- After paging:
- The only waste left is the unfilled part of each request's last page
- No external fragmentation: pages are all the same size, so any free page fits anyone
- Sharing becomes two page tables pointing at the same physical page
The parts
| Part | Job | mini-sglang |
|---|---|---|
| KV pool | Holds every request's K/V | kvcache/mha_pool.py, one big tensor (2, layers, pages, page_size, KV heads, head_dim) |
| Free page list | Where new pages come from | free_slots and allocate_paged in scheduler/cache.py |
| Page table | Where each request's pages are in the pool | page_table in engine/engine.py |
| Attention kernel that reads the page table | Fetches K/V page by page | attention/fa.py passes the page table to flash_attn_with_kvcache |
| Reference counts (only for sharing) | How many requests use a page | ref_count on Radix tree nodes |
- The first four are plain paging; reference counts are what make sharing possible
- Pool size: at startup it takes
--memory-ratio(default 0.9) of free GPU memory, subtracts the weights, and gives the rest to KV- Bytes per page = 2 (K and V) × layers × KV heads × head_dim × page_size × bytes per value, which is the per-token KV size from ML System 06 times page_size
- KV heads here means heads per GPU; with TP they're split across GPUs
free_slotsis a tensor on the GPU holding the first slot index of each page; pages are sliced off the front, and if there aren't enough, the Radix tree evicts firstallocate_pagedonly allocates pages for the span[cached_len, device_len)that doesn't have pages yet, rounded up to whole pages: pages arrive as the writing reaches thempage_tablestores a slot index per token, not page numbers- Before handing it to FlashAttention,
fa.pytakes every page_size-th entry and divides by page_size to get page numbers back
- Before handing it to FlashAttention,
Sharing and reference counts
- Once two page tables point at the same physical page, you have to track how many requests use it, and only reclaim it at zero
- mini-sglang keeps the count on Radix tree nodes, where one node covers a whole run of tokens
- When a request uses a matched prefix it calls
lock: from the matched node up to the root, every node'sref_countgoes up by 1 - When the request finishes,
unlockdecrements the same path
- When a request uses a matched prefix it calls
- A node at zero isn't deleted right away. It stays in the tree waiting for the next hit and just becomes "evictable"
- Admission counts evictable memory as available (
available_size= evictable + free pages × page_size). Cached KV doesn't take anyone's seat; it's cleared out only when the space is needed - Parallel sampling in the vLLM paper also relies on reference counts: several branches share the prompt's pages, and a branch that needs to write into a shared page copies it first (copy-on-write)
Page size
| Page size | Pros | Cons |
|---|---|---|
| Small (1) | Almost no waste; prefixes match down to a single token | Long page tables; the kernel looks up an address per token |
| Large (16, 64) | Short page tables; the kernel reads a whole block at once, which is faster | Half a page wasted on average in the last page; prefixes only match in whole pages |
- The vLLM paper's default block is 16 tokens
- mini-sglang defaults to
--page-size 1 --attention-backenddefaults toauto: trtllm on B200-class GPUs (SM100),fa,fion H100 (SM90),fiotherwise- trtllm only accepts 16, 32 or 64 and overrides anything else to 64; mini-sglang's FlashInfer backend only supports 1
Where shared prefixes come from
- Different people ask different questions. What can be reused is the long, identical opening in front of the question. SGLang calls this RadixAttention
- Sources:
- System prompts: a support app sends every user the same 1000-token block of rules, followed by a 20-token question. With 4 users: no cache means computing 4 × 1020 = 4080 tokens; with the cache, 1020 + 3 × 20 = 1080. For agents this block also holds every tool description, often several thousand to tens of thousands of tokens
- Multi-turn chat / agent loops, the biggest saving: the model doesn't remember the last turn, so every turn resends the whole history
- Turn 5 = everything from turns 1–4 + the new question
- After an agent calls tool X it sends "history + tool result"; the history all hits, and only the tool result is computed. A task goes back and forth dozens of times, saving a big chunk every time
- Different questions about the same document; few-shot examples
- Once two users' prompts diverge, the parts after the split can't help each other. What gets stored past the split is for the same user's own next turn
Why only a prefix
- A token's K/V is computed while looking at every token before it (causal attention)
- If two requests are identical from the first token on, the K/V for that stretch is exactly the same
- If they differ by one token, every K/V from that point on differs
- So a piece of text with something different in front of it can't be reused, even if the text itself is word for word the same
Why a tree on top of the KV cache
- A plain KV cache only lives inside one request: when the request finishes, its slots go back
- To the engine, the next turn is a brand-new request. The API carries nothing like "I'm A, turn 5"; the engine just gets a sequence of tokens and has to work out whether it has computed this opening before, and where in the pool it is
- The tree is the index to that old KV:
- Fast lookup: walk down from the root token by token until something doesn't match, and you know how much can be reused
- No duplicates: 1000 users with the same system prompt store it once, and each user's branch grows out below it
- Easy eviction: when memory runs short, delete the least recently used leaves. A leaf is one request's own tail, so deleting it doesn't touch the shared part
- The tree is the index; the KV stays in the pool: mini-sglang's tree nodes store only "these token ids → these slots in the pool", never K/V
- On a hit, the slot indices are copied into the new request's row of
page_table. Not a single byte of KV is copied or recomputed - Every request goes through the same Scheduler and looks things up in this one tree, so the KV cache goes from one request's private notes to something shared by all requests and all turns
- The tree matches by content and has no idea which branch belongs to which user. A's next turn walks back down A's branch only because that's the only branch with the same content
An example
One word is one token, and S = chat template + system prompt:
① A: S Beijing weather how → answer sunny
root
└─ S Beijing weather how sunny
② B: S Shanghai food → S hits; split after S, compute only "Shanghai food"
root
└─ S
├─ Beijing weather how sunny
└─ Shanghai food
③ A, turn 2: S Beijing weather how sunny need umbrella
→ hits all the way to "sunny", compute only "need umbrella"
④ A goes back to turn 1 and asks "Beijing food" in a new thread
→ hits up to "Beijing"; split again after "Beijing"
root
└─ S
├─ Beijing
│ ├─ weather how sunny need umbrella
│ └─ food
└─ Shanghai food
- ④ is forking a new thread mid-conversation: the earlier KV hits directly. An engine that stored KV per conversation would hit nothing for the new thread
- The new part after the fork point still needs a prefill before decode can start. A prefill with
cached_len > 0like this is called an extend - This assumes the branch hasn't been evicted yet
Limits
- No system prompt, all first turns, unrelated questions → almost nothing saved
- Nothing is kept forever: when memory is tight, the least recently accessed leaves are evicted, so a user coming back much later may start from scratch. A hit saves work, and a miss doesn't break anything
- Only identical tokens match: if one token near the start differs (say the system prompt includes the current time), nothing after it hits
- With page size > 1, matching works only in whole pages, and the leftover partial page isn't reused
In mini-sglang
- Lookup:
CacheManager.match_req(scheduler/cache.py) deliberately ignores the last token. At least 1 token has to be computed so there are logits to sample from - Tree walk:
RadixPrefixCache._tree_walk(kvcache/radix_cache.py). A radix tree is a compressed trie: one node holds a whole run of tokens- Finds the child by the next token (by the next whole page when page_size > 1)
fast_compare_keyfinds the first mismatch, then rounds down to a whole page- If only part of a node matches, it calls
split_atthere - Nodes along the path get a fresh timestamp, which eviction uses
- Admission (
PrefillAdder):- After a match it calls
lock, then checks memory again: locked nodes no longer count as evictable - Copies the slot indices into the request's
page_tablerow - Reserves only for the part that missed:
extend_len + output_len, withextend_len = input_len - cached_len. More hits mean more requests fit in a round
- After a match it calls
- Registering:
cache_req- Right after prefill,
cache_req(finished=False)inserts the prompt into the tree. While this request is still decoding, later requests can already hit its prompt - When it finishes,
cache_req(finished=True)inserts the whole thing, prompt plus generated answer, and doesn't delete it - The insert length is rounded down to whole pages; the partial last page stays out of the tree and is freed when the request ends
- Two requests with the same opening that prefill at the same time can't hit each other, so both compute it; the one that inserts second finds it already there and returns its duplicate slots
- Right after prefill,
- Eviction:
RadixPrefixCache.evict- Takes only leaves with
ref_count == 0, puts them in a min-heap by timestamp, and deletes from the oldest - When a parent becomes an unused leaf after that, it joins the heap too
- Called only when
_allocatefinds too few free pages, so it frees space on demand
- Takes only leaves with