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.
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
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.
t equals W over B.
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.
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.
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.
nvidia-smi shows the GPU near 100% busy, yet tokens per second are low. That number counts the time any kernel runs, not the FLOPs it does.Chapter 1
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.
t of b equals the max of two things: W plus b times M, over B; and b times two N, over F.
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.
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.
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.
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.
Chapter 2
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.
U equals the sum over i of ell-i, over S times T.
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.
(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.
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.
Chapter 3
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.
m equals two times n-L times h times d times q.
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.
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.
Blue blocks are the weights. Each warm cell is one sequence's KV cache. Pick a model and drag the context length.
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.
Chapter 4
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.
waste equals the ceiling of n over s, times s, minus n.
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.
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.
Each row is one request. Warm is memory holding tokens. Grey is memory reserved but empty. Switch the allocator and drag the average length.
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.
Chapter 5
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.
t-pre equals two N times n, over F.
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.
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.
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.
Chapter 6
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.
c equals tau times F, over two N.
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.
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.
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.
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.
Chapter 7
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:
The last fix moves the memory wall itself. Call the bytes per parameter q. The weight bytes become N times q.
t equals N times q, over B.
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.
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.
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.
Chapter 8
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.
t-x equals n times m, over B-link.
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.
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.
Pink is the prompt's prefill time. Blue is the time to move its KV cache. Pick a link and drag the prompt length.
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.
Chapter 9
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.
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.
Every engine below does continuous batching and paged KV memory. They differ in what they built first and where they are now.
| Engine | Built first | Where it stands |
|---|---|---|
| vLLM | PagedAttention and continuous batching (Kwon et al., 2023) | Prefix caching by hashing full blocks; chunked prefill on by default in V1 |
| SGLang | RadixAttention: a radix tree of cached prefixes (Zheng et al., 2024) | Up to 6.4 times faster on programs with many shared prefixes |
| TensorRT-LLM | NVIDIA's compiled engines, in-flight batching, FP8 | TensorRT backend removed; PyTorch-only, with paged KV block reuse, FP8 and FP4 on B200 |
| TGI | Hugging Face's server with continuous batching and Paged Attention | In maintenance mode; Hugging Face recommends vLLM or SGLang |
| NVIDIA Dynamo | Not an engine: it coordinates engines across nodes | Disaggregated prefill and decode over vLLM, SGLang or TensorRT-LLM |
Choose by measuring. Ask three questions first:
Then load-test two engines on a day of your own traffic. Compare p99 TTFT, p99 ITL and tokens per second per GPU.
Chapter 10
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 formula | Meaning | Value here |
|---|---|---|
| t = W / B | shortest decode step | 14 GB / 2,039 GB/s = 6.87 ms, 146 tokens/s |
| MFU | tokens/s × 2N / peak FLOPs | 0.65% at batch 1 on an A100 |
| t(b) | max of memory time and math time | b = 64 at 500 tokens: 15.1 ms, 4,240 tokens/s |
| Ridge | F / B, FLOPs per byte | A100 153; H100 295 |
| U | useful seat-steps share | static 0.44; continuous 1.0 with a queue |
| m = 2 nL h d q | KV bytes per token | Llama 2 7B 524,288; Llama 3 8B 131,072 |
| Paged waste | ⌈n / s⌉ s − n | 300 tokens: 4 slots (1.3%) against 85% reserved |
| tpre = 2N n / F | ideal prefill time | 1,000 tokens: 44.9 ms; 8,000: 359 ms |
| c = τ F / 2N | largest chunk inside the ITL budget | τ = 34.9 ms: 778 tokens, use 512 |
| t = N q / B | step time with q bytes per weight | H100: BF16 4.18 ms, FP8 2.09 ms |
| tx = n m / Blink | KV move for a split fleet | 8,000 tokens: NVLink 9.3 ms, 25 GbE 1.34 s |
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
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.