← Inference From First Principles

PagedAttention

A KV cache in fixed-size blocks: how much memory contiguous allocation wastes, what block tables, reference counts and copy-on-write buy, and what greedy admission costs.

Imagine a server with room in its KV memory for 32,768 tokens. If it reserves 1,024 token slots for every sequence, so that no sequence can ever run out of room, it can hold at most 32 sequences. In a simulated chat-like workload, on average only 33% of those reserved slots held a valid token during the steady part of the run. The rest was capacity set aside for tokens that had not been, and mostly never would be, generated.

Now hand out memory in 16-token blocks, only as each sequence grows. With the same budget, the simulator held about 92 sequences at once (with a 5% safety margin, explained below), or 96 with none. Real tokens filled about 98% of the blocks actually handed out. Over 3,000 requests, the run took 5,611 scheduler steps against 15,260 for reserving the maximum: about 2.72 times fewer. (Simulated scheduler steps, before accounting for GPU execution and prefill.)

Remove the safety margin, though, and things go wrong. New prompts get admitted even when there is barely room for their replies, and the scheduler has to preempt running sequences (evict them and restart them later) to make space: 2,094 times in the chat-like run. That pushed its cost to 13,754 steps (5,378 scheduler steps, plus a four-step penalty for each preemption). Still better than reserving the maximum, but far worse than with the margin, and worse than the 10,637 of a policy that reserves only each request’s declared limit.

(All of these are modelled step counts from a simulator, not measured latency or throughput. And the declared-limit comparison has a flaw, explained below, that the chapter keeps visible.)

So paging solves a memory-layout problem, but how much of that solution becomes useful work depends on admission and eviction policy. This chapter builds a reference paged KV cache for GPT-2, measures the cost of gathering its blocks back together for attention, and runs a synthetic scheduler experiment. Neither the gather-based implementation nor the simulator is a production PagedAttention kernel.

Where this sits

Key-Value Caching compared growing and preallocated caches: for eight sequences at 960 tokens, PyTorch’s allocator reserved 2,926 MiB with concatenation versus 1,108 MiB with static buffers, for 540 MiB of actual cache. (Reservation is not a direct measure of fragmentation, but it shows that allocation behaviour matters.) Attention and Its Computational Cost found where KV bytes overtake weight bytes, and Prefill and Decode showed requests competing for one timeline. Now the thing being managed becomes many independently growing sequences sharing one pool of physical blocks.

The Inference Lab gains a block layer: a reference-counted BlockAllocator, BlockTables with forking and copy-on-write, a PagedKV tensor pool, ragged-batch GPT-2 decoding, and a deterministic simulator comparing allocation policies. These give three different kinds of evidence: unit tests of selected safety properties, one GPU implementation checked for correctness and speed, and a simulation under assumed request lengths. An allocator should ultimately be judged on correctness, reserved versus useful bytes, concurrency, preemptions and end-to-end service targets, not on any single utilisation percentage.

For the Pi series, agent conversations, tool outputs and shared system prompts produce contexts of unpredictable length, often with repeated prefixes. A block pool can hold them without reserving every possible future position, and reference counts let sequences share a prefix without copying it. (Actual reuse still needs the identity checks from Key-Value Caching: matching block tables do not prove that two requests used the same model, positions or tokenisation.) Prefix Caching builds lookup and eviction on top.

Where contiguous allocation wastes memory

Storing each sequence’s cache as one contiguous region can waste memory in three distinct ways:

Kind of waste What it is What paging does about it
Advance reservation Space committed now for tokens that may be generated later Removes it: blocks are granted as the sequence grows
Internal fragmentation Unfilled slots inside a fixed-size allocation Limits it to the partly filled last block of each sequence
External fragmentation and allocator overhead Free memory split into pieces too small for a new large allocation; memory held by caching allocators Avoids needing contiguous space per sequence, at block granularity

(Advance reservation is a design choice, not something contiguous storage requires: contiguous buffers can also grow or be reallocated. And Key-Value Caching’s reserved-memory gap was not shown to be external fragmentation.)

The simulation

The simulator models mainly advance reservation and last-block slack. It does not model a real GPU allocator, kernels, arrival times, host transfers or external fragmentation.

Its rules. A saturated queue of 3,000 requests; a budget of 32,768 KV token slots; prompt and output lengths drawn from lognormal distributions, capped at a 1,024-token context. Every resident sequence advances one generated token per scheduler step, and prefill takes no simulated time. Three workloads (the distributions are set by their medians; these means come from 5,000 separate samples):

Workload Mean prompt Mean output Mean final length
Chat-like 217 154 371
Long prompt, short answer 627 47 674
Short prompt, long answer 47 359 406

The policies. reserve_max commits 1,024 slots per sequence. reserve_declared commits min(1,024, prompt + 512). Paging allocates 16-token blocks on demand.

A flaw in the declared-limit comparison. The request generator does not cap every output at 512 tokens. In the seeded samples, 92 chat-like requests and 681 short-prompt/long-answer requests need more than their declared reservation, and the simulator simply lets them grow. So the declared-limit rows below are informative about the intended comparison, but they cannot support a real capacity comparison until the admission or length rule is fixed (logged as a defect).

What “utilisation” means here. The simulator’s memory_utilisation is the sum of real tokens in resident sequences, divided by the slots reserved or allocated for them, averaged over steps while requests are waiting. It is a packing ratio, not the fraction of the 32,768-slot pool in use.

Policy Chat-like Long prompt Long answer
Reserve the maximum (1,024) 33% 61% 30%
Reserve the declared limit 48% 64% 55%
16-token blocks, on demand 98% 99% 97%

Reserving the maximum fills only 30–61% of what it commits; on-demand blocks fill 97–99% of what they hand out. Neither number says how much of the GPU is in use, or how many requests per second the system serves. In particular, a safety margin deliberately leaves part of the pool empty, so packing can stay near 98% while the pool is less full and fewer sequences fit.

Where contiguous allocation wastes memory

Paging

The idea. Separate where a token sits logically in its sequence from where its keys and values sit physically in memory.

  • A physical block stores the keys and values for a fixed number of consecutive positions, for all layers.
  • Each sequence has a block table mapping logical block \(i\) (positions \(ib\) to \(ib+b-1\)) to a physical block id. A sequence’s blocks need not be adjacent.
  • The allocator hands out blocks as a sequence grows and takes them back when the last owner releases them. (PagedKV allocates the whole tensor pool up front; “on demand” refers to assigning blocks to sequences, not to allocating GPU memory.)
  • Reference counts let several sequences point at the same blocks. Full shared blocks stay read-only; a shared, partly filled last block must be copied on write before a branch appends to it.

The mapping borrows from virtual memory, but there are no page faults or hardware address translation. BlockAllocator.alloc() pops one id from a Python free list in constant time; allocating several, building tables and copying shared blocks cost more.

What it does not remove. Last-block slack, table metadata, and the possibility of running out of free blocks. For scale: a 1,024-token sequence in 16-token blocks needs a table of 64 ids, 256 bytes if they were ideal 32-bit integers (Python lists cost more), against 72 MiB of fp32 GPT-2 KV data for that sequence.

What it costs in the last block

Each sequence’s last block is usually only partly full. If final lengths are roughly uniform modulo the block size \(b\), the last block wastes about \((b-1)/2\) slots on average. Dividing by the mean final length \(\bar L\) gives a quick approximation:

\[ \text{waste} \approx \frac{b-1}{2\,\bar{L}} \]
For the chat-like workload, \(\bar L\approx371\). Comparing the approximation with the simulator's measured loss (one minus `memory_utilisation`):
Block size \(b\) Predicted waste Measured waste
1 0% 0.0%
16 2.0% 2.2%
64 8.5% 8.7%
128 17.1% 16.0%
256 34% 27.3%

At 16 and 64 tokens the approximation is within a few tenths of a percentage point. At 256 it overshoots (34% against 27.3%), because the approximation divides by useful tokens rather than allocated slots, and because length variation and the simulator’s time weighting start to matter. (They are not the same estimator.)

So why not \(b=1\)? It removes last-block slack entirely, but needs a table entry per token and many fine-grained indirect reads. Smaller blocks also mean more allocation and metadata work. The stand-alone gather benchmark below shows only a modest difference across block sizes for one shape, and does not measure a fused kernel or table-read overhead. Block size should be chosen together with the attention kernel and the real length distribution, not from the slack formula alone.

The real cache

PagedKV preallocates key and value pools shaped [layers, physical_blocks, block_size, heads, head_dim], with one physical block id shared across layers. prefill_paged adapts the forward_cached interface from Key-Value Caching for a single sequence by gathering its blocks. forward_paged_decode advances every sequence in a ragged batch by one position: it gathers each sequence’s blocks into padded contiguous tensors and masks the padding before attention.

That makes it a working reference for paged storage and bookkeeping, not the fused PagedAttention algorithm of Kwon and colleagues, which reads blocks directly during attention. (The full pool stays allocated even while many blocks are free.)

It is the same function

Four prompts of 5, 19, 40 and 77 tokens were decoded together for 20 steps with 16-token blocks, and compared with independent caches from Key-Value Caching. Every greedy token matched. The largest absolute logit difference was \(1.129\times10^{-3}\). (Dividing that by a large logit would suggest parts-per-million agreement, but that is not a valid relative bound near logits close to zero.) Small-model CPU tests separately cover ragged decoding, block reuse and forked branches. This establishes correctness for the tested cases, not for every batch order, pool exhaustion, mixed models or masks.

Sharing and copy-on-write

A worked example. A 40-token prefix fills two 16-token blocks and half of a third. Fork it into two branches:

Step Physical blocks What happened
Fork 3 Both tables point at the same three blocks; nothing copied
Branch 1 appends a token 4 Its shared partial third block is copied first, then written
Branch 2 appends a token 4 It is now sole owner of the original third block, so it writes in place

Four physical blocks instead of the six that two separate 40-token prefixes would need: the two full prefix blocks stay shared. Both branches matched recomputation, within \(3.05\times10^{-5}\) and \(6.10\times10^{-5}\).

This demonstrates reference-counted ownership and copy-on-write. It does not measure prefix-hit rates or a cache shared across requests.

A safety defect. BlockTables.reserve performs the copy-on-write of a shared partial block before trying to allocate any further blocks the reservation needs. If a later allocation fails, the copy stays installed even though the reservation raised OutOfBlocks. The existing no-leak test covers a failed reservation without a shared partial block, so this case is untested. It needs an atomic rollback and a regression test (logged as a defect).

Block tables and copy-on-write

What the gather costs

Before attention, the reference implementation copies each sequence’s scattered blocks into contiguous K and V tensors, padded to the longest sequence. A fused paged kernel reads the blocks in place instead. So this measures the gather-based reference path, not such a kernel.

The set-up. The same hand-written GPT-2 forward pass with a static cache and with a paged cache; 15 decode calls per cell, two runs. (The static cache was filled by a real forward pass; the paged pool’s lengths and tables were set up without computing real prefix keys and values. So this times the decode path at comparable shapes, not end-to-end generation.)

Batch Context Static cache Paged (16-token blocks) Ratio
1 128 18.1 – 19.6 ms 18.8 – 21.1 ms 1.04 – 1.08
8 128 22.0 ms 24.3 – 24.6 ms 1.12
32 128 18.5 – 21.3 ms 20.4 – 21.4 ms 0.96 – 1.16
64 128 20.3 – 22.8 ms 20.9 – 22.0 ms 0.96 – 1.03
32 512 18.3 – 18.7 ms 33.6 – 37.5 ms 1.8 – 2.0
64 512 19.4 – 19.9 ms 59.2 – 63.8 ms 3.0 – 3.3

Small batches and short contexts: no consistent difference. Both sit at roughly 18–25 ms per step, consistent with large framework and dispatch overhead (not isolated). These batch-1 static-cache times are about twice the 8.3–8.5 ms measured for a nominally similar step in Memory Bandwidth and Compute Bottlenecks; the harnesses differ and the gap is unexplained.

Large batches and longer contexts: the paged path took 1.8–2.0 times as long at batch 32 with 512 tokens, and 3.0–3.3 times at batch 64. That last cache holds \(64\times512\times73{,}728\approx2.42\) decimal GB of fp32 K/V state (2.25 GiB). Gathering it into new tensors and then reading them again adds data movement; padding, layout, indexing, kernel choice and launches may add more. Without memory counters, the extra 40 ms cannot be assigned to a known number of memory passes.

The conclusion is narrow but useful: this gather path gets expensive at large batch and context. PagedAttention addresses exactly this, with a kernel that reads through the block table without building a contiguous copy. The experiment motivates such a kernel; it does not measure one, or show that it would remove every overhead here.

Isolating one gather. A single gather of eight 512-token sequences, 12 heads, head dimension 64, fp16: 6 MiB of output for one of K or V in one layer, so 12 MiB of nominal read-plus-write traffic. Physical block ids either shuffled or in order:

Block size Gather time, scattered In order
1 81 – 82 µs 80 – 81 µs
16 78 µs 77 – 78 µs
256 74 µs 74 µs

Larger blocks helped a little (about 81–82 µs down to 74 µs), and shuffled order cost at most about 1 µs. That works out to roughly 154–170 GB/s of nominal traffic, an estimate, not measured bandwidth. This microbenchmark is much smaller than the full multi-layer K-and-V gather during decode, and it says nothing about table-read overhead or access locality inside a fused kernel.

The policy is where it succeeds or fails

On-demand allocation admits a request once its prompt’s blocks fit, without reserving room for its future output. So a later decode step can find the pool empty. Then something must give.

The simulator’s rules.

  • Preemption: when a sequence needs a block and none is free, the most recently admitted resident request is preempted: its blocks are freed, and it goes back into the queue to restart from its original prompt.
  • Watermark: a new prompt is admitted only if a chosen fraction of the pool would still be free afterwards.
  • Cost: the table reports scheduler steps until all 3,000 requests finish, plus a four-step surcharge per preemption. (The simulator already replays the lost generation work; the surcharge is an extra fixed charge, not a measured prefill cost.)

These are simple policies for illustration, not a measured production scheduler. Same seeded requests, 16-token blocks, 32,768-token budget, saturated queue. Lower is better under these assumptions:

Policy Chat-like Long prompt Long answer
Reserve the maximum 15,260 4,665 35,223
Reserve the declared limit 10,637 4,536 19,711
Paged, watermark 0 13,754 3,877 94,960
Paged, watermark 5% 5,611 3,106 17,752
Paged, watermark 10% 5,858 3,273 14,599
Paged, watermark 20% 6,550 3,671 14,489
Paged, watermark 30% 7,446 4,186 15,650

(Declared-limit rows carry the over-limit defect described earlier.)

How preemptions respond to the margin:

Watermark Chat-like Long prompt Long answer
0 2,094 228 20,809
5% 11 0 1,501
10% 2 0 613

Watermark tradeoff

What the tables show.

  • No margin can be disastrous. With a zero watermark, paging beat maximum reservation on chat-like and long-prompt work, but was far worse on long answers once the surcharge was added: 94,960 steps against 35,223. Without the surcharge that same run took only 11,724 steps, so the ranking depends heavily on how preemptions are priced.
  • A small margin fixes most of it. At 5–10%, preemptions nearly vanish for chat-like and long-prompt work. They do not vanish for long answers (1,501 and 613).
  • Too much margin wastes concurrency. In the chat-like workload, mean resident sequences fall from about 96 at zero watermark to about 68 at 30%, while block packing stays near 98%, another reminder that packing is not pool utilisation.

Against maximum reservation, a 5–10% watermark cut the simulated step counts by 2.6–2.7× (chat-like), 1.4–1.5× (long prompt) and roughly 2.0–2.4× (long answer). Kwon and colleagues’ PagedAttention paper independently reports 2–4× higher throughput at comparable latency for the vLLM serving system against particular baselines of its time. That is published system evidence, not a confirmation of these simulated ratios; the similar size is not a reproduction.

What the simulator leaves out. There is no arrival process (the queue is always full), every resident sequence advances exactly one token per step, prefill takes no time, and preempted work is replayed with a fixed surcharge instead of the prefill costs measured in Prefill and Decode. A real service would also need KV memory for prefills in progress, uneven decode times, client-visible TTFT and TPOT, fairness, deadlines, and other preemption or host-spill options. The point here is that policy matters a great deal, not which watermark is best in production.

A projection, by arithmetic

How does this scale to a bigger model? Take an illustrative 7B-class architecture with 32 layers, 32 KV heads and head dimension 128. In fp16, one token’s keys and values take \(2\times32\times32\times128\times2=524{,}288\) bytes: 0.5 MiB per token, and 512 MiB for a 1,024-token sequence.

Given a hypothetical 10 GiB of KV-only memory:

  • reserving 1,024 tokens per sequence fits 20 sequences;
  • on-demand blocks at the simulated 98% packing, with the chat-like mean of 371 tokens, fit about 54: \(10{,}240\,\text{MiB}\times0.98/(371\times0.5\,\text{MiB})\approx54\).

That is an expected-capacity ratio, not a guarantee that 54 variable-length requests will always fit. No 7B model was loaded or measured. The 10 GiB excludes weights, activations, workspace, block tables, allocator reserves and other users. And parameter count does not fix KV size: grouped-query and multi-query attention can use far fewer KV heads than query heads, shrinking this a lot (Multi-Head and Multi-Latent Attention). The arithmetic shows why on-demand allocation matters more as the per-token cost grows; it does not predict achievable throughput or batch size.

Inference Lab increment

The Lab now has:

  • BlockAllocator (block ids and reference counts) and BlockTables (sequence mappings, reservations, fork and copy-on-write). Tests cover a failed fresh multi-block allocation; a failure after partial-block copy-on-write still needs an atomic rollback and a regression test.
  • PagedKV, prefill_paged and forward_paged_decode: a preallocated physical pool and a gather-based, masked ragged-batch forward pass. Not a fused PagedAttention kernel.
  • simulate(policy, workload, budget, block_size, watermark): seeded and deterministic, returning steps, penalised step totals, preemptions, resident concurrency and memory_utilisation (a packing ratio). The declared-limit output cap and the admission and recomputation model need strengthening before results can guide real capacity decisions.
  • Entry points python examples/ch14/paged_cache.py simulate, python examples/ch14/paged_cache.py decode and python examples/ch14/paged_cache.py gather; the last two need CUDA and a GPT-2 checkpoint.

The reporting rule: report valid KV tokens, allocated block bytes, free pool bytes, mean and peak resident sequences, preemptions, actual recomputation work and service latency separately. Block packing is not pool occupancy, and neither predicts throughput. Block tables buy flexible capacity; the kernel and the scheduler still have to turn it into correct, affordable execution.

Limits of this chapter’s evidence

About the simulator

  • Synthetic, not serving throughput. Lognormal lengths, a permanently full queue, one token per resident request per step, no prefill time, and an assumed eviction surcharge.
  • Utilisation has a specific denominator: real tokens over allocated or reserved slots, not the fraction of the GPU KV pool in use.
  • The declared-limit comparator lets outputs exceed their reservation (92/3,000 chat-like and 681/3,000 long-answer requests).
  • Not modelled: swapping, real arrivals, fairness, priority-aware preemption, cache hit rates, or a production scheduler comparison.

About the implementation and measurements

  • Gather-based, not fused. The measured slowdown is specific to indexed gathers, padding and the hand-written model; a production kernel’s overhead is unknown.
  • Two timing runs, one session, no hardware traffic counters and no end-to-end request trace.
  • Limited correctness coverage: four GPT-2 sequences for 20 steps, one shared 40-token prefix with two branches, and small-model CPU tests.
  • Copy-on-write rollback on a failed reservation is untested and currently incorrect.

What you should now be able to do

  • Distinguish advance reservation, last-block slack and allocator-level fragmentation, without treating them as the same measurement.
  • Build a block table, and explain how reference counting and copy-on-write keep two diverging continuations correct.
  • Compute per-token KV bytes and last-block waste, and distinguish allocated-block packing from whole-pool occupancy.
  • Explain why a gather-based path can be slower than a fused paged kernel, and what would need profiling to account for the difference.
  • Say how a watermark affects concurrency and preemptions in this simulator, without claiming a measured production benefit.
  • Recognise an under-reservation bug when output exceeds its declared limit, and the atomic-rollback requirement for partial-block copy-on-write.
  • Keep demonstrated GPT-2 cache correctness, synthetic scheduler results and arithmetic projections for larger models apart.

Paging decides where each sequence’s state lives; it does not decide which sequences run together at each step, or what happens when a new request arrives in the middle of others’ decoding. Continuous Batching takes up that scheduling side.

Key terms

  • Physical block/page: a fixed-capacity pool region containing KV data for a number of token positions.
  • Logical block table: a per-sequence map from logical positions to physical block IDs.
  • Reference count: the number of live block-table owners of a physical block.
  • Copy-on-write: making a private block copy when a branch must modify shared data.
  • Advance reservation: capacity committed for possible future generated tokens before they exist.
  • Internal fragmentation: unused slots within a reserved region or the final allocated KV block.
  • External fragmentation: free space split into pieces that cannot satisfy a requested contiguous allocation.
  • Block-packing efficiency: valid logical KV token slots divided by resident allocated block slots; distinct from GPU-pool occupancy.
  • Preemption: removing a resident request to reclaim its KV blocks, with work that must later be resumed or recomputed.
  • Admission watermark: the fraction of pool capacity withheld as free headroom when admitting new prompts.

Reader exercises

  1. Reproduce the block-size waste table and calculate both resident block-packing efficiency and fraction of the total 32,768-token pool allocated. How can one be 98 per cent while the other is much lower?
  2. Fix reserve_declared by enforcing output <= declared_limit, or by growing reservations safely. Regenerate the comparison table and explain which policy rankings change.
  3. Add a test that forks a sequence with a partly filled shared block, then attempts a reservation requiring more blocks than remain free. Make reserve atomic: failure must restore references, tables and copy queues to their earlier state.
  4. Replace newest-request preemption with a policy based on already-generated work. Measure preemptions and replayed tokens as well as total simulated steps for all three workloads.
  5. Add a cost function derived from Prefill and Decode’s prefill and decode timings instead of a constant four-step surcharge. Does the best watermark change when recomputation scales with prefix length?
  6. Compare the stand-alone indexed gather with a contiguous copy at identical tensor shapes; then profile a complete decode step’s gather, attention and dispatch costs separately.
  7. Derive the 7B-class projection for 32 versus 8 KV heads, and report the KV-only estimate separately from the model’s full-device memory requirement.

References

Evidence in this chapter

Claim Evidence and limitation
Fixed-size blocks, block tables, reference counts and copy-on-write Established in the PagedAttention paper; selected mechanisms implemented and unit-tested here
Maximum reservation has 30–61% packing; paged blocks have 97–99% packing Synthetic simulation; ratios concern resident reserved/allocated slots, not total GPU KV-pool occupancy
Last-block waste is approximately \((b-1)/(2\bar L)\) Analytic approximation under a modulo-uniform assumption; reported comparison differs at large block sizes
Ragged-batch GPT-2 paged decode reproduces four independent streams Book result: four prompts, 20 steps, identical greedy tokens; maximum absolute logit difference 1.129e-3
Forked 40-token prefix shares blocks correctly for two branches Book result: three blocks shared initially, four after append; one experiment
Gather-based decode costs up to 3.3× static at batch 64, context 512 Book result: two GPU runs; no fused paged-attention kernel tested and no hardware traffic counters
Indexed gather is nearly indifferent to physical block order Book result: one fp16 gather shape; timing range depends modestly on block size
Zero-watermark admission causes many preemptions Book simulation result; strongly affected by fixed extra preemption penalty
Five-to-ten-per-cent watermarks reduce preemptions Book simulation result, but long-answer workload still has 613–1,501 preemptions
Declared-limit baseline is a valid capacity constraint Not established: 92 chat-like and 681 long-answer sampled requests exceed their reserved allowance
Reservation rollback is atomic after a partial-block COW Not established: current code mutates the shared-last-block mapping before later allocation may fail
KV-only 7B-class capacity of roughly 20 full-length or 54 mean-length sequences in 10 GiB Arithmetic based on 32 KV heads and 0.5 MiB/token; not a full-device capacity or performance benchmark
Fused paged kernel, real request latency and throughput, swapping, real traces Not measured