← All field notes
LLM Memory Planning

Paged Attention: Calculate KV Cache Blocks and Memory Waste

Calculate logical KV payload, rounded block allocation, unused tail slots and decode growth with a reproducible three-request example.

Paged attention changes how a serving engine allocates and addresses its KV cache. It does not make each cached token smaller. To budget memory, start with bytes per token, round each live request up to whole blocks, and then account for growth and the rest of the runtime.

This guide uses a reproducible allocation example: three hypothetical requests, a fixed token-block size, and an explicitly assumed KV payload. The arithmetic was checked on a CPU; it is not a GPU benchmark or a claim about a particular vLLM deployment.

What PagedAttention changes

An autoregressive model reuses earlier attention keys and values during generation. The original PagedAttention paper addresses memory lost to fragmentation and duplicated cache storage in serving systems. Its reported throughput gains belong to its evaluated models, workloads, and comparison systems; they are not a speedup forecast for this example.

Paging lets a request's logical token blocks refer to physical blocks that need not sit next to each other. A lookup structure supplies the mapping, and allocation can follow demand. Hugging Face's conceptual documentation also explains how block sharing can avoid duplicating cached prefixes across related generations.

Our budget below deliberately excludes sharing. Counting each request independently makes the rounding visible. It should not be presented as an engine's exact peak memory: real implementations add metadata, workspace, alignment and other allocations.

The vLLM paged-attention design page now labels its kernel walkthrough as historical. Use it to understand layouts, not as an instruction to edit a current kernel file. Backend support and allocator settings must be checked against the version actually deployed.

Keep logical KV and allocated KV separate

For a conventional full-attention transformer with a uniform KV layout, a useful logical payload formula is:

KV bytes per token = 2 × layers × KV heads × head dimension × bytes per element

The factor of two counts keys and values. KV heads can differ from query heads; grouped-query attention matters here. See the KV-cache explanation before substituting model parameters.

For this worked example, assume 32 layers, 8 KV heads, head dimension 128 and two bytes per cached element. This gives 131,072 bytes per token, or 128 KiB. These are illustrative inputs, not a claim about a named model. We use binary units throughout: one MiB is 1,048,576 bytes.

With block size B tokens and current request length T:

blocks = ceil(T / B)
allocated token slots = blocks × B
unused tail slots = allocated token slots − T
allocated KV payload = allocated token slots × KV bytes per token

Request length here means all tokens whose KV remains resident, including the cached prompt and generated tokens. Sliding-window or hybrid attention, quantized cache scales, parallel partitioning and shared prefixes require a more specific model. Do not blindly apply this single-layout expression to them.

A three-request block budget

Assume three live requests contain 37, 81 and 130 resident tokens. Use blocks of 16 tokens. Each block therefore holds 2 MiB of our assumed KV payload.

Request Tokens Blocks Tail slots
A 37 3 11
B 81 6 15
C 130 9 14
Total 248 18 40

The allocated token-slot counts are 48, 96 and 144, for a total of 288. The corresponding payload budget is:

Request Logical KV Allocated KV
A 4.625 MiB 6 MiB
B 10.125 MiB 12 MiB
C 16.25 MiB 18 MiB
Total 31 MiB 36 MiB

The 5 MiB difference is capacity reserved in those final blocks but not occupied by these tokens. Under this simplified, independent-request model, each positive-length request has fewer than 16 unused tail slots. Across three requests, the upper bound is 45 slots, because each can waste at most 15.

For comparison, suppose a different policy reserved 256 token slots for each request from the start. It would reserve 768 slots, or 96 MiB of payload capacity, for the same 248 tokens. Our 16-token blocks allocate 36 MiB, 60 MiB less than that chosen reservation policy. This is not a measured saving against an actual serving engine. An allocator that reserved only the exact current lengths would have a different comparison.

Growth changes the allocation staircase

Now let every request retain 16 more generated tokens. Their resident lengths become 53, 97 and 146. The block counts become 4, 7 and 10: 21 blocks, or 42 MiB. Logical KV becomes 37 MiB; the tail capacity remains 5 MiB for this particular increment.

Smaller increments illustrate why current allocation is not the final peak. Request B uses 96 allocated slots at length 81. It still fits after growing to 96 tokens; at 97 it needs another block. In this example, that one-token boundary crossing adds 2 MiB of allocated payload.

For a conservative no-sharing budget in which all requests can coexist until their configured maximum lengths, round up those maximum lengths separately. That is a capacity bound under the stated assumptions, rather than a prediction of how the scheduler will overlap requests. Completion, eviction or preemption can change the live set.

Reproduce the calculation

This standard-library Python example uses only integer arithmetic for block counts. It does not load a model or require a GPU.

lengths = [37, 81, 130]
block_tokens = 16
kv_bytes_per_token = 2 * 32 * 8 * 128 * 2
MiB = 1024 ** 2

for tokens in lengths:
    blocks = (tokens + block_tokens - 1) // block_tokens
    slots = blocks * block_tokens
    print(tokens, blocks, slots - tokens,
          tokens * kv_bytes_per_token / MiB,
          slots * kv_bytes_per_token / MiB)

for increment in (0, 16):
    current = [tokens + increment for tokens in lengths]
    blocks = sum((tokens + block_tokens - 1) // block_tokens
                 for tokens in current)
    logical = sum(current) * kv_bytes_per_token / MiB
    allocated = blocks * block_tokens * kv_bytes_per_token / MiB
    print("increment", increment, "logical_MiB", logical,
          "allocated_MiB", allocated)

The total lines should show logical_MiB 31.0 allocated_MiB 36.0, then logical_MiB 37.0 allocated_MiB 42.0. If your result differs, first check whether you used KV heads rather than query heads, counted both K and V, and kept MiB separate from decimal MB.

Choose a block size with workload evidence

For these same lengths, blocks of 8, 16 and 32 tokens allocate 264, 288 and 320 token slots respectively. At our assumed payload size, that is 33, 36 and 40 MiB. Smaller blocks reduce rounding waste in this example, but that alone does not select a production setting.

More blocks can mean more mapping entries and different backend access behavior. Supported sizes and the resulting performance depend on the engine and attention backend. Measure latency, throughput and memory pressure with the actual version and a representative distribution of request lengths; do not pick a setting from tail-waste arithmetic alone.

Prefix sharing is another separate variable. When several requests reuse an eligible cached prefix, shared physical blocks can lower the unique physical-block count. Cache identity, sharing rules and copy-on-write behavior matter. Simply summing all logical request lengths can then overcount physical storage, while assuming all prefixes are shared can underbudget it.

Turn the cache budget into a GPU plan

Use the ModelFit KV-cache calculator to establish logical KV capacity, then add a block-allocation estimate for your request mix. The context-window VRAM guide connects context length and concurrency to the broader memory plan.

Before committing capacity, record:

  • The model's real attention layout, KV precision, parallelism and engine version.
  • Prompt lengths, generation limits and the number of concurrently resident requests.
  • Block size, eligible prefix sharing and the intended scheduling policy.
  • Weights, activations, temporary workspace, graph allocations and runtime headroom beyond KV payload.
  • Measured peak memory and latency under both typical and long-request traffic.

The tables here budget KV payload only. They do not prove that a GPU can fit the model or sustain a target service level. A calculator provides a transparent starting point; deployment measurements check the assumptions.

Common questions

Does paged attention compress the KV cache?

No. Paging manages placement and allocation. KV-cache quantization changes representation size; prefix sharing avoids some duplication. Treat those as distinct mechanisms when building a budget.

Is tail waste the same as all wasted GPU memory?

No. Our tail calculation counts unused token slots inside allocated blocks. It excludes other allocator effects, metadata, workspace and memory reserved elsewhere by the runtime.

Should I multiply the largest request by the batch size?

That can describe a deliberately conservative reservation assumption, but it loses the actual request-length distribution. For the no-sharing block model, round each simultaneously resident request up separately, then sum. State whether you used current or maximum resident lengths.

Can this table predict a throughput improvement?

No. It can explain the difference between logical payload and rounded capacity for fixed inputs. Throughput requires an actual workload and a measured serving configuration.

Method and responsibility

Prepared by the ModelFit content team. Technical sources and arithmetic checked on November 23, 2026. The worked figures are hypothetical CPU-recalculated examples; no GPU benchmark was performed for this article. The ModelFit homepage includes promoted links to Flatkey GPU services; those links are marked as sponsored in the page markup. This guide makes no hardware availability or performance guarantee.

Primary references

Continue planning

Test the model against real GPU memory.

Open the VRAM calculator →
Paged Attention: KV Cache Blocks and Memory Waste · ModelFit