Inference Engineering

Lesson 6: Continuous batching · Workbook

Continuous batching: the workbook

The full working behind lesson 6. Why a batch slot is worth keeping full, how output lengths vary, static batching and its waste formula, iteration-level scheduling and selective batching, the simulator and what it shows, what the papers measured, and seven exercises to check yourself.

A language model generates its answer one token per forward pass, and nobody knows in advance how many tokens an answer will take. One user asks for a yes or no, another for a page of code. Put both in the same batch and the short one is done long before the long one.

The simplest server ignores this: it starts a batch, runs it until every request in it is finished, and only then starts the next one. Continuous batching (also called iteration-level scheduling) instead re-forms the batch after every forward pass, so a finished request leaves at once and a waiting one takes its place. On the workload simulated in this lesson, 5 requests per second, static batching falls behind and its queue grows for the whole run, while continuous batching keeps up using 46% of its slot-time; mean latency drops from 9.34 s to 936 ms. When both are overloaded, at 12 requests per second, continuous batching delivers about 2.7 times the tokens per second. vLLM and the serving systems after it build on the idea, and the lessons after this one assume it.

Why a batch slot is worth keeping full

The roofline lesson showed that decode is memory-bound: each step reads every weight once, whether one sequence uses them or many. A batch slot is a position in that step for one sequence. On an H100 running Llama 3.1 8B in BF16, at a 600-token context:

8 times the tokens for 4% more time. The extra sequences ride on weight reads the GPU was doing anyway, which is the whole reason batching works (the roofline lesson introduced both phases). It also means the opposite: a slot that is empty, or busy with a request that has already finished, throws away a token the GPU could have produced almost for free. A scheduler’s job is to keep slots full of useful work.

This lesson uses 8 slots so the pictures stay readable. Real servers run tens to hundreds, limited mostly by how much KV cache fits in memory (the KV cache, the subject of lesson 4); the arguments are the same.

Output lengths vary a lot

To see what happens with real-looking traffic, this lesson builds a workload of 100 requests. Each has a 512-token prompt. Output lengths are drawn from a log-normal distribution: the logarithm of the length is normally distributed, which gives what chat traffic looks like, many short answers and a few very long ones. Its median is 128 tokens and the spread σ\sigma (the standard deviation of the log) is 1, capped at 1024 tokens. Requests arrive at random, on average 5 per second (a Poisson process: independent arrivals, exponential gaps between them).

In the sample this lesson uses, lengths run from 13 to 1024 tokens. The median is 110, but the mean is 200, pulled up by the tail: 10 requests need 512 tokens or more, four times the distribution’s median, while 56% need 128 or fewer. (For reference, a log-normal with these parameters has a mean of 211 before the cap.) The vLLM paper makes the same point about real data: its ShareGPT trace, taken from real conversations, has outputs 5.8 times longer on average than the Alpaca instruction dataset, “with higher variance”.

The exact shape does not matter much. What matters is that in any batch of 8, the longest request is usually several times longer than the typical one.

Static batching

Static batching, or request-level batching, works like this. When the engine is idle, take up to 8 waiting requests. Run one prefill for all of them, which produces each one’s first token. Then run decode steps until the longest request in the batch has all its tokens. Return the results, and start over.

The Orca paper (Yu et al., OSDI 2022) names the two problems this causes:

A small example makes the cost exact. Take 2 slots and three requests that arrive together, needing 4, 1, 1 tokens. Count each forward pass as one unit of time.

For a single static batch whose requests need L1,…,LbL_1, \dots, L_b tokens, the batch runs for Lmax⁡L_{\max} steps, so the fraction of slot-steps that are wasted is

waste=∑i(Lmax⁡−Li)b Lmax⁡.\text{waste} = \frac{\sum_i \left(L_{\max} - L_i\right)}{b \, L_{\max}} .

With long-tailed lengths, Lmax⁡L_{\max} is usually far above the typical LiL_i, so this fraction is large.

Iteration-level scheduling

Orca’s fix is to make the scheduler decide again after every forward pass, which the paper calls an iteration. The loop is:

  1. Remove every request that produced its last token in the previous iteration, and return its result now.
  2. Fill the free slots with waiting requests, first come first served.
  3. Run one iteration over everyone in a slot: new arrivals get their prefill, everyone else gets one decode step.

Step 3 hides a real difficulty. A new request has a few hundred prompt tokens to process; a running one has a single token. Their tensors have different shapes, so they cannot simply be stacked into one batch. Orca’s second idea, selective batching, handles it. Operations that treat each token independently, such as the weight matrix multiplies and layer norms, run on all tokens from all requests flattened into one long list. Only attention, where each token must see its own request’s earlier tokens, is split per request. The weights are still read once per iteration.

That makes a mixed iteration cheaper than running prefill and decode separately, but not free. On our setup, 7 sequences decoding alone take 4.65 ms per step, and one 512-token prefill alone takes 7.29 ms. Together in one iteration they take 7.52 ms: the prefill reuses the weight reads, but its arithmetic makes that one step 1.6 times as long for everyone in the batch. Keep that in mind; the lesson Chunked prefill and disaggregation is about this stall.

A simulator

Every number from here on comes from a small discrete-event simulator in this site’s code. It serves the same 100 requests twice, once with each scheduler, on one H100 with 8 slots. Time advances one iteration at a time, and the cost of each iteration is the roofline floor from the first lesson for exactly the work in it: the decode steps (with each sequence’s actual context length) plus any prefills, with the weights read once. Requests that arrive during an iteration wait for the next one. A seeded random number generator draws the arrivals and lengths, so the same seed always gives the same run.

Two choices to be aware of. Latency here is end-to-end: from arrival to the moment the request’s result is returned and its slot is free. Under static batching that is the end of the batch, as in the systems Orca describes. And the static scheduler does not wait for a batch to fill; when the engine is idle it takes whatever is waiting.

Press Play to watch both schedulers serve the same arrivals, or Step to move from one join or leave to the next. Hover or tap a bar to see that request’s length and latency.

Both schedulers on the same arrivals

generating tokensfinished, slot held until the batch endsrequest arrives

StaticContinuous
Throughput (tok/s)
Mean latency
p99 latency
Slot utilization

Hover or tap a bar for that request's details.

Llama 3.1 8B in BF16 on one H100, 8 slots, 100 requests with 512-token prompts. Each row is a slot and each bar a request; colors only tell neighboring requests apart. Top: under static batching, faded bars are finished requests still holding their slot. Bottom: under continuous batching, slots refill as soon as they free. Throughput counts output tokens only.

What the simulation shows

With the default workload:

StaticContinuous
Throughput (output tokens/s)533783
Mean latency9.34 s936 ms
p99 latency16.5 s4.74 s
Mean time in the queue6.88 s2.78 ms
Slot utilization33%46%
Time to serve all 10037.5 s25.5 s

Throughput is total output tokens (19,971 here) divided by the time to serve all 100, counted from the first arrival. p99 latency is the latency that 99% of requests are at or below: here, the second-worst of the 100. Slot utilization is the share of all slot-time spent producing a token that someone asked for.

The latency gap is the striking part, and almost all of it is queueing. Under static batching, 49% of all slot-time goes to finished requests holding their slot, while new arrivals wait outside. The server cannot keep up with 5 requests per second, so the queue grows for the whole run. Continuous batching serves the same arrivals with time to spare: the average request waits 2.78 ms for a slot.

Two things decide how much continuous batching helps.

The spread of output lengths. Drag the spread slider to 0 and every request needs exactly 128 tokens. At 5 requests per second both servers now keep up, so both deliver what arrives (586 against 592 tokens/s, with 35% and 34% of slot-time used); that says nothing about waste. Raise the rate to 12 as well, so static batching runs at 79% utilization, and continuous batching gains only 6% (1,265 against 1,336 tokens/s), because no request finishes early. Mean latency is still lower with continuous batching (1.05 s against 668 ms) because late joiners do not wait for a whole batch. At the same rate with the spread back at 1, continuous batching delivers 2.7 times the throughput, and at a spread of 1.5, 3.0 times: the gap opens quickly as the spread rises from 0, then levels off.

The load. At 1 request per second both schedulers keep up, so both deliver what arrives: 178 against 184 tokens/s. Throughput can only differ when the server is the bottleneck. Latency still differs (2.23 s against 912 ms), for the same two reasons as before.

The opening scene

The lesson’s opening scene runs the same simulator on a toy stream: 21 diners, 6 seats, the first 14 rounds, with answer lengths from 2 to 13 tokens. Seating uses one time unit per round, as in the small example above. Each round is then priced at the roofline floor of a decode step for every occupied seat, finished or not, at a 600-token context. Over the window, static batching makes 38 useful tokens in 64.7 ms, 587 tokens per second with 45% of seat-rounds useful. Continuous batching makes 84 in 64.7 ms, 1,298 tokens per second with 100% useful: 2.2 times as many.

Its last stage holds every conversation at 8,192 tokens. A decode step for one such conversation has a floor of 4.80 ms; for 52, the most that fit (exercise 7), it is 21.2 ms, because each step reads every conversation’s KV cache as well as the weights. That is 4.4 times as long for 52 times the tokens.

What the papers measured

Orca’s evaluation ran GPT-3-sized models on NVIDIA A100s against NVIDIA FasterTransformer served through a request-level scheduler. For the 175B model at a matched median normalized latency (end-to-end latency divided by the number of generated tokens) of 190 ms per token, the paper reports 0.185 requests per second for FasterTransformer and 6.81 for Orca, a 36.9× throughput improvement. That figure combines iteration-level scheduling with the rest of Orca’s system, so it is not a measurement of scheduling alone.

Anyscale’s engineering blog (a vendor benchmark, so treat it as secondary) compared serving stacks for OPT-13B on one A100-40GB. Against static batching, it reports about 8× from frameworks that do continuous batching, and up to 23× from vLLM, which adds better memory management on top.

What continuous batching leaves unsolved

Memory. A slot needs room for its request’s KV cache, and that cache grows by one token every step until the request ends, at a length nobody knows in advance. Orca’s scheduler handles this by reserving space for each request’s maximum allowed length (its max_tokens) before admitting it. That is safe but wasteful: most requests stop far short of the maximum, so fewer of them fit at once. The vLLM paper (Kwon et al., SOSP 2023) measured this. It compared vLLM against three versions of Orca that reserve the actual output length (an oracle), up to twice it, or the model’s full 2,048-token limit, On ShareGPT, vLLM sustains 1.7–2.7× the request rate of Orca (Oracle) and 2.7–8× that of Orca (Max) at similar latency, and up to 22× that of FasterTransformer; the abstract summarizes this as 2–4× over the state of the art. The next lesson, Paged KV memory, explains how.

Prefill stalls. As computed above, an iteration that includes a long prompt is much slower than a decode-only one, and every running request waits for it. Long prompts make this worse. The lesson Chunked prefill and disaggregation covers the fixes.

Fair measurement. Throughput, mean latency and tail latency trade against each other, and the right numbers depend on the arrival pattern. The lesson Measuring a serving system covers how to benchmark this honestly.

Check yourself

Work each one out before opening the answer. Every answer comes from the same simulator and formulas as the figures. The last two revisit earlier lessons that this one builds on.

Exercise 1. A static batch of 8 requests from the simulation needs 66, 155, 53, 20, 31, 264, 65, 116 output tokens. What fraction of its slot-steps produce a token someone asked for?

%
Show the worked answer

The batch runs for the longest request, 264 steps, so it has 8 × 264 = 2,112 slot-steps. The requests need 770 tokens in total, so only 36% of the slot-steps are useful and 64% are waste. Continuous batching would have given each freed slot to a waiting request.

Exercise 2. Two slots, three requests arriving at the same moment needing 4, 3, 1 tokens, in that order, one time unit per iteration. What is the mean latency under each scheduler, and what does the order of admission change?

Show the answer

Static: the first two run together until time 4, then the 1-token request runs alone and ends at 5. Latencies 4, 4, 5, mean 4.33. Continuous: the 3-token request leaves at 3 and the third request takes its slot, finishing at 4. Latencies 4, 3, 4, mean 3.67. Admit them as 1, 3, 4 instead and continuous latencies become 1, 3, 5, mean 3.00. The shortest request waits behind longer ones because it was queued last; first come, first served does not know lengths. Schedulers that predict output length try to fix this.

Exercise 3. In the simulator above, set the spread slider to 0, so every request needs the same number of tokens. Does continuous batching still help?

Show the answer

Not for throughput, but the default rate hides why. At 5 requests per second both servers keep up, so both deliver what arrives: 586 against 592 tokens/s, with 35% and 34% of slot-time used. Raise the rate to 12, so static batching runs at 79% utilization, and continuous batching gains only 6% (1,265 against 1,336 tokens/s), because no request finishes early. Mean latency still drops, from 1.05 s to 668 ms at that rate (909 ms to 595 ms at 5), because requests that arrive during a batch start at the next iteration instead of waiting for the batch to end. Continuous batching fixes both of Orca’s problems; equal lengths remove only the first.

Exercise 4. At 1 request per second, both schedulers report almost the same throughput. Why, and does that make them equally good there?

Show the answer

Both servers keep up with the arrivals, so both deliver what arrives: 178 and 184 tokens/s over the run. Throughput only separates schedulers when the server is the bottleneck. They are not equally good: mean latency is 2.23 s under static batching and 912 ms under continuous batching. Always report latency next to throughput.

Exercise 5. 7 sequences are decoding at a 600-token context when a new request with a 512-token prompt joins. How much longer is that iteration than a decode-only one, and who pays for it? Enter how many times as long.

×
Show the worked answer

A decode-only step for the 7 takes 4.65 ms. With the prefill added it takes 7.52 ms, about 1.6× as long. All 7 running users get their next token that much later; that gap between tokens is the stall chunked prefill splits up. It is still cheaper than running the prefill as a separate step (11.9 ms in total), because the mixed iteration reads the weights once.

Exercise 6. From lesson 1: Llama 3.1 8B in BF16 on one H100, every sequence at a 1,024-token context. At the roofline floor, how many times as many tokens per second does a decode step for 64 sequences deliver as a decode step for 1?

×
Show the worked answer

One sequence: the floor is 4.52 ms per step, so 221 tokens per second. Sixty-four sequences: 7.05 ms per step for 64 tokens, 9,079 tokens per second, about 41× as many. The step is memory-bound either way and the weights are read once for the whole batch; what grows is the attention reads, one cache per sequence. That is why every empty or finished-but-held seat in a batch is lost throughput, and why continuous batching keeps refilling them.

Exercise 7. From lesson 4: one H100 (80 GB) with 10% held back serves Llama 3.1 8B with BF16 weights and a BF16 KV cache. How many 8,192-token conversations fit at once? That is the most seats a scheduler can fill at that length.

conversations
Show the worked answer

52. After the weights and the reserve, the space left for the cache divided by each conversation’s 1.07 GB of keys and values gives 52, rounded down. Continuous batching can only refill a seat if the new request’s cache fits, and a request’s cache grows every step until it ends. Reserving room for the longest possible answer wastes most of that space; the next lesson shows how to stop reserving.

Sources

  1. Yu, Jeong, Kim, Kim, Chun (2022). Orca: A Distributed Serving System for Transformer-Based Generative Models. OSDI '22, pp. 521–538. Introduces iteration-level scheduling and selective batching. Section 3 describes early-finished and late-joining requests; Section 4.2 the scheduler and its max_tokens reservation; Section 6 the 36.9× result against FasterTransformer
  2. Kwon, Li, Zhuang, Sheng, Zheng, Yu, Gonzalez, Zhang, Stoica (2023). Efficient Memory Management for Large Language Model Serving with PagedAttention. SOSP '23. arXiv:2309.06180. vLLM. Section 2.3 summarizes iteration-level batching; Section 6 compares against three Orca variants that reserve different amounts of KV memory
  3. Daniel, Shen, Liang, Liaw (2023). How continuous batching enables 23x throughput in LLM inference while reducing p50 latency. Anyscale blog. Secondary source: a vendor benchmark of OPT-13B on one A100-40GB, against static batching
  4. Llama 3.1 8B model card (Meta). The model in every simulation on this page
  5. NVIDIA H100 product page, specifications table. The GPU in every simulation on this page

Back to lesson 6: Continuous batching