# KV Cache Explained: How LLMs Generate Tokens Faster and What It Costs in GPU Memory

> 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: 2026-11-25 13:31:02+00:00

**Recommendation:** 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.
More in the playbook "Inference and self-hosting": <https://wpnews.pro/playbooks/inference-serving>

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.
