Before you start: words you need#
| Word | Plain meaning |
|---|---|
| Executor | The object in the engine core that sends one instruction to every GPU process and collects the answer. |
| Worker | One process that owns one GPU. It loaded that GPU’s share of the weights and holds its KV cache. |
| Model runner | The object inside a worker that does one step: build the input tensors, run the model, sample. |
| Rank | The number of one worker in a group of workers (rank 0, rank 1, …). |
| Shard | The slice of a weight matrix that one GPU holds under tensor parallelism (14.c). |
| Persistent batch | Per-request state (block tables, temperatures, …) kept on the worker between steps, so each step only applies what changed. |
| Pinned memory | CPU memory the operating system promises not to move, so the GPU can copy from it asynchronously. |
| Synchronisation | Making the CPU wait until the GPU has finished its queued work. In a model runner it is almost always a bug. |
1. What is it?#
The scheduler produces a plan: “these requests, this many tokens each, these blocks” (17.a). Three layers turn that plan into arithmetic:
- The executor delivers the plan to every GPU that holds a piece of the model.
- The worker is the process that owns one GPU. It loaded the weights and allocated the KV cache at startup.
- The model runner inside it does the real work each step. It keeps a table of every active request, assembles this step’s input tensors from that table, calls the model, samples, and reports back.
The runner is where most of vLLM’s per-token CPU cost is spent. Its central trick, never rebuild what did not change, is worth understanding before reading any tensor code.
vLLM v0.32.0 (18 October 2026) ships two model runners. Model Runner V2 (MRV2) has been the default since v0.25.0 and is what you get unless a feature it does not support forces the older one. This lesson reads the v0.32.0 source. Facts checked on 12 November 2026.
2. Why does it exist?#
A model that fits on one GPU could, in principle, be called directly from the engine loop. Three things make the split necessary:
- Many GPUs. Under tensor parallelism (14.c) every GPU must run every layer at the same time with the same batch. Somebody has to broadcast the plan, and only one rank should answer.
- Process isolation. CUDA state, memory pools and NCCL groups belong to a process. Keeping them in a worker process means the engine core’s scheduling loop is never blocked by Python work on the GPU side (16.d).
- CPU cost per step. At hundreds of requests per step, rebuilding every per-request tensor in Python each token would cost more than the forward pass of a small model. The runner exists to make that cost small and to keep it off the GPU’s critical path.
3. Simple analogy#
A restaurant chain sends tonight’s order list to each kitchen (the executor). Each kitchen has its own staff and ovens (the worker). The head cook in each kitchen (the model runner) keeps a whiteboard with one row per table. When a table leaves or arrives, the cook wipes or writes one row. The cook never redraws the whole whiteboard for every dish, and never stops cooking to wait for a waiter to read it.
4. Tiny example: one step with two GPUs#
EngineCore schedule() -> SchedulerOutput {A: 1 token, B: 512 tokens, C finished}
Executor put ("execute_model", SchedulerOutput) on the shared-memory queue
Worker 0, 1 both dequeue it
runner drop C's row; add B's new block IDs; A's row is unchanged
runner build input_ids, positions, block tables for 513 tokens
model forward pass; the two GPUs all-reduce inside every layer
Executor put ("sample_tokens", grammar bitmask)
runner sample one token for A and one for B
Worker 0 return ModelRunnerOutput {A: [token], B: [token]}
Worker 1 returns nothing: its answer would be identical5. Technical explanation#
The executor#
Executor (vllm/v1/executor/abstract.py) is a small interface. The engine core calls a handful
of methods and does not care how many GPUs are behind it:
| Method | Purpose |
|---|---|
execute_model(scheduler_output, non_block=...) | Run the forward pass. Can return a future. |
sample_tokens(grammar_output, non_block=...) | Sample from the logits just computed |
determine_available_memory() | Ask each worker how much memory is left for the KV cache |
get_kv_cache_specs() | Ask each worker what its layers need (17.i) |
initialize_from_config(kv_cache_configs) | Tell each worker to allocate its KV cache |
collective_rpc(method, args) | Call any method on every worker and gather the results |
collective_rpc is the general mechanism; the others are built on it. Loading a LoRA adapter,
profiling, sleep mode and weight reloading all go through it.
Executor.get_class picks the implementation from --distributed-executor-backend:
| Class | When | How workers are reached |
|---|---|---|
UniProcExecutor (uni) | One GPU, no extra process needed | A direct method call in the same process |
MultiprocExecutor (mp) | Several GPUs on one node, the usual case for -tp N | The shared-memory broadcast queue (16.d) |
RayDistributedExecutor (ray) | Workers on several nodes | Ray actors. VLLM_USE_RAY_V2_EXECUTOR_BACKEND=1 selects the newer RayExecutorV2, which reuses the multiprocess worker code. |
ExecutorWithExternalLauncher | Launched by torchrun, one engine per rank | No broadcast; every rank runs its own copy |
With MultiprocExecutor, execute_model has one line of substance: enqueue the method name and
arguments on the broadcast queue. Every worker dequeues and runs it; only the output rank replies.
The worker#
A worker (vllm/v1/worker/gpu_worker.py) is created once per GPU and does its important work at
startup:
- Claim the device (
init_device). Set the CUDA device from itslocal_rank, take the memory snapshot used for the budget, join the tensor-, pipeline- and data-parallel groups, and build the model runner (MRV2 or the older one). - Load the model (
load_model). Build thetorch.nn.Moduleand load only this rank’s shard. - Report and allocate (
get_kv_cache_spec,determine_available_memory,initialize_from_config). Run the memory profile, then allocate the KV cache tensors when told how many blocks (17.h). - Compile and warm up (
compile_or_warm_up_model). Runtorch.compile, capture CUDA graphs (18.d), run dummy batches.
After that the worker is a thin shell: execute_model forwards to the runner and, under pipeline
parallelism, passes intermediate activations to the next stage.
Weights are sharded while loading, not after#
Every vLLM model class has the same constructor:
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):Each layer creates only the slice of each weight matrix its rank owns. The architecture document explains the rejected alternative:
Suppose we want to run a 405B model (with roughly 810GB weights) with 16 H100 80GB GPUs. Ideally, every GPU should only load 50GB weights. If we change the model weights after the model is initialized, we need to load the full 810GB weights to every GPU and then shard the weights, leading to a huge memory overhead.
Quantisation works the same way: a layer that will run quantised is built quantised (18.j). Nothing is loaded at full size and shrunk afterwards.
The model runner’s job each step#
In MRV2 (vllm/v1/worker/gpu/model_runner.py, class GPUModelRunner), one
execute_model(scheduler_output) call does, in order:
| Step | MRV2 method | Older runner equivalent | What happens |
|---|---|---|---|
| 1 | finish_requests, free_states, add_requests, update_requests | _update_states | Apply the schedule: drop finished requests, give new ones a row, append new block IDs |
| 2 | gather_batch_req_state | _determine_batch_execution_and_padding | Order this step’s requests and choose a CUDA graph shape, synchronised across data-parallel ranks |
| 3 | prepare_inputs | _prepare_inputs | Build the flat input tensors (18.b), mostly with Triton kernels on the GPU |
| 4 | prepare_attn | _build_attention_metadata | Block tables and slot mappings for the attention backend (18.c) |
| 5 | encoder runner | _execute_mm_encoder | Run the vision or audio encoder for media scheduled this step (18.h) |
| 6 | graph replay or self.model(...) | _model_forward | The forward pass. Returns hidden states. |
Then sample_tokens(grammar_output) applies the grammar mask, runs the sampler (18.e) and the
drafter if speculative decoding is on (18.f), and returns a ModelRunnerOutput with one or more
token IDs per request.
The persistent batch#
Consider what the model needs for 500 running requests: a block table of 500 rows by thousands of columns, 500 temperatures, 500 top-p values, 500 seeds. In consecutive steps these are almost identical; perhaps two requests finished and three joined. The MRV2 design document states the idea:
The persistent batch optimization exploits the fact that request batches in consecutive steps are mostly identical. Only a few requests (if any) join or finish per step. By maintaining persistent state tensors and applying incremental diffs instead of reconstructing inputs from scratch, CPU overhead can be reduced significantly.
This is why the scheduler sends only differences for requests the worker already knows
(CachedRequestData, 17.a): the worker has everything else.
Two runners#
| Older runner (“V1 model runner”) | Model Runner V2 | |
|---|---|---|
| Location | vllm/v1/worker/gpu_model_runner.py, one file of about 7,300 lines | vllm/v1/worker/gpu/, split by feature (sample/, spec_decode/, mm/, model_states/, …) |
| Persistent state | The persistent tensors are the model inputs, so rows must stay in a required order and be compacted when requests leave | Each request owns a fixed row for its lifetime; inputs are gathered from state each step |
| Input preparation | NumPy on the CPU, then copied | Triton kernels on the GPU |
| Sampling | PyTorch operations | Triton kernels, including a Gumbel-max sampler |
| CUDA graphs | Implicit, through a dispatcher and wrappers | An explicit CudaGraphManager |
| Async scheduling (17.d) | Retrofitted; not with pipeline parallelism | Assumed from the start |
VllmConfig.use_v2_model_runner decides at startup:
- HiSparse sparse-MLA offloading and watermarking require MRV2 and force it on.
VLLM_USE_V2_MODEL_RUNNER=0or=1overrides everything else.- Without Triton, the older runner is used.
- Otherwise MRV2 is used unless
_get_v2_model_runner_unsupported_featuresfinds something. In v0.32.0 that list is short: thesuffix,medusa,mlp_speculatorandcustom_classspeculative methods, parallel drafting for EAGLE (P-EAGLE), draft models with a different vocabulary, pipeline parallelism undertorchrun, and some dual-batch-overlap options. The log names the reason: “Model Runner V2 does not yet support …; using the V1 model runner instead.”
6. Under the hood#
The MRV2 design is worth reading for three ideas that apply well beyond vLLM.
Fixed rows. Pre-allocate state for max_num_reqs rows (1,024 by default on most platforms).
A request takes a free row when it starts and keeps it until it ends. A preempted request is
treated as finished and re-added later. Nothing is ever shifted, so the older runner’s backup
copy of request state (CachedRequestState) is no longer needed.
No shared buffer between CPU and GPU. An asynchronous copy to the GPU reads a pinned CPU buffer later. If the CPU overwrites that buffer for the next step first, the GPU receives corrupt data. The older runner guards such buffers with an “async barrier”. MRV2 removes the hazard by copying from a private temporary:
self.states[req_idx] = new_req.data # self.states is NOT pinned
tmp_states = self.states.pin_memory() # a private pinned copy
states = tmp_states.to("cuda", non_blocking=True)The CPU keeps writing to self.states; the GPU reads tmp_states. No barrier, no race.
Send differences, apply them on the GPU. A block table is too large to copy every step.
StagedWriteTensor (vllm/v1/worker/gpu/buffer_utils.py) keeps the table on the GPU, collects
this step’s changes on the CPU, packs them into one contiguous buffer, copies that, and launches
one kernel to apply them:
state = StagedWriteTensor(size=(1024, 1000), dtype=torch.int32, device="cuda")
state.stage_write(row=2, start=3, value=[3, 1, 2])
state.stage_write(row=0, start=1, value=[-1, -2, -5])
state.apply_write()Why the runner must never synchronise#
All of this serves one rule: the Python thread must not wait for the GPU. Reading a GPU value
into Python (.item(), .tolist(), an unpinned .to("cuda")) forces all queued work to finish.
With async scheduling the engine has already queued the next step, so one accidental
synchronisation stalls the pipeline and silently removes the benefit. The MRV2 document describes
the target as “a CUDA stream with no CPU synchronization points. CPU entrypoints queue work onto
the stream.” The one unavoidable synchronisation, fetching sampled token IDs for the scheduler,
happens once per step, as late as possible.
How much a persistent batch saves#
This program runs the same request trace two ways: rebuilding every block-table row each step, and applying only what changed (one write per new block, plus one full row when a request joins).
package main
import (
"fmt"
"math/rand"
)
const (
maxReqs = 1024
steps = 2000
blockSize = 16
)
type req struct {
row int
tokens int // tokens so far
remaining int // tokens still to generate
}
func main() {
rng := rand.New(rand.NewSource(1))
active := map[int]*req{}
var freeRows []int
for i := maxReqs - 1; i >= 0; i-- {
freeRows = append(freeRows, i)
}
var rebuildWrites, diffWrites, joins, leaves int
nextID := 0
for s := 0; s < steps; s++ {
// A few requests arrive each step, with prompts of a few hundred tokens.
for arrivals := rng.Intn(3); arrivals > 0 && len(freeRows) > 0; arrivals-- {
row := freeRows[len(freeRows)-1]
freeRows = freeRows[:len(freeRows)-1]
r := &req{row: row, tokens: 200 + rng.Intn(800), remaining: 50 + rng.Intn(400)}
active[nextID] = r
nextID++
joins++
// Diff: write this request's whole row once (its block IDs so far).
diffWrites += r.tokens/blockSize + 1
}
for id, r := range active {
// Rebuild: copy this request's entire block-table row, every step.
rebuildWrites += r.tokens/blockSize + 1
// Diff: one new block ID, and only when a block boundary is crossed.
r.tokens++
if r.tokens%blockSize == 1 {
diffWrites++
}
r.remaining--
if r.remaining == 0 {
freeRows = append(freeRows, r.row) // the row is reused; nothing shifts
delete(active, id)
leaves++
}
}
}
fmt.Printf("%d steps, %d requests joined, %d finished, %d still active\n",
steps, joins, leaves, len(active))
fmt.Printf("block-table entries written, rebuilding each step: %d\n", rebuildWrites)
fmt.Printf("block-table entries written, applying diffs: %d\n", diffWrites)
fmt.Printf("ratio: %.0fx fewer writes\n", float64(rebuildWrites)/float64(diffWrites))
}Output:
2000 steps, 1974 requests joined, 1742 finished, 232 still active
block-table entries written, rebuilding each step: 20588110
block-table entries written, applying diffs: 102847
ratio: 200x fewer writesTwo orders of magnitude, and block tables are only one of a dozen per-request tensors. This is the saving that makes a Python model runner viable at hundreds of requests per step.
7. Performance implications#
- CPU time per step matters most for small models and small batches, where the forward pass is a few milliseconds. MRV2 moves input preparation onto the GPU, so it costs microseconds of launch time instead of milliseconds of Python.
- Async scheduling hides what is left. With async scheduling (the default when compatible), the scheduler and runner prepare step N+1 while the GPU runs step N. Anything that synchronises breaks the overlap.
- Only one rank returns output. Under tensor parallelism all ranks run the forward pass and the sampler; only the output rank serialises results back. The others do the same work so that they stay in step.
- Large state lives on the GPU. MRV2 keeps big per-request tensors in GPU memory and uses unified virtual addressing for a few CPU-resident ones (such as full prompt token lists), which costs a little GPU memory but removes per-step copies.
8. Production implications#
- Read the startup log. It names the executor, the model runner and, if the older runner was chosen, the feature that forced it. A surprise fallback is usually a speculative method or a parallelism option.
- Pin the runner when bisecting.
VLLM_USE_V2_MODEL_RUNNER=0switches back to the older runner. If a regression disappears, report it against MRV2; do not leave the override in production, since newer features (watermarking, HiSparse, DFlash and DSpark speculators) land in MRV2 first. - Startup work is per worker. Loading, profiling, compilation and graph capture all happen on every GPU. Multi-GPU startup time is set by the slowest worker.
collective_rpcis your debugging hook. From the offline API you can call any worker method on every rank, which is how most operational tooling (sleep mode, weight reload) works.
9. Common mistakes#
- Assuming vLLM rebuilds the batch every step. It applies diffs. A plugin or patch that mutates per-request state outside the runner’s update path will be overwritten or ignored.
- Adding a
.item()in the hot path. It silently synchronises and removes the async overlap. Profile with Nsight Systems (6.d) and look for gaps between steps. - Reading the older runner’s code as current.
gpu_model_runner.pyis still in the tree, but most deployments runvllm/v1/worker/gpu/. - Expecting every rank to return tokens. Only the output rank does; the others return nothing.
- Loading full weights and sharding later in a custom model. Build sharded layers from the start, or a large model will not fit during loading.
10. Hands-on exercise#
- In the program, make every request very short (
remaining: 2 + rng.Intn(4)) so that the batch turns over almost completely each step. What happens to the ratio? When does a persistent batch stop paying for itself? - Start a server and find the line that names the model runner. Then start it with a
speculative config using
"method": "suffix"and find the fallback message. - From the offline API, call
llm.collective_rpc("get_kv_cache_spec")withtensor_parallel_size=2. How many entries come back, and are they identical? - Open
vllm/v1/worker/gpu/model_runner.pyat the v0.32.0 tag and list every place inexecute_modelthat copies data from CPU to GPU. Which helper does each one use?
11. Interview questions#
- Why does every vLLM model class take the same constructor arguments, and what would break if weights were sharded after loading?
- What is wrong with copying a pinned CPU buffer to the GPU asynchronously and then reusing that buffer? How does MRV2 avoid it without a barrier?
- Under tensor parallelism, how many workers run the forward pass, and how many return the sampled tokens? Why?
- What is a persistent batch, and why does it lower CPU cost per step?
- Name two features that make vLLM v0.32.0 fall back to the older model runner.
12. Further reading#
Checked on 12 November 2026.
- Model Runner V2 design (vLLM v0.32.0 docs)
- Architecture overview: the class hierarchy and the 405B sharding example
vllm/v1/executor/abstract.py:Executorandget_classvllm/v1/executor/multiproc_executor.pyvllm/v1/worker/gpu_worker.pyvllm/v1/worker/gpu/model_runner.py: Model Runner V2vllm/v1/worker/gpu/buffer_utils.py:StagedWriteTensorvllm/v1/worker/gpu_model_runner.py: the older runnervllm/config/vllm.py:use_v2_model_runnerand_get_v2_model_runner_unsupported_features