Inference Engineering

Lesson 7: Paged KV memory · Workbook

Paged KV memory: the workbook

The full working behind lesson 7. Why booking each request's maximum length wastes most of the KV cache, the three kinds of waste, block tables and the paged attention kernel, block size, preemption, copy-on-write, and seven exercises to check yourself.

Every request a language model serves keeps a KV cache: the keys and values of every token it has seen, stored so the next token does not have to recompute them (lesson 4). Continuous batching lets a server run many requests at once, and the number it can run is set mostly by how many KV caches fit in GPU memory. So the way a server lays out that memory decides its throughput.

Before vLLM (2023), serving systems stored each request’s KV cache in one contiguous region, sized for the longest sequence the request might reach. Most of that region never held a token. The vLLM paper measured that only 20.4% to 38.2% of KV cache memory held actual token states in the systems it compared against. Its fix, PagedAttention, splits the cache into small fixed-size blocks and gives them out as a sequence grows, the way an operating system gives out pages of memory. Waste falls to less than one block per sequence, more requests fit, and the paper reports 2 to 4 times the throughput of earlier systems at the same latency.

This lesson rebuilds that argument with real numbers, then lets you watch both schemes fill the same memory.

Why the KV cache is hard to allocate

Take Llama 3.1 8B with a BF16 cache. Each token stores a key and a value vector in each of 32 layers for each of 8 KV heads, 128 numbers per vector, 2 bytes per number. That is 131 KB per token (131,072 bytes).

An 80 GB H100 holding the 16.1 GB of weights, with 10% held back as in lesson 4, has about 55.9 GB left. Ignoring activations, that is room for at most 426,784 tokens of KV cache, shared by every request on the GPU.

Two properties make that space awkward to manage:

Deep learning frameworks of the time expected each tensor to sit in one contiguous range of memory. The simplest way to give a growing tensor contiguous memory is to reserve the largest size it could ever need, up front. Earlier systems did exactly that.

Three kinds of waste

The vLLM paper names three ways a contiguous, reserved-up-front scheme wastes memory:

How bad is it? The paper profiled three versions of Orca, an earlier serving system that also batches at the level of single iterations. Orca’s code was not public, so the authors reimplemented it with three reservation policies: always reserve the maximum length (2,048 tokens for their model), reserve up to 2 times the true output length, and an idealized version that knows each output length in advance. Across the three, only 20.4% to 38.2% of the KV cache memory held token states. Even the version with perfect knowledge of output lengths wasted most of its memory, because reservation and external fragmentation remain. In the same figure, vLLM reached 96.3%.

A worked snapshot

Here are eight sequences in the middle of generation, with a contiguous scheme that reserves 2,048 slots for each. A slot holds one token’s keys and values across all layers. The paged column uses blocks of 16 tokens, which the next section explains.

LengthContiguous: reservedContiguous: unusedPaged: blocksPaged: unused
1372,0481,91197
5122,0481,536320
1,0002,0481,048638
332,0482,015315
2602,0481,7881712
1,7892,0482591123
752,0481,97355
6402,0481,408400
Total16,38411,93828150

The eight sequences hold 4,446 tokens. The contiguous scheme sets aside 16,384 slots for them, so 27.1% of what it reserves holds a token. (The paper’s 20.4% to 38.2% is measured differently, over a whole serving run and including free memory lost to fragmentation, but it tells the same story.) The paged scheme sets aside 4,496: 98.9%.

The snapshot cannot say which of the contiguous scheme’s unused slots are reserved for future tokens and which are internal fragmentation. That depends on where each sequence stops, which nobody knows yet. Either way, no other request can use them.

What that does to capacity

On the H100 above, with room for 426,784 tokens:

These are memory limits only. Compute and latency targets cap the batch too, but a scheduler cannot batch requests it has no memory for.

Paging the KV cache

Operating systems solved the same problem decades ago. A program sees a contiguous range of virtual addresses, but the memory behind it is a set of fixed-size pages scattered anywhere in physical RAM. A per-process page table maps each virtual page to a physical one, and the OS hands out pages only when the program first touches them.

PagedAttention applies this to the KV cache. The paper’s own analogy: blocks are pages, tokens are bytes, requests are processes.

Two guarantees follow.

Waste per sequence is less than one block. Blocks fill left to right and a new one is allocated only when the previous one is full, so at most one block per sequence is partly empty. For a sequence of LL tokens and block size BB:

unused slots  =  B⌈LB⌉−L  ≤  B−1\text{unused slots} \;=\; B\left\lceil \frac{L}{B} \right\rceil - L \;\le\; B - 1

At 16 tokens that is at most 15 slots, 1.97 MB for Llama 3.1 8B. If sequence lengths are spread evenly, the expected gap is about half a block, 983 KB per sequence. Compare the contiguous scheme, which can waste most of a 2,048-token region.

There is no external fragmentation. All blocks are the same size, so any free block fits any request. A request is never refused while enough blocks are free.

The next figure runs both schemes side by side on a larger memory of 512 slots, with a random stream of requests you control. Each request has a prompt, a maximum length the contiguous side must reserve, and a true output length the simulator knows but neither allocator does. Press Decode 1 step to generate one token for every running request, and Send a chat to send another. Then change the box (block) size. The same figure is the lesson’s playground.

Booked stretches versus boxes, step by step

Booked ahead, one stretch each

Paged, one box at a time

  • token stored
  • booked, not yet written
  • booked, never used
  • free, but no gap fits the next chat

Running chats. Pick one, or hover or tap a cell, to see its block table.

Each cell is one token slot; colors tell requests apart. Left: each request owns one outlined chunk sized for its maximum length. Lightly shaded cells will receive later tokens; hatched cells never will, and hatched free space is too fragmented for the request waiting at the head of the queue. Right: outlined boxes are physical blocks, handed out from a shuffled free list. Pick a request to see its block table.

A few things to try:

What the attention kernel does differently

A standard attention kernel assumes each sequence’s keys and values sit in one contiguous array. With paging they do not, so the kernel has to change. During decode, the new token’s query is compared against each block of keys in turn: the kernel looks up the block’s physical address in the block table, loads that block, computes the attention scores for its tokens, and combines them with the matching values. The arithmetic does not change. The paper writes ordinary attention for query token ii as a sum over blocks: KjK_j and VjV_j are the keys and values in block jj, AijA_{ij} is the vector of softmax scores for that block’s tokens, and dd is the head dimension.

Aij=exp⁡ ⁣(qi⊤Kj/d)∑t=1⌈i/B⌉exp⁡ ⁣(qi⊤Kt/d)1,oi=∑j=1⌈i/B⌉VjAij⊤A_{ij} = \frac{\exp\!\left(q_i^\top K_j / \sqrt{d}\right)}{\sum_{t=1}^{\lceil i/B \rceil} \exp\!\left(q_i^\top K_t / \sqrt{d}\right)\mathbf{1}}, \qquad o_i = \sum_{j=1}^{\lceil i/B \rceil} V_j A_{ij}^\top

Here 1\mathbf{1} is a column of BB ones, so multiplying by it adds up the block’s BB exponentiated scores. The denominator is the usual softmax total, gathered one block at a time. (The paper places 1\mathbf{1} inside the exponent; it means the same thing.) Only the addressing is new: each KjK_j and VjV_j is fetched from wherever the block table says it lives. (FlashAttention, lesson 9, also works block by block, for a different reason.)

vLLM’s original kernel adapted FasterTransformer’s attention kernel to read through the block table, assigning each block to one warp (a group of 32 GPU threads that execute in lockstep), so the threads read neighboring addresses within the block together. The block table costs something: the paper measured 20% to 26% higher latency for the attention kernel than FasterTransformer’s, from the table lookups, extra branches and support for sequences of different lengths in one batch. Attention is only part of each step, and the larger batches more than paid for it end to end.

Block size is a trade-off. Small blocks waste less memory in each sequence’s last block. Large blocks give the kernel more tokens to process in parallel per lookup. The paper tested sizes from 1 to 256 on two traces. On ShareGPT (long conversations), 16 to 128 performed best; on Alpaca (shorter sequences), 16 and 32 worked well and larger blocks were much worse, because sequences became shorter than one block. vLLM chose 16 as its default.

For the snapshot above, the block size moves utilization like this:

Block sizeSlots allocatedHolding a token
44,45699.8%
164,49698.9%
324,57697.2%

Running out of blocks

Paging admits requests without reserving room for their future tokens, so the free list can run dry while sequences are still growing. vLLM handles this with preemption, borrowed again from operating systems. Requests are served first come, first served; when memory runs out, the most recently arrived requests are preempted first. A preempted sequence gives up all of its blocks at once, since a sequence’s blocks are always read together. vLLM can bring it back in two ways:

The paged side of the memory-grid figure above uses recomputation. Send chats there until it runs out of blocks to see a count of paused chats appear.

Sharing blocks: copy-on-write

Because a block table is just a list of block numbers, two sequences can point at the same physical block. This matters whenever several sequences share a prefix.

vLLM keeps a reference count on each physical block: the number of block tables that point at it. A block with a count above 1 is read-only. When a sequence needs to write into a shared block, which only happens in a partly filled last block, the block manager first copies that one block to a free block, points the writing sequence at the copy, and decrements the original’s count. This is copy-on-write, the same mechanism an operating system uses when a process forks. Full blocks of a shared prefix are never copied.

Two answers sharing one question's boxes

Boxes in memory, 4 tokens each

The paper's Figure 8 example: a 7-token prompt, block size 4, two samples. Prefill writes the prompt once into physical blocks 7 and 1. Only the partly filled block is ever copied, and only once.

In that example, two separate copies would need 4 blocks; sharing needs 3. The savings grow with the prompt. Four samples of a 700-token prompt that generate 100, 180, 260 and 340 tokens need 230 blocks of 16 without sharing and 101 with it, a 56% saving.

The paper measured, on OPT-13B, memory savings of 6.1% to 9.8% for parallel sampling and 37.6% to 55.2% for beam search on the Alpaca trace, and 16.2% to 30.5% and 44.3% to 66.3% on ShareGPT. Beam search saves more because candidates share most of their history, not only the prompt. The same mechanism lets different requests share a common prefix, such as a long system prompt; that is the subject of lesson 8.

What paging does not fix

Paging removes wasted memory. It does not create memory. A server still has room for a fixed number of tokens, and when its requests need more, it must queue or preempt them. The KV cache per token is unchanged, which is why shrinking the cache and quantizing it still matter. Attention still reads every cached byte each decode step, so paging does nothing for its memory traffic; it changes only where those bytes live.

The design outlived its first kernel. vLLM’s documentation now describes the original PagedAttention CUDA kernel as a historical document, since current versions use other attention kernels. Those kernels still read the cache through block tables built by vLLM’s KV cache manager.

Check yourself

Work each one out before opening the answer. Every answer comes from the same functions as the tables and figures above and on the lesson page.

Exercise 1. Llama 3.1 70B stores 327,680 bytes of KV cache per token in BF16 (80 layers, 8 KV heads of dimension 128). With blocks of 16 tokens, how big is one block in one layer, and what is the most memory one sequence can waste? Enter the worst-case waste in KB.

KB
Show the worked answer

One block in one layer is 65.5 KB (65,536 bytes), the same as for the 8B model: both have 8 KV heads of dimension 128, and only the layer count differs. The worst case is a last block holding a single token, which leaves 15 empty slots across all 80 layers: 15 × 327,680 bytes = 4.92 MB (4,915,200 bytes).

Exercise 2. In the eight-sequence snapshot, what share of the contiguous scheme's memory holds tokens if it reserves 4,096 slots per sequence instead of 2,048?

%
Show the worked answer

13.6%, half of 27.1%. The tokens stay at 4,446 while the reservation doubles to 32,768 slots. Raising a model’s context limit makes contiguous reservation worse, while paged waste does not depend on the maximum length at all.

Exercise 3. Same snapshot, paged, but with blocks of 32 tokens instead of 16. How many slots are allocated, and what share holds tokens? Why might you still pick 32?

Show the answer

4,576 slots, 97.2%, against 4,496 slots and 98.9% at 16. Each sequence can now waste up to 31 slots instead of 15. You might still pick 32 because larger blocks give the attention kernel more contiguous work per block-table lookup; on the paper’s long-conversation trace, block sizes from 16 to 128 gave the best performance.

Exercise 4. One request asks for 4 samples of a 700-token prompt. They generate 100, 180, 260 and 340 tokens. With 16-token blocks, how many blocks does the request use with and without copy-on-write sharing? Enter the count with sharing.

blocks
Show the worked answer

Without sharing, each sample stores its whole sequence: 50 + 55 + 60 + 65 = 230 blocks. With sharing, the prompt’s 43 full blocks are stored once. Its last block holds 12 tokens and is shared too, until the samples write into it: the first 3 to write each get a copy, and the last one, by then the only reference, writes in place. So each sample ends up with its own version of that block, and every block after it is its own. Total 101 blocks, 56% fewer.

Exercise 5. Llama 3.1 8B in BF16 on an 80 GB H100. Ignoring activations, how many 2,000-token sequences fit with 16-token paging? How many fit if each request instead reserves 8,192 contiguous slots? Enter the paged count.

sequences
Show the worked answer

The KV budget is 426,784 tokens, or 26,674 blocks of 16. A 2,000-token sequence needs 125 blocks, so 213 sequences fit with paging. Reserving 8,192 slots each fits only 52, about 4 times fewer, with sequences of the same length. That ratio is the reason paging raised throughput: the batch a scheduler can build is limited by memory.

Exercise 6. From lesson 4: Llama 3.1 8B has 32 layers and 8 KV heads of dimension 128, stored in BF16. How much KV cache does one 8,192-token conversation need? Enter GB.

GB
Show the worked answer

2 × 32 × 8 × 128 × 2 bytes = 131,072 bytes per token; 8,192 × 131,072 bytes = 1.07 GB. With 16-token blocks that conversation fills 512 blocks exactly, so paging wastes nothing on it; reserving the model’s full 131,072-token context for it would hold 16 times as much memory as it uses.

Exercise 7. From lesson 6: recall static batching. A batch of 4 requests needs 3, 12, 5, 8 output tokens, one token per request per step (the first comes from the prefill step). What share of its slot-steps produce a token someone asked for?

%
Show the worked answer

The batch runs until its longest request is done, 12 steps, so it has 4 × 12 = 48 slot-steps, of which 28 produce a token: 58.3%. It is the same mistake as reserving memory for the longest possible reply, made in time instead of space: static batching holds a slot until the longest request ends, and contiguous allocation holds memory for a length the request may never reach. Continuous batching fixed the first; paging fixes the second.

Sources

  1. Kwon, Li, Zhuang, Sheng, Zheng, Yu, Gonzalez, Zhang, Stoica (2023). Efficient Memory Management for Large Language Model Serving with PagedAttention. SOSP 2023. arXiv:2309.06180. The vLLM paper. Utilization figures from its Figure 2 and §1; the three kinds of waste from §3.1 and Figure 3; block tables from §4.2 and §4.3; copy-on-write from §4.4 and Figure 8; preemption from §4.5; sharing savings from §6.3; kernel overhead and block size from §7.1 and §7.2
  2. vLLM documentation. Paged Attention (design notes). A walkthrough of the original PagedAttention CUDA kernel. The page marks itself as a historical document: current vLLM uses different kernels, still driven by block tables
  3. Yu, Jeong, Kim, Kim, Chun (2022). Orca: A Distributed Serving System for Transformer-Based Generative Models. OSDI 2022. The iteration-level scheduler that vLLM compares against. Orca's code was not public, so the vLLM paper reimplemented it
  4. Llama 3.1 8B config.json (ungated copy). 8 KV heads of dimension 128 in 32 layers; max_position_embeddings 131,072
  5. NVIDIA H100 product page, specifications table. 80 GB of HBM on the SXM part

Back to lesson 7: Paged KV memory