Roadmap/Phase 03
PHASE 03 OF 06

Inference Engines

Learn how vLLM, SGLang and TensorRT-LLM turn one slow model into a fast shared service.

0%
10 topics23 lessons74 h
In plain English

A trained model on its own is like a brilliant chef who can only cook one meal at a time and forgets the recipe between orders. An inference engine is the whole restaurant kitchen built around that chef: it takes orders from many customers at once, keeps half-finished dishes warm on numbered shelves, decides who gets served next, and makes sure the expensive oven (the GPU) is never sitting idle. This phase opens the doors of the three most important kitchens in the industry, vLLM, SGLang and TensorRT-LLM, and teaches you how each one is organised and how to measure which is fastest for a given job.

What you can do afterwards

You can stand up an OpenAI-compatible LLM server with vLLM or SGLang, explain how its scheduler and KV cache allocator work by simulating them in Python, read a TensorRT-LLM engine config, and produce a benchmark report with time to first token, inter-token latency and throughput under concurrent load.

Milestones

  1. M1Anatomy of a serving system
  2. M2Memory and scheduling internals
  3. M3Alternative engines
  4. M4Measuring engines

Capstone projects

Three sizes. The small one is part of finishing this phase (it carries 15% of the phase bar); medium and large are tracked but optional. Each lists what to build, what to leave out, what to measure, and what reviewers will look at.

Small

Build your own continuous-batching inference server

CPU · your Mac~8 h
one evening to a weekend · required for phase completion

Put the GPT-2 engine you wrote in Phase 1 behind an OpenAI-compatible API with a real scheduler: iteration-level batching, a paged KV cache with a block budget, admission control and preemption, all on CPU. It proves the phase because every component you simulated or read about in vLLM now exists as code you can step through, and the throughput gain over one-request-at-a-time serving is a number you measured.

Scope

  • A FastAPI process exposing /v1/completions and /v1/chat/completions with SSE streaming and OpenAI-shaped errors.
  • An engine process that runs one step loop; each step runs the batch of running sequences through your Phase-1 GPT-2 decoder with a padded or ragged attention path.
  • A paged KV cache with 16-token blocks, block tables per sequence and a fixed block pool.
  • A scheduler that admits waiting requests every iteration under the block budget, preempts the newest sequence when blocks run out, and resumes it by recompute.
  • A /metrics endpoint with running, waiting, block usage and preemption counters.
  • A bench script that drives the server at concurrency 1, 4 and 16 and reports TTFT, ITL and tokens per second.

Out of scope

  • GPU execution or custom kernels.
  • Prefix caching and chunked prefill (large capstone).
  • Sampling beyond greedy, temperature and top-k.

What to measure

Correctness versus your single-sequence engine
How · greedy 64-token outputs for 8 prompts served concurrently compared with the same prompts served one at a time
Target · 8 of 8 identical token sequences
Throughput gain from continuous batching
How · total tokens per second at concurrency 16 versus concurrency 1, 128 output tokens, median of 3 runs
Target · at least 4x on an 8-core CPU
Block budget invariant
How · an assertion in the step loop plus the /metrics block-usage gauge sampled every 100 ms
Target · never exceeds the pool size; zero assertion failures over a 200-request run
Preemption behaviour
How · run with a pool sized for 4 sequences and send 16 long requests
Target · preemption counter above 0, all 16 requests complete, outputs identical to the unconstrained run
Time to first token at concurrency 16
How · p50 and p99 from the bench script
Target · report both; p99 within 3x p50

Pay attention to

  • Padded batches silently corrupt attention if the mask and position ids are wrong for sequences of different lengths; test with lengths 5 and 200 in one batch.
  • A sequence that finishes mid-step must free its blocks before the next admission decision or the budget drifts upward.
  • Preempting by recompute must reset the sequence's position counter and block table, otherwise it resumes with stale KV.
  • Streaming must flush per token; buffering in the ASGI server makes TTFT look like e2e.
  • Measure throughput by counted output tokens, not by number of SSE chunks.

Acceptance (all must pass)

  • ☐pytest passes the 8-prompt correctness test and the block-budget invariant test.
  • ☐The openai Python client completes streaming and non-streaming requests against the server without modification.
  • ☐The preemption scenario completes with the counter above 0 and identical outputs.
  • ☐README contains the concurrency 1/4/16 table and a paragraph explaining the throughput curve.
Deliverable · A repository with api/, engine/, scheduler/ and kv/ packages, tests, bench.py and a README with the measured table.
Stretch · Add prefix sharing with refcounts and show the block savings for 8 requests sharing a system prompt. · Replace padded attention with a block-table gather so sequences of very different lengths waste no compute.
Medium

Build your own benchmark suite and compare vLLM vs SGLang on a T4

Colab T4 · free~20 h
a weekend or two · composes several builds

Turn your load generator into a reproducible benchmark suite and use it to produce a defensible head-to-head of vLLM and SGLang serving Qwen2.5-0.5B-Instruct on a free Colab T4: throughput-latency curves, TTFT and ITL percentiles at matched load, and a prefix-cache experiment that isolates RadixAttention against vLLM's prefix caching. It proves the phase because the result is a report a team could act on, with methodology that survives review.

Scope

  • A benchmark runner that launches each engine with pinned versions and documented arguments, waits for health, warms up, runs the workload matrix and tears down.
  • Three workloads with the same tokenizer-counted lengths on both engines, short chat (128 in, 128 out), long prompt (1,024 in, 128 out) and shared-prefix agent traffic (600-token system prompt plus 100-token user turns).
  • Open-loop sweeps at 5 request rates per workload, 3 repeats each, with results.json per run.
  • A prefix-cache experiment that toggles caching on and off in both engines and measures TTFT and prefill throughput on the shared-prefix workload.
  • Plots of throughput versus p99 TTFT and p99 ITL per engine per workload, and a percentile table at matched request rate.
  • A written report with methodology, results, a verdict per workload and a list of what would change the verdict.

Out of scope

  • Models larger than 1.5B parameters or quantized variants (T4 memory and time budget).
  • TensorRT-LLM (no Colab path without a paid GPU).
  • Tuning engine flags beyond the documented defaults plus one tuned configuration per engine.

What to measure

Methodology parity
How · a checklist in the report confirming identical model, dtype, max_model_len, sampling, dataset, token counting and warm-up on both engines
Target · all items checked, with the exact command lines
Repeatability
How · coefficient of variation of throughput across 3 repeats at each rate
Target · under 5 percent at rates below the knee
Throughput at matched p99 TTFT
How · interpolate each engine's curve at a 1 second p99 TTFT budget
Target · report both numbers per workload with the ratio
Prefix-cache effect
How · TTFT p50 on the shared-prefix workload, cache on versus off, per engine
Target · at least a 30 percent TTFT reduction with caching on for at least one engine; report both
Agreement with the engines' own tools
How · your throughput versus vllm bench serve and sglang.bench_serving at one matched rate
Target · within 5 percent

Pay attention to

  • Colab T4 sessions vary in clock and neighbour load; interleave engines run by run rather than finishing one engine first, and record GPU clocks with nvidia-smi.
  • SGLang and vLLM choose different default max-num-seqs and KV memory fractions; set them explicitly or the comparison is of defaults, not engines.
  • Count tokens with the model tokenizer on both sides; SSE chunk counts differ between engines.
  • Open-loop load that exceeds capacity makes queueing time dominate; mark the saturation point and do not compare percentiles past it.
  • Prefix caching only helps if requests arrive close enough together for the cache to be warm; report the arrival pattern.

Acceptance (all must pass)

  • ☐One command reproduces the full matrix from a fresh Colab session in under 90 minutes, excluding downloads.
  • ☐Every number in the report traces to a results.json committed in the repo.
  • ☐Curves for all three workloads and both engines are present with error bars from repeats.
  • ☐The report states a verdict per workload and the conditions under which it would flip.
Deliverable · A repository with the runner, raw results, plots and a 4-page report in markdown.
Stretch · Add a chunked-prefill on/off experiment on the long-prompt workload. · Add a third engine (llama.cpp server with a GGUF of the same model) to the short-chat workload.
Large

Build your own mini-vLLM

Colab T4 · free~40 h
1-3 weeks · portfolio piece

Write a GPU inference engine from scratch over a Hugging Face model: an OpenAI-compatible API, an asynchronous engine loop, a continuous-batching scheduler with chunked prefill, a paged KV cache with block tables, prefix caching via a radix tree, and a paged attention path in PyTorch. The target is Qwen2.5-0.5B-Instruct on a Colab T4 within 2-3x of vLLM's throughput on the same workload. This is the portfolio project for the phase, the kind of repository that gets you a systems interview.

Scope

  • A model runner that loads Qwen2.5-0.5B weights from safetensors into your own decoder modules (RMSNorm, RoPE, GQA, SwiGLU) in fp16 on GPU.
  • A paged KV cache with a block pool, block tables and a gather-based attention path over a [num_blocks, block_size, heads, head_dim] cache, with SDPA for prefill.
  • A scheduler with iteration-level batching, a token budget per step, chunked prefill, admission control and preemption by recompute.
  • Prefix caching with hashed full blocks or a radix tree, refcounts and LRU eviction.
  • An OpenAI-compatible server with SSE streaming, greedy, temperature, top-k and top-p sampling, stop strings and usage accounting.
  • CUDA Graphs or torch.compile for the decode step, measured before and after.
  • A benchmark using your load generator against both your engine and vLLM on the same T4 and workload.

Out of scope

  • Tensor parallelism or multi-GPU.
  • Custom CUDA kernels for attention (use PyTorch ops; Phase 2 and 4 cover kernels).
  • Models other than Qwen2.5-0.5B and 1.5B.
  • Quantization.

What to measure

Correctness versus transformers
How · greedy 64-token outputs for 20 prompts served at concurrency 16 compared with transformers generate on the same prompts in fp16
Target · at least 18 of 20 identical token sequences, and all 20 identical when both run in fp32 on a short 16-token output
Throughput relative to vLLM
How · output tokens per second at the request rate where vLLM's p99 TTFT is 1 second, short-chat workload, 3 repeats
Target · within 2-3x of vLLM (your engine at least one third of vLLM's throughput)
Decode step time
How · median step time at batch 32 with and without CUDA Graphs or torch.compile
Target · at least 1.5x faster with graphs; report both
Prefix-cache saving
How · prefill tokens computed on the shared-prefix workload with caching on versus off
Target · at least 50 percent fewer prefill tokens computed, TTFT p50 reduced
Memory safety
How · a 30-minute soak at 2x the knee request rate while sampling torch.cuda.memory_allocated
Target · no out-of-memory, block pool usage never above capacity, memory flat after warm-up
Preemption correctness
How · pool sized for 8 sequences, 64 long concurrent requests
Target · all complete, outputs identical to a run with an unlimited pool

Pay attention to

  • Position ids and RoPE for chunked prefill must be offset by the chunk start; a wrong offset passes short tests and fails on long prompts.
  • Mixing a prefill chunk and decode tokens in one step needs a single attention call with per-sequence context lengths; off-by-one in the block table lookup for the last partial block is the classic bug.
  • Sampling in fp16 can produce ties and NaNs; sample in fp32 after the final projection.
  • The CPU side (tokenize, schedule, detokenize) can dominate at small models; profile with py-spy before touching GPU code.
  • Prefix cache blocks must only be reused when the hash chain matches from block zero; a hash on block content alone is wrong.
  • Measure vLLM with the same max-num-seqs and KV budget as your engine, or the comparison is unfair in both directions.

Acceptance (all must pass)

  • ☐pytest passes the correctness, block-budget, preemption and prefix-cache tests on CPU with a tiny random-weight model and on Colab with Qwen2.5-0.5B.
  • ☐The openai client works unmodified for streaming and non-streaming chat completions.
  • ☐A benchmark table shows your engine and vLLM on the same T4 and workload, and your throughput is at least one third of vLLM's.
  • ☐A design document with a component diagram and a page on what you would change to reach parity.
  • ☐The engine runs from a clean clone with one command on Colab.
Deliverable · A public repository with the engine, server, tests, benchmark results versus vLLM, a design document and a write-up suitable as a blog post.
No GPU? · Run the same engine on CPU with Qwen2.5-0.5B in fp32 or with a 4-layer random-weight model; keep every test and every metric except the vLLM throughput ratio, and replace it with the throughput ratio of your engine against transformers generate at batch 1.
Stretch · Add speculative decoding with an n-gram draft and measure acceptance rate. · Add a Triton paged-attention kernel and compare against the PyTorch gather path. · Support Qwen2.5-1.5B and show where the T4 KV budget forces preemptions.