KV Cache Calculator: Estimate Memory per Request and Batch
A KV cache calculator should answer two different questions: how much raw cache one request can occupy at its peak, and how much raw cache an uneven concurrent batch can occupy together. Those are not the same as a model's advertised context window, request count, or loaded weight size.
This worksheet is for inference planning. It calculates the raw key/value tensor payload from a model configuration and a resident-token budget, then separates that result from weights, runtime workspace, allocator behavior, and operating headroom. It is not a benchmark or a promise that a server will fit.
01 / The quick calculation
For a conventional full-attention decoder with equal key and value dimensions, the KV cache calculator starts with bytes per resident token:
bytes_per_token = 2 × L × Hkv × D × B
request_cache_bytes = bytes_per_token × Trequest
batch_cache_bytes = bytes_per_token × Σ(Trequest_i)
| Symbol | Meaning | Unit |
|---|---|---|
2 |
one key tensor plus one value tensor | dimensionless |
L |
attention layers that retain KV state | layers |
Hkv |
key/value heads per layer | heads |
D |
elements in each KV head | elements |
B |
bytes per cached element | bytes / element |
Trequest |
resident tokens for one sequence | tokens |
For a peak-admission estimate, set Trequest to prompt tokens + allowed generated tokens. For an in-flight observation, use the tokens the sequence currently retains. The batch term is the sum across concurrent resident sequences; it is not simply “batch size × maximum context” unless every sequence has the same cap.
Hugging Face documents a key cache and a value cache for every layer, with cache tensors shaped by batch, heads, sequence length, and head dimension. That shape is why tokens—not user accounts or requests per day—drive this baseline. Read the cache mechanics in Transformers.
02 / Collect the five inputs before using a KV cache calculator
| Input | Where to get it | Why it matters |
|---|---|---|
Layers (L) |
Exact model configuration | More cache-retaining layers increase bytes per token. |
KV heads (Hkv) |
Exact model configuration | Use KV heads, not query heads, for grouped-query attention. |
Head dimension (D) |
hidden_size ÷ attention_heads, if the config does not state it |
It determines the vector width stored per KV head. |
Cache bytes (B) |
Resolved runtime cache dtype | A raw FP16/BF16 assumption is 2 bytes; a raw FP8 payload assumption is 1 byte. |
| Token budget per sequence | Prompt cap + output cap (or current resident tokens) | It turns architecture into a request and batch workload. |
This KV cache calculator deliberately leaves weight precision out of its formula. A 4-bit weight plan can still use an FP16 cache. Treat the weight format and cache dtype as separate inputs, then combine the cache result with weights and runtime allocations in a full fit check.
For context-window definitions and the difference between a model maximum and an active workload, read Context windows and KV cache →.
03 / Worked example: one request, then an uneven four-request batch
The following is a calculated estimate, not a Meta or vLLM measurement. It uses Llama 3.1 8B architecture values published by Meta: 32 layers, 32 attention heads, 8 KV heads, and hidden dimension 4,096. The derived head dimension is 4,096 ÷ 32 = 128. Inspect Meta's model definition.
Assumptions
| Input | Value | Classification |
|---|---|---|
| Model | Llama 3.1 8B Instruct | source fact |
Layers (L) |
32 | source fact |
KV heads (Hkv) |
8 | source fact |
Head dimension (D) |
128 | calculation |
| Cache dtype | FP16/BF16, B = 2 bytes |
planning assumption |
| Prefix reuse, CPU offload, compression, and block rounding | no credit | planning assumption |
Per-request estimate
Suppose request A can have a 4,096-token prompt and generate up to 1,024 new tokens. Its peak token budget is 5,120.
bytes_per_token = 2 × 32 × 8 × 128 × 2
= 131,072 bytes
= 128 KiB
request A = 131,072 × (4,096 + 1,024)
= 671,088,640 bytes
= 0.625 GiB
So this KV cache calculator returns 0.625 GiB of raw cache for request A at its full 5,120-token allowance. It does not include the model's weights, CUDA graphs, temporary workspaces, driver memory, or any other process on the GPU.
Batch estimate: do not flatten unequal requests into one context number
Now admit four concurrent requests with different prompt and output budgets:
| Sequence | Prompt cap | Output cap | Peak resident tokens | Raw FP16/BF16 cache |
|---|---|---|---|---|
| A | 4,096 | 1,024 | 5,120 | 0.625 GiB |
| B | 2,048 | 1,024 | 3,072 | 0.375 GiB |
| C | 1,024 | 512 | 1,536 | 0.188 GiB |
| D | 8,192 | 1,024 | 9,216 | 1.125 GiB |
| Batch total | — | — | 18,944 | 2.312 GiB |
batch cache = 131,072 × (5,120 + 3,072 + 1,536 + 9,216)
= 2,483,027,968 bytes
= 2.3125 GiB
The useful result is the sum of each sequence's resident-token budget. A four-request batch does not inherently require four times the largest request's cache. Conversely, a max_num_seqs=4 setting does not prove that four long requests fit: the token limits chosen for those requests decide the raw payload.
04 / Copyable KV cache calculator
Use this small KV cache calculator for a conventional full-attention model. Replace the architecture values with the exact checkpoint configuration and pass each concurrent request's peak token budget.
GiB = 2**30
def kv_bytes_per_token(layers, kv_heads, head_dim, bytes_per_element):
return 2 * layers * kv_heads * head_dim * bytes_per_element
def request_kv_bytes(bytes_per_token, prompt_tokens, max_new_tokens):
return bytes_per_token * (prompt_tokens + max_new_tokens)
def batch_kv_bytes(bytes_per_token, request_budgets):
return bytes_per_token * sum(
prompt_tokens + max_new_tokens
for prompt_tokens, max_new_tokens in request_budgets
)
# Llama 3.1 8B architecture inputs
per_token = kv_bytes_per_token(
layers=32,
kv_heads=8,
head_dim=128,
bytes_per_element=2, # FP16/BF16 planning assumption
)
requests = [
(4096, 1024),
(2048, 1024),
(1024, 512),
(8192, 1024),
]
print(per_token) # 131072 bytes
print(request_kv_bytes(per_token, *requests[0]) / GiB) # 0.625
print(batch_kv_bytes(per_token, requests) / GiB) # 2.3125
If a server sees partially decoded requests, replace each maximum with the tokens it currently retains. If you use this KV cache calculator as an admission policy, keep the peak output allowance; that protects the upper bound rather than merely describing a momentary snapshot.
05 / FP8 changes the raw cache term, not the whole deployment
With the same Llama architecture and batch tokens, a one-byte FP8 payload assumption gives half the raw data term: 1.156 GiB instead of 2.3125 GiB. That is a raw-data comparison, not a measured VRAM reservation or quality claim.
vLLM documents FP8 KV-cache options, scale calibration paths, and dtype support requirements. It also documents a configurable KV-cache memory budget rather than tying physical allocation only to the active batch. Check vLLM's quantized KV-cache documentation and cache configuration for the installed release.
Before changing cache dtype, verify:
- The selected runtime, hardware, attention backend, and checkpoint support it.
- Any required scaling or calibration data is resolved correctly.
- Startup logs show the dtype you intended—not an inherited
autochoice you assumed. - Peak GPU allocation still has room for weights and runtime allocations.
06 / Convert the raw result into a GPU fit decision
A KV cache calculator gives a tensor baseline. A usable server needs more than that baseline.
- Calculate raw per-request and batch cache using the exact architecture and token limits.
- Add the actual checkpoint's loaded weights, packing metadata, and measured runtime workspace.
- Check what the runtime reserves after startup; vLLM can manage cache capacity as a memory budget and blocks, so reserved memory can differ from the active-token arithmetic.
- Keep an explicit operating reserve. ModelFit's calculator applies a 15% headroom policy; that is planning guidance, not a benchmark guarantee.
- Load-test the longest simultaneous requests you intend to admit.
Run the full ModelFit calculator → to combine weight format, context, concurrent sequences, GPU count, cache precision, and operating headroom. Then inspect the exact architecture fields for supported checkpoints in the ModelFit model directory →.
Do not divide a single-GPU cache number by GPU count and call the result per-GPU memory. Tensor-parallel placement, replicated buffers, block allocation, and communication workspace require runtime-specific verification.
07 / FAQ
Does a KV cache calculator use the model's full advertised context window?
Only if your deployment actually admits that many resident tokens per sequence. For a capacity policy, use the configured prompt-plus-output cap. For a live snapshot, use the resident tokens currently held by each active sequence.
Is one request's cache shared with another request?
Do not claim a sharing discount in the worksheet unless your runtime confirms the exact reuse behavior and memory accounting. This article's calculation assumes no prefix-reuse, offload, compression, or cache-sharing credit.
Why use KV heads instead of query heads?
The cached keys and values have the KV-head dimension. Grouped-query attention can have fewer KV heads than query heads; using query heads in the formula can overstate the raw cache estimate.
Can this KV cache calculator size every model architecture?
No. It is a baseline for conventional full-attention layouts. Sliding-window, hybrid local/global, latent-attention, multimodal, and custom-cache architectures need their own model- and runtime-specific accounting.
08 / Use the result as a worksheet, not a guarantee
The practical KV cache calculator rule is: derive bytes per token from the model, multiply by each request's resident-token budget, sum the batch, then validate the runtime's actual reservation with headroom. That turns “four requests” into a concrete memory decision.
When the worksheet and load test support a deployment choice, review current GPU capacity on Flatkey Compute ↗. ModelFit is an independent planning surface that links qualified deployment decisions to Flatkey Compute; estimates are planning guidance, not benchmark guarantees.
09 / Sources and method
- Hugging Face Transformers — How caching works. Used for per-layer K/V cache behavior and the cache tensor dimensions. Accessed 2026-10-27.
- Meta Llama model definitions. Used for Llama 3.1 8B Instruct layer, attention-head, KV-head, and hidden-dimension inputs. Accessed 2026-10-27.
- vLLM — Quantized KV Cache and CacheConfig. Used for FP8 support/calibration caveats, block-based cache behavior, and explicit cache-memory budgeting. Accessed 2026-10-27.
- ModelFit Business Profile and live calculator source. Used only for the calculator inputs and the product's 15% operating-headroom convention. Project knowledge revision 12, checked 2026-10-27.
All byte-to-GiB conversions use 1 GiB = 2^30 bytes. Architecture values are source facts, arithmetic outputs are calculated estimates, and cache-dtype/workload choices are operational assumptions stated above.
