Inference terms

What is the KV cache? How LLMs use memory

The KV cache is GPU memory that holds the attention keys and values of every token a language model has already processed. Storing them means each new token only computes its own keys and values instead of recomputing the whole sequence. It grows linearly with context length and concurrent requests, so it often decides how many users one GPU can serve.

What the KV cache is

A transformer generates text one token at a time. At every layer, attention compares the newest token with all earlier tokens, using a key vector and a value vector for each of them. Those keys and values do not change once computed, so inference engines keep them in GPU memory and reuse them on every later step. That store is the key-value cache.

Without it, generating token 1,000 would mean recomputing keys and values for the 999 tokens before it, at every layer. With it, the model computes one new key and one new value per layer and reads the rest from memory. The trade is compute for memory, and on long contexts the memory side gets large.

Inference has two phases. Prefill processes the whole prompt at once and writes its keys and values into the cache. Decode then produces output tokens one by one, appending a little to the cache each step and reading all of it. The PagedAttention paper describes this memory as large and dynamic, growing and shrinking as requests come and go.

References: Kwon et al., Efficient Memory Management for LLM Serving with PagedAttention

The KV cache size formula

The memory per token is: 2 × layers × KV heads × head dimension × bytes per element. The 2 counts one key and one value. Multiply by the number of tokens held, which is context length times concurrent sequences, to get the total.

Use the number of key-value heads, not attention heads. Models with grouped-query attention share each key-value head across several query heads. Llama 3.1 8B has 32 attention heads but only 8 key-value heads, which cuts its cache to a quarter of what full multi-head attention would need.

Worked example with Llama 3.1 8B in BF16. Its config lists 32 layers, 8 key-value heads and a head dimension of 128. So 2 × 32 × 8 × 128 × 2 bytes = 131,072 bytes, or 128 KiB per token. An 8,192-token conversation needs 1 GiB. A single request at the full 131,072-token context needs 16 GiB, the same as its weights.

Llama 3.3 70B has 80 layers, 8 key-value heads and a head dimension of 128. That gives 320 KiB per token: 2.5 GiB for an 8K context and 40 GiB for the full 128K window. Check every new model in its config.json before you size a GPU, or run the numbers in the VRAM calculator.

The KV cache size formula
Model (BF16 cache)Layers × KV heads × head dimPer token8K contextFull 128K context
Llama 3.1 8B32 × 8 × 128128 KiB1 GiB16 GiB
Llama 3.3 70B80 × 8 × 128320 KiB2.5 GiB40 GiB
Llama 3.1 8B, FP8 cache32 × 8 × 12864 KiB0.5 GiB8 GiB
Llama 3.3 70B, FP8 cache80 × 8 × 128160 KiB1.25 GiB20 GiB

References: Llama 3.1 8B Instruct config.json (Hugging Face mirror) · Llama 3.3 70B Instruct config.json (Hugging Face mirror)

How cache memory sets concurrency

GPU memory splits into weights, activations and runtime overhead, and the cache. Weights are fixed. Whatever remains decides how many tokens can be in flight, and therefore how many requests the server can batch together.

Take an 80 GB H100 SXM serving Llama 3.1 8B. The BF16 weights take roughly 16 GB (8 billion parameters × 2 bytes). Assume, for illustration, that 50 GiB is left for the cache after activations and overhead. At 128 KiB per token that holds about 409,600 tokens: 50 conversations at 8K each, or 3 at the full 128K.

When the cache fills, engines stop admitting work or evict it. vLLM preempts requests when cache space runs short and recomputes them later, which its docs say can raise end-to-end latency. That is why a server with free compute can still queue requests: it has run out of cache, not of FLOPs. The LLM VRAM budget guide walks through the full memory split.

References: NVIDIA H100 specifications · vLLM documentation: Optimization and tuning

Configure it in vLLM, SGLang and llama.cpp

In vLLM, --gpu-memory-utilization sets the fraction of GPU memory the engine may use, and the cache gets what is left after weights and activations. The optimization guide notes that a higher value gives a larger cache. --max-model-len caps context length, --kv-cache-dtype picks the storage type (auto follows the model dtype), --block-size sets tokens per cache block, and --kv-cache-memory-bytes fixes the size per GPU directly.

In SGLang, --mem-fraction-static sets the share of memory for weights plus the cache pool, --max-total-tokens caps the pool, --context-length caps context and --kv-cache-dtype accepts options such as fp8_e4m3 and fp8_e5m2. Its --enable-hierarchical-cache option adds a host-memory tier sized by --hicache-ratio.

In llama.cpp, -c (--ctx-size) sets the context size, and 0 loads it from the model. -np sets the number of server slots that share it. -ctk and -ctv choose key and value cache types, with f16 as the default and q8_0, q4_0 and others available. Watch usage with vLLM's vllm:kv_cache_usage_perc metric or SGLang's sglang:token_usage.

Configure it in vLLM, SGLang and llama.cpp
EngineMemory budgetContext capCache data typeWatch
vLLM--gpu-memory-utilization, --kv-cache-memory-bytes--max-model-len--kv-cache-dtype (auto, fp8, fp8_e4m3, fp8_e5m2)vllm:kv_cache_usage_perc
SGLang--mem-fraction-static, --max-total-tokens--context-length--kv-cache-dtype (auto, fp8_e4m3, fp8_e5m2, bf16 and more)sglang:token_usage
llama.cpp-c total context shared by -np slots-c (--ctx-size)-ctk / -ctv (f16 default, q8_0, q4_0 and more)Server log and /slots

References: vLLM documentation: vllm serve arguments · vLLM documentation: Optimization and tuning · SGLang documentation: Server arguments · llama.cpp server README · vLLM documentation: Metrics design

Shrinking the cache: FP8, GQA and paging

Three levers cut cache memory. The first is a smaller data type. vLLM documents FP8 cache storage as a way to reduce the footprint so you can store more tokens, which improves throughput and allows longer contexts. Going from 2 bytes to 1 byte halves the per-token cost. Without calibration vLLM uses scales of 1.0, and it recommends calibrated scales for best accuracy, so test quality on your own prompts.

The second is architecture, which you choose with the model. Grouped-query attention, as in the Llama 3 family, already divides the cache by the ratio of query heads to key-value heads. The third is allocation. PagedAttention stores the cache in fixed-size blocks instead of one contiguous slab per request, and the vLLM authors report that this cut waste from 60-80% in earlier systems to under 4%.

Weight quantization is a separate lever. It frees memory that the cache can then use, which LLM quantization for inference covers.

References: vLLM documentation: Quantized KV cache · vLLM blog: Easy, fast, and cheap LLM serving with PagedAttention

How the KV cache changes cost per token

On a rented GPU you pay per hour, so cost per token is the hourly rate divided by tokens produced per hour. Decode is usually limited by memory bandwidth, so batching more sequences together raises total output with little extra time per step. The cache sets how large that batch can get, which links cache size directly to price per token.

This illustrative example uses assumed figures, not measurements. One GPU costs an assumed $2 per hour. With a BF16 cache it fits 50 concurrent 8K conversations and, by assumption, produces 1,500 output tokens per second. Switching to an FP8 cache fits about 100, and we assume output rises to 2,400 tokens per second. Measure your own numbers before relying on them.

How the KV cache changes cost per token
Setup (illustrative)Concurrent 8K sequencesAssumed output tokens/sTokens per hourCost per million tokens at $2/h
BF16 cache501,5005.4 million$0.37
FP8 cache1002,4008.64 million$0.23

Common misconceptions

Each of these comes up often when teams size inference GPUs. The fix is usually to run the formula above for the real model and real traffic.

Common misconceptions
MisconceptionWhat is actually true
If the weights fit, the model fitsWeights plus cache plus activations must fit; long contexts can need as much cache as weights
Cache size depends on attention headsIt depends on key-value heads; GQA models need far less
The cache only matters for long promptsMany short requests at once add up the same way as one long one
Free GPU compute means room for more usersA full cache causes queuing or preemption even when compute is idle
A smaller cache type is freeFP8 or q8_0 saves memory but can affect accuracy; test it

References: Kwon et al., Efficient Memory Management for LLM Serving with PagedAttention · vLLM documentation: Optimization and tuning

Related terms

PagedAttention is how vLLM allocates cache memory in blocks. Continuous batching decides which requests share the cache each step. Time to first token measures the prefill phase that fills it, and tokens per second measures the decode phase that reads it. FlashAttention speeds up the attention math that uses it.

Checklist and next step

Read layers, key-value heads and head dimension from the model config. Compute bytes per token. Multiply by context length and target concurrency. Add weights and a margin for activations. Decide whether an FP8 cache is acceptable after testing quality. Then pick a GPU whose memory covers the total with headroom.

When the numbers point to a GPU, NeuraMesh rents it by the hour: choose a GPU such as the H100, a plan, GPU count, hours and region on rent GPUs, and you receive a confirmed quotation, typically within one business day, with nothing charged until you approve. If you are unsure which card fits, ask the compute advisor.

NeuraMesh prices for these GPUs

NeuraMesh prices per GPU-hour in USD, excluding taxes, as of 2026-11-27. Live prices are on the rental pages.
GPUMemoryData centerValue
RTX 409024 GB$0.46$0.40
L40S48 GB$1.26$0.54
A10080 GB$1.56$0.98
H10080 GB$2.88$2.00

Every order is confirmed in a quotation before you pay. See all GPU prices.

Questions readers ask

How much memory does the KV cache use?

Per token it is 2 × layers × key-value heads × head dimension × bytes per element. Llama 3.1 8B in BF16 needs 128 KiB per token, so 1 GiB per 8,192 tokens. Multiply by context length and the number of concurrent requests.

Does a longer context window cost more memory?

Yes, linearly. Doubling the tokens held doubles cache memory. Setting a lower maximum context with --max-model-len in vLLM or -c in llama.cpp is a direct way to save memory if your traffic does not need the full window.

Does FP8 cache storage hurt quality?

It can. vLLM notes that without calibration all scales are 1.0 and recommends calibrated scales for maximum accuracy. Run your own evaluation set before and after the switch.

Why does vLLM say there is not enough cache space?

Weights and activations left too little memory for the requested context. Raise --gpu-memory-utilization, lower --max-model-len or --max-num-seqs, use an FP8 cache, or move to a GPU with more memory or tensor parallelism.

Is the KV cache the same as prompt caching?

Not quite. The cache always exists during a request. Prefix or prompt caching keeps cache blocks after a request ends so a later request with the same prefix can reuse them and skip part of prefill.

Sources and editorial notes

Primary documentation reviewed November 24, 2026. Provider descriptions reflect published documentation. Recommendations are our analysis; worked figures are illustrative unless explicitly stated otherwise. No independent provider benchmark or uptime ranking is claimed.

Read the editorial policy.

Need this GPU? Rent it from NeuraMesh: choose a GPU and plan, get a confirmed quotation, and pay only when you approve. See pricing.