Phase 03/Memory and scheduling internals/Continuous and dynamic batching
PHASE 03 · Memory and scheduling internals

Continuous and dynamic batching

0%
6 h5 subtopics2 lessons · 1 required
In plain English

Imagine a bus that only departs when every seat is full and only returns when every passenger has reached their stop. Passengers with short trips sit waiting for the longest trip to finish, and newcomers wait at the stop for the bus to come back. That is static batching, and it wastes most of the GPU's time. Continuous batching is a bus that never stops moving: at each block it lets finished passengers off and lets new ones on, so seats are never empty for long. Because a GPU generating one word at a time is mostly waiting on memory, filling every seat is almost free, which is why this one idea gives a 10 to 20x throughput gain. You will build a simulator to see it.

Why it matters

Decode is memory-bandwidth bound, so the cost of a step barely grows with batch size until compute saturates. Continuous batching exploits this and is the reason modern engines reach thousands of tokens per second per GPU. Understanding it is required for every scheduler and benchmarking decision.

Hiring signal

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Baseten, Cerebras, CoreWeave, Databricks, ElevenLabs, Fireworks, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Explain why decode throughput scales almost linearly with batch size up to a knee.
  • Contrast static, dynamic and continuous (iteration-level) batching with timelines.
  • Simulate continuous batching in Python and measure utilization and latency versus static batching.
  • Explain how prefill and decode are mixed in one step and why chunked prefill exists.
  • Estimate the batch size at which decode becomes compute-bound on a given GPU.

Key concepts

Static batching
Fixed batch of requests runs from first prefill until the last sequence finishes; slots sit idle after early finishes.
Dynamic batching
The server waits a short window to gather arriving requests into one batch; still request-level granularity.
Continuous batching
Also called iteration-level scheduling; the batch is rebuilt every decode step so finished sequences leave and new ones join.
Padding waste
Compute spent on pad tokens when sequences of different length share a dense batch; avoided by packing tokens.
Memory-bound decode
Each decode step reads all weights once; adding sequences adds little time until arithmetic intensity reaches the roofline knee.
Chunked prefill
Splitting a long prefill into pieces mixed with decode tokens so a long prompt does not stall other users' tokens.
Arithmetic intensity
FLOPs per byte moved; batch size multiplies it for decode because weights are reused across sequences.

Subtopics

  1. 1. Why batching is almost free for decode

    Roofline view, weights read once per step, arithmetic intensity grows with batch size until the compute knee.

  2. 2. Static and dynamic batching

    Request-level batching, padding, head-of-line blocking by the longest sequence, and the timeout window trade-off.

  3. 3. Iteration-level scheduling (Orca)

    Rebuilding the batch each step, selective batching of attention versus dense layers, and the vLLM implementation.

  4. 4. Mixing prefill and decode

    Prefill-prioritised steps versus chunked prefill, token budgets per step, and the effect on TTFT and ITL.

  5. 5. The throughput-latency curve

    As concurrency rises, throughput saturates while per-token latency climbs; choosing an operating point.

Resources

Hands-on lessons

L1

Simulate static versus continuous batching on CPU

CPU · your Macscript120 minrequired

Goal · A discrete-event simulator that reports GPU slot utilization, mean latency and throughput for static and continuous batching on the same request trace.

  1. 1Model a GPU step as cost = base + per_token * active_tokens with base 20 ms and per_token 0.1 ms; prefill of n tokens costs n per_token in one step.
  2. 2Generate 300 requests with Poisson arrivals (rate 4 per second), prompt lengths 32-512 and output lengths 16-256.
  3. 3Implement static batching with batch size 16 where the batch runs until its longest sequence finishes.
  4. 4Implement continuous batching with a max of 16 slots that admits waiting requests every step and frees slots on completion.
  5. 5Record per request queue time, TTFT and end-to-end latency, plus slot utilization (occupied slots divided by 16 per step).
  6. 6Print a table and plot latency CDFs for both policies; then sweep max slots 4, 16, 64 for continuous batching.
  7. 7Write three sentences on where the throughput curve bends and why.
Deliverable
batching_sim.py and a PNG with the latency CDFs and the throughput-versus-slots plot.
Check
Continuous batching achieves at least 2x the output tokens per second of static batching and above 80 percent slot utilization on this trace.
L2

Measure the decode batch-size knee on a T4

Colab T4 · freenotebook60 minoptional

Goal · A plot of decode step time versus batch size for Qwen2.5-0.5B showing the flat region and the knee.

  1. 1Load Qwen/Qwen2.5-0.5B-Instruct in float16 with transformers on the T4.
  2. 2Prefill a 64-token prompt replicated to batch sizes 1, 2, 4, 8, 16, 32, 64, 128.
  3. 3Time 20 single-token decode steps per batch size with torch.cuda.synchronize and take the median.
  4. 4Plot ms per step and tokens per second versus batch size; mark where ms per step starts rising faster than 10 percent per doubling.
Deliverable
A notebook with the two plots and the batch size at the knee.
Check
Step time at batch 16 is less than 1.5x step time at batch 1.

Build your own

Build your own continuous batching scheduler simulator

PythonCPU · your Mac~7 h

A discrete-event simulator of an LLM engine's step loop, from static batches to iteration-level scheduling with a token budget, preemption and chunked prefill.

The real thing: github.com/vllm-project/vllm/blob/main/vllm/v1/core/sched/scheduler.py ↗

How you know a stage passes

A CLI, sim.py, with subcommands gen, run and sweep, plus tests/test_sim.py written first. Every stage adds tests on tiny hand-computable traces (3 to 5 requests) where you assert the exact step count, utilisation and per-request latency, and invariant checks that run inside the step loop on larger random traces (fixed seeds). Run `pytest -q`; a stage passes when its tests pass and earlier tests still pass.

Stages, in order. Each one leaves you with something that runs.0/7
  1. 01a trace and a cost model
    sim.py gen writes a JSONL trace of requests (arrival time, prompt tokens, output tokens) and a cost model gives prefill time as a*tokens+b and decode step time as c+d*batch using constants you fit from the T4 lesson or defaults.
    test · `python sim.py gen --n 200 --seed 0` writes a byte-identical file on two runs, and the cost model unit test reproduces the four constants from a synthetic fit within 1 percent.
  2. 02static batching baseline
    Requests are grouped into batches of B; a batch runs until its longest output finishes and nothing joins mid-batch.
    test · On a 4-request trace with outputs 10, 10, 10 and 40 tokens at B=4, slot utilisation equals 70/160 exactly and the reported number matches your hand calculation.
  3. 03iteration-level scheduling
    At every step, finished sequences leave and waiting sequences join up to max_num_seqs, so the batch is refilled continuously.
    test · On the 200-request trace, throughput is at least 1.5x static at the same B, mean latency is lower, and every request finishes with exactly its requested output tokens.
  4. 04a KV token budget for admission
    The scheduler admits a request only if its prompt plus max output tokens fit in the remaining KV token budget.
    test · An assertion inside the step loop that the sum of allocated tokens across running sequences never exceeds the budget holds for 10 random traces, and admission is refused at least once with a budget of 4,096 tokens.
  5. 05preemption and recompute
    With optimistic admission, running out of budget mid-decode preempts the most recently admitted sequence, which restarts from its prompt when space frees.
    test · With a tight budget every request still finishes, output token counts match the unpreempted run, the preemption counter is above 0, and preempted requests show a visible latency gap in the per-request log.
  6. 06chunked prefill
    Prefills are split into chunks so that every step's total tokens stays under max_num_batched_tokens and decode steps are never blocked behind a long prompt.
    test · No step exceeds the token cap (loop assertion), and on a trace with 2,000-token prompts p99 inter-token latency drops by at least 30 percent versus unchunked at equal throughput.
  7. 07the throughput-latency curve
    sim.py sweep runs the simulator over a range of arrival rates and writes a CSV plus a plot of throughput and p99 latency versus offered load.
    test · curve.png and curve.csv exist; throughput saturates at a plateau while p99 latency rises by more than 5x past the knee, and the knee rate is printed.

Knowledge check

QWhy can a GPU decode 32 sequences in nearly the same time as 1?

Each step is dominated by reading the weights from memory, which happens once regardless of batch size; extra sequences only add small per-token work until compute saturates.

QWhat is head-of-line blocking in static batching?

Short requests in a batch wait for the longest one to finish before their slots can be reused and before new requests can start.

QWhat problem does chunked prefill solve?

A long prompt's prefill in a single step would stall every running decode, spiking their inter-token latency; chunking spreads it across steps.

QHow does continuous batching change the throughput versus latency trade-off?

It lets the operator pick a concurrency level; raising it increases throughput until saturation while each token's latency rises, so there is an operating point to choose.

Completion

  • All 5 subtopics marked done
  • All 1 required lessons done
  • All subtopics marked completed.
  • Lesson l1 simulator and plots saved with the written explanation of the knee.
  • Can draw the static and continuous batching timelines from memory.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →