Phase 06/Reading production engines/Reading vLLM source code
PHASE 06 · Reading production engines

Reading vLLM source code

0%
14 h6 subtopics2 lessons · 1 required
In plain English

You have used vLLM as a black box that takes prompts and returns tokens. Now you open the box. Reading a large codebase is like learning the layout of a hospital you have only visited as a patient. You start at the front desk (the API server), follow a request to triage (the scheduler), watch it get a bed (KV cache blocks), and see which specialists touch it (the attention backends and model runner). You will not read every file; you will trace one request end to end and write down the map, so that next time a question comes up you know exactly which room to walk into.

Why it matters

Every performance bug report, every "why is TTFT high under load" question, and every feature request in inference serving eventually requires reading engine code. Engineers who can trace a request through vLLM in an hour are the ones who get asked to fix the hard problems.

Hiring signal

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Anyscale, 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

  • Trace a single generate request from the OpenAI-compatible server to the sampled token and back.
  • Name the responsibilities of the engine core, scheduler, KV cache manager, model runner and attention backend.
  • Locate where continuous batching, prefix caching and CUDA graph capture are implemented.
  • Explain how the V1 engine's process split and asynchronous scheduling differ from the original design.
  • Produce an annotated call graph that another engineer could use as a guide.

Key concepts

Engine core
The loop that pulls scheduled requests, runs one model step, and returns outputs; lives in vllm/v1/engine.
Scheduler
Decides which requests run this step and how many tokens each gets; in V1 it treats prefill and decode uniformly as token budgets.
KV cache manager
Allocates fixed-size blocks to requests, frees them on completion, and implements prefix caching via block hashes.
Model runner
Prepares input tensors, calls the model forward, and manages CUDA graph capture and replay.
Attention backend
Pluggable implementation of paged attention (FlashAttention, FlashInfer, Triton) selected at startup.
Block table
Per-request list mapping logical token positions to physical KV cache block ids.
Sampler
Converts logits to token ids applying temperature, top-p, penalties and logprobs.

Subtopics

  1. 1. Repository layout and entry points

    Map vllm/entrypoints, vllm/engine, vllm/v1, vllm/attention, vllm/model_executor and csrc; identify which are legacy and which are the V1 path.

  2. 2. Request lifecycle through the V1 engine

    Follow AsyncLLM to EngineCore to Scheduler.schedule to ModelRunner.execute_model and back through the output processor.

  3. 3. Scheduler and KV cache manager

    Read vllm/v1/core/sched/scheduler.py and kv_cache_manager.py; understand token budgets, preemption and block hashing for prefix caching.

  4. 4. Model runner and CUDA graphs

    Read gpu_model_runner.py; find where input batches are padded for graph capture and how graph replay is chosen per batch size.

  5. 5. Attention backends and custom ops

    Read vllm/v1/attention/backends and csrc/attention; connect the Python metadata objects to the kernels they launch.

  6. 6. Reading strategy for large codebases

    Use grep, call hierarchy, git blame and failing tests to navigate; read design docs and RFC issues before code.

Resources

documentation
article

Hands-on lessons

L1

Annotated call graph of one generate request

CPU · your Macreading-code300 minrequired

Goal · Produce a markdown document that traces one chat completion request through vLLM V1 with file and line references at every hop.

  1. 1git clone https://github.com/vllm-project/vllm and check out the latest release tag; note the commit hash in your document.
  2. 2Start at vllm/entrypoints/openai/api_server.py and find the handler for /v1/chat/completions; record the function and the object it calls.
  3. 3Follow into vllm/v1/engine/async_llm.py and vllm/v1/engine/core.py; record how requests cross the process boundary.
  4. 4Open vllm/v1/core/sched/scheduler.py; annotate schedule() with the decisions it makes (new requests, running requests, preemption, token budget).
  5. 5Open vllm/v1/core/kv_cache_manager.py; record allocate_slots and free and how block hashes enable prefix caching.
  6. 6Open vllm/v1/worker/gpu_model_runner.py; find execute_model, the attention metadata build, and CUDA graph capture/replay.
  7. 7Open the attention backend directory and locate the backend class for FlashAttention; record which kernel is called.
  8. 8Draw the full path as a mermaid or ASCII call graph with a one-line note per node and a path:line reference.
Deliverable
vllm-request-trace.md containing the call graph, commit hash and at least 12 path:line references.
Check
A second person (or you after a week) can open any referenced path:line and find the described function; every hop from HTTP to sampled token is covered with no gaps.
L2

Instrument the scheduler and watch continuous batching

CPU · your Macscript120 minoptional

Goal · Add logging to Scheduler.schedule and observe how a mixed prefill and decode batch is formed step by step.

  1. 1pip install vllm in a fresh venv on Linux or Colab CPU runtime; on a Mac use a Colab CPU runtime or Docker (vLLM has a CPU backend: set VLLM_TARGET_DEVICE=cpu when building, or use the published CPU image).
  2. 2Patch vllm/v1/core/sched/scheduler.py to log, per step, the number of running requests, scheduled tokens per request and preemptions.
  3. 3Run facebook/opt-125m with the offline LLM API and submit 8 prompts of varying lengths with max_tokens=32.
  4. 4Record the log and plot scheduled tokens per request versus step number.
  5. 5Explain in a short paragraph when prefill tokens and decode tokens share a step.
Deliverable
A patch file plus a plot of tokens scheduled per step.
Check
The plot shows at least one step where a new request's prefill tokens are scheduled alongside other requests' single decode tokens.
Fallback
If vLLM will not install, read the scheduler and write the expected log by hand for the same 8 prompts, then compare with a real log from a friend's machine or Colab.

Build your own

Build your own vLLM call-graph explorer

PythonCPU · your Mac~8 h

A static import and call-graph tool for vllm/v1 that answers "who calls this" and renders the request path as Markdown with path:line references.

The real thing: github.com/scottrogowski/code2flow ↗

How you know a stage passes

Write tests/test_graph.py first against a frozen vLLM checkout (pin the commit in tests/VLLM_COMMIT and clone it in a fixture). Every stage adds assertions on the graph your tool produces from vllm/v1 (node and edge counts for a known file, presence of specific edges, exact path:line for a known definition) plus a CLI invocation that must exit 0. Run `pytest -q`; a stage is done when its test passes and all earlier tests still pass.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01module index with ast
    A `vgraph index <repo>` command walks vllm/v1, parses every file with ast, and records each class, function and method with its file and line number into a JSON index.
    test · The index contains an entry for Scheduler.schedule in vllm/v1/core/sched/scheduler.py whose line matches `grep -n 'def schedule' | head -1`; the CLI exits 0 and the JSON has at least 300 definitions.
  2. 02import graph
    Every import and from-import inside vllm/v1 becomes a directed edge between modules; relative imports are resolved to dotted paths.
    test · The import graph has an edge from vllm.v1.engine.core to vllm.v1.core.sched.scheduler and no edge pointing at a module that does not exist in the index; `vgraph imports vllm.v1.engine.core` prints the sorted list.
  3. 03call edges with receiver resolution
    Calls inside each function are resolved to definitions using local names, imports, self attributes assigned in __init__, and type annotations; unresolved calls are counted, not dropped.
    test · The graph has a call edge from EngineCore.step to Scheduler.schedule and from Scheduler.schedule to KVCacheManager.allocate_slots; the unresolved-call ratio printed by `vgraph stats` is below 40 percent.
  4. 04query commands
    `vgraph callers <symbol>`, `vgraph callees <symbol>` and `vgraph path <from> <to>` answer questions in under a second from the cached graph; path uses BFS over call edges.
    test · `vgraph path vllm.entrypoints.openai.api_server:create_chat_completion vllm.v1.sample.sampler:Sampler.forward` prints a chain of at least 6 hops each with path:line, and `vgraph callers KVCacheManager.allocate_slots` lists Scheduler.schedule.
  5. 05Markdown and Mermaid report
    `vgraph report <from> <to> -o trace.md` writes a Markdown document with one section per hop (signature, file:line, a 5-line code excerpt) and a Mermaid flowchart of the path.
    test · trace.md renders in GitHub preview, every path:line in it exists in the pinned checkout (a test opens each file and checks the line contains the symbol name), and the Mermaid block has one node per hop.
  6. 06diff two commits
    `vgraph diff <commitA> <commitB>` indexes both checkouts and prints added, removed and moved definitions and changed call edges along the request path.
    test · Running the diff between the pinned commit and one release later lists at least one moved or renamed symbol with its old and new path:line, and the tool's own lesson l1 trace document regenerates from the new commit without a missing-symbol error.

Knowledge check

QIn the vLLM V1 scheduler, how are prefill and decode distinguished?

They are not special-cased; each request has a number of tokens to compute this step, and the scheduler fills a token budget. A new request simply asks for many tokens and a decoding request asks for one.

QWhere does prefix caching live, and what key does it use?

In the KV cache manager; it hashes block-sized chunks of token ids (chained with the previous block hash) and reuses physical blocks whose hash matches.

QWhy does the model runner pad batches before CUDA graph replay?

CUDA graphs are captured for fixed shapes, so the runner pads the batch to the nearest captured size to reuse a graph instead of launching kernels one by one.

QWhich component decides which attention kernel is actually launched?

The attention backend selected at startup based on hardware and config; the model's attention layer calls into it through a common interface.

Completion

  • All 6 subtopics marked done
  • All 1 required lessons done
  • Lesson l1 call graph written with path:line references and committed to your notes repository.
  • Can describe the role of scheduler, KV cache manager, model runner and attention backend without notes.
  • All subtopics marked completed.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →