Pidoku

The Engine Core Loop

Module 16 Lesson 16.g 50 min Difficulty 3/5

Prerequisites 16.f


Before you start: words you need#

WordPlain meaning
FutureA placeholder for a result that is not ready yet. You can start work, keep going, and collect the result later.
Non-blocking callA call that returns at once, usually with a future, instead of waiting for the work to finish.
Grammar bitmaskFor structured output (JSON, regex), a mask of which tokens the grammar allows next (18.e).
Batch queueA short queue of batches that have been scheduled and started on the GPU but whose results have not been processed yet.
Async schedulingPlanning step N+1 while the GPU is still running step N (17.d).
Utility callA remote method call from the API server to the engine core, such as “load this LoRA adapter” (16.d).
Sleep modeReleasing a server’s GPU memory while keeping its process alive, so it can be woken quickly.

1. What is it?#

The engine core is a while loop. Each turn it empties its inbox, asks the scheduler what to run, sends that to the workers, waits for sampled tokens, tells the scheduler what happened, and posts the results. That is one step, and one step produces at most one token per request (more with speculative decoding).

In the default configuration the loop does something subtler: it plans step N+1 while the GPU is still computing step N, so the GPU does not wait for Python. Understanding this loop is understanding where every millisecond of per-token latency goes. Read from the v0.32.0 source (vllm/v1/engine/core.py); facts checked on 13 November 2026.

flowchart TB
  A[":i-mail: <b>Drain input queue</b><br/><small>ADD, ABORT, UTILITY</small>"] --> B{"has work?"}
  B -- "no" --> A
  B -- "yes" --> C[":i-list-checks: <b>scheduler.schedule()</b><br/><small>pick tokens, allocate blocks</small>"]
  C --> D[":i-split: <b>executor.execute_model()</b><br/><small>non-blocking, returns a future</small>"]
  D --> E[":i-code: <b>get_grammar_bitmask()</b><br/><small>runs while the GPU works</small>"]
  E --> F[":nvidia: <b>wait for forward pass</b><br/><small>then sample_tokens()</small>"]
  F --> G[":i-ban: <b>process aborts</b><br/><small>that arrived meanwhile</small>"]
  G --> H[":i-check: <b>scheduler.update_from_output()</b><br/><small>append tokens, stop checks, free</small>"]
  H --> I[":i-message-square: <b>output queue</b><br/><small>to the output thread</small>"]
  I --> A
  class A,I io
  class B,C,G,H queue
  class D,E neutral
  class F compute

2. Why does it matter?#

Every generated token passes through this loop once. Anything the loop does in Python between two forward passes is time the GPU may spend idle, multiplied by every token of every request. The loop’s design (split model calls, abort handling, the batch queue) is a list of answers to one question: how do we keep a GPU busy from a single Python thread? And when a server misbehaves (stalls during a LoRA load, spins at 100% CPU while idle-looking, refuses to free memory), the explanation is almost always in this loop.


3. Simple analogy#

An air-traffic controller with one runway. Each cycle they read new messages, decide which planes land next, clear them, wait for them to touch down, update the board, and announce arrivals. A good controller does not wait for a plane to stop rolling before clearing the next one; they clear plane N+1 while plane N is still on the runway, so the runway is never empty. But they cannot yet know where plane N will taxi to, so they plan N+1 with a pencilled-in gap that is filled when N reports in.


4. Tiny example: what overlap buys#

How much does overlapping scheduling with the GPU buy? This program times both loops for a range of batch sizes. CPU cost per step grows with the number of requests; GPU cost grows more slowly, so the idle gap matters most exactly when the server is busy.

Go
package main

import "fmt"

func main() {
	fmt.Printf("%8s %10s %10s %14s %14s %9s\n",
		"requests", "cpu ms", "gpu ms", "sync tok/s", "async tok/s", "gain")

	for _, n := range []int{1, 8, 32, 128, 256, 512} {
		// Rough shapes, not measurements: Python work is linear in batch size,
		// a decode forward pass has a fixed cost plus a small per-request cost.
		cpu := 0.25 + 0.012*float64(n) // schedule + update_from_output
		gpu := 8.0 + 0.03*float64(n)   // one decode step

		syncStep := cpu + gpu // the GPU waits while Python plans the next step
		asyncStep := gpu      // planning overlaps the previous forward pass
		if cpu > gpu {
			asyncStep = cpu // Python is now the bottleneck
		}

		syncTok := float64(n) / syncStep * 1000
		asyncTok := float64(n) / asyncStep * 1000
		fmt.Printf("%8d %10.2f %10.2f %14.0f %14.0f %8.1f%%\n",
			n, cpu, gpu, syncTok, asyncTok, 100*(asyncTok/syncTok-1))
	}
}

Output:

requests     cpu ms     gpu ms     sync tok/s    async tok/s      gain
       1       0.26       8.03            121            125      3.3%
       8       0.35       8.24            932            971      4.2%
      32       0.63       8.96           3335           3571      7.1%
     128       1.79      11.84           9394          10811     15.1%
     256       3.32      15.68          13472          16327     21.2%
     512       6.39      23.36          17208          21918     27.4%

The costs are invented shapes, not measurements, but the pattern is the real one: the gain grows with concurrency, which is why async scheduling became the default. Notice the if cpu > gpu branch as well: once Python’s per-step work exceeds the forward pass, a faster GPU does not help. That happens with very small models at very high concurrency, and it motivates the Rust frontend and moving work off the engine core’s main thread.


5. Technical explanation#

The loop itself#

EngineCoreProc.run_busy_loop:

Python
def run_busy_loop(self):
    """Core busy loop of the EngineCore."""
    while self._handle_shutdown():
        # 1) Poll the input queue until there is work to do.
        self._process_input_queue()
        # Publish request counts before and after GPU step to ensure freshness.
        self._maybe_publish_request_counts()
        # 2) Step the engine core and return the outputs.
        self._process_engine_step()
        self._maybe_publish_request_counts()

    raise SystemExit

(The request-count publishing is for data-parallel load balancing and does nothing otherwise.) “Busy” has a precise meaning. _process_input_queue blocks on the queue only when there is nothing to do:

Python
def has_work(self) -> bool:
    """Returns true if the engine should be stepped."""
    return (
        self.engines_running
        or self.scheduler.has_requests()
        or bool(self.batch_queue)
    )

With no requests the engine sleeps on input_queue.get() and uses no CPU. The moment one request exists, the loop spins without sleeping until every request is finished. An idle vLLM server shows about 0% CPU for the engine core; a loaded one shows 100% of one core. Both are correct.

One step, the simple way#

EngineCore.step() is the version to learn first:

Python
def step(self) -> tuple[dict[int, EngineCoreOutputs], bool]:
    if not self.scheduler.has_requests():
        return {}, False
    scheduler_output = self.scheduler.schedule(self._should_throttle_prefills())
    future = self.model_executor.execute_model(scheduler_output, non_block=True)
    grammar_output = self.scheduler.get_grammar_bitmask(scheduler_output)
    with (...):
        model_output = future.result()
        if model_output is None:
            model_output = self.model_executor.sample_tokens(grammar_output)

    # Before processing the model output, process any aborts that happened
    # during the model execution.
    self._process_aborts_queue()
    engine_core_outputs = self.scheduler.update_from_output(
        scheduler_output, model_output
    )
    ...
    return engine_core_outputs, scheduler_output.total_num_scheduled_tokens > 0

Five things happen, in this order:

#CallWhat it doesRuns on
1scheduler.schedule()Chooses how many tokens of which requests run; allocates KV blocks; returns a SchedulerOutput (17.a)CPU, engine core
2execute_model(non_block=True)Ships the SchedulerOutput to the workers and returns at once with a future—
3get_grammar_bitmask()For requests using structured output, computes which tokens the grammar allows nextCPU, while the GPU runs
4future.result() then sample_tokens()Waits for the forward pass, then sends the bitmask and asks the workers to sampleGPU
5update_from_output()Appends each new token to its request, checks stop conditions, frees blocks of finished requests, builds EngineCoreOutputsCPU, engine core

Why the model call is split in two. The forward pass does not need to know which tokens a JSON grammar permits; only sampling does. So execute_model starts the forward pass and returns None, the engine core computes the grammar bitmask on the CPU during the forward pass, and sample_tokens(grammar_output) delivers it just in time. Structured output therefore costs CPU time that mostly overlaps with GPU time rather than adding to it.

Why aborts are processed between 4 and 5. A forward pass takes milliseconds to hundreds of milliseconds. Any client that disconnected during it has an abort waiting. Applying those aborts before update_from_output means the scheduler never appends a token to, or allocates another block for, a request nobody is waiting for.

One step, the default way: the batch queue#

step() has a flaw. Between “forward pass finished” and “next forward pass started”, the GPU is idle while Python runs update_from_output and then schedule. That is typically one to a few milliseconds, on every token.

So the engine keeps a small queue of batches that have been scheduled but not finished. Its size is VllmConfig.max_concurrent_batches:

Python
@property
def max_concurrent_batches(self) -> int:
    # PP requires PP-size concurrent batches to fill the pipeline.
    # Async scheduling requires 2 concurrent batches to overlap.
    pp_size = self.parallel_config.pipeline_parallel_size
    if self.scheduler_config.async_scheduling:
        if self.use_v2_model_runner:
            return pp_size + 1
        # V1 Model Runner does not fully support async scheduling with PP.
        if pp_size <= 1:
            return 2
    return pp_size

Async scheduling is on by default for generative models (the cases where it is switched off are listed in 17.d). The queue size is therefore 2 on an ordinary single-GPU server, and the engine uses step_with_batch_queue instead of step. Its docstring describes the flow:

1. Try to schedule a new batch if the batch queue is not full.
   If a new batch is scheduled, directly return an empty engine core
   output. In other words, fulfilling the batch queue has a higher priority
   than getting model outputs.
2. If there is no new scheduled batch, meaning that the batch queue
   is full or no other requests can be scheduled, we block until the first
   batch in the job queue is finished.
3. Update the scheduler from the output.

The effect is that batch N+1 is scheduled and sent to the worker while batch N is still on the GPU. When N finishes, N+1 is already waiting in the worker and starts with no gap.

synchronous        GPU: [ step 1 ]......[ step 2 ]......[ step 3 ]
                   CPU:           [u+s]          [u+s]

async scheduling   GPU: [ step 1 ][ step 2 ][ step 3 ][ step 4 ]
                   CPU: [s2]  [u1+s3] [u2+s4] [u3+s5]
                                                     u = update_from_output, s = schedule

There is a catch, and it shapes the scheduler. When batch N+1 is being scheduled, the tokens that batch N will sample do not exist yet. The scheduler schedules the next decode step for a request without knowing its previous output token, and the worker, which does know it, fills it in. Structured output gives back part of the overlap, because a grammar needs that token before it can build the next mask: step_with_batch_queue then starts the forward pass of N+1 at once but defers its sampling until N’s output is processed. Both mechanisms are the subject of 17.d.

Pipeline parallelism uses the same queue for a different reason. With the model split across two GPUs in series, GPU 0 is free as soon as it has handed its activations to GPU 1. A queue of at least PP batches keeps every stage busy with a different batch, removing what the code calls “pipeline bubbles” (19.a).

What happens after a step#

Python
def _process_engine_step(self) -> bool:
    """Called only when there are unfinished local requests."""
    # Step the engine core.
    outputs, model_executed = self.step_fn()
    # Put EngineCoreOutputs into the output queue.
    for output in outputs.items() if outputs else ():
        self.output_queue.put_nowait(output)
    # Post-step hook.
    self.post_step(model_executed)

    # If no model execution happened but there is still scheduler work
    # (e.g. WAITING_FOR_REMOTE_KVS or delayed KV connector frees), yield
    # the GIL briefly to allow background transfer threads to make progress.
    if not model_executed and self.scheduler.has_requests():
        time.sleep(0.001)

    return model_executed
  • Outputs are keyed by client index: a step’s results are split per API server, so each API server receives only its own requests (16.d).
  • post_step collects draft tokens for speculative decoding when async scheduling is off (18.f).
  • The one-millisecond sleep is the single place the busy loop yields. It applies when requests exist but none could run, for instance when every waiting request is waiting for KV data to arrive from another machine (19.b). Without it the loop would spin at 100% CPU and starve the threads doing that transfer.

6. Under the hood#

Messages other than requests#

_handle_client_request dispatches on the type byte from 16.d:

TypeAction
ADDadd_request(): the request joins the scheduler’s waiting queue
ABORTabort_requests(), which calls scheduler.finish_requests(ids, FINISHED_ABORTED); idempotent, so the duplicate from the fast aborts queue is harmless
UTILITYLook up a method on the engine core by name, call it, post the result
EXECUTOR_FAILEDraise RuntimeError("Executor failed."): a worker died; take the engine down
WAKEUPNothing. It exists only to unblock input_queue.get()

Utility calls run on the main loop thread, between steps. That is why operations such as loading a LoRA adapter or resetting the prefix cache are safe without locks: no step is in progress while they run. It is also why a slow utility call stalls generation for everyone.

Pause, sleep and wake#

Three utility methods change the loop’s behaviour without stopping the process.

pause_scheduler(mode) has three modes (PauseMode in vllm/v1/engine/__init__.py). In all of them, new requests are queued until resume:

ModeIn-flight requests
abort (default)Aborted immediately
waitAllowed to finish; the pause completes when they have drained
keepFrozen in place; no steps run until resume

sleep(level, mode) builds on it, to release GPU memory while keeping the process alive:

LevelEffect (from the docstring)Use
0“Pause scheduling only. Requests are still accepted but not processed. No GPU memory changes.”A brief hold
1“Offload model weights to CPU, discard KV cache.”Share a GPU between models that take turns; waking is fast
2“Discard all GPU memory.”Longest idle, or before loading new weights; waking needs the weights again

wake_up() reverses it and resumes scheduling once memory is back. Levels 1 and 2 need the server started with --enable-sleep-mode (which switches on vLLM’s custom CUDA memory allocator so whole regions can be released). The HTTP routes /sleep?level=…, /wake_up, /is_sleeping, /pause and /resume are development endpoints: they exist only when the server runs with VLLM_SERVER_DEV_MODE=1. Reinforcement-learning loops use pause in wait mode, or sleep, to swap in new weights between rounds of generation.

Start-up of the engine core#

Before the loop runs, EngineCore.__init__ does the work whose results you read in the startup log (16.b), in this order:

  1. Create the executor, which starts the workers and loads the model (18.a).
  2. _initialize_kv_caches: ask the workers for each layer’s cache requirements, profile free memory, compute the number of blocks, tell the workers to allocate them, then compile and warm up (17.h).
  3. Create the structured output manager and the scheduler.
  4. Size the batch queue from max_concurrent_batches, which chooses step or step_with_batch_queue.
  5. Build the block hasher for prefix caching, then call freeze_gc_heap(): mark everything allocated so far as permanent so the garbage collector never scans it again.

Two decisions taken here surprise people later. If the model has no KV cache (an encoder-only embedding model), chunked prefill is switched off. If any layer attends non-causally (prefix-LM attention, for example), both chunked prefill and prefix caching are switched off, because both assume a token’s KV depends only on the tokens before it. Both cases log a line saying so.


7. Performance implications#

  • The gap between forward passes is pure overhead. The batch queue hides it when Python is faster than the GPU; when it is not (tiny model, huge batch), Python sets the speed.
  • Structured output and speculative decoding eat into the overlap. Deferred sampling and draft-token handling add work on the critical path (17.d, 18.f).
  • Utility calls stall all requests. Loading a LoRA adapter from slow storage, or resetting the prefix cache, is paid by every in-flight request.
  • The engine core needs a whole physical core whenever it has work (16.d).

8. Production implications#

  • Do not load adapters or reset caches on a hot server from a slow path; pre-load adapters at start (--lora-modules) or load them off-peak.
  • An engine core at 100% CPU with requests present is normal. At 100% with no requests, look for requests stuck waiting on remote KV transfers.
  • Sleep mode and /pause are for controlled environments (RL training, GPU time-sharing). They need VLLM_SERVER_DEV_MODE=1, which also exposes other unauthenticated control endpoints; never enable it on a public server.
  • A model with non-causal layers gets no prefix caching; capacity planning that assumed cache hits will be wrong.

9. Common mistakes#

  1. Reading 100% engine-core CPU as a bug. It is a busy loop by design whenever work exists.
  2. Assuming aborts take effect immediately. They take effect after the forward pass in progress.
  3. Expecting async scheduling to help a CPU-bound server. It hides Python time only up to the length of a forward pass.
  4. Calling /sleep on a normal server. The route does not exist without VLLM_SERVER_DEV_MODE=1, and levels 1–2 also need --enable-sleep-mode.
  5. Treating a utility call as free. It runs on the loop thread and blocks the next step.

10. Hands-on exercise#

  1. In the program, change the GPU cost to 2.0 + 0.01*n (a much smaller model). At which batch size does Python become the bottleneck?
  2. On a running server, watch the engine core’s CPU with top while idle and while serving one long request. Explain both readings using has_work().
  3. Start a server with VLLM_SERVER_DEV_MODE=1 vllm serve <model> --enable-sleep-mode, POST to /sleep?level=1, and watch nvidia-smi. Then POST to /wake_up. How long does each take, and where did the weights go in between?
  4. In vllm/v1/engine/core.py at tag v0.32.0, find step_with_batch_queue. Under what condition does it return None without waiting for the GPU?

11. Interview questions#

  1. In step(), why is get_grammar_bitmask called after execute_model and not before it?
  2. What information is missing when the engine schedules batch N+1 before batch N has finished, and who fills it in?
  3. Why is it safe to add a LoRA adapter without a lock, and what does it cost?
  4. Why does the busy loop sleep for one millisecond when no model ran but requests exist?
  5. What is the difference between sleep levels 1 and 2?
  6. Why does a non-causal attention layer disable prefix caching?

12. Further reading#

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

  • vllm/v1/engine/core.py: run_busy_loop, step, step_with_batch_queue, _handle_client_request, pause_scheduler, sleep
  • vllm/config/vllm.py: max_concurrent_batches, when async scheduling is enabled
  • Sleep mode
  • The scheduler that step() calls: 17.a. Async scheduling in detail: 17.d.

↑↓ navigate↵ openesc close

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