{"slug": "kv-cache-explained-how-llms-generate-tokens-faster-and-what-it-costs-in-gpu", "title": "KV Cache Explained: How LLMs Generate Tokens Faster and What It Costs in GPU Memory", "summary": "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²).", "body_md": "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.\n\n“The model weights are only 16 gigabytes,” Rohan muttered, staring at nvidia-smi on his 80GB A100. \"Where did the other 64 gigabytes go?\"\n\nWelcome 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**.\n\nUnlike 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.\n\nSuppose you give a model a 1,000-token prompt and ask for a 500-token summary:\n\nWithout 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.\n\nTo understand how we eliminate this redundant work, we have to look inside a single Transformer layer’s self-attention block.\n\nWhen 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:\n\nTo 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:\n\nHere 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.\n\nInstead 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.\n\nLook at what changes between the two workflows:\n\nWe trade **compute** (FLOPs) for **memory capacity and bandwidth** (VRAM) to achieve a fast, constant generation speed.\n\nWhen 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:\n\nRohan 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.\n\nThe exact memory footprint per token (in bytes) is:\n\n```\nBytes per Token = 2 × n_layers × n_kv_heads × d_head × bytes_per_param\n```\n\nLet’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):\n\n```\nBytes per Token = 2 × 32 × 32 × 128 × 2 = 524,288 bytes = 0.5 MB per token\n```\n\nNow watch what happens at scale:\n\nWhat 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.\n\nTo see the impact empirically, consider an 8B parameter model (FP16) running on an NVIDIA A100–80GB GPU across varying sequence lengths:\n\nNotice two things:\n\nWhen 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:\n\nIn production inference engines like **vLLM**, **TensorRT-LLM**, or **SGLang**, every configuration knob balances three competing forces: **latency (TTFT/TPOT)**, **throughput**, and **VRAM stability**.\n\n9. Conclusions\n\nBefore 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:\n\nPython\n\n``` python\nimport 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)\n```\n\nWith 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.\n\nBy 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.\n\nThe 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.\n\nKwon, 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\n\n[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.", "url": "https://wpnews.pro/news/kv-cache-explained-how-llms-generate-tokens-faster-and-what-it-costs-in-gpu", "canonical_source": "https://pub.towardsai.net/kv-cache-explained-how-llms-generate-tokens-faster-and-what-it-costs-in-gpu-memory-3504684a2bbd?source=rss----98111c9905da---4", "published_at": "2026-11-25 13:31:02+00:00", "updated_at": "2026-11-25 13:42:57.732469+00:00", "lang": "en", "topics": ["large-language-models", "ai-infrastructure", "ai-research", "machine-learning"], "entities": ["Llama-2-7B", "Llama-3-8B", "Meta", "Qwen", "GPT", "A100"], "also_reported_by": [], "takeaway": "KV cache memory per token equals 2 × n_layers × n_kv_heads × d_head × bytes_per_param — 0.5 MB per token for Llama-2-7B in FP16 versus 128 KB for Llama-3-8B, whose 8 KV heads instead of 32 cut the cache 4x.", "recommendation": {"advice": "Size GPU memory for the KV cache, not just weights: budget 0.5 MB per token for Llama-2-7B in FP16 and 128 KB for Llama-3-8B, and prefer GQA models with fewer KV heads to cut cache 4x.", "playbook": "inference-serving", "playbook_url": "https://wpnews.pro/playbooks/inference-serving"}, "alternates": {"html": "https://wpnews.pro/news/kv-cache-explained-how-llms-generate-tokens-faster-and-what-it-costs-in-gpu", "markdown": "https://wpnews.pro/news/kv-cache-explained-how-llms-generate-tokens-faster-and-what-it-costs-in-gpu.md", "text": "https://wpnews.pro/news/kv-cache-explained-how-llms-generate-tokens-faster-and-what-it-costs-in-gpu.txt", "jsonld": "https://wpnews.pro/news/kv-cache-explained-how-llms-generate-tokens-faster-and-what-it-costs-in-gpu.jsonld"}}