← All field notes
LLM Memory Planning

KV Cache Memory Explained: Context, Concurrency, and VRAM

A formula-first guide to KV cache memory, active tokens, concurrent sequences, FP8/FP16 cache, and practical GPU headroom.

KV Cache Memory Explained: Context, Concurrency, and VRAM

KV cache memory is the GPU memory used to retain the attention keys and values for tokens that an LLM has already processed. It makes autoregressive decoding practical, but it is also why a model that loads successfully can still run out of VRAM under long context or concurrent traffic.

The planning rule is simple: weight memory is mostly shared; KV cache memory grows with the active tokens held by every resident sequence. Before reserving a GPU, calculate the raw cache, then validate the runtime's actual reservation alongside weights and workspace.

This article covers inference, not training or fine-tuning.

01 / Start with the cache shape, not parameter count

During inference, an attention layer stores a key tensor and a value tensor for each processed token. Hugging Face documents these caches as per-layer tensors whose dimensions include batch size, heads, sequence length, and head dimension. The previous keys and values can then be reused for the next token instead of being recomputed. Read the cache mechanics in the Transformers documentation.

For a conventional full-attention decoder with equal key and value dimensions, use this raw KV cache memory estimate:

KV cache bytes = 2 × L × Hkv × D × B × ΣTi
Symbol Meaning Unit
2 one key plus one value tensor dimensionless
L attention layers that retain KV state layers
Hkv key/value heads per layer heads
D elements per KV head elements
B bytes per cached element bytes/element
ΣTi total resident tokens across active sequences tokens

If S sequences all reach T tokens, substitute S × T for ΣTi.

This is a tensor-size calculation, not a promise about a running server. KV cache memory can also reflect block rounding, scaling metadata, cache sharing, attention variants, offloading, allocator behavior, and runtime workspace. Treat the formula as the baseline you must explain—not the final GPU reservation.

02 / Context and concurrency use the same token budget

For one fixed full-attention model and cache dtype, KV cache memory scales approximately linearly with active tokens:

  • Double the tokens in one active request → roughly double the raw cache.
  • Double equally long active requests → roughly double the raw cache.
  • Keep total active tokens equal → raw cache can be similar, even when the request mix differs.

That last point is useful but incomplete. One 32K-token request and four 8K-token requests can have similar raw KV cache memory, while scheduling, prefill behavior, tail latency, prefix reuse, and request admission still differ. This is memory planning—not a performance prediction.

Use prompt tokens plus generated tokens for each resident sequence. A 6K prompt allowed to produce 2K new tokens belongs in an 8K token budget. Registered users, requests per day, and an advertised model maximum are not substitutes for peak active tokens.

For broader context-window mechanics, see Context windows and KV cache →.

03 / Worked example: Llama 3.1 8B, 4 × 8K, FP16 cache

This example makes the KV cache memory arithmetic reproducible. It is a calculated estimate, not a vendor measurement or a vLLM benchmark.

Assumptions

Input Value Classification
Model architecture Llama 3.1 8B source fact
Layers (L) 32 source fact
Query heads 32 source fact
KV heads (Hkv) 8 source fact
Hidden size 4,096 source fact
Head dimension (D) 4,096 ÷ 32 = 128 calculation
Cache precision (B) FP16 = 2 bytes/element operational assumption
Active sequences (S) 4 workload assumption
Total tokens per sequence (T) 8,192 workload assumption
Prefix sharing / offload / cache compression none credited operational assumption

Meta's Llama model definitions list the 3.1 8B architecture with 32 layers, 32 attention heads, 8 KV heads, and hidden dimension 4,096. Inspect the source definition. The 8 KV heads—rather than all 32 query heads—are the important GQA input for the cache calculation.

Calculation

Bytes per token = 2 × 32 × 8 × 128 × 2
                = 131,072 bytes
                = 128 KiB

Raw cache = 131,072 × 8,192 × 4
          = 4,294,967,296 bytes
          = 4.00 GiB

Reproduce it directly:

GiB = 2**30
layers = 32
kv_heads = 8
head_dim = 4096 // 32
cache_bytes_per_element = 2  # FP16 or BF16 raw values
tokens_per_sequence = 8192
concurrent_sequences = 4

kv_cache_bytes = (
    2 * layers * kv_heads * head_dim * cache_bytes_per_element
    * tokens_per_sequence * concurrent_sequences
)

print(kv_cache_bytes)            # 4294967296
print(kv_cache_bytes / GiB)      # 4.0

The result is 4.00 GiB of raw KV cache memory for this specific architecture and workload. It does not include model weights, quantization metadata, CUDA graphs, temporary workspaces, non-cache activations, GPU driver use, other processes, or an operating reserve. Add those components before deciding that a GPU fits.

04 / A small workload change can create a large cache change

The table below holds the same Llama 3.1 8B architecture constant. FP8 values are the idealized raw one-byte cache payload; do not treat them as an exact runtime allocation.

Workload Total resident tokens Raw FP16 / BF16 cache Raw FP8 cache payload*
1 sequence × 8K 8,192 1.00 GiB 0.50 GiB
4 sequences × 8K 32,768 4.00 GiB 2.00 GiB
1 sequence × 32K 32,768 4.00 GiB 2.00 GiB
4 sequences × 32K 131,072 16.00 GiB 8.00 GiB

*The FP8 column is a raw-data calculation using one byte per element. Cache scales, block rounding, kernel support, and runtime implementation can change the allocated figure.

This is why KV cache memory deserves its own budget. Reducing weight precision can make a checkpoint load, but it does not automatically shrink the cache. Likewise, raising concurrency changes the cache while leaving the shared weight payload nearly unchanged.

05 / FP8 can reduce the cache component—not all VRAM

For the raw formula, changing from a two-byte FP16/BF16 cache to one-byte FP8 values roughly halves the cache-data term. It does not halve model weights, runtime workspace, or total GPU memory.

vLLM exposes a cache dtype setting and documents its supported cache formats. Its current configuration also notes that cache capacity is tied to the engine's memory budget unless a specific byte budget is set. Check the vLLM cache configuration for your installed release.

Before switching KV cache precision, verify all of the following:

  1. Your runtime and GPU support the selected cache dtype.
  2. The checkpoint or runtime supplies any required scaling information.
  3. The quality impact is acceptable for your workload.
  4. The resolved cache dtype in server logs matches the requested configuration.
  5. The measured peak allocation still leaves your operating reserve.

Do not infer cache precision from weight quantization. A 4-bit weight plan and an FP16 KV cache are a common, valid combination; they are separate inputs.

06 / Raw cache is not the same as a real VRAM fit

Use this sequence to turn KV cache memory into a deployment decision:

  1. Calculate the raw cache. Use the model's actual layer count, KV heads, head dimension, cache dtype, and peak active tokens.
  2. Profile the chosen runtime. Paged runtimes can reserve or grow cache in blocks, and their memory budgets may not equal the active-token tensor total.
  3. Add the non-cache memory. Account for loaded weights, quantization and packing overhead, workspaces, temporary allocations, and other GPU consumers.
  4. Apply an explicit operating ceiling. ModelFit uses a 15% operating headroom policy in its calculator; this is a planning convention, not a performance guarantee.
  5. Load test the peak workload. Test representative prompts, output caps, and simultaneous requests—not only a short single-user chat.

The ModelFit calculator → keeps weights, KV cache, and runtime workspace visible as separate inputs to the fit check. Then use the hardware directory → to compare the resulting per-GPU envelope with actual VRAM classes.

Tensor parallelism needs a per-GPU check

Do not blindly divide a single-GPU KV cache number by the number of GPUs. Depending on model layout and runtime, cache placement, replicated buffers, block allocation, and communication workspace can change per-device usage. Use the framework's reported per-GPU cache capacity after startup, then validate the target concurrent workload.

07 / Debug the common OOM pattern: “it works for one user”

When a model fits for one short request but fails under traffic, ask these questions in order:

Check Why it matters Corrective action
Are prompt and output tokens both budgeted? Generated tokens remain in the cache too. Set a total-token limit, not only a prompt limit.
Is peak concurrency different from average concurrency? KV cache memory follows concurrent resident tokens. Set an admission limit and test it.
Did you use KV heads, not query heads? GQA/MQA change bytes per token. Read the checkpoint configuration.
Is the reported cache dtype actually active? Weight dtype and KV dtype are independent. Inspect startup configuration and logs.
Does the runtime reserve in blocks or a static pool? Allocated VRAM can exceed the raw token calculation. Profile immediately after startup and at peak.
Is there a realistic headroom policy? A zero-margin fit is fragile. Reduce context/concurrency or select more VRAM.

This diagnostic path is more useful than asking whether the model “fits.” The better question is: does this model, context cap, concurrent-token budget, cache dtype, and runtime reservation fit with operating headroom?

08 / FAQ

Does KV cache memory always use the model's maximum context?

Not necessarily. The raw formula follows resident tokens, while an implementation may allocate or reserve cache in blocks or pools. Set the maximum context deliberately, then inspect the runtime's allocated cache capacity rather than assuming a short prompt means no reservation.

Why does KV cache memory grow with concurrent requests if weights are shared?

Each active sequence needs its own history of keys and values. The loaded model weights can serve many requests, but cache state belongs to the resident token history of each request.

Does 4-bit weight quantization reduce KV cache memory?

Not by itself. Weight format and KV cache dtype are separate decisions. Calculate KV cache memory from the cache dtype the runtime will actually use.

Is the formula valid for every transformer architecture?

No. It is the baseline for conventional full-attention KV layouts. Sliding-window, hybrid local/global, latent-attention, multimodal, and custom cache architectures require model- and runtime-specific accounting.

09 / Make the cache budget a fit check

KV cache memory is not a fixed property of a model name. It is a workload-dependent allocation driven by architecture, cache precision, total resident tokens, and concurrency. Calculate the baseline, reserve room for the rest of the runtime, then validate the peak workload before paying for capacity.

When that worksheet supports a real deployment decision, check the current GPU options on Flatkey Compute ↗. ModelFit is an independent planning surface that links qualified deployment decisions to Flatkey Compute; estimates are planning guidance, not benchmark guarantees.

Sources and method

  • Hugging Face Transformers — How caching works. Used for the per-layer key/value cache behavior and tensor dimensions. Accessed 2026-10-24.
  • Meta Llama model definitions. Used for the Llama 3.1 8B architecture values in the worked example. Accessed 2026-10-24.
  • vLLM cache configuration. Used for cache-dtype and memory-budget behavior. Accessed 2026-10-24.

All GiB values above are calculated with 1 GiB = 2^30 bytes. Calculated estimates and operational assumptions are labeled separately from source facts. No performance, availability, or pricing claims are made.

Continue planning

Test the model against real GPU memory.

Open the VRAM calculator →
KV Cache Memory Explained: Context, Concurrency & VRAM · ModelFit