Blog/Inference Foundations/Part 7
Continuous Batching and PagedAttention
Two ideas that let one GPU serve far more people: refill the batch after every word, and hand out KV cache memory in pages instead of reserving it up front. We build both on the tiny factory and measure what each one buys.

At the end of Part 6 we had a worksheet that said one H100 fits 54 people chatting at once with Llama 3.1 8B. It also had two quiet assumptions:
- Everyone in a batch starts and finishes together.
- Every chat gets its full notebook space reserved the moment it arrives.
Real servers drop both. The first fix is called continuous batching. The second is PagedAttention. Today we build both on the same tiny factory as before and measure what each one is worth.
The bus that waits for the last passenger
Picture the factory's typewriter as a bus with 8 seats. Each trip through the 12 floors types one word for everyone on board (that's the batching from Part 3: the big tables are fetched once and shared by every seat).
The simple way to run the bus: fill all 8 seats, drive until every passenger has their full answer, then let the next 8 on. Engineers call this static batching.
The catch is that answers have wildly different lengths. "What's the capital of France?" needs a few words. "Write me a cover letter" needs hundreds. On a static bus, the short answers finish early and their seats ride along empty until the longest one is done. Meanwhile people at the bus stop wait.
Continuous batching changes one rule: after every single word, anyone who's finished gets off and someone from the queue gets on. The bus never waits for its slowest passenger.
Measuring it
I wrote batching.py on top of the factory from Part 3 (engine.py: GPT-2-small shape, random weights, NumPy on a 2-core CPU). 32 chats are waiting at the start. Each has a 32-token question. Answer lengths are long-tailed like real chats: most short, a few very long.
32 requests, prompt 32 tokens each; answer lengths: min 8, median 59, mean 111, max 480
total answer tokens to produce: 3,563
static continuous
decode steps 1,658 634
seats doing real work 27% 70%
wall time (s) 125.3 44.9
answer tokens/s 28.4 79.3
avg wait for first word (s) 49.7 9.8
p90 wait for first word (s) 93.3 23.3
avg time to finish (s) 57.8 18.5
p90 time to finish (s) 97.8 38.2
speed-up in answer tokens/s: 2.79x
Same machine, same model, same 3,563 words to write. 2.8 times the throughput, just from changing who gets a seat when.
The second row explains it. On the static bus only 27% of seat-trips produced a real word. The rest were empty seats carried along for the ride. Continuous batching kept 70% busy (the last stretch is one long answer with nobody left to fill the seats around it).

And it isn't only throughput. People feel the waiting:
- Time to first word dropped from 49.7 s to 9.8 s on average. On the static bus you can't even start until the whole previous batch is done.
- The shorter half of the chats finished in 12.9 s on average instead of 45.6 s. Short questions stop being stuck behind long answers.
This idea comes from the Orca paper (OSDI 2022), which called it iteration-level scheduling: decide who's in the batch on every iteration, not once per batch. On GPT-3 175B they reported 36.9× the throughput of NVIDIA FasterTransformer at the same latency. Every serious engine does this now.
The same run on a GPU
A CPU makes the effect easy to watch, so I also ported the factory to PyTorch (batching_gpu.py) and ran the same 32 chats on an NVIDIA T4 in FP16 (three runs, middle one kept):
device: Tesla T4, float16
static continuous
decode steps 1,658 634
seats doing real work 27% 70%
answer tokens/s 142 469
avg wait for first word (ms) 9,786 1,829
avg time to finish (s) 11.43 3.40
speed-up in answer tokens/s: 3.29x
Same steps, same empty seats, and a slightly bigger win: 3.3× the throughput (3.0× to 3.3× across the three runs). The GPU is faster at everything, but it still can't type for a seat nobody is sitting in.
What it costs
Someone joining mid-ride needs their question read first (prefill) before they can get their first word. That reading happens while everyone else is waiting for their next word. In Part 3 we saw a 1,024-token question freeze 8 typers for 4.7 s. That's why continuous batching almost always comes with chunked prefill: feed the newcomer's question in small pieces between words, so the bus never stops for long.
The other waste: reserved seats in the notebook
Continuous batching keeps the seats full. But how many seats can the bus have? That's a memory question, and Part 6 answered it with a pessimistic rule: reserve each chat's longest possible notebook up front, because you don't know how long the answer will be.
Let's see what that costs. Same 32 chats, and now a fixed amount of notebook room: 4,096 tokens (302 MB at this factory's 72 KB per token). The server promises chats up to 1,024 tokens, so reserving up front means 4 chats at a time, whatever their real length.
Most of our chats are under 100 tokens. So most of each reservation is empty paper that nobody else can use.
Pages instead of reservations
PagedAttention borrows a trick operating systems have used for decades: don't give a program one big block of memory. Give it small pages, one at a time, as it needs them, and keep a list of where they are.
For the notebook it works like this:
- All notebook memory is one shared pool of pages. A page holds the K and V cards for a fixed number of tokens (16 in my script).
- Each chat has a block table: a short list saying "my tokens 0–15 are in page 41, tokens 16–31 are in page 7, …". The pages don't need to sit next to each other.
- When a chat fills its last page, it grabs one more from the pool. When it finishes, all its pages go straight back.
In paged_kv.py the change to the factory is small. Writing a new token's cards means finding its page and slot:
pg, slot = u["pages"][(s + j) // PAGE], (s + j) % PAGE
self.K[i, :, pg, slot], self.V[i, :, pg, slot] = kk[:, j], vv[:, j]
Reading the notebook for attention means collecting that chat's pages in order:
pages = u["pages"][:(e + PAGE - 1) // PAGE]
Kc = self.K[i][:, pages].reshape(HEADS, -1, HD)[:, :e]
First check, as always: does it give the same answer? Three chats with odd-length questions (40, 7 and 23 tokens), then 30 words each, run through both versions of the factory:
1) Same answer with pages?
3 chats, prompts of 40, 7 and 23 tokens, then 30 words each
biggest difference in any number: 0.0e+00
pages in use: 12 x 16 = 192 token slots for 160 tokens
Identical, to the last digit. And the only waste is the unfilled end of each chat's last page: 192 slots held for 160 tokens.
What pages buy
Now the same 32 chats with the same 4,096 tokens of notebook room, both ways:
2) The same 32 chats, notebook room for 4,096 tokens (302 MB at 72 KB/token), longest chat allowed 1,024
reserve 1,024 16-token pages
chats in the batch, average 3.3 7.4
chats in the batch, peak 4 32
room holding real tokens 15% 95%
decode steps to serve all 32 1,064 480
chats sent back (preempted) 0 0
-> 2.2x more chats per step, 2.2x fewer steps
With reservations, only 15% of the notebook memory held real tokens. With pages, 95%. Same memory, and at the busiest moment it held all 32 chats instead of 4.
That 15% isn't a quirk of my toy. The vLLM paper (Kwon et al., SOSP 2023) measured that existing systems used only 20.4% to 38.2% of their KV cache memory for actual tokens. With pages they got near-zero waste and 2 to 4 times the throughput of FasterTransformer and Orca at the same latency.
(This part of the script counts tokens and pages rather than running the factory, so it measures memory, not speed. The 480 steps is simply the longest answer: everyone fit at once, so nobody waited.)
When the pool runs dry
Pages create a new risk. Reservations never run out mid-answer. Pages can: if every chat keeps growing, the pool empties. A paged server has to decide who loses their pages (usually the newest arrival), send them back to the queue and redo their work later. That's preemption. With 4,096 tokens of room our 32 chats never hit it, but squeeze the room and it shows up, and it's one of the main causes of a sudden slow answer under load.
What pages cost
Pages aren't free to read. In NumPy, collecting scattered pages means copying them into one block first:
3) What pages cost: read one floor of a 512-token notebook (12 heads)
contiguous: 34 us 32 scattered pages: 379 us (11.0x)
About 11 times slower for that one read on my CPU (small timings like this wobble from run to run). Real GPU engines don't copy: their attention kernel takes the block table and reads each page where it sits (vLLM started by adapting FasterTransformer's attention kernel to do exactly that). The lookups still cost a little, but far less than the memory they free up.
Pages also make sharing easy. Two chats that start with the same system prompt can point their block tables at the same pages instead of storing two copies. That's the idea behind prefix caching, which gets its own post later.
Back to the H100
In Part 6, Llama 3.1 8B on one H100 left room for about 442,000 tokens of notebook. Reserve 8,192 tokens per chat and that's 54 chats.
With pages, the limit becomes the tokens actually in flight, not the tokens promised. If the chats on your server average 2,000 tokens at any moment (an assumption: check your own logs), the same card holds about 221 chats: 442,000 ÷ 2,000. Four times more people, without buying anything.
Whether 221 people all get a fast answer is the other half of the story. Every one of them adds their notebook to each decode step's reading (Part 4's roofline). Memory now stops being the first limit, and speed takes over.
Cheat sheet
| Idea | What changes | What it buys | What it costs |
|---|---|---|---|
| Static batching | Batch fixed until its longest answer ends | Simple | Empty seats; short chats wait for long ones (27% busy here) |
| Continuous batching | Seats refilled after every word | 2.8× throughput on CPU, 3.3× on a T4, 5× faster first word | Newcomers' prefill interrupts others (use chunked prefill) |
| Reserved notebooks | Each chat gets its maximum length up front | Never runs out mid-answer | 15% of memory holds real tokens here |
| Paged notebooks | 16-token pages handed out as needed | 95% of memory used, 2.2× more chats per step here | Page lookups; preemption when the pool runs dry |
What's next
Continuous batching fills every seat. Pages fill every byte. But each user still gets just one word per trip through the tables. Part 8: Speculative Decoding Basics shows how a small helper model guesses several words ahead so the big model can check them all in one trip, without changing a single word of the answer.
Every number in this post comes from three scripts: batching.py (static vs continuous batching, real timed runs), batching_gpu.py (the same run in PyTorch on an NVIDIA T4, FP16, Google Colab) and paged_kv.py (the paged notebook: the same-answer check, a token-and-page count of memory use, and a timing of the page read). The two CPU scripts run on engine.py, the same tiny GPT-2-shaped factory as Part 3, in float32 NumPy on a 2-core cloud CPU. Real servers tune the details (page size, how many seats, who gets preempted), so treat these as the shape of the effect and measure your own.
Part 7 of 10 · Inference Foundations
Read the whole series
- One Request, End to End: Tokenize, Prefill, Decode, Stream15 min read
- A Forward Pass for One Token: Where the FLOPs Go14 min read
- Prefill vs Decode: Two Phases, Two Bottlenecks11 min read
- The Roofline Model for LLM Inference11 min read
- The KV Cache From Scratch9 min read
- How Much GPU Memory Do I Need?10 min read
- Continuous Batching and PagedAttentionYou are here
- Speculative Decoding BasicsComing soon
- Tensor, Pipeline and Expert ParallelismComing soon
- Quantization Formats: FP16, BF16, FP8, INT8, INT4Coming soon