Unit 7 of 9

Batching and scheduling: one weight read, many requests

  • 55 min
  • Reading, walkthrough, and knowledge check

What you’ll learn

  • Calculate how much batching raises decode throughput from a model’s size and a GPU’s memory bandwidth.
  • Draw static and continuous batching schedules for the same requests and count the empty slots in each.
  • Build a padded batch with an attention mask and read each request’s next-token logits from the right position.
  • Explain how a scheduler admits waiting requests under a KV cache budget, and what it does when the cache runs out.
  • Pick a batch size that meets an inter-token latency target from the latency and throughput trade-off.

Why one request at a time wastes the GPU

Serve Llama 3.1 8B on an 80 GB H100 to one user and the answer streams at close to 200 tokens per second. Serve ten users one after another and each of them waits ten times as long. The GPU is not short of arithmetic. It is waiting on memory, and this lesson shows how to give that memory traffic more work to do.

You saw in the KV cache lesson that every decode step reads all of the model’s weights. Compare how long that read takes with how long the math takes:

One decode step for one request, Llama 3.1 8B in BF16 on an H100 SXM

  1. Bytes to read: 8.03 billion parameters × 2 bytesabout 16.06 GB
  2. Time to read them at 3.35 TB/s16.06 GB / 3.35 TB/s ≈ 4.8 ms
  3. Math per token: about 2 operations per parameter2 × 8.03 billion ≈ 16.1 GFLOP
  4. Time for that math at 989 TFLOPS (dense BF16)16.1 GFLOP / 989 TFLOPS ≈ 0.016 ms

ResultThe weight read takes about 300 times longer than the math

So for one request, the math units sit idle more than 99% of each step. Batching fixes this: the engine runs several requests through the model in the same step, one new token each. The weights are read once per step no matter how many requests share it, so each extra request adds only its own small share of work.

One at a timeOne at a time: A, 0 to 4.87 msAOne at a time: B, 4.87 to 9.75 msBOne at a time: C, 9.75 to 14.62 msCOne at a time: D, 14.62 to 19.5 msDOne batchOne batch: A, B, C, D, 0 to 5.11 msA, B, C, D02468101214161820Time (ms), idealized
Four requests each need their next token. One at a time, the GPU reads the 16 GB of weights four times. In one batch it reads them once and all four tokens are ready after about 5.1 ms.

The batch is not quite free. Each request also reads its own KV cache, and those reads are not shared. At 2,048 tokens of context, one request’s cache is 2,048 × 128 KiB = 256 MiB, about 0.27 GB. Four requests add about 1.1 GB to the 16.06 GB of weights: 17.1 GB per step, or 5.1 ms, instead of 19.5 ms for four separate steps.

Static batching versus continuous batching

Real requests do not start or finish together. One answer ends after 20 tokens, another runs to 800. How the engine forms batches decides how much of the GPU those differences waste.

Static batching forms a batch, runs it until every request in it has finished, and only then starts the next batch. Take six waiting requests, A to F, on a GPU that runs four at a time. Each needs one prefill step and then a few decode steps: A needs 4 steps in total, B 10, C 6, D 3, E 5, and F 4.

Slot 1Slot 1: 0 to 1Slot 1: A, 1 to 4ASlot 1: idle, 4 to 10idleSlot 1: 10 to 11Slot 1: E, 11 to 15ESlot 2Slot 2: 0 to 1Slot 2: B, 1 to 10BSlot 2: 10 to 11Slot 2: F, 11 to 14FSlot 2: idle, 14 to 15idleSlot 3Slot 3: 0 to 1Slot 3: C, 1 to 6CSlot 3: idle, 6 to 15idleSlot 4Slot 4: 0 to 1Slot 4: D, 1 to 3DSlot 4: idle, 3 to 15idle0246810121416Scheduler stepE and F startall doneprefilldecodeidle slot
Static batching with four slots. A, C, and D finish early, but their slots stay empty until B finishes at step 10. E and F cannot start until then.

The six requests need 4 + 10 + 6 + 3 + 5 + 4 = 32 slot-steps of real work, but the schedule occupies 4 slots for 15 steps, which is 60 slot-steps. Only 53% of the batch capacity does useful work, and E and F wait 10 steps before their first token.

Continuous batching, also called iteration-level scheduling, rebuilds the batch at every step. When a request finishes, the scheduler frees its slot and its KV cache, and the next waiting request joins at the following step. The idea was published as Orca in 2022, and most serving engines work this way today.

Slot 1Slot 1: 0 to 1Slot 1: A, 1 to 4ASlot 1: 4 to 5Slot 1: F, 5 to 8FSlot 1: idle, 8 to 10idleSlot 2Slot 2: 0 to 1Slot 2: B, 1 to 10BSlot 3Slot 3: 0 to 1Slot 3: C, 1 to 6CSlot 3: idle, 6 to 10idleSlot 4Slot 4: 0 to 1Slot 4: D, 1 to 3DSlot 4: 3 to 4Slot 4: E, 4 to 8ESlot 4: idle, 8 to 10idle0246810121416Scheduler stepE joinsall doneprefilldecodeidle slot
Continuous batching with the same requests. D finishes at step 3 and E takes its slot, A finishes at step 4 and F takes its slot. Everything is done by step 10. The late empty slots appear only because the queue is empty.

The same 32 slot-steps now fit in 4 × 10 = 40, so 80% of the capacity does useful work. E waits 3 steps instead of 10, and F waits 4. This is the rule to remember: when one sequence finishes, the scheduler admits waiting work into the freed slot, if memory allows. It does not wait for the longest request, and it never touches the caches of the requests that are still running.

A request can join a batch that is already moving because each request carries its own state: its KV cache, its position counter, its sampling settings, and its stop conditions. The batch is only the set of requests that run in this step.

Padding, attention masks, and wasted work

Prefill processes many tokens per request at once, and simple kernels want a rectangular tensor: every row the same length. When prompts of different lengths share such a tensor, the shorter ones are filled out with a pad token ID, and an attention mask records which positions hold real tokens (1) and which hold padding (0).

Take three prompts and a byte-level tokenizer, which makes every UTF-8 byte one token: Hi is 2 tokens, and batch and three are 5 each. The batch becomes a 3 × 5 tensor:

promptposition01234HiHHiimaskedmaskedmaskedbatchbbaattcchhthreetthhrreeeereal token (mask 1)padding (mask 0)
The padded batch for Hi, batch, and three. Twelve of the fifteen slots hold real tokens; the three padded slots are masked so no real token attends to them.

Padding creates two correctness rules. First, attention must give padded keys zero weight, so the mask is applied to the attention scores before the softmax, together with the causal mask from the attention lesson. Second, each request’s next-token logits come from its own last real position, which is its length minus one: positions 1, 4, and 4 here. Reading position −1 for every row would read a pad position for Hi.

Padding also costs work. Every padded slot still passes through every matrix multiplication, and its result is thrown away. The wasted fraction is 1 − (sum of lengths) / (rows × longest length):

Wasted slots in a padded prefill

  1. Hi, batch, three: lengths 2, 5, 512 real of 3 × 5 = 15 slots, so 20% wasted
  2. Lengths 8 and 19 real of 2 × 8 = 16 slots, so 44% wasted
  3. Prompts of 100, 400, and 2,000 tokens2,500 real of 3 × 2,000 = 6,000 slots, so 58% wasted
  4. Llama 3.1 8B math for that last batch, at about 16.1 GFLOP per token6,000 × 16.1 GFLOP ≈ 96 TFLOP instead of 2,500 × 16.1 GFLOP ≈ 40 TFLOP

ResultAt 989 TFLOPS the padded prefill needs at least 97 ms instead of 41 ms

Static batching pads in time as well: the empty slots in the first timeline are finished requests that keep their place in the batch. Two fixes help. Bucketing groups requests of similar length so each batch pads less. Packing removes padding entirely: the engine concatenates every request’s tokens into one long row and gives the attention kernel each request’s length. TensorRT-LLM’s documentation, for example, states that its continuous batching requires packed inputs with no padding.

The latency and throughput trade-off

Two numbers describe a decode workload. Throughput is the output tokens per second the whole GPU produces. Inter-token latency is the time between two tokens of the same response, which one user feels as streaming speed. Batching raises the first and also raises the second, because every request added to a step adds its KV cache read and makes the step longer.

A simple model shows the shape of the trade-off. Take Llama 3.1 8B in BF16 with 2,048 tokens of context per request, and assume each step takes exactly as long as its memory reads: 16.06 GB of weights plus 0.27 GB per request, at 3.35 TB/s.

Output tokens per second, whole GPU02,0004,0006,0008,00010,00005101520Inter-token latency (ms)Batch 1 to 192: 4.87, 205Batch 1 to 192: 5.44, 1,472Batch 1 to 192: 6.08, 2,633Batch 1 to 192: 7.36, 4,349Batch 1 to 192: 9.92, 6,450Batch 1 to 192: 15.05, 8,504Batch 1 to 192: 20.18, 9,515batch 13264128192Illustrative values, not measurements.
Idealized decode for Llama 3.1 8B on an H100 with 2,048-token contexts. Throughput climbs steeply at first and then flattens, while inter-token latency keeps rising. The curve ends at batch 192, where the 52 GB KV budget is full.
The same idealized model in numbers
Requests in the batchBytes read per stepStep time (inter-token latency)Tokens per second
116.06 + 0.27 = 16.3 GB4.9 ms205
3216.06 + 8.6 = 24.7 GB7.4 ms4,349
6416.06 + 17.2 = 33.2 GB9.9 ms6,450
12816.06 + 34.4 = 50.4 GB15.1 ms8,504
19216.06 + 51.5 = 67.6 GB20.2 ms9,515

Read the curve in two halves. From batch 1 to 64, throughput rises 31 times while each user’s tokens arrive only twice as slowly. From 64 to 192, throughput rises by half again while latency doubles once more. The useful question is not “what batch is fastest” but “what is the largest batch that still meets my latency target”. If you promise users at least 100 tokens per second (10 ms between tokens), this model says to stop around 64 requests.

Real engines land below these numbers, because no kernel reaches full memory bandwidth and each step does other work. The shape holds, though, and you measure the real curve by raising concurrency step by step, as the serving capstone shows.

How a scheduler admits requests

The scheduler is the loop that decides, before every step, which requests run. With continuous batching it repeats the same five moves:

  1. Retire finished requests

    Remove every request that produced its end token, hit a stop string or its token limit, or was cancelled. Free its KV cache.

  2. Keep running requests going

    Each running request needs room in the cache for one more token’s keys and values.

  3. Admit waiting requests in arrival order

    Admit the next request while three limits all hold: the batch has a free slot, the step’s token budget has room for its prompt, and the KV cache has room for its prompt.

  4. Run one forward pass

    New prompts (prefill tokens) and one token from each running request (decode tokens) go through the model together.

  5. Sample and stream

    Pick one token per request, send it to its client, and check its stop conditions for the next round.

The hard part is the cache limit, because a request’s cache keeps growing after it is admitted. Here is the choice in numbers, using the 52 GB budget from the KV cache lesson. That budget assumed the engine may use 90% of GPU memory, a setting chosen for the example; vLLM 0.28.0 defaults to 92%.

Admitting requests with 2,000-token prompts and up to 1,000 output tokens

  1. Cache budget in tokens at 128 KiB per token52,000,000,000 / 131,072 ≈ 396,700 tokens
  2. Reserve the worst case: 2,000 + 1,000 tokens each396,700 / 3,000 ≈ 132 requests
  3. Grow on demand, if answers average 500 tokens: a running request holds about 2,000 + 250 tokens on average396,700 / 2,250 ≈ 176 requests

ResultGrowing on demand runs about a third more requests, at the risk of running out of cache mid-answer

Engines with a paged cache, such as vLLM, grow on demand. When the cache fills and a running request cannot grow, the scheduler preempts one: it pauses a request, frees its cache, and puts it back in the queue. In vLLM V1 the default is to recompute the preempted request’s cache later rather than copy it to CPU memory. Nothing fails, but that request’s latency jumps, which is why the preemption count belongs on every dashboard.

Prefill needs a limit of its own. A 2,000-token prompt costs about 2,000 × 16.1 GFLOP ≈ 32 TFLOP, at least 32 ms on an H100. If it runs as one piece, every running request waits for that step, and at batch 64 users see a gap of three or four normal steps. Chunked prefill splits a long prompt into pieces that fit a per-step token budget and runs one piece per step next to the decode tokens. A 512-token chunk costs about 8 ms of math. vLLM V1 enables chunked prefill by default where it can, schedules waiting decode tokens first, and chunks any prefill that does not fit in --max-num-batched-tokens.

Try it: measure and schedule batches

You need Python 3.9 or later and NumPy. The first script feels the effect of sharing a weight read on your own CPU. It multiplies one token from each of 64 requests by a 4,096 × 14,336 matrix, the shape of one Llama 3.1 8B MLP projection, first one request at a time and then as one batch.

share_weights.py
import time

import numpy as np

rng = np.random.default_rng(0)
# One weight matrix shaped like a Llama 3.1 8B MLP projection, stored in float32.
weights = rng.standard_normal((4096, 14336), dtype=np.float32)
tokens = rng.standard_normal((64, 4096), dtype=np.float32)  # one token, 64 requests


def seconds(work, repeats=5):
    work()  # warm up
    start = time.perf_counter()
    for _ in range(repeats):
        work()
    return (time.perf_counter() - start) / repeats


alone = seconds(lambda: [token @ weights for token in tokens])
together = seconds(lambda: tokens @ weights)
same = np.allclose(np.stack([token @ weights for token in tokens]), tokens @ weights,
                   rtol=1e-4, atol=1e-3)
print(f"weight matrix: {weights.nbytes / 1e6:.0f} MB")
print(f"64 requests one at a time: {alone * 1e3:6.1f} ms")
print(f"64 requests in one batch:  {together * 1e3:6.1f} ms")
print(f"batching is {alone / together:.0f}x faster; same results: {same}")
You should see something like
weight matrix: 235 MB
64 requests one at a time:  327.1 ms
64 requests in one batch:    13.7 ms
batching is 24x faster; same results: True

The numbers above came from an Apple M3 Pro laptop; yours will differ. The pattern should not: one batched multiplication reads the 235 MB matrix once instead of 64 times and runs many times faster, with the same results. If the batch is not clearly faster, check that you timed tokens @ weights and not a Python loop.

The second script replays the schedules from the timelines above, so you can change the workload and watch both policies respond:

batch_schedule.py
import numpy as np

# Steps each request needs: one prefill step plus its decode steps.
# All six requests are waiting when the server starts.
names = ["A", "B", "C", "D", "E", "F"]
steps = np.array([4, 10, 6, 3, 5, 4])
slots = 4  # requests the GPU runs at once


def static_batching(steps, slots):
    start = np.zeros(len(steps), dtype=int)
    clock = 0
    for first in range(0, len(steps), slots):
        start[first:first + slots] = clock
        clock += steps[first:first + slots].max()  # wait for the longest
    return start


def continuous_batching(steps, slots):
    free_at = np.zeros(slots, dtype=int)  # step at which each slot frees up
    start = np.zeros(len(steps), dtype=int)
    for i, n in enumerate(steps):
        slot = np.argmin(free_at)  # the first slot to free up
        start[i] = free_at[slot]
        free_at[slot] += n
    return start


policies = [("static", static_batching), ("continuous", continuous_batching)]
for label, schedule in policies:
    start = schedule(steps, slots)
    finish = start + steps
    total = finish.max()
    print(f"{label:>10}: done after {total} steps, "
          f"slot use {steps.sum() / (slots * total):.0%}, "
          f"mean wait {start.mean():.2f} steps, mean finish {finish.mean():.2f}")
    spans = [f"{n}:{s}-{f}" for n, s, f in zip(names, start, finish)]
    print(" " * 12 + "  ".join(spans))
You should see
    static: done after 15 steps, slot use 53%, mean wait 3.33 steps, mean finish 8.67
            A:0-4  B:0-10  C:0-6  D:0-3  E:10-15  F:10-14
continuous: done after 10 steps, slot use 80%, mean wait 1.17 steps, mean finish 6.50
            A:0-4  B:0-10  C:0-6  D:0-3  E:3-8  F:4-8

The third script builds the padded batch from the grid figure and checks the two correctness rules on a toy one-layer model with random weights. It runs each prompt alone as the reference, then compares the batched logits against it under five setups:

padded_batch.py
import numpy as np

# Byte-level tokens: every UTF-8 byte is one token ID from 0 to 255.
prompts = ["Hi", "batch", "three"]
ids = [list(text.encode("utf-8")) for text in prompts]
lengths = np.array([len(tokens) for tokens in ids])
width = lengths.max()


def pad(ids, left=False):
    batch = np.zeros((len(ids), width), dtype=int)  # 0 is the pad ID
    mask = np.zeros((len(ids), width), dtype=int)
    for row, tokens in enumerate(ids):
        start = width - len(tokens) if left else 0
        batch[row, start:start + len(tokens)] = tokens
        mask[row, start:start + len(tokens)] = 1
    return batch, mask


batch, mask = pad(ids)
print("batch shape", batch.shape, "lengths", lengths.tolist())
print("mask:\n", mask)
print(f"real tokens: {mask.sum()} of {mask.size} slots, {mask.mean():.0%} used")
print("last real position per row:", lengths - 1)

# A toy one-layer model with random weights: embed, causal attention, logits.
rng = np.random.default_rng(0)
d = 16
embed = rng.normal(size=(256, d))
wq, wk, wv = rng.normal(size=(3, d, d))
unembed = rng.normal(size=(d, 256))


def forward(batch, mask):
    x = embed[batch]  # (rows, width, d)
    q, k, v = x @ wq, x @ wk, x @ wv
    scores = q @ k.transpose(0, 2, 1) / np.sqrt(d)
    n = batch.shape[1]
    allowed = np.tril(np.ones((n, n), dtype=bool)) & (mask[:, None, :] == 1)
    scores = np.where(allowed, scores, -1e9)  # masked keys get zero weight
    weights = np.exp(scores - scores.max(axis=-1, keepdims=True))
    weights /= weights.sum(axis=-1, keepdims=True)
    return weights @ v @ unembed  # (rows, width, 256)


# Reference: each prompt alone, no padding, logits at its last token.
alone = np.stack([forward(np.array([t]), np.ones((1, len(t)), dtype=int))[0, -1]
                  for t in ids])


def matches(logits, positions):
    rows = np.arange(len(ids))
    return bool(np.allclose(logits[rows, positions], alone))


no_mask = np.ones_like(mask)
print("right padding, masked, read at length - 1:",
      matches(forward(batch, mask), lengths - 1))
print("right padding, masked, read at position -1:",
      matches(forward(batch, mask), -1))
print("right padding, no padding mask:",
      matches(forward(batch, no_mask), lengths - 1))
left, left_mask = pad(ids, left=True)
print("left padding, masked:", matches(forward(left, left_mask), -1))
print("left padding, no padding mask:", matches(forward(left, no_mask), -1))
You should see
batch shape (3, 5) lengths [2, 5, 5]
mask:
 [[1 1 0 0 0]
 [1 1 1 1 1]
 [1 1 1 1 1]]
real tokens: 12 of 15 slots, 80% used
last real position per row: [1 4 4]
right padding, masked, read at length - 1: True
right padding, masked, read at position -1: False
right padding, no padding mask: True
left padding, masked: True
left padding, no padding mask: False

The first lines match the grid figure: 12 of 15 slots are real, and each row’s logits live at positions 1, 4, and 4. Reading position −1 instead gives Hi the logits of a pad slot, so the comparison fails. The last three lines are the trap from the callout. With right padding, dropping the padding mask still passes, because the causal mask already hides pads that come after the real tokens. Left padding puts the pads before the real tokens, inside every query’s causal window, so only the padding mask keeps the results right. The toy model has no position embeddings; a real model would also need each left-padded row’s positions counted from its first real token.

Common mistakes

Symptoms you may see, their usual cause, and the fix
SymptomLikely causeFix
Short prompts in a batch produce nonsense; long ones are fineNext-token logits were read at position −1, which is padding for short rows.Read each row at its own length minus one.
Batched outputs differ from single-request outputsPadded keys are not masked, or left-padded rows got the wrong position IDs.Mask padded keys before the softmax and count each row’s positions from its first real token.
Tests pass, but batched decode drifts after the first tokenThe tests used right padding only, which the causal mask already hides.Add a test that masks a key inside the context.
Throughput barely rises with more usersStatic batching, or a low cap on running requests, leaves slots empty.Use continuous batching and raise the cap until latency or the cache limits you.
Inter-token latency spikes whenever a long prompt arrivesThe whole prefill ran in one step and stalled every decode.Enable chunked prefill with a per-step token budget.
Latency jumps and the preemption count risesMore requests were admitted than the cache can hold as their answers grow.Lower the running-request cap or maximum output length, or use a smaller cache format.
Padding waste looks lower than the bill suggestsPercentages from different buckets were averaged.Add up real and padded slots across buckets, then divide once.

How real engines batch and schedule

  • vLLM runs continuous batching over a paged KV cache. In V1, chunked prefill is on by default where possible, decode tokens are scheduled before new prefills, and preempted requests are recomputed. --max-num-seqs caps the requests in one step and --max-num-batched-tokens caps the tokens. See continuous batching in vLLM.
  • TensorRT-LLM calls the same idea in-flight batching, which its documentation also names continuous or iteration-level batching. It requires packed inputs with no padding.
  • Orca, the system that introduced iteration-level scheduling, also used selective batching: the matrix multiplications run on all requests’ tokens together, while attention runs per request, because each request has its own cache length.

On a vLLM dashboard, four metrics tell you where the batch stands: vllm:num_requests_running, vllm:num_requests_waiting, vllm:kv_cache_usage_perc, and the vllm:num_preemptions counter. Requests waiting while the cache sits near 1.0 means memory is the limit. Requests waiting while the cache has room means a cap such as --max-num-seqs is. Watch vllm:inter_token_latency_seconds as the running count rises to see the trade-off from the plot on your own hardware.

Go deeperWhen does batching stop helping?

A kernel is limited by memory when it does few operations per byte it reads. In BF16 every weight is 2 bytes and every request does 2 operations with it, so a decode step does about B operations per weight byte for a batch of B. The H100 can do 989 × 10¹² operations for every 3.35 × 10¹² bytes it reads, about 295 operations per byte. On weights alone, decode stays memory-bound until the batch nears 300.

The KV cache pushes that point further away. Cache reads grow with every request and are used by only that request, so they add bytes without adding shared work. At long contexts decode stays memory-bound at any batch the cache can hold. Prefill is the opposite: a 2,000-token prompt does about 2,000 operations per weight byte, well past 295, so it is limited by compute. That difference is why mixing prefill chunks with decode tokens in one step uses both resources at once.

One more subtlety: a batched matrix multiplication may add numbers in a different order than a single-row one, so results can differ in the last few bits. The NumPy script compares with a tolerance for that reason. Greedy decoding can occasionally pick a different token when two candidates are almost tied.

Next: move fewer bytes per step

Batching shares each weight read among many requests. Quantization shrinks the read itself by storing weights in fewer bits. Because small-batch decode is limited by bytes moved, fewer bytes means faster steps and more room for the KV cache.

Llama 3.1 8B with a published FP8 checkpoint instead of BF16

  1. Checkpoint size16.06 GB in BF16, 9.08 GB in FP8
  2. Weight read per step at 3.35 TB/s4.8 ms in BF16, 9.08 GB / 3.35 TB/s ≈ 2.7 ms in FP8
  3. Batch-1 ceilingabout 209 tokens per second in BF16, about 369 in FP8
  4. Memory freed for the KV cache16.06 − 9.08 = 6.98 GB ≈ 53,000 more tokens
  5. 8,192-token requests that fit48 in BF16, 58.98 GB / 1 GiB per request ≈ 54 in FP8

ResultFewer bytes per weight speeds up decode and adds capacity

Why is the FP8 checkpoint 9.08 GB and not 8.03 GB, and what do fewer bits cost in accuracy? The quantization lesson answers both.

Cheat sheet

  • A decode step reads every weight once, however many requests it serves: about 16 GB and 4.8 ms for Llama 3.1 8B on an H100.
  • At batch 1 the math takes about 0.016 ms of that step. Batching fills the idle math units.
  • Each request still reads its own KV cache, so steps get longer as the batch grows.
  • Continuous batching refills a finished request’s slot at the next step; static batching waits for the longest request.
  • Padded slots cost full compute. Read logits at length minus one, and mask padded keys.
  • Pick the largest batch that meets your inter-token latency target.
  • Admission is limited by slots, the per-step token budget, and the KV cache; a full cache causes preemption.
  • Chunked prefill keeps long prompts from stalling everyone else’s tokens.

Walkthrough

One step of a continuous-batching scheduler

Request traceReady

Knowledge check

When one sequence in a continuous batch finishes, what should the scheduler do?

Choose one answer

Sources and further reading

Finished this unit?