Pidoku

Sizing the Cache: From Gigabytes to Blocks

Module 17 Lesson 17.h 50 min Difficulty 3/5

Prerequisites 12.f, 17.e


Before you start: words you need#

WordPlain meaning
--gpu-memory-utilizationThe share of the GPU’s total memory this vLLM instance may use, for everything.
Profiling runOne forward pass with dummy inputs at startup, used to measure how much working memory the model needs.
ActivationsTemporary tensors created during a forward pass. They grow with the number of tokens in the batch.
CUDA graphA recorded sequence of GPU work replayed with one launch (5.f); it needs memory of its own.
KV headsThe number of key/value heads per layer (num_key_value_heads), often far fewer than query heads (12.g).
Page sizeBytes one block takes in one layer (or one group of layers).
Tensor parallelism (TP)Splitting each layer across several GPUs (14.c).

1. What is it?#

The number of blocks in the pool is fixed at startup and never changes. It is the result of one subtraction and one division: take the share of the GPU you allowed vLLM to use, subtract what the weights and working memory need, and divide what remains by the size of one block.

That quotient decides how many tokens can be in flight at once, which decides how many requests can run together, which decides whether your server preempts (17.c). You can compute it on paper before renting a GPU, because the three numbers that drive it (layers, KV heads and head size) are in the model’s config.json. The general KV cache arithmetic is in 12.f; this lesson follows vLLM’s own startup code.

Facts checked on 12 November 2026 against vLLM v0.32.0.


2. Why does it matter?#

The KV cache is where concurrency lives. Weights are a fixed cost; every extra gigabyte left for the cache is more requests in the batch and fewer preemptions. The most common startup failure for a long-context model on a modest GPU (“KV cache is needed, which is larger than the available KV cache memory”) is this calculation coming out negative, and it is fixed in seconds once you can read it.


3. Simple analogy#

Packing a moving van. The van’s size is the GPU; you may use 92% of it (the utilisation). The furniture (weights) goes in first, then you leave room for people to move around while loading (activations, CUDA graphs). Whatever space is left is cut into identical boxes (blocks). How many boxes you get decides how much you can carry, however you later decide to fill them.


4. Tiny example: Llama-3.1-8B on a 24 GiB GPU#

24 GiB × 0.92                          = 22.1 GiB this instance may use
− 15.0 GiB weights (BF16)
− ~0.8 GiB activations, CUDA context, CUDA graphs
                                       ≈  6.3 GiB for the KV cache

bytes per token = 32 layers × 8 KV heads × (128 + 128) × 2 bytes = 128 KiB
6.3 GiB / 128 KiB                      ≈ 51,000 tokens

The model’s full context is 131,072 tokens, so not even one full-length request fits, and vLLM refuses to start unless --max-model-len is lowered.


5. Technical explanation#

Step 1: the budget#

When a worker starts it takes a snapshot of the GPU and computes its budget (vllm/v1/worker/utils.py):

Python
requested_memory = math.ceil(
    init_snapshot.total_memory * cache_config.gpu_memory_utilization
)
...
    f"... is less than desired GPU memory utilization "
    f"({cache_config.gpu_memory_utilization}, ...). Decrease GPU memory "
    f"utilization or reduce GPU memory used by other processes."

--gpu-memory-utilization defaults to 0.92. It is a fraction of total memory, and a limit for this instance: weights, working memory and KV cache together. It does not know about other processes; two vLLM servers sharing one GPU must each be given their own share, for example 0.45.

If another process already holds more than 8% of the card, the default fails at startup with the error above. The fix is a lower utilisation, not a retry.

Step 2: measure what the model needs#

The worker loads the weights, then runs one forward pass with dummy inputs of the largest size the scheduler will ever send, and watches memory (memory_profiling in vllm/utils/mem_utils.py). The profiler sorts GPU memory into three kinds:

1. memory used by anything other than the current vLLM instance
2. memory used by torch in the current vLLM instance
3. memory used in the current vLLM instance, but not by torch

non-KV-cache memory =
     a. model weights                       (kind 2)
   + b. peak activation tensors             (kind 2: the rise in torch's peak during the dummy pass)
   + c. non-torch components                (kind 3: CUDA context, NCCL, backend buffers)

The dummy pass matters. Activation memory grows with the batch, and the largest batch is max_num_batched_tokens tokens. Raising that flag raises (b) and so shrinks the KV cache: a larger token budget costs memory twice, once directly and once in blocks you no longer have.

A fourth term: CUDA graphs are captured after the KV cache is sized, so vLLM estimates their memory first and subtracts it (vllm/v1/worker/gpu_worker.py):

Python
self.available_kv_cache_memory_bytes = (
    self.requested_memory
    - profile_result.non_kv_cache_memory
    - cudagraph_memory_estimate_applied
)

The startup log says so explicitly: “CUDA graph memory profiling is enabled (default since v0.21.0). The current –gpu-memory-utilization=0.9200 is equivalent to –gpu-memory-utilization=0.90xx without CUDA graph memory profiling”, followed by the value to use if you want the cache size you had before. VLLM_MEMORY_PROFILER_ESTIMATE_CUDAGRAPHS=0 turns the estimate off (and logs a warning).

The result appears as Available KV cache memory: 18.4 GiB.

Step 3: the size of one block#

Each attention layer reports what its cache needs as a KV cache spec. For ordinary attention (AttentionSpec in vllm/v1/kv_cache_interface.py):

Python
@property
def state_content_size_bytes(self) -> int:
    ...
    return (self.head_size + self.head_size_v) * get_dtype_size(self.dtype)

@property
def unpadded_page_size_bytes(self) -> int:
    return self.num_heads * self.num_states * self.state_content_size_bytes

num_heads is the number of KV heads and num_states is the number of tokens per block. In plain terms, for one layer and one block:

page size = KV heads × tokens per block × (key size + value size) × bytes per number

            8      ×       16          ×    (128 + 128)          ×        2
          = 65,536 bytes for one layer of Llama-3.1-8B

and a block spans every layer:

bytes per block = layers × page size  = 32 × 65,536 = 2,097,152 bytes = 2 MiB
bytes per token = bytes per block / 16 = 131,072 bytes = 128 KiB

The inputs come from config.json:

Quantityconfig.json fieldLlama-3.1-8B
Layersnum_hidden_layers32
KV headsnum_key_value_heads8
Head sizehead_dim, or hidden_size / num_attention_heads4096 / 32 = 128
Bytes per numbertorch_dtype (bfloat16 = 2), or --kv-cache-dtype2

important

Use num_key_value_heads, not num_attention_heads. Most current models use grouped-query attention (12.g), where many query heads share few key/value heads. Llama-3.1-8B has 32 attention heads but only 8 KV heads, so its cache is a quarter of what the wrong field suggests. Latent attention (MLA, DeepSeek-style) stores one compressed vector per token instead and has its own spec (17.i).

Step 4: divide#

Python
num_blocks = available_memory // bytes_per_block
num_blocks = may_override_num_blocks(vllm_config, num_blocks)

The KV cache tensors are then allocated with room for num_blocks pages, and the number is sent to the engine core, which builds the BlockPool (17.e).

--num-gpu-blocks-override N replaces the computed value. The config describes its purpose: “Used for testing preemption.” Do not use it to get more blocks than fit; the memory still has to exist.

Step 5: the sanity check, and the log line#

Before allocating, vLLM checks that at least one request of maximum length fits:

ValueError: To serve at least one request with the model's max seq len (131072),
(16.00 GiB KV cache is needed, which is larger than the available KV cache memory
(6.31 GiB). Based on the available memory, the estimated maximum model length is 51440.
Try increasing `gpu_memory_utilization` ... or decreasing `max_model_len` ...

The message contains its own fix: pass --max-model-len at or below the estimate. Or let vLLM choose: with --max-model-len -1 (or auto), it uses the model’s full context if it fits, and otherwise searches for the largest length that does, logging “Auto-fit max_model_len: reduced from 131072 to 51440 to fit in available GPU memory”.

On success:

GPU KV cache size: 688,304 tokens, Maximum concurrency for 32,768 tokens per request: 21.01x

Read those two numbers differently:

  • Tokens is the hard capacity: the sum of prompt and generated tokens over all running requests cannot exceed it (shared prefix blocks count once).
  • Maximum concurrency assumes every request uses the whole context window. Real requests are far shorter: if yours average 2,000 tokens, this cache holds about 340 of them, not 21.

A useful planning rule: capacity ÷ p95 total tokens per request should comfortably exceed max_num_seqs. If it does not, expect preemption (17.c).

Tensor parallelism changes the arithmetic#

With --tensor-parallel-size N, KV heads are split across the GPUs, so:

bytes per token, per GPU = (single-GPU value) / N

(If a model has fewer KV heads than GPUs, heads are replicated and the division stops at one head per GPU.) Each GPU also has its own budget. Splitting a model over more GPUs therefore raises cache capacity twice over: weights per GPU shrink, leaving more room, and each token costs less on each card.


6. Under the hood#

The picture#

flowchart LR
  GPU[":nvidia: <b>GPU total memory</b><br/><small>e.g. 24 GiB</small>"] -->|"× gpu_memory_utilization (0.92)"| REQ["<b>requested</b><br/><small>22.1 GiB</small>"]
  REQ --> SUB{"subtract"}
  W[":i-hard-drive: weights"] --> SUB
  A[":i-activity: peak activations<br/><small>one max-size dummy batch</small>"] --> SUB
  NT[":i-package: non-torch<br/><small>CUDA context, NCCL</small>"] --> SUB
  CG[":i-circuit-board: CUDA graph estimate"] --> SUB
  SUB --> AV["<b>available for KV cache</b>"]
  AV -->|"÷ bytes per block"| NB[":i-layers: <b>num_gpu_blocks</b>"]
  NB -->|"× 16"| TOK["<b>capacity in tokens</b>"]
  TOK -->|"÷ max_model_len"| CON["<b>maximum concurrency</b><br/><small>worst case</small>"]
  class GPU,W,NB memory
  class REQ,AV,TOK,CON neutral
  class SUB queue
  class A,NT,CG compute

Skipping the measurement#

--kv-cache-memory-bytes N sets the cache size directly. The log then says it “skipped memory profiling. This does not respect the gpu_memory_utilization config.” It is the right tool when several processes share a GPU and each must have an exact, predictable cache, and it shortens startup. vLLM’s tuning guide notes that the startup log prints the exact value that reproduces the current allocation; it is valid only on the same GPU with the same free memory.

What does not count#

  • Other processes on the GPU. vLLM measures them once and assumes they do not change. If another process grows afterwards, vLLM can run out of memory later although its own use is constant. The profiler asserts the opposite case too, and reports “This happens when other processes sharing the same container release GPU memory while vLLM is profiling during initialization.”
  • Growth after startup. There is none by design. If memory use climbs while serving, something outside the KV cache is allocating: typically a backend workspace reaching a new maximum, or a LoRA adapter being loaded (22.f covers out-of-memory debugging).

The calculator#

The whole calculation for three models. Change the numbers to match your hardware before you rent it.

Go
package main

import "fmt"

const (
	GiB       = 1 << 30
	blockSize = 16
)

type model struct {
	name      string
	layers    int
	kvHeads   int     // num_key_value_heads, not num_attention_heads
	headDim   int     // hidden_size / num_attention_heads
	weightGiB float64 // as loaded
	maxLen    int
}

// bytesPerToken is the KV cache cost of one token on one GPU:
// layers x KV heads x (key + value) x bytes per element.
func (m model) bytesPerToken(dtypeBytes, tp int) int {
	return m.layers * (m.kvHeads / tp) * (2 * m.headDim) * dtypeBytes
}

func size(m model, gpuGiB, util float64, dtypeBytes, tp int, otherGiB float64) {
	requested := gpuGiB * util
	available := requested - m.weightGiB/float64(tp) - otherGiB
	perBlock := m.bytesPerToken(dtypeBytes, tp) * blockSize
	blocks := int(available * GiB / float64(perBlock))
	tokens := blocks * blockSize
	fmt.Printf("%-14s %3.0f GiB x%d  util %.2f  kv %2d-bit | %5.1f KiB/token  %5.1f GiB for KV  %8d tokens  %5.1fx at %d\n",
		m.name, gpuGiB, tp, util, dtypeBytes*8,
		float64(m.bytesPerToken(dtypeBytes, tp))/1024, available, tokens,
		float64(tokens)/float64(m.maxLen), m.maxLen)
}

func main() {
	qwen := model{"Qwen2.5-1.5B", 28, 2, 128, 2.9, 32768}
	llama8 := model{"Llama-3.1-8B", 32, 8, 128, 15.0, 131072}
	llama70 := model{"Llama-3.3-70B", 80, 8, 128, 131.5, 131072}

	const other = 0.8 // peak activations + non-torch memory + CUDA graphs, GiB per GPU

	fmt.Println("Small model, small GPU:")
	size(qwen, 24, 0.92, 2, 1, other)

	fmt.Println("\nSame model and GPU, two knobs:")
	size(qwen, 24, 0.50, 2, 1, other)
	size(qwen, 24, 0.92, 1, 1, other) // --kv-cache-dtype fp8

	fmt.Println("\n8B model:")
	size(llama8, 24, 0.92, 2, 1, other)
	size(llama8, 80, 0.92, 2, 1, other)

	fmt.Println("\n70B model: does not fit one 80 GiB GPU; tensor parallel over 2 and 4:")
	size(llama70, 80, 0.92, 2, 2, other)
	size(llama70, 80, 0.92, 2, 4, other)
}

Output:

Small model, small GPU:
Qwen2.5-1.5B    24 GiB x1  util 0.92  kv 16-bit |  28.0 KiB/token   18.4 GiB for KV    688304 tokens   21.0x at 32768

Same model and GPU, two knobs:
Qwen2.5-1.5B    24 GiB x1  util 0.50  kv 16-bit |  28.0 KiB/token    8.3 GiB for KV    310816 tokens    9.5x at 32768
Qwen2.5-1.5B    24 GiB x1  util 0.92  kv  8-bit |  14.0 KiB/token   18.4 GiB for KV   1376624 tokens   42.0x at 32768

8B model:
Llama-3.1-8B    24 GiB x1  util 0.92  kv 16-bit | 128.0 KiB/token    6.3 GiB for KV     51440 tokens    0.4x at 131072
Llama-3.1-8B    80 GiB x1  util 0.92  kv 16-bit | 128.0 KiB/token   57.8 GiB for KV    473488 tokens    3.6x at 131072

70B model: does not fit one 80 GiB GPU; tensor parallel over 2 and 4:
Llama-3.3-70B   80 GiB x2  util 0.92  kv 16-bit | 160.0 KiB/token    7.1 GiB for KV     46192 tokens    0.4x at 131072
Llama-3.3-70B   80 GiB x4  util 0.92  kv 16-bit |  80.0 KiB/token   39.9 GiB for KV    523296 tokens    4.0x at 131072

How to read it:

  • Two rows show a concurrency below 1.0. vLLM refuses to start those configurations: not even one full-length request fits. Both become usable once --max-model-len is lowered; the capacity in tokens is unchanged, but the check passes and the server can admit many shorter requests.
  • FP8 KV doubles the tokens; halving the utilisation more than halves them, because the weights are a fixed cost.
  • The 70B model goes from barely usable on two 80 GiB GPUs to comfortable on four: capacity grows more than 11 times for twice the hardware.
  • The value of other is a guess; it is the one input you must measure. Start the server once, read Available KV cache memory from the log, and solve for it.

7. Performance implications#

KnobEffect on capacityCost
Quantised weights (AWQ, GPTQ, FP8, NVFP4)Large: frees weight memory for cacheSome quality (13.b, 18.j)
--kv-cache-dtype fp8×2: one byte per number instead of twoSmall quality loss; backend support varies (13.h)
--kv-cache-dtype nvfp4About ×3.5 (4-bit values plus scales)More quality risk; on supported GPUs only (v0.32.0 added SM8x/SM12x)
More GPUs with tensor parallelismLargeHardware; communication overhead
--gpu-memory-utilization 0.95A few percentLess margin against out-of-memory
Lower --max-num-batched-tokensShrinks peak activationsSlower prefill
Lower --max-num-seqsShrinks per-request buffers and CUDA graphsLess concurrency
--max-model-lenNone on capacity in tokens; raises “maximum concurrency” and lets startup passLong requests rejected

Some models already default to a compact cache with --kv-cache-dtype auto: DeepSeek-V3.2 uses FP8, and since v0.32.0 so does GLM-5.x on Blackwell (SM100). Check the startup log for the dtype in force.


8. Production implications#

  • Size before you buy. Bytes per token from config.json, weights from the checkpoint size, and a measured other give capacity to within a few percent.
  • Plan on p95 request length, not on max_model_len.
  • Shared GPUs: give each instance its own utilisation share or --kv-cache-memory-bytes, and keep other processes’ memory stable.
  • After a vLLM upgrade, recheck Available KV cache memory. Changes to CUDA graph sizing or backends shift it, and a cache that shrank by 10% shows up as more preemptions.

9. Common mistakes#

  1. Using num_attention_heads for the KV calculation. Use num_key_value_heads.
  2. Thinking --gpu-memory-utilization is a share of free memory. It is a share of total memory.
  3. Lowering --max-model-len to “get more cache”. Capacity in tokens is unchanged.
  4. Raising --max-num-batched-tokens and wondering why the cache shrank. The profiling run uses that batch size.
  5. Reading “maximum concurrency” as real concurrency. It assumes every request is full length.

10. Hands-on exercise#

  1. Find num_hidden_layers, num_key_value_heads, hidden_size and num_attention_heads in the config.json of a model you use. Add it to the program. How many tokens fit on your GPU?
  2. For Llama-3.1-8B on 24 GiB, what --max-model-len makes the worst-case concurrency exactly 8?
  3. Start a real server twice, with --max-num-batched-tokens 2048 and 16384, and compare Available KV cache memory. The difference is the extra peak activation memory.

11. Interview questions#

  1. Which config.json field gives the number of heads that matters for the KV cache, and why is it often smaller than the number of attention heads?
  2. vLLM refuses to start, saying the KV cache needed is larger than what is available. Name two flags that fix it and what each gives up.
  3. Why does raising max_num_batched_tokens reduce the number of KV blocks?
  4. Why does tensor parallelism raise KV capacity by more than the number of GPUs added?
  5. What do “GPU KV cache size” and “Maximum concurrency” in the startup log each mean?

12. Further reading#

Checked on 12 November 2026, against the v0.32.0 tag.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in