Phase 03/Memory and scheduling internals/PagedAttention and KV cache management
PHASE 03 · Memory and scheduling internals

PagedAttention and KV cache management

0%
7 h5 subtopics2 lessons · 1 required
In plain English

While a model writes an answer, it keeps notes about every word it has seen so far (the KV cache). Older servers reserved one long, fixed shelf per conversation for these notes, sized for the longest possible answer, so most of the shelf sat empty and no one else could use it. PagedAttention borrows a trick from how your computer manages memory: it chops the notes into small equal pages, stores them wherever a page is free, and keeps a table that says which pages belong to which conversation. Nothing is wasted, pages can be shared between conversations that start the same way, and the GPU can hold several times more simultaneous chats. This topic has you build that page allocator yourself.

Why it matters

KV cache capacity is the single biggest lever on serving throughput because it decides how many requests can decode together. Fragmentation in naive allocators wasted 60 to 80 percent of KV memory; PagedAttention is why vLLM beat earlier systems by 2 to 4x and it is now standard in every engine.

Hiring signal

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Baseten, Cerebras, Cohere, CoreWeave, Crusoe, Databricks, ElevenLabs, Fireworks, Hugging Face, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Explain internal and external fragmentation in contiguous KV allocation and quantify the waste.
  • Describe block tables and how the attention kernel gathers KV from non-contiguous blocks.
  • Implement a block allocator with allocate, append-token, free and prefix sharing in Python.
  • Explain copy-on-write for beam search and parallel sampling.
  • Describe preemption by recomputation versus swapping when blocks run out.

Key concepts

KV block
A fixed-size chunk (typically 16 tokens) of key and value cache for all layers, the unit of allocation.
Block table
Per-sequence list mapping logical block index to physical block id, passed to the attention kernel.
Internal fragmentation
Memory reserved for a sequence but never used because the answer finished early.
External fragmentation
Free memory split into pieces too small to fit a new contiguous reservation.
Prefix caching
Hashing the tokens of full blocks so identical prefixes map to the same physical block with a reference count.
Copy-on-write
Sharing a block between sequences until one writes to it, then copying; used for parallel sampling.
Preemption
Evicting a running sequence when blocks run out, either recomputing it later or swapping its blocks to CPU.
Gather overhead
Extra indirection the kernel pays to look up physical blocks; small compared with the memory savings.

Subtopics

  1. 1. Why contiguous KV allocation fails

    Reservation for max length, early finishes and unknown output lengths produce 60-80 percent waste per the vLLM paper's measurements.

  2. 2. Blocks, block tables and the kernel

    Logical to physical mapping, how the paged attention kernel reads the block table, and the cost of block size choices.

  3. 3. The block manager

    Free list, allocation on prefill, one new block per block_size decode tokens, freeing on completion.

  4. 4. Prefix caching and sharing

    Content hashing of full blocks, reference counts, LRU eviction of cached blocks, and copy-on-write.

  5. 5. Running out of memory

    Watermark reservation, preemption by recompute versus swap, and why vLLM V1 defaults to recompute.

Resources

paper
article
repo

Hands-on lessons

L1

Implement a paged KV block allocator in Python

CPU · your Macscript150 minrequired

Goal · A BlockManager class with block tables, prefix sharing and refcounts, plus a measurement of fragmentation versus a contiguous allocator.

  1. 1Define BlockManager(num_blocks, block_size) with a free list and a dict seq_id to block table.
  2. 2Implement allocate_prefill(seq_id, prompt_tokens) and append_token(seq_id) that allocates a new block only when the last one is full.
  3. 3Implement free(seq_id) returning blocks to the free list and add refcounts so shared blocks are freed only at zero.
  4. 4Add prefix caching by hashing full blocks (hash of prefix tokens) and reusing a cached block when the hash matches.
  5. 5Write a ContiguousAllocator that reserves max_len slots per sequence for comparison.
  6. 6Simulate 500 requests with random prompt lengths 50-500 and output lengths 20-400 (uniform), max_len 1024, on a budget of 2000 blocks of 16 tokens.
  7. 7Record peak concurrent sequences and wasted slots for both allocators; print a comparison table.
  8. 8Rerun with 60 percent of requests sharing a 200-token system prompt and report the extra concurrency from prefix caching.
Deliverable
block_manager.py, a test file with at least 8 pytest cases, and a printed comparison table.
Check
All tests pass; the paged allocator sustains at least 2x the concurrent sequences of the contiguous one and no physical block is ever double-owned without a refcount above 1.
L2

Gather attention over paged blocks in PyTorch

CPU · your Macnotebook60 minoptional

Goal · Show numerically that attention computed over a block table equals attention over a contiguous cache.

  1. 1Create a physical KV pool tensor of shape (num_blocks, block_size, n_heads, head_dim) with random values.
  2. 2Build a block table for a 40-token sequence that scatters its 3 blocks to non-adjacent physical ids.
  3. 3Gather K and V via the block table, trim to 40 tokens, and compute softmax attention for a random query.
  4. 4Build the contiguous equivalent and assert torch.allclose on the outputs.
Deliverable
A notebook with the passing allclose assertion.
Check
torch.allclose(paged_out, contiguous_out, atol=1e-5) is True.

Build your own

Build your own paged KV block manager

PythonCPU · your Mac~7 h

The allocator behind PagedAttention, from a free list of fixed-size blocks to prefix hashing, copy-on-write and LRU eviction, verified against a reference contiguous cache.

The real thing: github.com/vllm-project/vllm/blob/main/vllm/v1/core/block_pool.py ↗

How you know a stage passes

Write tests/test_block_manager.py first. Every stage adds property-style tests over random workloads (fixed seeds) that assert invariants of the allocator, and a comparison test that runs the same token sequences through a plain contiguous KV cache and checks that logical token positions map to identical values after gathering through your block table. Run `pytest -q`; a stage is done when its tests pass and all earlier tests still pass.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01a block pool with a free list
    BlockPool(num_blocks, block_size=16) hands out block ids from a free list and takes them back; it never hands out the same block twice.
    test · Allocating all N blocks succeeds, the N+1th allocation raises NoFreeBlocks, and after freeing everything len(pool.free_ids) equals N; a random allocate/free fuzz of 10,000 steps never produces a duplicate live id.
  2. 02block tables and slot mapping
    Each sequence owns a block table; append_tokens grows it one block at a time and slot_mapping(pos) returns (physical_block, offset).
    test · A 100-token sequence occupies exactly 7 blocks; slot_mapping(37) equals (block_table[2], 5); gathering a torch KV cache through the table reproduces the contiguous cache with torch.equal.
  3. 03prefix hashing
    Every full block gets a content hash chained on its parent block's hash; a dict maps hashes to physical blocks so identical prefixes resolve to the same blocks.
    test · Two sequences with the same 64-token prefix share 4 physical blocks; the hash of block i for prefix A differs from block i of prefix B when they diverge in block 0 even if block i's own tokens are identical.
  4. 04refcounts and copy-on-write
    Shared blocks carry refcounts; forking a sequence and appending diverging tokens into a partially filled shared block copies that block first.
    test · After fork and one diverging append, exactly 1 new block is allocated, the original sequence's gathered KV is unchanged, and the shared blocks have refcount 2.
  5. 05LRU eviction of cached blocks
    Freed blocks with a hash stay cached (refcount 0) in an LRU queue and are reclaimed only when the free list is empty, oldest first.
    test · With a 32-block pool and a 10-sequence workload totalling 400 blocks of demand, no allocation fails, and the eviction log shows blocks evicted in strictly increasing last-used order.
  6. 06fragmentation benchmark
    A script compares your allocator against a reserve-max-length contiguous allocator on a synthetic trace of 1,000 requests with random lengths up to 2048.
    test · Average internal waste per sequence is below block_size/2 tokens for paged and above 50 percent of reserved memory for contiguous; both numbers and the plot are in README.

Knowledge check

QWhat are the two kinds of waste PagedAttention eliminates?

Internal fragmentation (reserved-but-unused slots inside a sequence's allocation) and external fragmentation (free gaps too small to reuse).

QHow many new KV blocks does a running sequence need per decode step with block size 16?

On average one sixteenth of a block; a new block is allocated only when the current last block is full.

QWhy does prefix caching need reference counts?

Several sequences may map to the same physical block; it can only be returned to the free list when the last one releases it.

QWhat does the scheduler do when a new request needs blocks and none are free?

It preempts a running sequence, either freeing its blocks and recomputing it later or swapping its blocks to CPU memory.

Completion

  • All 5 subtopics marked done
  • All 1 required lessons done
  • All subtopics marked completed.
  • Lesson l1 block_manager.py passes its tests and the comparison table is saved.
  • Can explain block tables and prefix caching with a diagram in under five minutes.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →