Serving Engines

A 7B model on one A100 gives one user about 146 tokens per second. Put 64 users in the same pass and the same GPU makes about 4,200 tokens per second, and each user still gets 66.

Pick a way to fill the GPU, then press Run. Each row is a seat in the batch, each warm bar is one request. Drag the length spread and watch the grey gaps. Then we build, piece by piece, what vLLM, SGLang and TensorRT-LLM do to keep every seat busy.

You need to know that a language model makes one token at a time and that it keeps a cache of past keys and values. A little Python helps for the code. We build the rest from zero.

GPU numbers come from NVIDIA's A100 and H100 spec sheets. Engine facts come from the vLLM, Orca, SGLang, Sarathi-Serve and DistServe papers and from the vLLM, TensorRT-LLM and TGI docs, listed in the Field Guide.

Fill the GPU three ways

60%

Illustrative simulation: a full queue of requests with seeded random answer lengths, 400 decode steps. Tokens per second use this page's step-time model (Chapter 1) for a 7B model in FP16 on an A100 80GB, with 500 tokens of context per request.

Chapter 0

One User, One Percent Busy

Time one token on a real GPU and find the clock that decides it

Here is the server everyone writes first. It takes one request, runs the model to the end, sends the answer, and only then takes the next request.

pythonwhile True:
    req = queue.get()                        # wait for one request
    out = model.generate(req.prompt)          # run it start to finish
    req.respond(out)                        # only then look at the queue again

It works. On an A100, a 7B model gives that one user about 146 tokens per second. Yet the GPU's compute units work for less than 1% of that time. Why?

A GPU has two speeds. Memory bandwidth is how many bytes per second it moves from its main memory, the HBM, to its compute units. Compute throughput is how many floating point operations (FLOPs) per second those units do. The A100 80GB moves 2,039 GB per second and does 312 trillion FLOPs per second in BF16.

To make one token, the model uses every weight once. So every weight travels from HBM to the compute units once per token. Call the size of all the weights in bytes W. Call the memory bandwidth B. Call the time for one step t.

Say it aloud

t equals W over B.

t
t the time for one decode step: one new token for each sequence in the batch, in seconds.
W
W the bytes of weights: 7 billion parameters at 2 bytes each is 14 GB.
/
over divide: bytes divided by bytes per second gives seconds.
B
B the memory bandwidth: 2,039 GB per second on an A100 80GB.
In plain words

Divide the weight bytes W by the bandwidth B. That is the shortest time t that one step can take, because no step finishes before its weights arrive.

With numbers

W = 14 GB and B = 2,039 GB/s, so t = 14 / 2,039 = 6.87 ms. One user gets 1 / 0.00687 = 146 tokens per second.

Now count the math. A forward pass does about 2 FLOPs per parameter per token: one multiply and one add. That is 14 billion FLOPs. At 312 trillion per second, the math takes 0.045 ms. So the compute units work 0.045 ms out of every 6.87 ms: 0.65% of the time.

Time one token

Blue is the time to read the weights. Purple is the time to do the math. Pick a GPU and a model size.

Spec-sheet numbers: dense BF16 throughput (NVIDIA lists twice these values "with sparsity") and HBM bandwidth. FP16 weights, 2 FLOPs per parameter per token, batch 1, KV cache reads ignored here.

The purple bar is a sliver. The GPU waits for bytes, not for math. This regime is memory-bound. Try the H100: it has 3.2 times the FLOPs but only 1.6 times the bandwidth, so its compute is even more idle, at 0.34%. Model size does not change the share either. Bytes and FLOPs both grow with the parameter count, so the ratio stays fixed.

The failure: symptom, measurement, fix

The road

  1. Batching and the roofline: share one weight read, and meet the wall the KV cache builds.
  2. Continuous batching: refill each seat the step it frees.
  3. The KV cache bill: price each token's memory and count the users who fit.
  4. PagedAttention: hand out KV memory in 16-token blocks.
  5. Prefix caching and RadixAttention: compute a shared prompt once.
  6. Chunked prefill: stop one long prompt from stalling everyone.
  7. Kernels, graphs and FP8: cut launches and bytes per weight.
  8. Disaggregated serving: separate prefill and decode GPUs, and price the move.
  9. One request, end to end: the whole engine, and how to pick one.
  10. Field guide: numbers, checklist, code and sources.
A team moves its batch-1 server from an A100 to an H100, which has 3.2 times the FLOPs. Speed per user rises only about 1.6 times. Why?

Chapter 1

Batching and the Roofline

Share one weight read across many users, then find the wall that the KV cache builds

The GPU reads the 14 GB of weights once per step, for any number of sequences. Put 64 users in one step and the math grows 64 times, while the weight bytes stay the same.

Each sequence also has a KV cache: the key and value vectors of all its earlier tokens, kept so the model does not compute them again. Every step reads each sequence's whole KV cache once, so that read grows with the batch. Chapter 3 prices it.

Call the batch size b, the number of sequences in one step. Call the KV cache bytes of one sequence M. Call the number of parameters N and the compute throughput F. The step takes as long as the slower of two jobs: moving the bytes, or doing the math.

Say it aloud

t of b equals the max of two things: W plus b times M, over B; and b times two N, over F.

t(b)
t of b the time for one decode step with b sequences in it.
max
the max of the larger of the two times; the step waits for the slower job.
W
W the weight bytes, read once per step: 14 GB.
b
b the batch size: how many sequences share this step.
M
M the KV cache bytes of one sequence, read once per step.
B
B the memory bandwidth: 2,039 GB per second.
b
b the same batch size: each sequence needs its own math.
2N
two N FLOPs per token: one multiply and one add for each of the N parameters.
F
F the compute throughput: 312 trillion FLOPs per second.
In plain words

Add the weight bytes W to b copies of the KV bytes M and divide by B: that is the memory time. Multiply b by 2N and divide by F: that is the math time. The step takes the larger one.

With numbers

b = 64 users with 500 tokens of context each, so M = 500 × 0.524 MB = 262 MB. Memory time: (14 + 64 × 0.262) / 2,039 = 30.8 GB / 2,039 GB/s = 15.1 ms. Math time: 64 × 14 billion / 312 trillion = 2.9 ms. So t = 15.1 ms. The batch makes 64 / 0.0151 = 4,240 tokens per second, 29 times one user, and each user still gets 66.

Grow the batch

The warm curve is total tokens per second. The purple dashed line is the math ceiling. Red marks batches whose KV caches do not fit in 80 GB. Drag the batch, then pick a context length.

64

The step-time formula above for a 7B model in FP16 on an A100 80GB (Llama 2 7B shape: 0.524 MB of KV per token). Ideal kernels; real engines reach less. The memory limit ignores activations and the headroom an engine keeps.

With no KV cache, the curve climbs until b = 153, where the math time catches the memory time. That point is the ridge: 312 trillion FLOPs divided by 2,039 GB/s is 153 FLOPs per byte. Past it the GPU is compute-bound. This plot is a roofline.

Real sequences carry context. At 1,000 tokens each, memory runs out before the ridge: the 66 GB left after the weights holds 125 such caches. So decode stays memory-bound in practice, and the number of KV caches that fit caps the batch.

The failure: symptom, measurement, fix

Sequences of 1,000 tokens each run a 7B model on an A100. Which limit stops the batch from growing?

Chapter 2

Continuous Batching

Refill each seat the step it frees, instead of waiting for the slowest request

Four requests share a batch. Their answers turn out to be 100, 100, 100 and 400 tokens long. Nobody knows the lengths in advance, because each request stops when the model emits its end token.

Static batching keeps a batch together until every member finishes. So this batch runs 400 steps. Three seats sit empty for the last 300, while requests wait in the queue.

Measure the waste. Call the number of tokens request i makes ℓi. Call the number of seats S and the number of steps the batch runs T. Call the share of seat-steps that made a token the busy share, U.

Say it aloud

U equals the sum over i of ell-i, over S times T.

U
U the busy share: the share of seat-steps that made a token, from 0 to 1.
Σi
the sum over i add one term for each request in the batch.
ℓi
ell-i the number of tokens request i makes.
S
S the number of seats in the batch.
×
times seats times steps counts every seat-step the GPU paid for.
T
T the number of steps the batch runs.
In plain words

Add up the tokens ell-i that every request made. Divide by the seat-steps the batch held: S seats for T steps. The result U is the useful share.

With numbers

(100 + 100 + 100 + 400) / (4 × 400) = 700 / 1,600 = 0.44. So 56% of the seat-steps made nothing. With 15 answers of 20 tokens and 5 of 800 in 20 seats, U = 4,300 / 16,000 = 0.27.

Continuous batching decides the batch again at every step. When a request finishes, the scheduler removes it and puts a waiting request into the free seat at the next step. The Orca paper (Yu et al., OSDI 2022) named this iteration-level scheduling. TensorRT-LLM calls it in-flight batching. vLLM, SGLang, TensorRT-LLM and TGI all do it.

Free a seat, fill a seat

Four seats, answers of 100, 100, 100 and 400 tokens, and a queue behind them. Grey is a seat that holds no request. Switch the scheduler.

The four lengths are this page's example. The queued requests after them are 100 tokens each, illustrative.

With a queue behind it, the continuous batch fills the three free seats at step 101. U is 1.0 while the queue lasts. That is 1,600 tokens from 1,600 seat-steps, 2.3 times the static batch. The loop that does it is short:

pythondef step(active, queue, max_seats, model):
    active = [s for s in active if not s.done]       # drop finished requests
    while len(active) < max_seats and queue:
        active.append(queue.pop(0))                  # fill free seats now
    toks = model.forward_one_step(active)            # one token for each seat
    for s, t in zip(active, toks):
        s.tokens.append(t)
        s.done = t == EOS or len(s.tokens) >= s.max_tokens
    return active

Compare it with Chapter 0. That server called generate() once per request. This one calls a single step again and again, and looks at the queue between steps.

The failure: symptom, measurement, fix

Four seats hold answers of 100, 100, 100 and 400 tokens under static batching. What is the utilization U?

Chapter 3

The KV Cache Bill

Price the memory each token holds and count the users who fit

A chat user has 1,000 tokens of conversation so far. To make token 1,001, attention needs the key and value vectors of every earlier token, in every layer. The engine keeps them in HBM. That store is the KV cache.

Name the parts of one token's entry. Call the number of layers nL. Call the number of key-value heads h and the length of each head's vector d. Call the bytes per number q. Call the KV bytes per token m.

Say it aloud

m equals two times n-L times h times d times q.

m
m the KV cache bytes one token holds.
2
two one key vector and one value vector.
nL
n-L the number of layers: 32 in Llama 2 7B.
h
h the number of key-value heads: 32 in Llama 2 7B, 8 in Llama 3 8B.
d
d the numbers in one head's key or value vector: 128.
q
q bytes per number: 2 for FP16 or BF16.
In plain words

In each of the n-L layers, for each of the h heads, a token stores a key and a value of d numbers, each q bytes. Multiply them out to get m.

With numbers

Llama 2 7B: m = 2 × 32 × 32 × 128 × 2 = 524,288 bytes, 0.524 MB per token. A 1,000-token conversation holds 524 MB, and 125 of them fill the 66 GB left after the weights.

Llama 3 8B uses grouped-query attention (GQA): its 32 query heads share 8 key-value heads. So h = 8 and m is 131,072 bytes, a quarter of Llama 2's. The device shows what that buys.

Fill 80 GB with conversations

Blue blocks are the weights. Each warm cell is one sequence's KV cache. Pick a model and drag the context length.

1,024

Model shapes from the published Llama 2 and Llama 3 configurations, FP16 weights and KV. The 80 GB ignores activations and the headroom real engines keep, so real counts are lower.

Now reserve memory the simple way. An engine that allows 2,048 tokens per request sets aside 2,048 × 0.524 MB = 1.07 GB when the request arrives. Suppose the prompt plus answer averages 300 tokens. The request uses 157 MB of its 1,073 MB. So 85% of each reservation is never touched, and 66 GB holds only 61 requests. The vLLM authors measured that earlier systems wasted 60% to 80% of KV memory this way.

The failure: symptom, measurement, fix

A model has 32 layers, 8 KV heads of 128 numbers each, and stores KV in FP16. How many bytes does one token hold?

Chapter 4

PagedAttention

Hand out KV memory in small blocks, the way an operating system hands out pages

An operating system does not give a program one huge piece of RAM up front. It gives fixed-size pages as the program needs them. A page table maps the program's addresses to wherever each page sits. PagedAttention, from the vLLM paper (Kwon et al., SOSP 2023), does the same for the KV cache.

The engine cuts KV memory into blocks of 16 tokens each. A request gets a new block only when its last block is full. A per-request block table maps the request's block 0, 1, 2 to physical blocks anywhere in the pool. The attention kernel reads keys and values through that table.

So the only waste is the empty end of each request's last block. Call the tokens a request holds n and the block size s.

Say it aloud

waste equals the ceiling of n over s, times s, minus n.

waste
waste token slots held by a request but empty.
⌈ ⌉
the ceiling of round up to the next whole number, because a block is all or nothing.
n
n the tokens the request holds now.
s
s the block size in tokens: 16 by default in vLLM.
s
s again: blocks times block size gives slots held.
n
minus n take away the slots in use.
In plain words

Round the token count n up to whole blocks of s tokens. Subtract n. What remains is the empty end of the last block, never more than s minus 1 slots.

With numbers

n = 300 and s = 16: 300 / 16 = 18.75, rounded up to 19 blocks, so 304 slots. Waste = 304 − 300 = 4 slots, 1.3%. Reserving 2,048 slots wasted 1,748, which is 85%.

That changes the count. A 16-token block of Llama 2 7B holds 8.4 MB, so 19 blocks are 159 MB. The 66 GB pool now holds 414 requests of 300 tokens instead of 61: 6.8 times more seats. The vLLM authors report under 4% KV waste in practice, and 2 to 4 times the throughput of earlier systems at the same latency.

Reserve the maximum, or page it

Each row is one request. Warm is memory holding tokens. Grey is memory reserved but empty. Switch the allocator and drag the average length.

300

Eight illustrative requests whose lengths spread around the average. Counts use a 66 GB pool and Llama 2 7B's 0.524 MB per token. The 16-token block is vLLM's default; the 60% to 80% and under 4% figures come from the vLLM team.

Requests can also share blocks. Ask for four samples of one 1,024-token prompt. All four block tables point at the same 64 prompt blocks. A reference count on each block records how many tables use it. A sample gets its own copy of a block only when it writes a token the others do not have: copy-on-write. With 50 new tokens each, that is 64 + 4 × 4 = 80 blocks, against 4 × 68 = 272 if every sample copied the prompt.

The failure: symptom, measurement, fix

A request holds 1,000 tokens in 16-token blocks. How many token slots are empty?

Chapter 5

Prefix Caching and RadixAttention

Compute a shared prompt once and let every request that starts with it reuse the blocks

A support bot starts every request with the same 1,000-token system prompt: rules, tool schemas, two examples. Then comes the user's question. A hundred users means a hundred copies of the same first 1,000 tokens.

Prefill is the first pass over a prompt. All prompt tokens go through the model in one step, so the math, not the bytes, sets the time. Call the number of prompt tokens n, the parameters N and the compute throughput F. Call the prefill time tpre.

Say it aloud

t-pre equals two N times n, over F.

tpre
t-pre the prefill time for one prompt, at best.
2N
two N FLOPs per token: 14 billion for a 7B model.
n
n the number of prompt tokens that need prefill.
F
F the compute throughput: 312 trillion FLOPs per second on an A100.
In plain words

Multiply the prompt tokens n by 2N FLOPs each. Divide by F. Real kernels reach only part of F, so real prefill takes longer than t-pre.

With numbers

n = 1,000: t-pre = 14 billion × 1,000 / 312 trillion = 44.9 ms. For 100 users that is 4.49 s of GPU time spent on the same 1,000 tokens.

Prefix caching keeps those KV blocks after a request ends. When a new prompt starts with the same tokens, its block table points at the cached blocks, and prefill runs only on the new tail. The 100 users then cost 44.9 ms once for the system prompt. vLLM's docs say it finds a match by hashing each full block together with every token before it, and evicts the least recently used blocks first.

RadixAttention is SGLang's version (Zheng et al., 2024). It stores every cached prompt in a radix tree: each edge holds a run of tokens, and each path from the root is a prompt. A new request walks down the tree as far as its tokens match. The tree catches shared system prompts, few-shot examples and multi-turn chat, where turn 3 starts with turns 1 and 2. SGLang reports up to 6.4 times the throughput of earlier systems on such programs.

Grow the prefix tree

Each chip sends one request. Yellow edges are tokens it found in the tree. Pink edges are tokens it had to prefill. Send them in any order.

Illustrative token counts: system prompts of 1,000 tokens, questions of 60, an answer plus a second turn of 200. Times use t-pre for a 7B model on an A100 at ideal speed.

The failure: symptom, measurement, fix

Every prompt starts with "Today is 2026-11-22." and then the same 1,000-token system prompt. Why is the prefix hit rate low across days?

Chapter 6

Chunked Prefill

Slice a long prompt so it never stalls the users who are already reading

Thirty-two users are reading answers as they stream. A decode step for all of them takes 15.1 ms. Then an 8,000-token document arrives. Its prefill takes 359 ms at best. If the engine runs it in one step, every reader's next token waits 374 ms.

Two latencies matter here. Inter-token latency (ITL) is the gap between two tokens a user sees. Time to first token (TTFT) is the wait before the first one. Readers notice an ITL spike as a stutter.

Chunked prefill splits the prompt into chunks. Each step carries one token for every reader plus one chunk of prompt. Sarathi-Serve (Agrawal et al., OSDI 2024) calls this stall-free scheduling. vLLM's docs say its V1 engine turns chunked prefill on by default and schedules all waiting decodes before any prefill.

How big should a chunk be? Call the chunk size in tokens c. Call the time each step may spend on prefill τ: your ITL budget minus the decode time.

Say it aloud

c equals tau times F, over two N.

c
c the chunk size: prompt tokens added to each step.
τ
tau the prefill time allowed per step: the ITL budget minus the decode step time.
F
F the compute throughput: 312 trillion FLOPs per second.
2N
two N FLOPs per prompt token: 14 billion.
In plain words

Multiply the spare time tau by F to get the FLOPs you can spend. Divide by 2N FLOPs per token. That is the largest chunk c that keeps every reader inside the budget.

With numbers

A 50 ms ITL budget minus a 15.1 ms decode step leaves tau = 34.9 ms. c = 0.0349 × 312 trillion / 14 billion = 778 tokens. Round down to 512, because real kernels run below F.

Slice the long prompt

Each block is one step. Blue is decode for the 32 readers. Pink is a slice of the 8,000-token prompt. The ruler at the top is a 50 ms ITL budget; a red outline marks a step longer than it. Drag the chunk size.

512

The step-time model of Chapters 1 and 5: a 7B model on an A100, 32 readers at 1,000 tokens of context, prefill at ideal speed. Decode and prefill times add up in each step, a simple model.

Chunks trade one latency for the other. At 512 tokens the worst ITL is 38 ms, but the document's own TTFT grows to 600 ms. Without chunking the TTFT is 374 ms and every reader stalls 374 ms. In vLLM the knob is max_num_batched_tokens: its docs say smaller values give better ITL and larger values better TTFT.

The failure: symptom, measurement, fix

Your ITL budget is 50 ms and a decode step takes 15 ms. Prefill runs 22,000 tokens per second. About how big can a chunk be?

Chapter 7

Kernels, Graphs and FP8

Shrink the fixed costs of each step: kernel launches and bytes per weight

A decode step is not one GPU program. In plain PyTorch, each operation is a separate kernel: a matrix multiply, a norm, an activation. The CPU launches each kernel on the GPU, and each launch costs the CPU a few microseconds. When the GPU step is long, the launches hide behind it. When the step is short, the GPU waits for the CPU.

Three fixes appear in every major engine:

  1. Kernel fusion merges neighbour operations, such as a bias add and an activation, into one kernel. That means fewer launches and fewer trips to HBM for the in-between values.
  2. CUDA graphs record a whole decode step once and replay it with one launch. vLLM and SGLang capture graphs for a set of batch sizes.
  3. Lower precision stores each weight in fewer bytes. FP8 uses 1 byte instead of 2, on H100 and newer NVIDIA GPUs.

The last fix moves the memory wall itself. Call the bytes per parameter q. The weight bytes become N times q.

Say it aloud

t equals N times q, over B.

t
t the shortest decode step at batch 1.
N
N the number of parameters: 7 billion.
q
q bytes per parameter: 2 for BF16, 1 for FP8.
B
B the memory bandwidth: 3,350 GB per second on an H100 SXM.
In plain words

Multiply the parameters N by the bytes q each one takes to get the weight bytes. Divide by B. Halve q and the step time halves.

With numbers

BF16 on an H100: 7 billion × 2 / 3,350 GB/s = 4.18 ms, or 239 tokens per second for one user. FP8: 7 billion × 1 / 3,350 = 2.09 ms, or 479 tokens per second.

Shave one decode step

The top bar is CPU time to launch the step's kernels. The bottom bar is GPU time to read the weights. The step takes the longer one. Toggle the fixes.

Weight-read times come from the formula above (7B model, batch 1). The launch side is illustrative: 600 kernels per step at 5 µs each unfused, 200 after fusion, one graph launch of 20 µs. Real counts depend on the model and the engine.

TensorRT-LLM, NVIDIA's engine, began as an ahead-of-time compiler: it built a fixed engine for one model, shape and GPU before serving. Its current docs say that NVIDIA removed the TensorRT engine backend. PyTorch is now its only execution backend, with no engine build step. Its speed comes from fused kernels, CUDA graphs, FP8 and, on B200, FP4.

The failure: symptom, measurement, fix

At batch 1, a 7B model moves from BF16 to FP8 weights on an H100. What happens to the shortest step time?

Chapter 8

Disaggregated Serving

Run prefill and decode on separate GPUs and pay once to move the KV cache

Chunking makes prefill and decode take turns on one GPU. They still compete. Prefill wants the math, decode wants the bandwidth, and every step is a compromise between them.

Disaggregated serving gives each phase its own GPUs. A prefill GPU reads the prompt and builds its KV cache. It sends the cache to a decode GPU, which streams the answer. Each pool scales on its own. DistServe (Zhong et al., OSDI 2024) reports 7.4 times more requests, or a 12.6 times tighter latency target, than systems that mix the phases. NVIDIA Dynamo runs this split across nodes with vLLM, SGLang or TensorRT-LLM as the engine.

The price is the move. Call the prompt tokens n, the KV bytes per token m and the link bandwidth Blink. Call the transfer time tx.

Say it aloud

t-x equals n times m, over B-link.

tx
t-x the time to move one prompt's KV cache from the prefill GPU to the decode GPU.
n
n the prompt tokens.
m
m KV bytes per token: 0.524 MB for Llama 2 7B (Chapter 3).
Blink
B-link the bandwidth of the link between the two GPUs, one way.
In plain words

Multiply the prompt tokens n by the bytes m each holds to get the cache size. Divide by the link bandwidth B-link. That is t-x, paid once per request.

With numbers

n = 8,000, so the cache is 8,000 × 0.524 MB = 4.19 GB. NVLink on an H100 moves 450 GB/s each way: t-x = 9.3 ms. Four 400 Gb/s InfiniBand links give 200 GB/s: 21 ms. One 25 Gb/s Ethernet link gives 3.1 GB/s: 1.34 s.

Price the move

Pink is the prompt's prefill time. Blue is the time to move its KV cache. Pick a link and drag the prompt length.

8,000

Prefill at ideal speed on an H100 (989 TFLOP/s dense BF16, 7B model). NVIDIA lists H100 NVLink at 900 GB/s, the total of both directions. Link speeds are line rates; real transfers run slower.

The rule: split only if the move costs much less than the prefill it follows. On an H100, prefill of 8,000 tokens takes 113 ms at best. NVLink and InfiniBand pass. Plain 25 Gb/s Ethernet costs twelve times the prefill and fails.

The failure: symptom, measurement, fix

A 4.19 GB KV cache must move between two GPUs over 25 Gb/s Ethernet, after a 113 ms prefill. Is the split worth it?

Chapter 9

One Request, End to End

Follow one request through every part you built, then match an engine to your traffic

Each chapter built one part. A real request passes through all of them in order. Pick a request below and step it through the engine. Every number comes from a formula on this page.

Trace one request

Pick a request, then press Step or Play. The teal dot is your request. The panel shows what each stage costs.

Illustrative requests on a 7B model and one A100: 32 other readers at 1,000 tokens of context (15.1 ms per decode step), 512-token chunks, 16-token blocks, ideal prefill speed. The chat turn finds its first 1,500 tokens cached; only whole blocks count.

Look at where the time goes. The chat turn reuses 93 cached blocks, so its first token comes in about 20 ms. The long document has nothing cached and pays 16 chunks, about 600 ms. In every case, the batch step from Chapter 1 sets the decode time per token.

Matching an engine to your traffic

Every engine below does continuous batching and paged KV memory. They differ in what they built first and where they are now.

EngineBuilt firstWhere it stands
vLLMPagedAttention and continuous batching (Kwon et al., 2023)Prefix caching by hashing full blocks; chunked prefill on by default in V1
SGLangRadixAttention: a radix tree of cached prefixes (Zheng et al., 2024)Up to 6.4 times faster on programs with many shared prefixes
TensorRT-LLMNVIDIA's compiled engines, in-flight batching, FP8TensorRT backend removed; PyTorch-only, with paged KV block reuse, FP8 and FP4 on B200
TGIHugging Face's server with continuous batching and Paged AttentionIn maintenance mode; Hugging Face recommends vLLM or SGLang
NVIDIA DynamoNot an engine: it coordinates engines across nodesDisaggregated prefill and decode over vLLM, SGLang or TensorRT-LLM

Choose by measuring. Ask three questions first:

  1. How much of each prompt repeats earlier prompts? If most of it does, a strong prefix cache decides the bill.
  2. How long are prompts against answers? Long prompts make the chunk budget and the split matter.
  3. What GPUs do you run? FP8 and FP4 kernels need H100 or B200 class hardware.

Then load-test two engines on a day of your own traffic. Compare p99 TTFT, p99 ITL and tokens per second per GPU.

Why does the chat turn get its first token about 30 times sooner than the long document?

Chapter 10

Field Guide

Keep the terms, the numbers, the checklist and the code in one place

Decode reads every weight and every KV cache once per step, so bytes set its speed. A serving engine keeps the batch large and full: it refills seats each step, hands out KV memory in blocks, reuses shared prefixes, slices long prompts, trims launch overhead and bytes per weight, and can split prefill from decode.

Term or formulaMeaningValue here
t = W / Bshortest decode step14 GB / 2,039 GB/s = 6.87 ms, 146 tokens/s
MFUtokens/s × 2N / peak FLOPs0.65% at batch 1 on an A100
t(b)max of memory time and math timeb = 64 at 500 tokens: 15.1 ms, 4,240 tokens/s
RidgeF / B, FLOPs per byteA100 153; H100 295
Uuseful seat-steps sharestatic 0.44; continuous 1.0 with a queue
m = 2 nL h d qKV bytes per tokenLlama 2 7B 524,288; Llama 3 8B 131,072
Paged waste⌈n / s⌉ s − n300 tokens: 4 slots (1.3%) against 85% reserved
tpre = 2N n / Fideal prefill time1,000 tokens: 44.9 ms; 8,000: 359 ms
c = τ F / 2Nlargest chunk inside the ITL budgetτ = 34.9 ms: 778 tokens, use 512
t = N q / Bstep time with q bytes per weightH100: BF16 4.18 ms, FP8 2.09 ms
tx = n m / BlinkKV move for a split fleet8,000 tokens: NVLink 9.3 ms, 25 GbE 1.34 s

Checklist before you ship a serving config

  1. Compute MFU and KV cache usage under real load. Low MFU with full KV memory means memory is your cap.
  2. Set the maximum length to what users send, not to the model's limit.
  3. Put fixed prompt text first and read the prefix cache hit rate.
  4. Set the per-step token budget from your p99 ITL target.
  5. Test FP8 or FP4 with your own eval set before you switch.
  6. Split prefill and decode only if the KV move costs far less than the prefill.
  7. Load-test two engines on your own traffic; record p99 TTFT, p99 ITL and tokens per second per GPU.

The core, in code

pythonimport math

W, B, F, N = 14e9, 2.039e12, 312e12, 7e9         # bytes, bytes/s, FLOP/s, params
m = 2 * 32 * 32 * 128 * 2                          # KV bytes per token: 524,288

def step_time(b, ctx):                              # Chapter 1
    return max((W + b * ctx * m) / B, b * 2 * N / F)

class BlockPool:                                     # Chapter 4
    def __init__(self, n_blocks, size=16):
        self.free, self.size, self.ref = list(range(n_blocks)), size, {}
    def alloc(self):
        blk = self.free.pop(); self.ref[blk] = 1; return blk
    def share(self, blk):                              # prefix reuse, copy-on-write
        self.ref[blk] += 1
    def release(self, blk):
        self.ref[blk] -= 1
        if self.ref[blk] == 0: self.free.append(blk)

def blocks_needed(n, size=16):
    return math.ceil(n / size)

print(round(step_time(1, 0) * 1e3, 2), "ms")               # 6.87 ms
print(round(64 / step_time(64, 500)), "tokens/s")        # 4240
print(blocks_needed(300) * 16 - 300, "empty slots")    # 4

Keep going

Sources

  1. Kwon et al., “Efficient Memory Management for Large Language Model Serving with PagedAttention”, SOSP 2023. arXiv:2309.06180; the vLLM launch post for the 60% to 80% and under 4% waste figures.
  2. Yu et al., “Orca: A Distributed Serving System for Transformer-Based Generative Models”, OSDI 2022. USENIX
  3. Zheng et al., “SGLang: Efficient Execution of Structured Language Model Programs”, 2024. arXiv:2312.07104
  4. Agrawal et al., “Taming Throughput-Latency Tradeoff in LLM Inference with Sarathi-Serve”, OSDI 2024. arXiv:2403.02310
  5. Zhong et al., “DistServe: Disaggregating Prefill and Decoding for Goodput-optimized Large Language Model Serving”, OSDI 2024. arXiv:2401.09670
  6. vLLM docs: automatic prefix caching and optimization and tuning (chunked prefill, preemption).
  7. TensorRT-LLM docs: overview and TensorRT backend removed.
  8. Hugging Face Text Generation Inference docs (maintenance-mode notice) and NVIDIA Dynamo.
  9. NVIDIA A100 and H100 spec sheets.
The takeaway. No serving engine makes the GPU faster. Each one finds a way to make the same weight read serve more tokens, and to stop memory and latency budgets from shrinking the batch.

Teach it back: open Present or Teach and derive 146 tokens per second for one user and 4,240 for sixty-four, out loud. Then go back to the seats and predict the grey share of each strategy before you press Run.

Serving Engines: vLLM, SGLang, TensorRT-LLM
Kwon et al., 2023 · Back to Gleams