Understanding KV Cache: Accelerating LLM Inference and Analyzing VRAM Costs
This article explores the principles of KV Cache, a critical technique for accelerating Large Language Model (LLM) inference by avoiding redundant calculations. It covers how KV Cache works during the prefill and decode phases, provides a formula and code snippet to estimate its VRAM consumption, discusses the impact of cache hits on inference costs, and outlines common engineering optimization strategies.
1. Background
Large Language Models (LLMs) generate text token by token. For every new token generated, the model performs a forward pass using the entire preceding context. If the model reprocesses the entire sequence from scratch at each step, the computational cost grows rapidly as the text gets longer. Key-Value Cache (KV Cache) is a standard method to solve this redundant computation, serving as a foundational capability in modern inference services.
2. Redundant Computation in Autoregressive Generation
Take the sequence “The weather today” as an example. In the first step, the model reads these tokens and outputs the next token, “is”. In the second step, the input becomes “The weather today is”, and the model outputs “good”.
The standard attention mechanism generates three sets of vectors for each token: Query (Q), Key (K), and Value (V). When computing attention for the current position, the model calculates the similarity between the current Q and the K of all positions, then takes a weighted sum of all V using the resulting weights.
The problem is that the K and V of historical tokens were already computed in the previous step. They only depend on the token itself and its preceding context, and they do not change when a new token is added. If these results are not saved, the second step will recompute the K and V for “The weather today”, yielding the exact same results as the first step. The longer the sequence, the more apparent this waste becomes.
3. How KV Cache Works
The KV Cache approach is straightforward: once the K and V for each token are computed, they are saved and directly read in subsequent steps without recalculation. The inference process is divided into two phases:
- Prefill: The model processes all user input prompts at once, computing the K and V for each position and writing them into the cache. This phase is computationally intensive but can be parallelized.
- Decode: At each step, only the newly generated token is fed into the model. The model computes its Q, K, and V, appends the new K and V to the end of the cache, and then uses the new Q to compute attention scores against all K in the cache, multiplied by all V in the cache to produce the output.
In the decode phase, the per-step computation is reduced from “processing the entire sequence” to “processing a single new token.” However, each step still needs to read the entire cache, and the read volume is proportional to the sequence length. Therefore, the speed of the decode phase is often limited by VRAM bandwidth rather than compute capacity.
4. Estimating VRAM Usage
The size of the KV Cache can be calculated using the following formula:
KV Cache Size = 2 × Number of Layers × Number of Heads × Head Dimension × Sequence Length × Bytes per Value
The coefficient 2 in the formula corresponds to the two sets of vectors, K and V.
Let’s demonstrate with a set of easy-to-calculate example parameters. Assume a model has 32 layers, 32 attention heads, a head dimension of 128, a sequence length of 4096, and uses FP16 format where each value takes 2 bytes. These parameters are set for calculation purposes and do not represent an actual model configuration.
- KV size of a single token in a single layer: 2 × 32 × 128 × 2 = 16384 bytes, which is 16 KB.
- Single token covering all 32 layers: 16 KB × 32 = 512 KB.
- 4096 tokens: 512 KB × 4096 = 2 GB.
- Processing 10 concurrent requests (batch size of 10): 2 GB × 10 = 20 GB.
As we can see, the cache size is directly proportional to the number of layers, heads, sequence length, and concurrency. In long-text or large-batch scenarios, the KV Cache may consume more VRAM than the model weights themselves, becoming the primary constraint in deployment.
The following code can quickly estimate the usage under different configurations:
def kv_cache_bytes(layers, heads, head_dim, seq_len,batch_size=1, bytes_per_value=2):"""Estimate the bytes occupied by the KV cache, K and V each take a portion."""return (2 * layers * heads * head_dim* seq_len * batch_size * bytes_per_value)size = kv_cache_bytes(layers=32, heads=32, head_dim=128,seq_len=4096, batch_size=10)print(f"{size / 1024**3:.1f} GiB") # Outputs 20.0 GiB
When planning a deployment, you can first calculate the cache requirement based on the expected maximum context length and concurrency, then subtract the model weights and runtime overhead from the total GPU VRAM to determine the available concurrency limit.
5. Cache Hits and Inference Costs
When multiple requests share the same prefix—such as identical system prompts, fixed few-shot templates, or the history of a multi-turn conversation—the K and V for these prefixes are exactly the same. Inference services can retain this part of the cache for reuse by subsequent requests. This mechanism is commonly referred to as prefix caching. Upon a cache hit, the prefill computation for the corresponding tokens can be skipped.
The benefits of a cache hit are mainly threefold:
- Reduced computation: Hit portions do not need to be recalculated.
- Lower Time-to-First-Token (TTFT): Users wait less time for the first token.
- Decreased input costs: Some services offer a lower pricing rate for input tokens that hit the cache. Specific rules are published by the service provider and vary significantly between services; refer to the official documentation for accurate information.
The hit rate is determined by the business scenario. Scenarios like multi-turn conversations, fixed templates, and repeated queries on the same document typically have a high hit rate. Scenarios where every input is entirely different have almost no reusable prefixes.
Cache reuse also comes at a cost. The cache occupies VRAM, and service providers must design eviction policies to decide which caches to keep and which to release. In multi-tenant environments, it is also crucial to ensure cache isolation between different users to prevent one user’s context from being inferred by another user through cache behavior.
6. Engineering Optimization Strategies
In real-world systems, common optimization techniques include:
- KV Cache Quantization: Storing K and V in lower precision formats like FP8 or INT8 can reduce footprint exponentially. Precision loss must be verified through evaluation, not just by looking at VRAM numbers.
- Reducing KV Heads: Architectures like Grouped Query Attention (GQA) allow multiple query heads to share the same set of K and V, reducing the cache size structurally. Such designs must be determined during the training phase.
- Paged VRAM Management: Dividing the cache into fixed-size blocks, allocating and reclaiming them on demand to reduce VRAM fragmentation and waste.
- Limiting Context Length and Concurrency: Setting reasonable limits for maximum input length and concurrent requests to prevent a single request or burst traffic from exhausting VRAM.
- Optimizing Prompt Structure: Placing stable, unchanging content (system instructions, templates, examples) at the beginning of the prompt and variable content at the end, thereby increasing the probability of prefix hits.
7. Conclusion
KV Cache is fundamentally a trade of VRAM for compute. It eliminates the redundant calculation of historical tokens in autoregressive generation, significantly accelerating decoding speed, but VRAM usage grows linearly with sequence length and concurrency. Mastering the formula allows you to estimate the required VRAM for deployment and determine concurrency limits. For cost optimization, focus on the cache hit rate and improve reuse through stable prompt structures and sound caching strategies.
