KV Cache Explained: How LLMs Generate Tokens Faster and What It Costs in GPU Memory A technical explainer details how the KV (Key-Value) cache lets decoder-only Transformer models such as Llama, Qwen and GPT generate tokens without recomputing static key and value projections, trading compute for GPU memory. The piece gives the per-token footprint formula (2 × n_layers × n_kv_heads × d_head × bytes_per_param), which yields 0.5 MB per token for Llama-2-7B in FP16 (2 × 32 × 32 × 128 × 2 = 524,288 bytes) and 128 KB per token for Llama-3-8B, whose Grouped-Query Attention with 8 KV heads instead of 32 cuts cache size 4x. It frames the cost as the reason an 8B model with 16 GB of weights can exhaust an 80GB A100 under concurrent load, since self-attention without caching scales quadratically at O(N²). At 2:14 AM, Rohan stared at his terminal in disbelief. His team had just deployed a fine-tuned 8B parameter model onto a dedicated GPU node, expecting crisp, real-time responses for their customer intelligence copilot. The first few words streamed out smoothly. By paragraph three, the stream sputtered like an engine running dry. By paragraph six, a single prompt was taking nearly twelve seconds to finish — and when ten users hit the endpoint at once, the GPU crashed with a dreaded CUDA out of memory error. “The model weights are only 16 gigabytes,” Rohan muttered, staring at nvidia-smi on his 80GB A100. "Where did the other 64 gigabytes go?" Welcome to the central paradox of modern Large Language Model LLM inference. Making an LLM think fast isn’t just about raw compute — it is about remembering what it already thought about, and paying the steep memory rent to store those memories. That mechanism is the KV Key-Value Cache . Unlike traditional neural networks that take an input and spit out a complete answer in a single forward pass, decoder-only Transformers like Llama, Qwen, and GPT are autoregressive . They generate text one token at a time, feeding every newly generated token back into the model to predict the next one. Suppose you give a model a 1,000-token prompt and ask for a 500-token summary: Without optimization, the model recomputes the exact same internal representations for those first 1,000 prompt tokens 500 separate times . Because self-attention compares every token against every preceding token, the total computational cost scales quadratically — O N² — with sequence length. Your GPU spends 95% of its energy re-reading the past instead of writing the future. To understand how we eliminate this redundant work, we have to look inside a single Transformer layer’s self-attention block. When a token’s embedding vector xₜ enters an attention layer, the model multiplies it by three learned weight matrices — W Q, W K, and W V — to project the token into three distinct vectors: To compute the attention output for the newest token at position t , the model calculates how strongly its Query qₜ aligns with the Keys of all tokens from position 1 to t , scales and normalizes those scores via Softmax, and takes a weighted sum of their Values: Here is the crucial insight: causal masking . In autoregressive generation, past tokens can never attend to future tokens. Because a past token’s embedding x ᵢ where ī < t never changes once processed, its projections k ᵢ = x ᵢ · W K and v ᵢ = x ᵢ · W V remain completely static across every subsequent generation step. Instead of recalculating k₁, k₂, …, kₜ₋₁ and v₁, v₂, …, vₜ₋₁ at every step, we save them in high-speed GPU High Bandwidth Memory HBM right after they are computed the first time. Look at what changes between the two workflows: We trade compute FLOPs for memory capacity and bandwidth VRAM to achieve a fast, constant generation speed. When Rohan profiled his copilot’s latency the next morning, he discovered that LLM inference actually consists of two completely different phases with opposite hardware bottlenecks: Rohan pulled out a notepad to solve the mystery of his vanished 64GB of VRAM. Every single token in every active sequence stores a Key vector and a Value vector in every Transformer layer. The exact memory footprint per token in bytes is: Bytes per Token = 2 × n layers × n kv heads × d head × bytes per param Let’s plug in the numbers for a classic Llama-2–7B architecture which uses standard Multi-Head Attention where n kv heads = n heads = 32, d head = 128, n layers = 32 running in FP16 2 bytes : Bytes per Token = 2 × 32 × 32 × 128 × 2 = 524,288 bytes = 0.5 MB per token Now watch what happens at scale: What about modern Llama-3–8B ? Meta introduced Grouped-Query Attention GQA with n kv heads = 8 instead of 32—cutting the KV cache size by 4x to 128 KB per token 1 GB per 8K context . Even so, at 32K or 128K context windows across dozens of concurrent enterprise users, the KV cache easily dwarfs the model weights themselves. To see the impact empirically, consider an 8B parameter model FP16 running on an NVIDIA A100–80GB GPU across varying sequence lengths: Notice two things: When Rohan realized his naive serving loop was pre-allocating contiguous memory chunks for maximum sequence lengths — wasting up to 70% of VRAM to fragmentation — he implemented four industry-standard optimizations: In production inference engines like vLLM , TensorRT-LLM , or SGLang , every configuration knob balances three competing forces: latency TTFT/TPOT , throughput , and VRAM stability . 9. Conclusions Before signing off that night, Rohan ran a quick benchmark script on his workstation to verify the exact speed and memory trade-off using PyTorch and Hugging Face transformers: Python python import timeimport torchfrom transformers import AutoModelForCausalLM, AutoTokenizermodel id = "Qwen/Qwen2.5-3B-Instruct"tokenizer = AutoTokenizer.from pretrained model id model = AutoModelForCausalLM.from pretrained model id, torch dtype=torch.float16, device map="cuda" prompt = "Explain distributed consensus in detail. " 40 ~320 tokensinputs = tokenizer prompt, return tensors="pt" .to "cuda" def benchmark use cache: bool : torch.cuda.empty cache torch.cuda.reset peak memory stats start = time.perf counter with torch.no grad : = model.generate inputs, max new tokens=256, use cache=use cache, do sample=False, torch.cuda.synchronize elapsed = time.perf counter - start peak mem gb = torch.cuda.max memory allocated / 1024 3 print f"use cache={use cache:<5} | Time: {elapsed:.2f}s | Peak VRAM: {peak mem gb:.2f} GB" benchmark use cache=True benchmark use cache=False With use cache=True, generating 256 tokens finished in 3.4 seconds . Turning it off use cache=False stretched the exact same generation to 14.8 seconds —and the gap widens exponentially as prompts grow longer. By migrating his deployment to a PagedAttention engine with FP8 KV quantization and shared system-prompt prefix caching, Rohan brought his copilot’s p95 latency back under 400 milliseconds and tripled concurrent user capacity on the same A100. The takeaway for every AI engineer moving from prototype to production is simple: model weights are a fixed entry fee, but the KV cache is the variable rent. Master how it is allocated, compressed, and reused, and you turn sluggish, memory-starved models into fast, scalable systems. Kwon, W., Li, Z., Zhuang, S., Sheng, Y., Zheng, L., Yu, C. H., Gonzalez, J., Zhang, H., & Stoica, I. 2023 . Efficient Memory Management for Large Language Model Serving with PagedAttention. Proceedings of the 29th Symposium on Operating Systems Principles , 611–626. https://doi.org/10.1145/3600006.3613165 https://doi.org/10.1145/3600006.3613165 arXiv PDF: https://arxiv.org/pdf/2309.06180 https://arxiv.org/pdf/2309.06180 Cited by: 11608 KV Cache Explained: How LLMs Generate Tokens Faster and What It Costs in GPU Memory https://pub.towardsai.net/kv-cache-explained-how-llms-generate-tokens-faster-and-what-it-costs-in-gpu-memory-3504684a2bbd was originally published in Towards AI https://pub.towardsai.net on Medium, where people are continuing the conversation by highlighting and responding to this story.