KV Cache Explained: How LLMs Generate Tokens Faster and What It Costs in GPU Memory
From the publisher’s feed, collected in the ZeroLabs newsroom.
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.1. The Inference Problem: Why LLMs Slow Down Over TimeUnlike 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:To generate token 1,001, the model processes 1,000 tokens.To generate token 1,002, the model processes 1,001 tokens.To generate token 1,500, the model processes 1,499 tokens.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.2. Transformer Attention FundamentalsTo 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:Query (qₜ = xₜ · W_Q): What this current token is looking for in the context.Key (kₜ = xₜ · W_K): What this token advertises about itself to future tokens.Value (vₜ = xₜ · W_V): The actual semantic information this token passes forward if a Query matches its Key.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 ī kᵢ = xᵢ · W_K and vᵢ = xᵢ · W_V remain completely static across every subsequent generation step.3. KV Cache Explained VisuallyInstead 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:WITHOUT KV CACHE (Slow): To generate a new token (like “faster”), the model has to send every single previous token (“How”, “LLMs”, “generate”, “tokens”) along with the new one through the Transformer Attention block. This means the GPU must recalculate all previous keys and values at every single step. Compute effort grows with every word, making the system get slower and slower.WITH KV CACHE (Fast): The model processes the new token (“faster”) by calculating only its own brand-new query, key, and value (qₜ, kₜ, vₜ). It immediately appends kₜ, vₜ to the KV Cache stored in GPU Memory (HBM). To generate the output, Transformer Attention simply fetches the "Saved Past KV" from memory and combines it with the single new qₜ, kₜ, vₜ from "faster". The past isn't recalculated—it’s just reused.We trade compute (FLOPs) for memory capacity and bandwidth (VRAM) to achieve a fast, constant generation speed.4. Step-by-Step Token Generation: Prefill vs. DecodeWhen 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:The Prefill Phase (Prompt Processing): You send the initial prompt: "Summarize the Q3 revenue report..." (say, 2,000 tokens). Because all 2,000 tokens are known upfront, the GPU processes them in parallel in one massive matrix-matrix multiplication (GEMM). During prefill, the model populates the initial KV Cache for all 2,000 tokens across every layer. This phase is compute-bound—it saturates the GPU's Tensor Cores and determines your Time to First Token (TTFT).The Decode Phase (Autoregressive Generation): Now the model generates token 2,001, then 2,002, one by one. At each step, the GPU only multiplies a single token vector against the model weights and reads the entire stored KV Cache from HBM into on-chip SRAM to compute attention. Because the GPU reads gigabytes of weights and KV vectors just to perform math on one token, the Tensor Cores sit mostly idle waiting for memory transfers. This phase is memory-bandwidth-bound and determines your Time Per Output Token (TPOT).5. The Math: How Much GPU Memory Does the KV Cache Cost?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_paramLet’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 tokenNow watch what happens at scale:A single request with an 8,192-token context consumes 8,192 × 0.5 MB = 4.0 GB of VRAM—just for one user!With a batch size of 16 concurrent users, the KV Cache alone demands 64 GB of VRAM. Add 14 GB for the model weights, and an 80GB A100 runs completely out of memory.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.6. Performance Benchmarks: Compute vs. BandwidthTo see the impact empirically, consider an 8B parameter model (FP16) running on an NVIDIA A100–80GB GPU across varying sequence lengths:Notice two things:Without caching, moving from 512 to 4,096 tokens causes decode speed to collapse by nearly 8x. With KV caching, single-stream decode speed barely budges.Increasing batch size from 1 to 32 only increases per-token latency slightly (from 13 ms to 28 ms) while multiplying total system throughput by 15x — because the GPU loads the model weights once and amortizes that memory read across 32 users’ KV caches simultaneously.7. Optimization Techniques: Taming the Memory BeastWhen 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:Grouped-Query Attention (GQA) & Multi-Query Attention (MQA): Architectural changes during training where multiple Query heads share a single Key and Value head. GQA (used in Llama 3, Mistral, and Qwen2.5) slashes KV memory by 4x–8x with virtually zero accuracy loss.PagedAttention (vLLM): Inspired by virtual memory paging in operating systems. Instead of reserving one giant contiguous block of VRAM per request, PagedAttention breaks the KV cache into small, non-contiguous fixed-size blocks (e.g., 16 tokens per block) mapped via a block table. Internal fragmentation drops below 4%, allowing 2x–4x larger batch sizes on the exact same GPU.FP8 / INT8 KV Cache Quantization: Compressing cached Keys and Values from 16-bit floats down to 8-bit numbers cuts KV memory footprint and HBM bandwidth pressure in half, preserving >99% of model quality on long-context reasoning tasks.Prefix Caching (Automatic Context Reuse): If 500 user requests share the exact same 3,000-token system prompt or RAG document block, the serving engine computes those KV blocks once, hashes them, and shares the read-only physical memory blocks across all concurrent requests — dropping TTFT for cached prefixes by up to 80%.8. Production Deployment and Trade-OffsIn production inference engines like vLLM, TensorRT-LLM, or SGLang, every configuration knob balances three competing forces: latency (TTFT/TPOT), throughput, and VRAM stability.Throughput vs. Latency: Large batch sizes maximize GPU utilization and lower cost per million tokens, but once the combined size of model weights plus active KV caches saturates HBM bandwidth, every user experiences sluggish streaming.Preemption & Swapping: When an unexpected spike of long-context prompts fills the KV block pool, the scheduler must either preempt lower-priority requests (evicting their KV cache and recomputing it later) or swap KV blocks over PCIe to CPU RAM — trading a temporary latency spike to prevent an OOM crash.Disaggregated Prefill and Decode: At massive scale, production architectures separate compute-heavy Prefill nodes from memory-heavy Decode nodes, transferring the newly computed KV cache over high-speed NVLink or InfiniBand so long prompts never stall active token streams.9. ConclusionsBefore 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:Pythonimport 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: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.ReferencesKwon, 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 (arXiv PDF: https://arxiv.org/pdf/2309.06180) Cited by: 11608KV Cache Explained: How LLMs Generate Tokens Faster and What It Costs in GPU Memory was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.