Continuous Batching Under the Hood: What Actually Happens Inside vLLM When 100 Requests Hit at Once

2026-11-29来源 dev.toEnglish

If you come from traditional deep learning, your mental model of batching is straightforward. You gather $N$ inputs, pad them with zeros so their dimensions match, pack them into a tensor, and push that tensor through your model in a single forward pass.

When developers first stand up an inference server for a large language model using that approach, throughput drops off a cliff.

Generative language models do not work like ResNet or BERT. In an LLM, requests arrive asynchronously. One user sends a 50-word prompt and wants a 10-word reply. Another user uploads a 3,000-word documentation file and asks for an 800-word summary.

If you group those two requests into a classic static batch, two things go wrong immediately:

  1. Massive padding waste: You have to pad the shorter prompt with thousands of useless <pad> tokens so the matrix dimensions line up.
  2. Execution stalling: The short request finishes generating its 10 tokens in 200 milliseconds. But because the batch runs as a single unit, that finished request remains trapped in GPU memory for another 12 seconds, waiting for the 800-token summary to finish. New incoming requests queue up outside the engine, unable to use the GPU.

Modern inference engines like vLLM, TensorRT-LLM, and TGI achieve 10x to 20x higher throughput because they throw static batching out the window. They use an architecture called Continuous Batching (originally introduced as iteration-level scheduling by the Orca paper at OSDI 2022).

Here is the exact mechanical breakdown of what happens inside the engine when 100 requests hit your server at once.

1. The Core Illusion: The Batch Is Not an Object

In a framework like PyTorch, a batch is usually a concrete Python object: a tensor with shape (batch_size, seq_len, hidden_dim).

In modern LLM engines, no persistent batch object exists.

Inside the scheduler loop of vLLM V1, a batch is simply a transient calculation made right before each GPU forward pass. What actually persists in memory are two queues and a collection of cursors:

  • waiting: A FIFO queue of new requests that have arrived but have not yet executed on the GPU.
  • running: A list of active requests currently generating tokens.
  • num_computed_tokens: A per-request cursor tracking how many tokens the model has processed into the Key-Value (KV) cache.

Every time the engine loop spins, the scheduler asks a specific question: which requests get to advance right now, and by how many tokens?

Its central ledger is a dictionary:

num_scheduled_tokens: dict[str, int] = {req_id: count} 

If a request is actively generating text, count is 1. If a request is running a chunked prompt, count might be 512. If a request is blocked waiting for memory, count is 0.

The batch exists only for the duration of a single forward pass kernel execution. The moment the forward pass finishes, the scheduler recomputes membership from scratch.

2. Iteration-Level Scheduling (The Orca Model)

Static batching schedules work at the request level: a batch is formed when requests enter, and it disbands only when every request finishes.

Continuous batching schedules work at the iteration level: scheduling happens between individual token generation steps.

Mathematically, if $\mathcal{B}_s$ is the set of requests running in step $s$:

$$\mathcal{B}_{s+1} = (\mathcal{B}_s \setminus \mathcal{F}_s) \cup \mathcal{A}_s$$

Where:

  • $\mathcal{F}_s$ is the set of requests that finished in step $s$. They emitted an <eos> token or hit their max token limit. Their completed text is streamed immediately to the user via Server-Sent Events (SSE), and their KV cache memory is freed.
  • $\mathcal{A}_s$ is the set of waiting requests admitted for step $s+1$.
  • The total size $|\mathcal{B}_{s+1}|$ is bounded by available GPU memory and the maximum sequence cap.
Step s: [ Req 1 (gen 9/10) ] [ Req 2 (gen 44/500) ] [ Req 3 (gen 120/120 - EOS) ] | EVICTED & FREED | Step s+1: [ Req 1 (gen 10/10) ] [ Req 2 (gen 45/500) ] [ Req 4 (Prompt Chunk 1) ] 

Because the scheduler regains control after every token, a sequence that finishes is evicted within 15 milliseconds. Its slot and its memory pages are immediately assigned to a waiting request. No slot sits idle.

3. The Two Workloads: Prefill vs Decode

To understand why continuous batching gets complicated in production, you have to look at the hardware reality of GPU execution. An LLM performs two completely different computational workloads during its lifetime.

The Prefill Phase (Prompt Evaluation)

When a request first arrives, the model must read the entire prompt and compute initial KV tensors for all prompt tokens.

  • Operation: General Matrix Multiply (GEMM).
  • Arithmetic Intensity: High. Because all prompt tokens are processed simultaneously in parallel, the GPU can reuse weight matrices across the entire sequence.
  • Hardware Bottleneck: Compute-bound. The GPU tensor cores run at near 100% theoretical FLOPS.

The Decode Phase (Autoregressive Token Generation)

Once the prompt is ingested, the model generates one new token per step. To generate token $T+1$, it reads token $T$ and attends to all previous KV pairs.

  • Operation: General Matrix-Vector Multiply (GEMV).
  • Arithmetic Intensity: Low (near 1.0). To generate just one single token, the GPU must stream every single weight of the model from High-Bandwidth Memory (HBM) into on-chip SRAM cache. For a 70B parameter model at FP16, the GPU reads 140 GB of weights from VRAM to compute one token.
  • Hardware Bottleneck: Memory-bandwidth bound. Tensor cores spend most of their time idling, waiting for bytes to crawl across the memory bus.
Metric Prefill Phase Decode Phase
Input Size Entire prompt ($N$ tokens) 1 token per sequence
BLAS Operation GEMM (Matrix-Matrix) GEMV (Matrix-Vector)
Bottleneck Compute (Tensor Cores) Memory Bandwidth (HBM)
Arithmetic Intensity High ($O(\text{prompt_length})$) Low ($\approx 1$ FLOP / byte)
Latency Metric Time to First Token (TTFT) Inter-Token Latency (ITL)

In naive continuous batching, when an engine batches running decodes together with a fresh 4,000-token prefill, a major problem arises: the prefill bubble.

4. The Prefill Bubble & Head-of-Line Blocking

Suppose your engine is currently running decode loops for 32 active users. Each token generation step takes 25 milliseconds. The users see smooth streaming text at 40 tokens per second.

Suddenly, User 33 submits a prompt containing a 6,000-token system prompt and legal document.

If the engine runs that entire 6,000-token prefill in the next forward pass, compute time spikes. Instead of taking 25ms, that single forward pass takes 650ms.

For the 32 decoding users, their text stream freezes for two-thirds of a second. This phenomenon is an Inter-Token Latency (ITL) spike. In high-concurrency systems, back-to-back long prefills completely destroy the interactive experience for existing users.

5. The Solution: Chunked Prefill and Piggybacking

To solve the prefill bubble, modern engines like vLLM and TensorRT-LLM introduce Chunked Prefill (based on research from Sarathi and Split-Fuse).

Instead of treating a prompt as an indivisible block of work, the scheduler establishes a global token budget per iteration, governed by the configuration parameter max_num_batched_tokens (typically set to 2,048 or 4,096 tokens).

The Scheduling Priority Order

During every scheduling step, the engine fills the token budget using a strict two-stage process:

  1. Priority 1 (RUNNING Decodes): The scheduler visits every active request in the running queue first. Each decode request gets exactly 1 token allocated from the budget. If you have 64 running sequences, 64 tokens are deducted from your budget.
  2. Priority 2 (WAITING Prefills): The remaining token budget (token_budget = max_batched_tokens - 64) is allocated to pending requests in the waiting queue.

If a new request arrives with a 3,000-token prompt, but the remaining token budget is only 1,500 tokens, the scheduler does not reject or postpone the request. It slices it:

num_new_tokens = min(remaining_prompt_tokens, token_budget) 

In this iteration, the model computes the first 1,500 tokens of the prompt and writes their key-value pairs into physical KV cache blocks. The request is immediately added to the running queue with a flag is_prefill_chunk = True.

In the next iteration, the remaining 1,500 prompt tokens are scheduled. Only after the final chunk finishes does the request transition to autoregressive token generation.

Token Budget: 2048 tokens Running Decodes: 48 tokens (48 active users) Remaining Budget: 2000 tokens Incoming Request (3500 tokens): Iteration 1: [ 48 Decode Tokens ] + [ 2000 Tokens of Prompt A (Chunk 1) ] Iteration 2: [ 48 Decode Tokens ] + [ 1500 Tokens of Prompt A (Chunk 2) ] + [ 452 Tokens of Prompt B ] Iteration 3: [ 49 Decode Tokens (including Prompt A's first generated token) ] 

The Compute Piggybacking Bonus

Chunked prefill does more than protect decode latency; it actually makes the GPU run faster overall.

Because the decode phase is memory-bandwidth bound and tensor cores sit idle waiting for weights to transfer from HBM, piggybacking a 512-token or 1,024-token prefill chunk onto those decodes utilizes the idle compute cores.

The GPU loads the model weights once, executes the memory-bound decodes, and simultaneously feeds the compute-bound prefill chunk through the tensor cores. You get free prompt processing without degrading decode latency.

6. How the Scheduler Tracks Memory: KV Page Allocation

Allocating tokens in the scheduler is only half the battle. A request cannot run unless physical GPU memory exists to store its attention keys and values.

This is where continuous batching links directly with PagedAttention.

In naive systems, engines pre-allocated contiguous memory for the worst-case maximum sequence length (e.g. 4,096 tokens). If a user only generated 50 tokens, the remaining 4,046 slots sat completely wasted.

Under PagedAttention, GPU VRAM is partitioned into fixed-size physical blocks (typically 16 or 32 tokens per block).

Before the scheduler commits any token allocation (whether a 1-token decode or a 512-token prefill chunk), it calls:

can_allocate = kv_cache_manager.allocate_slots(request, num_scheduled_tokens) 

The behavior differs between queues:

  • In the WAITING Queue: If allocate_slots returns None (meaning the GPU memory watermark is reached), the scheduler executes a clean break. New requests wait safely in the queue outside the GPU.
  • In the RUNNING Queue: If a currently active request generates a token that requires a new KV block, but free memory has hit zero, the engine cannot simply wait. It must take action to avoid a CUDA out-of-memory crash.

Handling Memory Exhaustion Through Preemption

When active requests demand more memory blocks than physically exist in VRAM, the engine invokes preemption:

  1. Victim Selection: The scheduler selects a victim request from the running queue (usually the lowest priority or most recently arrived request).
  2. Preemption Strategy:
    • Recomputation: The victim is stopped, its allocated KV blocks are freed back to the memory pool, and its status is reverted to WAITING. When memory clears up later, the engine simply re-prefills its prompt and continues.
    • Swapping: The victim's KV blocks are transferred across the PCIe bus into host CPU system RAM. When VRAM frees up, the blocks are swapped back to the GPU.

Because continuous batching manages memory in tiny discrete blocks rather than large monolithic buffers, preemptions are rare under normal load.

7. Production Tuning: The Three Knobs That Matter

When configuring an engine like vLLM for high-concurrency production workloads, three scheduler settings dictate system performance:

1. --max-num-seqs (Maximum Active Sequences)

This controls the maximum number of requests that can be in the running state simultaneously.

  • Setting this too low leaves GPU memory bandwidth underutilized.
  • Setting this too high forces small KV cache block allocations, increasing the probability of preemption and memory thrashing under bursty traffic.
  • Typical production value: 128 to 256 for 8B-70B models on modern 80GB GPUs.

2. --max-num-batched-tokens (Iteration Token Budget)

This is the total token cap (decodes + prefill chunks) permitted in a single forward pass.

  • A smaller value (e.g. 512 or 1024) provides ultra-consistent, low inter-token latency for interactive chat applications.
  • A larger value (e.g. 4096 or 8192) increases overall token throughput for bulk background processing jobs, but increases latency variance.
  • Typical production value: 2048 for balanced chat APIs.

3. --enable-chunked-prefill

In vLLM V1, chunked prefill is enabled by default. If you run custom pipelines or older engine versions, ensure this flag is explicitly enabled. Without it, long prompts will cause periodic 500ms+ stutter in all concurrent active streams.

Summary Mental Model

When you send a request to a modern LLM cluster:

  1. Your request enters a queue; it does not trigger a private container or worker.
  2. The scheduler re-evaluates the active batch between every token generation step.
  3. Every active stream gets its single token computed first.
  4. Remaining token capacity is used to slice incoming prompts into manageable prefill chunks.
  5. Completed requests vanish from memory the instant they output <eos>, freeing memory pages for the next token iteration.

Continuous batching turns an unpredictable, variable-length text generation pipeline into a predictable, high-throughput streaming assembly line.

原文:https://www.a8q9.cn/en/article/continuous-batching-under-the-hood-what-actually-happens-inside-vllm-when-100-re-ed6015.html

相关文章