Skip to main content
Vantaige

Architecture & Memory Deep Dive

What is KV Cache? Sizing, Formulas & VRAM Impact

Why your local LLM runs out of memory on long prompts, how the attention mechanism caches tokens, and how Grouped-Query Attention (GQA) and DeepSeek's MLA slashed memory requirements by up to 90%.

Interactive KV Cache Calculator

See how architecture, context tokens, and precision dictate real GPU memory consumption.

Architecture: gqa

32 layers · 32 query heads · 8 KV heads (4:1 GQA group)

32,768 tokens
1 sequence

Multi-user servers (like vLLM) multiply the KV cache by active parallel requests.

Calculated Memory Demand
4.00 GiBKV Cache only

Formula: 2 (Keys + Values) × 32 layers × 8 KV heads × 128 head dim × 32,768 tokens × 2 bytes

Model Weights (Q4_K_M):4.9 GiB
KV Cache (32k tokens):+4.00 GiB
Estimated Runtime Overhead:+1.0 GiB
Total Minimum VRAM Required:~9.9 GiB
Architectural Impact

Because this model uses GQA (8:1 ratio), this KV cache is 4x smaller than it would be with legacy MHA (which would have required 16.0 GiB).

Open Full VRAM Calculator for this Model

1. Why Does Autoregressive Generation Need a KV Cache?

When an LLM generates a response, it produces one token at a time in an autoregressive loop. To predict the very next token, the self-attention mechanism must compute how the current token relates to every preceding token in the prompt and response history.

In naive matrix multiplication, generating token #2,000 would require running the entire neural network over tokens 1 through 1,999 from scratch. This would cause generation speed to slow to a crawl, scaling quadratically as $O(N^2)$.

💡 The KV Cache Solution:During the initial prompt ingestion (“prefill”), the model calculates the Key (what information is stored) and Value (the actual contextual content) vectors for every token and caches them in GPU memory. When generating the next token, it only computes a single new Query vector and compares it against the cached Keys and Values.

The result: token generation speed remains constant ($O(1)$). But the price you pay is GPU memory consumption that grows linearly with every token processed.

2. The Exact KV Cache Mathematical Formula

For standard transformer architectures (such as Llama 3, Mistral, Qwen, Gemma, and DeepSeek), the size of the KV cache in bytes is given by:

KV Cache (Bytes) = 2 × L × H_kv × d × T × S × B
2 (Keys + Values)Separate tensors stored for both Key and Value vectors.
L (Layers)Number of transformer blocks (e.g. 32 for 8B, 80 for 70B).
H_kv (KV Heads)Number of Key-Value attention heads (e.g. 8 in Llama 3).
d (Head Dimension)Dimension per head (typically 128 in modern LLMs).
T (Context Tokens)Total active sequence length (prompt + output tokens).
B (Bytes Per Element)2 bytes for FP16/BF16, 1 byte for FP8, ~0.56 bytes for Q4_0.

3. The Attention Evolution: MHA vs. GQA vs. MLA

The history of open LLMs over the past two years is largely a fight to prevent the KV cache from overwhelming GPU VRAM.

Legacy (2020–2023)
MHA (Multi-Head)

Ratio: 1 Query Head : 1 KV Head.

Every query head keeps its own independent Key and Value tensor. Extremely memory-intensive: at 32k tokens, Llama 1 7B consumed ~8 GiB just for KV cache.

⚠️ Scales poorly above 8k context.
Current Standard (2024–2026)
GQA (Grouped-Query)

Ratio: 4 to 8 Query Heads : 1 KV Head.

Used by Llama 3, Mistral, Qwen 2.5, and Gemma. Groups multiple query heads to share a single KV head. Reduces KV cache memory by 75% to 87.5% with zero perceptible loss in reasoning quality.

✅ Enables 32k to 128k on consumer GPUs.
Next-Gen Frontier
MLA (Multi-Head Latent)

Ratio: Low-Rank Latent Compression.

Invented by DeepSeek for V2, V3, and R1. Projects Key and Value matrices into a compact 512-dim latent vector before caching. Achieves 90%+ memory reduction compared to standard MHA.

🚀 DeepSeek 128k context takes <2.5 GB VRAM!

4. How to Quantize the KV Cache (Save 50% to 75% Memory)

If your model fits into VRAM at short context but you need long-context capability (for coding, PDF reading, or multi-turn agent conversations), you can quantize the cache:

FP8 KV Cache (vLLM & TensorRT)50% Reduction

Cuts cache memory in half by moving from FP16 (2 bytes) to FP8 (1 byte). Supported on modern NVIDIA Ada Lovelace (RTX 4090) and Hopper (H100) GPUs.

vllm serve model --kv-cache-dtype fp8
Q8_0 & Q4_0 (llama.cpp / Ollama)Up to 72% Reduction

Quantizes keys and values into 8-bit or 4-bit integer blocks with FlashAttention. Enables 64k+ context on consumer 16GB cards.

llama-cli --cache-type-k q4_0 --cache-type-v q4_0

Frequently Asked Questions about KV Cache

When a model first loads into VRAM, only the model weights and runtime context buffers are resident (~5 GB for an 8B Q4 model). As your conversation grows, the KV cache must store the key and value vectors for every single past token. At 32k or 64k tokens, the KV cache can consume an extra 2 GB to 6 GB. If your GPU (such as an 8GB RTX 3060 Laptop or 4060) has no headroom left, CUDA triggers an immediate Out of Memory crash.

For standard Grouped-Query Attention (GQA) and Multi-Head Attention (MHA), the formula is: Bytes = 2 (Keys + Values) × Layers × KV Heads × Head Dimension × Context Tokens × Concurrent Sequences × Bytes Per Element. For 16-bit precision (FP16/BF16), Bytes Per Element is 2. For FP8, it is 1. Divide the total bytes by 1024³ to get GiB.

Instead of caching high-dimensional key and value vectors for dozens of attention heads, MLA compresses the key and value representations into a single low-rank latent vector (rank 512) alongside a decoupled RoPE head vector (rank 64). During generation, the engine caches only 576 dimensions per token rather than 4,096+, allowing massive 128k context windows to fit on a single GPU.

No! Weight quantization only shrinks the static weight matrices of the neural network on disk and in VRAM. By default, the KV cache remains unquantized 16-bit floating-point (FP16). To shrink the KV cache itself, you must explicitly enable KV cache quantization in your inference engine (e.g. FP8 in vLLM or Q8_0/Q4_0 in Ollama / llama.cpp).

In llama.cpp, pass the flags `--cache-type-k q8_0 --cache-type-v q8_0` (or `q4_0` for maximum memory savings). In Ollama, you can enable Flash Attention (`OLLAMA_FLASH_ATTENTION=1`) and configure your Modelfile with quantized context settings.

Ready to calculate the exact VRAM for your model?

Select any real checkpoint in our VRAM Calculator to see its weights, KV cache, and runtime reserve.

Launch VRAM Calculator

Knowledge & Deep Dives

VRAM & Local AI Knowledge Hub

Everything you need to know about sizing hardware, understanding model architecture, and running local LLMs without out-of-memory crashes.

50+ Terms8 min reference
Master the technical terminology: GGUF vs. Safetensors, K-quants, KV cache, GQA, MoE total vs. active parameters, and Apple unified memory.
Interactive search & filter
Practical hardware takeaways
Alphabetical index
Explore guide
Config Decoder7 min read
Inspect Hugging Face repositories like an ML engineer: decode config.json, identify true context windows, and avoid the MoE parameter trap.
Interactive config.json inspector
MoE active vs total trap
GGUF naming decoded
Explore guide
License Matrix5 min read
The legal and practical differences between true OSI Open Source AI and open-weight models like Llama 3, DeepSeek, Qwen 2.5, and Gemma 2.
Full license comparison matrix
Commercial usage caps
Synthetic distillation rules
Explore guide
Hardware Tiers9 min read
What hardware to actually buy: VRAM capacity tiers (8GB to 96GB), memory bandwidth vs. TFLOPS, Apple Silicon vs. Nvidia, and dual-GPU builds.
8GB to 96GB breakdown
Why bandwidth dictates tok/s
RAM offload PCIe bottlenecks
Explore guide