Pidoku

The Map: One Request, End to End

Module 16 Lesson 16.c 45 min Difficulty 2/5

Prerequisites 16.b


Before you start: words you need#

WordPlain meaning
ProcessA running program with its own memory. vLLM runs as several processes that send each other messages.
StepOne trip through the engine’s loop: decide a batch, run one forward pass, record the results.
SchedulerThe part of the engine that decides, every step, which requests run and how many of their tokens.
Token budgetThe most tokens one step may process (max_num_batched_tokens, 17.b).
DetokeniseTurn token IDs back into text.
ZeroMQ, msgpackA messaging library for sockets between processes, and a compact binary format for the messages (16.d).
Prefill / decodeReading the prompt, and then producing output one token at a time (12.c).

1. What is it?#

A map of vLLM: the route one request takes through the code, and where every piece of the code base sits relative to that route.

A request crosses up to three kinds of process and about a dozen named objects. Text becomes token IDs in the API server. Token IDs cross a socket to the engine core, where a scheduler decides, once per step, how many tokens of each request the GPU will process, and a KV cache manager hands out the memory blocks for them. The schedule goes on to the worker, whose model runner builds tensors and calls the model. One new token per request comes back the same way, is turned into text, and is streamed to the client. Then the loop runs again.

Everything else in Modules 16–19 is a closer look at one stop on this route. File paths and class names are from the v0.32.0 tag. Facts checked on 13 November 2026.

flowchart TB
  subgraph P0["API server process (asyncio)"]
    direction LR
    H[":i-globe: <b>HTTP handler</b><br/><small>FastAPI route</small>"] --> R[":i-file-text: <b>Renderer</b><br/><small>chat template, tokenise</small>"]
    R --> IP[":i-funnel: <b>InputProcessor</b><br/><small>validate, build request</small>"]
    IP --> AL[":vllm: <b>AsyncLLM</b><br/><small>admission, per-request queue</small>"]
    OP[":i-message-square: <b>OutputProcessor</b><br/><small>detokenise, stop strings</small>"] --> H
  end
  subgraph P1["Engine core process (busy loop)"]
    direction LR
    SCH[":i-list-checks: <b>Scheduler</b><br/><small>token budget, queues</small>"] --- KV[(":i-layers: <b>KVCacheManager</b><br/><small>block pool, prefix cache</small>")]
    SCH --> EX[":i-split: <b>Executor</b><br/><small>fan out to workers</small>"]
  end
  subgraph P2["Worker: one per GPU (inside the engine core with one GPU)"]
    direction LR
    MR[":pytorch: <b>Model runner</b><br/><small>build batch, sample</small>"] --> M[":nvidia: <b>Model + attention kernel</b>"]
  end
  AL -->|"EngineCoreRequest<br/>ZMQ + msgpack"| SCH
  EX -->|"SchedulerOutput"| MR
  MR -->|"ModelRunnerOutput<br/>sampled token IDs"| SCH
  SCH -->|"EngineCoreOutputs"| OP
  class H,R,IP io
  class AL,SCH,EX queue
  class OP neutral
  class KV memory
  class MR,M compute

2. Why does it matter?#

vLLM’s vllm/ directory holds about 1.04 million lines of Python. Reading it top to bottom is hopeless, and most of it (model implementations, kernels’ Python wrappers, quantisation formats) is never on the path a request takes. With the route in your head you can open any file and answer the first question that matters: which stop is this, and does it run once per request or once per token? Code that runs once per token is where performance lives.


3. Simple analogy#

A restaurant again. The waiter (API server) takes the order in words and writes it as item codes on a ticket. The ticket goes through the hatch (a socket) to the head chef (scheduler), who every minute decides which tickets the cooks work on next and which fridge shelf (KV cache block) each dish uses. The cooks (workers) do the cooking (the forward pass) and send back one finished dish per table. The waiter turns item codes back into dishes the guest understands (detokenising) and carries them out one dish at a time (streaming). The chef never speaks to a guest; the cooks never see a menu.


4. Tiny example: three requests, budget of eight#

The whole route, shrunk to a Go program you can hold in your head. There is no model; “running the GPU” just advances counters. What it keeps is the real control flow: a per-step token budget, running requests served before waiting ones, long prompts cut into chunks, and a token sampled only when a request has caught up.

Go
package main

import (
	"fmt"
	"strings"
)

type request struct {
	id       string
	prompt   int // prompt tokens
	maxNew   int // tokens to generate
	output   int // tokens generated so far
	computed int // tokens whose KV cache is on the GPU
}

// total is what vLLM calls num_tokens: prompt plus output so far.
func (r *request) total() int { return r.prompt + r.output }

type slot struct {
	r *request
	n int
}

func main() {
	const budget = 8 // max_num_batched_tokens: tokens the GPU processes per step

	waiting := []*request{
		{id: "A", prompt: 5, maxNew: 3},
		{id: "B", prompt: 12, maxNew: 2},
		{id: "C", prompt: 3, maxNew: 4},
	}
	var running []*request

	for step := 1; len(waiting)+len(running) > 0; step++ {
		left := budget
		var plan []slot

		// 1. Running requests are scheduled first.
		for _, r := range running {
			if left == 0 {
				break
			}
			n := min(r.total()-r.computed, left)
			plan = append(plan, slot{r, n})
			left -= n
		}
		// 2. Waiting requests are admitted while budget remains.
		for len(waiting) > 0 && left > 0 {
			r := waiting[0]
			waiting = waiting[1:]
			running = append(running, r)
			n := min(r.total()-r.computed, left)
			plan = append(plan, slot{r, n})
			left -= n
		}

		// 3. "Forward pass": every scheduled token gets its KV computed.
		var parts, events []string
		for _, s := range plan {
			s.r.computed += s.n
			parts = append(parts, fmt.Sprintf("%s:%d", s.r.id, s.n))
			// 4. A request that has caught up gets one sampled token.
			if s.r.computed == s.r.total() {
				s.r.output++
				events = append(events, fmt.Sprintf("%s->token %d", s.r.id, s.r.output))
			}
		}

		// 5. Finished requests leave and free their memory.
		keep := running[:0]
		for _, r := range running {
			if r.output == r.maxNew {
				events = append(events, r.id+" done")
				continue
			}
			keep = append(keep, r)
		}
		running = keep

		fmt.Printf("step %d  batch [%-11s] used %d/%d  %s\n",
			step, strings.Join(parts, " "), budget-left, budget, strings.Join(events, ", "))
	}
}

Output:

step 1  batch [A:5 B:3    ] used 8/8  A->token 1
step 2  batch [A:1 B:7    ] used 8/8  A->token 2
step 3  batch [A:1 B:2 C:3] used 6/8  A->token 3, B->token 1, C->token 1, A done
step 4  batch [B:1 C:1    ] used 2/8  B->token 2, C->token 2, B done
step 5  batch [C:1        ] used 1/8  C->token 3
step 6  batch [C:1        ] used 1/8  C->token 4, C done

Read it line by line. In step 1, request B gets only 3 of its 12 prompt tokens: that is chunked prefill. In step 2, A is already decoding (one token per step) while B is still reading its prompt in the same batch: that is continuous batching. C waits two steps because the budget is full, and joins in step 3 without anything pausing for it.


5. Technical explanation#

The route, step by step#

Follow one chat request. Class names are real; file paths are relative to the repository root.

#WhereWhat happensCode
1API serverFastAPI receives POST /v1/chat/completions and validates the JSON.vllm/entrypoints/openai/chat_completion/
2API serverThe renderer applies the model’s chat template to the messages and tokenises the result. Images and audio are preprocessed here too (16.e).vllm/renderers/
3API serverInputProcessor.process_inputs() checks the prompt fits max_model_len, validates the sampling parameters and builds an EngineCoreRequest.vllm/v1/engine/input_processor.py
4API serverAsyncLLM.add_request() checks admission limits, registers the request with the OutputProcessor, and sends it to the engine core.vllm/v1/engine/async_llm.py
5SocketThe request is encoded with msgpack and sent over a ZeroMQ socket (16.d).vllm/v1/engine/core_client.py
6Engine coreAn input thread decodes it and, in preprocess_add_request(), builds the scheduler’s Request, computing the block hashes of its prompt for prefix caching (17.f).vllm/v1/engine/core.py
7Engine coreThe busy loop calls scheduler.schedule(). It decides how many tokens of each request run this step and asks the KVCacheManager for blocks. Result: a SchedulerOutput (17.a).vllm/v1/core/sched/scheduler.py
8Engine core → workerThe executor hands the SchedulerOutput to every worker of this engine: a direct call with one GPU, a shared-memory broadcast with several.vllm/v1/executor/
9WorkerThe model runner turns it into tensors (token IDs, positions, block tables), runs the forward pass and samples one token per request that is ready for one (18.a, 18.b).vllm/v1/worker/gpu/model_runner.py
10Engine corescheduler.update_from_output() appends the new tokens, checks stop conditions and frees the blocks of finished requests.vllm/v1/core/sched/scheduler.py
11SocketEngineCoreOutputs (new token IDs for every request that produced any) go back over a second socket, sent by an output thread.vllm/v1/engine/core.py
12API serverOutputProcessor detokenises incrementally, checks stop strings and puts a RequestOutput on that request’s queue. The HTTP handler formats it as a server-sent event (16.f).vllm/v1/engine/output_processor.py

Steps 7 to 11 repeat once per generated token. A 500-token answer goes around that inner loop 500 times; steps 1 to 6 happen once.

The scheduler has no “prefill phase”#

The most useful comment in the whole code base sits at the top of Scheduler.schedule():

Python
# NOTE(woosuk) on the scheduling algorithm:
# There's no "decoding phase" nor "prefill phase" in the scheduler.
# Each request just has the num_computed_tokens and
# num_tokens_with_spec. num_tokens_with_spec =
# len(prompt_token_ids) + len(output_token_ids) + len(spec_token_ids).
# At each step, the scheduler tries to assign tokens to the requests
# so that each request's num_computed_tokens can catch up its
# num_tokens_with_spec. This is general enough to cover
# chunked prefills, prefix caching, speculative decoding,
# and the "jump decoding" optimization in the future.

Every request carries two counters:

  • how many tokens it has (prompt, plus output so far, plus any guessed tokens), and
  • how many of those the GPU has already processed (num_computed_tokens).

Scheduling is closing the gap between them under a budget. A fresh 3,000-token prompt has a gap of 3,000. A request in the middle of generating has a gap of exactly 1: the token it just sampled. Reading a long prompt in pieces (chunked prefill), skipping a prompt that is already cached (prefix caching) and checking several guessed tokens at once (speculative decoding) are all the same operation with different gap sizes. Hold on to this idea; it makes Module 17 short.

One object holds every setting#

Every class in the engine is constructed with a single VllmConfig (vllm/config/vllm.py). It bundles the model, cache, scheduler, parallel and compilation configs and a dozen more. The design choice is deliberate: a new feature that touches only the model runner adds one field to the config instead of threading a new argument through the engine, executor, worker and runner constructors. When these modules say “the scheduler reads max_num_batched_tokens”, it reads it from vllm_config.scheduler_config.

“V1” and the names you will meet#

The engine was rewritten in 2025. The rewrite lives in vllm/v1/ and is the only engine today; the old one is gone, but the directory name stayed.

NameMeaning
V1The current engine architecture, as opposed to the original 2023 design
Model Runner V2 (MRV2)A newer rewrite of just the model runner, in vllm/v1/worker/gpu/. The default since v0.25.0 for models it supports; the older vllm/v1/worker/gpu_model_runner.py is the fallback (18.a)
AsyncLLMThe engine as seen from an asyncio program; what the server uses (16.f)
LLMEngineThe same, synchronous; what the offline LLM class uses
EngineCoreThe scheduler-plus-executor loop itself (16.g)
APCAutomatic prefix caching (17.f)
TP / PP / DP / EPTensor, pipeline, data and expert parallelism (19.a)
P/DPrefill/decode disaggregation: different machines for the two halves of a request (19.b)

6. Under the hood: the code base in one table#

Line counts of Python under each directory at v0.32.0, rounded. Almost none of it is on the route above.

DirectoryLinesWhat lives there
vllm/v1/186,000The engine. Scheduler, KV cache, engine core, executor, workers, sampling, metrics. Most of Modules 16–19 are about it.
vllm/entrypoints/44,000HTTP servers and CLI: OpenAI, Anthropic and Cohere routes, vllm serve, the offline LLM class
vllm/renderers/10,000Chat templates and tokenisation, per model family
vllm/model_executor/374,000Model implementations in models/, shared layers in layers/ (attention, MoE, quantisation), weight loaders
vllm/models/150,000Newer model families packaged with their own pieces
vllm/distributed/80,000Multi-GPU communication and the KV connectors that move cache between machines
vllm/config/17,000Every configuration object; VllmConfig bundles them all
vllm/compilation/16,000torch.compile integration and CUDA graph wrappers (18.d)
vllm/tool_parsers/, vllm/reasoning/20,000Turning model text into tool calls and separating reasoning from answers (18.i)
vllm/lora/, vllm/multimodal/28,000Adapter management; image, audio and video preprocessing
vllm/platforms/, vllm/plugins/6,000Hardware abstraction (CUDA, ROCm, XPU, CPU) and extension points (19.f)
csrc/—C++ and CUDA: custom kernels, all-reduce, quantisation
rust/—An experimental replacement for the API server, written in Rust (19.h)

Model code (model_executor/ plus models/) is nearly three times the size of the engine and is not on the control path: it is called, once per step, from step 9.

Inside vllm/v1/, these files are the ones to know by name:

vllm/v1/
  engine/
    async_llm.py          the API server's handle on the engine
    core_client.py        the socket client (one class per topology)
    core.py               EngineCore: the busy loop and step()
    input_processor.py    request validation
    output_processor.py   detokenise, stop strings, per-request queues
  core/
    sched/scheduler.py    schedule() and update_from_output()
    kv_cache_manager.py   allocate_slots(), get_computed_blocks()
    block_pool.py         the blocks, the free queue, the hash table
    kv_cache_utils.py     block hashing; turning memory into a block count
  executor/               one engine core talking to N workers
  worker/
    gpu_worker.py         process setup, memory profiling
    gpu/model_runner.py   Model Runner V2: build the batch, run the model, sample
    gpu_model_runner.py   the older model runner
  attention/backends/     FlashAttention, FlashInfer, Triton, MLA variants
  sample/                 the sampler and logits processors
  structured_output/      grammar-constrained decoding
  spec_decode/            speculative decoding proposers
  metrics/                Prometheus and logging

7. Performance implications#

  • Per-token code is the hot path. Steps 7–11 run hundreds of times per request. A millisecond of Python there is a millisecond added to every token of every request in the batch. Steps 1–6 run once and mostly affect time to first token.
  • The engine core is one Python thread deciding for the whole GPU. If scheduling takes longer than the forward pass, the GPU waits. Async scheduling (17.d) exists to hide that.
  • Text never reaches the engine core. Tokenising and detokenising live in the API server so that the scheduler’s loop never waits for them.

8. Production implications#

  • When latency is bad, place it on the route first. Long time to first token with a short queue points at steps 1–6 (frontend, 16.e) or a long prefill; slow tokens afterwards point at steps 7–11.
  • Logs are tagged by process. A message from EngineCore and one from APIServer come from different stops on the map.
  • Configuration questions are answered in vllm/config/: every flag is a field there, with its docstring.

9. Common mistakes#

  1. Thinking in prefill and decode phases. The scheduler has none; it closes gaps between two counters.
  2. Assuming the engine core sees text. It sees token IDs only; stop strings are checked back in the API server.
  3. Reading gpu_model_runner.py and assuming it is what runs. For most models Model Runner V2 in vllm/v1/worker/gpu/ is the default; check which one your server logs.
  4. Getting lost in model_executor/. It is the biggest directory and the least relevant to how serving works.

10. Hands-on exercise#

  1. Raise budget in the program to 32 and rerun. How many steps does B’s prompt take now? What did that do to A’s time between tokens in the early steps? This is the real trade-off behind --max-num-batched-tokens (17.b).
  2. Add a fourth request with prompt: 40. Watch it take several steps to read its prompt while the others keep producing tokens.
  3. In a checkout of vLLM at tag v0.32.0, open vllm/v1/engine/core.py and find EngineCore.step. Match its calls (schedule, execute_model, sample_tokens, update_from_output) to steps 7 to 10 in the table above.
  4. Run grep -n "def " vllm/v1/engine/output_processor.py. Which functions run once per token?

11. Interview questions#

  1. Which steps of the route happen once per request, and which happen once per token?
  2. A request in the middle of generating text has what gap between its two counters?
  3. In which process does tokenisation happen, and why is it not the engine core?
  4. Why does vLLM pass one VllmConfig to every class instead of individual arguments?
  5. How do chunked prefill, prefix caching and speculative decoding all fit one scheduling rule?

12. Further reading#

Checked on 13 November 2026, against the v0.32.0 tag.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in