PagedAttention
Wasted reservations
Nobody knows how long an answer will be. Older servers played safe: each request got one unbroken stretch of KV cache, big enough for the longest allowed answer. If a request may write 2,000 tokens but stops after 100, the space for the other 1,900 sat empty. Gaps between reservations wasted more. This waste is called fragmentation, and it could eat most of the KV cache.
Pages
PagedAttention, from the vLLM project, borrows an idea from operating systems. It cuts the KV cache into small fixed-size blocks (pages), each holding the keys and values for a few tokens, for example 16. A request gets a new block only when its last block is full. Blocks can sit anywhere in GPU memory; they don't need to be next to each other.
The block table
Each request keeps a block table. It lists the request's blocks in order (block 0, block 1, ...) and says where each one really sits in GPU memory. When attention needs earlier tokens, the engine follows the table to find them. When a request ends, its blocks go back to a free list for others.
More users per GPU
At most one block per request is partly empty, so very little memory is wasted. That freed memory holds more requests at the same time. A bigger batch means more tokens per second from the same GPU.
Preemption
Requests grow while they run, so memory can still run out. Then the engine preempts a request: it pauses it and frees its blocks so others can carry on. Later it either copies the saved blocks back from CPU memory (swap) or runs prefill again to rebuild them (recompute). The paused user waits, but the server does not crash.
Remember
- Reserving for the longest answer wastes memory.
- PagedAttention stores the KV cache in small blocks placed anywhere.
- The block table maps a request's blocks to their real spots.
- Less waste means more requests at once and more throughput.
- When memory runs out, the engine preempts a request: swap or recompute.