Lab 03 — Continuous Batching & PagedAttention
Phase: 08 — Inference Optimization at Depth | Difficulty: ⭐⭐⭐⭐⭐ | Time: 4–5 hours
vLLM's PagedAttention + continuous batching achieves 23× higher throughput than naive batching.
What you build
KVBlock— fixed-size memory block for KV cache storagePagedKVCache— block table mapping sequences to KV blocks, LRU eviction when OOMContinuousBatcher— admit new requests mid-batch, evict finished ones each stepsimulate_serving— end-to-end serving simulation with arrival/completion tracking
Key concepts
| Concept | What to understand |
|---|---|
| KV cache fragmentation | Static allocation wastes memory — paged allocation wastes ~0% |
| Block table | Sequence → list of physical block IDs (like virtual memory paging) |
| Continuous batching | Add/remove sequences each step — no waiting for full batch |
| LRU eviction | Evict least-recently-used blocks when new sequence can't fit |
| Preemption | Suspend running sequence, swap to CPU, resume when memory frees |
Files
| File | Purpose |
|---|---|
lab.py | Stubs with TODO markers |
solution.py | Complete working implementation |
test_lab.py | pytest suite |
requirements.txt | Dependencies |
Run
pip install -r requirements.txt
python lab.py
pytest test_lab.py -v