Good to see you again. In the previous lesson, you estimated the memory occupied by model weights and treated that value as a lower bound for serving. This lesson adds the largest request-dependent term in that budget: the key-value (KV) cache.
By the end, you will be able to estimate KV-cache memory from a model configuration, a context length, a batch size, and the cache precision. This is the calculation that turns a statement such as “the weights fit on this GPU” into the more useful question: “How many long, active requests can this system actually serve?”
Why inference needs a KV cache
An autoregressive language model generates one token at a time. When it generates the next token, self-attention needs access to the representations of prior tokens in the sequence.
Without a cache, generating token would repeatedly recompute attention-related information for tokens through . The KV cache avoids that repetition. For every processed token and every transformer layer, the engine stores:
- the key vector, ;
- the value vector, .
For the next generated token, the model computes a new query, key, and value for that token, appends the new key and value to the cache, and reuses all earlier cached keys and values.
Watch “KV Cache - Explained” by DataMListic for a compact visual explanation of why decoding would otherwise repeat work and how previously computed keys and values are reused.
Watch the problem to see why each new token needs prior context, then cache reuse for the mechanism by which the new token’s vectors are added while earlier vectors remain available.
The cache is therefore a deliberate trade-off:
- Benefit: much less repeated computation during decoding.
- Cost: memory grows as tokens accumulate.

During prefill, the model processes the prompt and writes K and V entries for all prompt tokens. During decode, it adds entries one generated token at a time. Thus, a sequence of 3,000 prompt tokens followed by 1,000 generated tokens requires cache capacity for roughly 4,000 token positions.
The memory formula
For a typical decoder-only transformer, the approximate KV-cache memory is:
where:
| Symbol | Meaning |
|---|---|
| Batch size: number of active sequence slots | |
| Tokens stored per sequence, including prompt and generated tokens | |
| One tensor for keys and one for values | |
| Number of transformer layers | |
| Number of key-value heads | |
| Dimension of each attention head | |
| Bytes per cached element |
The result is in bytes.
The factor of two is easy to forget: a cache contains both K and V, not merely one attention tensor. The layer count is equally important: each layer needs its own cache, because each layer computes its own attention representation.
For a model with standard multi-head attention, the number of KV heads equals the number of query heads:
In that common case:
So the formula can be written more compactly as:
This is the form you will often see in introductory sizing guides.
Mastering LLM Techniques: Inference Optimization
Read NVIDIA’s “LLM memory requirement” section to connect the formula to the broader serving-memory budget of weights plus KV cache.
In the section “LLM memory requirement,” begin with the batching explanation. Then read the formula and the Llama 2 7B example through the scaling implications. Focus on why sequence length and batch size are both direct multipliers of cache memory.
The important modern-model detail: KV heads, not always hidden size
Many newer models use grouped-query attention (GQA) or multi-query attention (MQA). These architectures use many query heads but fewer KV heads. They reduce the cache footprint because fewer distinct key and value vectors are stored per token.
For these models, use:
not the full model hidden size.
For example, a model might have:
but only:
With the same head dimension, its cache requires one quarter as much memory as a standard 32-head KV design. This is one reason architecture details in a model’s configuration file matter for inference capacity planning.
Precision: cache memory is separate from weight memory
The last term, , is the number of bytes stored for each key or value element.
| KV-cache representation | , bytes per element |
|---|---|
| FP32 | |
| FP16 or BF16 | |
| INT8 |
A serving engine may store weights in 4-bit form while using FP16 or BF16 for the KV cache. Do not assume that the cache has the same precision as the weights.
For a baseline estimate, FP16 or BF16 KV cache means:
Cache quantization can reduce this number, but exact memory use can then include quantization metadata, temporary buffers, or a small higher-precision residual cache. For initial capacity estimates, use the format configured by the inference engine and treat the result as approximate.
The KV Cache: Memory Usage in Transformers
Watch “The KV Cache: Memory Usage in Transformers” by Efficient NLP for a concise walkthrough of the factors in the formula and a large-model sizing example.
Watch the formula, identifying the K-and-V factor, bytes per value, layers, model dimension, sequence length, and batch size. Continue with the example to see how a large batch and long context can make cache memory exceed weight memory.
A reliable calculation workflow
When inspecting a model configuration, collect these values:
- Number of layers, .
- Number of KV heads, .
- Head dimension, .
- Maximum active tokens per sequence, .
- Batch size or number of active sequence slots, .
- KV-cache bytes per element, .
Then calculate in two stages.
First, find cache bytes per token, per sequence:
Then multiply by sequence length and batch size:
This two-stage method makes it easier to sanity-check your arithmetic. The per-token value tells you the memory cost of extending one active request by one additional token.
Worked example: a standard-attention 7B-style model
Consider a model with the following architecture:
| Configuration item | Value |
|---|---|
| Layers, | |
| KV heads, | |
| Head dimension, | |
| Cache precision | FP16 |
| Bytes per element, | |
| Batch size, | |
| Sequence length, |
First calculate per-token cache storage:
That is:
Now multiply by the context length:
This is approximately:
or:
So this one request, at 4,096 total cached tokens, uses roughly 2 GB of FP16 KV cache. That matches the common Llama 2 7B example used in inference-sizing references.
The model’s FP16 weights might be about 14 GB. On a 24 GB GPU, a rough initial budget is therefore:
| Memory category | Approximate amount |
|---|---|
| FP16 model weights | 14 GB |
| One 4,096-token KV cache | 2 GB |
| Remaining capacity | 8 GB |
That apparent 8 GB is not all safely available for additional requests: the engine also needs runtime workspaces, framework allocations, and some practical safety margin. Nevertheless, the calculation immediately shows why “the weights fit” is only the first screen.
Scaling the same workload
The formula is linear in both batch size and sequence length. For the same model and precision:
- doubling doubles KV memory;
- doubling doubles KV memory;
- doubling both multiplies KV memory by four.
Suppose the model above serves a batch of four sequences, each with capacity for 8,192 cached tokens:
That is approximately:
The cache has grown from 2 GiB to 16 GiB. The model weights did not change; only the workload configuration changed.
This is a central inference-engineering insight: long contexts and concurrency consume memory together. A configuration that is comfortable for one interactive request can become impossible when several long requests are active.
Worked example: grouped-query attention
Now consider a GQA model with:
| Configuration item | Value |
|---|---|
| Layers, | |
| Query heads | |
| KV heads, | |
| Head dimension, | |
| Cache precision | FP16 |
| Bytes per element, | |
| Batch size, | |
| Sequence length, |
Use the eight KV heads, not 32 query heads:
That is KiB per token per sequence. The total is:
So the total is:
Had you incorrectly used all 32 query heads as KV heads, you would estimate 32 GiB instead. That error could cause you to reject a configuration that is actually feasible, or misunderstand why a model can support a much larger context than a similarly sized older architecture.
What exactly counts as sequence length?
For KV-cache sizing, is the number of tokens that must remain available in the cache. In the usual full-context case:
If a request has a 6,000-token prompt and the server permits up to 2,000 output tokens, provision for:
not merely the prompt length.
There are two operational interpretations:
- Actual usage: cache grows as tokens are processed. A request that stops after 200 output tokens uses less than its maximum allowance.
- Reserved capacity: many engines allocate or reserve memory based on a configured maximum sequence length or cache pool. In that case, a conservative plan should use the reservation policy, not the average observed output length.
For a simple local baseline, calculate from the maximum prompt plus maximum generation length you intend to support. Later, when benchmarking real workloads, you can compare this safe upper bound with measured active-cache use.
Sanity checks before trusting an estimate
Use these checks to catch common mistakes:
| Check | What it prevents |
|---|---|
| Include the factor | Forgetting either keys or values |
| Multiply by every layer | Treating the cache as if it existed once for the whole model |
| Use for GQA or MQA | Overestimating based on query heads or hidden size |
| Include prompt plus generation tokens | Underestimating the final cache size |
| Multiply by active sequences | Mistaking a single-request estimate for a concurrent-serving estimate |
| Use KV precision, not weight precision | Assuming 4-bit weights imply a 4-bit cache |
| Keep units explicit | Mixing bytes, GB, GiB, token counts, and parameter counts |
The estimate is intentionally approximate. Real usage can differ because of memory alignment, engine-managed cache blocks, allocator behavior, metadata, and temporary tensors. But the architecture-level formula is the right first calculation for comparing configurations and rejecting impossible ones early.
Key takeaways
- The KV cache stores prior keys and values for every processed token and every transformer layer, avoiding repeated attention computation during generation.
- Approximate KV-cache memory is:
- In standard multi-head attention, is typically the model hidden size. In GQA and MQA, use the smaller KV-head count directly.
- Cache memory grows linearly with active sequence length, batch size, layer count, KV dimension, and bytes per cache element.
- Weight quantization and KV-cache precision are separate choices. A model can have compact weights while still using an FP16 or BF16 cache.
- For capacity planning, calculate the cache from the maximum supported prompt plus generated tokens, then leave headroom for engine overhead.
Next, you will shift from memory capacity to user-visible performance: distinguishing time to first token, inter-token latency, end-to-end latency, throughput, and concurrency.
Can't find a good explanation? Sign up and we'll make it for you
Sign up