Project: build a mini-vLLM with a paged KV cache and continuous batching
A multi-week portfolio brief: write a small LLM serving engine in Python and PyTorch with a block-based KV cache, a scheduler with a token budget, chunked prefill and preemption, prefix caching, sampling and an OpenAI-style streaming server. Prove it matches a reference, benchmark it against a baseline and vLLM, and write it up. Milestones, rubric and the questions reviewers ask.
By Sandip Maity, Applied AI Engineer
Key takeaways
- The heart of a vLLM-style engine is bookkeeping: block tables, a free list, reference counts and a scheduler that decides who runs each step.
- Prove correctness first: greedy outputs or logits must match a reference before any speed number counts.
- A simple gather-then-attend paged attention is correct and fast enough to start; a paged kernel is a stretch goal.
- Prefix caching needs hashes of full blocks chained to their parent, so equal prefixes share blocks and different prefixes never collide.
- Benchmark with open-loop arrivals against a baseline and against vLLM on the same model, hardware and workload.
Goal: build, test, measure and write up a small LLM serving engine that works the way vLLM does: a paged KV cache, a scheduler that batches requests continuously, prefix caching, sampling and a streaming API. The result is a repository a reviewer can run in ten minutes and a report that explains every number.
You need: Python and PyTorch, a small open model (0.5B parameters or smaller, so a laptop CPU can run the tests), and four to eight weeks part-time. A GPU helps for the final benchmark but is not required. Background: Build an Inference Engine (the forward pass, KV cache and batching), scheduling, chunked prefill and preemption, caching and how to build a portfolio project.
Honest limits. Your engine will be slower than vLLM, which has years of kernel work, CUDA graphs and a C++ and Python fast path. That is fine. The project shows that you understand the design and can measure it honestly. Claim "reaches X% of vLLM's throughput on this setup", not "competitive with vLLM".
#The brief
Write an engine that loads a real Llama-style or Qwen-style model from safetensors, serves it over HTTP with streaming, and runs many requests at once with a paged KV cache. Then prove three things: it is correct, its batching works (throughput rises with concurrency while latency stays bounded), and you know where its time goes.
flowchart LR C[Client] -->|POST /v1/completions| S[HTTP server<br/>streaming] S --> Q[Waiting queue] Q --> SCH[Scheduler<br/>token budget, max seqs] SCH --> BM[Block manager<br/>free list, block tables,<br/>prefix hashes] SCH --> MR[Model runner<br/>one forward per step] BM --> MR MR --> SM[Sampler] SM -->|new tokens| S SM --> SCH
#Minimum version
These are required. Build them in this order.
- Model runner. Your own forward pass in PyTorch for one architecture, loading weights from safetensors: embeddings, RMSNorm, RoPE, grouped-query attention, SwiGLU and the output head. Writing it yourself (instead of calling a library's model class) is what lets you control the KV cache. Read the model's
config.jsonfor the shapes, biases and whether the embeddings are tied. - Block manager. The KV cache is one preallocated tensor per layer, shaped as blocks of 16 tokens. Keep a free list, a block table per sequence (logical block to physical block), and a reference count per block. Allocate a block only when a sequence needs one.
- Paged attention, the simple way. For each sequence, gather its K and V from the block table into a contiguous tensor and call
torch.nn.functional.scaled_dot_product_attention. This is slower than a paged kernel but correct, and it lets you test everything else. - Scheduler. Each step, pick which requests run, under a token budget (for example 2,048 tokens) and a maximum number of running sequences. Decode tokens go first, then prefill fills the remaining budget. Long prompts are split into chunks across steps (chunked prefill).
- Preemption. When a running sequence needs a block and none is free, preempt the most recently admitted request: free its blocks and put it back at the front of the queue. When it runs again, it recomputes its KV cache.
- Sampling. Greedy, temperature, top-p and top-k, with a per-request seed so results are reproducible, and stop conditions (end-of-sequence token, stop strings,
max_tokens). - Server. An OpenAI-style
/v1/completionsendpoint with server-sent events, a/healthendpoint, a maximum prompt length that returns an HTTP 400, and cancellation when the client disconnects. - Metrics. Per step: running and waiting counts, KV blocks used, tokens scheduled, preemptions. Per request: time to first token, inter-token latency, prompt and output tokens. Expose them at
/metricsor log them as JSON lines.
Same hardware, same requests
Gaps are wasted GPU time. Continuous batching (used by llama.cpp server, vLLM and others) finishes sooner and keeps the GPU busier, which is how one machine serves many users.
Six requests (lengths 4, 9, 3, 6, 5, 2 steps = A to F) share 3 slots. Static batching waits for the slowest request in each batch. Continuous batching refills a slot the moment it frees up.
#Size the cache before you write it
Work out how many tokens fit, because it decides your batch size. For a model with layers, KV heads and head dimension , stored in 2-byte bf16:
For Qwen2.5-0.5B (check its config.json: 24 layers, 2 KV heads, head dimension 64) that is bytes, 12 KiB per token. A 4 GiB cache then holds about 349,500 tokens: 21,845 blocks of 16. Small models with grouped-query attention leave a lot of room. Write the same calculation for your model in the report.
Contiguous: reserve the maximum length (6 blocks) per sequence
Paged: blocks handed out as tokens arrive
Sequence A starts
Its first 16 tokens fill one block. Contiguous allocation (top) must reserve room for the maximum length up front.
Each cell is a 16-token block of KV memory. Colour = which sequence owns it; hatched = reserved but empty.
#Stretch goals
Pick one or two after the minimum version is measured.
- Prefix caching. Hash each full block from its tokens and its parent block's hash, keep freed blocks in an LRU cache keyed by that hash, and reuse them when a new request has the same prefix. Measure TTFT with and without it on a workload with a shared system prompt.
- A paged decode kernel. Replace gather-then-attend for decode with a Triton kernel that reads K and V straight from the blocks (a decode attention kernel in Triton). Compare inter-token latency at 16 and 64 sequences.
- CUDA graphs for decode. Capture the decode step for a few fixed batch sizes and pad to the nearest one (streams, events and CUDA graphs). Measure the step time at batch 1.
- Speculative decoding with a smaller draft model of the same family, with acceptance rate and speed-up reported (speculative decoding).
- Structured output with a grammar or JSON schema mask (grammar-constrained decoding).
The rest is Pro
Keep reading this full lab
Pro unlocks this full lab, every advanced lesson, the hands-on labs and completion certificates.
One year
$25
365 days, no auto-renewal
Lifetime Best value
$75
pay once, keep it forever
7-day refund, no questions asked. One payment, no auto-renewal.Compare plansHave a licence key?
Not ready? Keep learning free
Free lessons from Portfolio Projects, no sign-up. Or follow the free roadmap →
Not ready? Take the free 5-day email course
One short email a day for five days, each built on a free lesson, then the occasional new lesson or offer. Unsubscribe in one click.
Still to come in this lab
- Milestones
- Tests that matter
- Benchmark plan
- Rubric
- What a reviewer will ask you
- Checklist
- Where to go next
You will be able to answer
- Why does a paged KV cache let an engine run more requests at once?
- Two requests share a 1,536-token system prompt and the block size is 16. With prefix caching, what do they share?
- Your greedy outputs match the reference at batch size 1 but differ in a few tokens at batch size 16 in bf16. What is the most likely explanation?
- Memory runs out mid-decode. What does preemption by recompute do?