Module lessons (2/4)
Context Windows, Attention & KV-Cache
The Two Phases of LLM Inference: Prefill vs Decode
When an LLM serves a request, execution splits into two radically distinct computational stages:
During the decode phase, the model must read all previous Key and Value vectors from GPU High Bandwidth Memory (HBM) for every single generated token. Without caching, generating token t would require recomputing attention across all 1 … t-1 tokens, scaling quadratically with O(N²).
The Memory Footprint of the KV-Cache
The KV-cache trades memory capacity for execution speed. For each token in the context, every Transformer layer stores two vectors: Key and Value.
The memory footprint formula in bytes is:
KV_Cache_Bytes = 2 * precision_bytes * num_layers * num_heads * head_dim * seq_lenWhere:
2accounts for Key and Value matrices.precision_bytesis2for FP16/BF16, or1for FP8 quantization.num_layersis the number of transformer blocks.num_heads * head_dimis the hidden size (or Key-Value dimension in Grouped-Query Attention).
| Model Architecture | Layers | KV Dimension | FP16 Memory per 1,000 Tokens | 128k Context Memory |
|---|---|---|---|---|
| Llama-3-8B (GQA: 8 KV) | 32 | 1,024 | ~0.13 GB | ~16.8 GB |
| Llama-3-70B (GQA: 8 KV) | 80 | 1,024 | ~0.33 GB | ~42.0 GB |
| Dense 70B (64 heads MHA) | 80 | 8,192 | ~2.62 GB | ~335.5 GB (OOM) |
Notice why modern architectures use Grouped-Query Attention (GQA): by sharing Key-Value heads across multiple Query heads, the KV-cache shrinks by up to 8x, making 128k context windows feasible on single GPUs.
Check Your Understanding
Why is the decode phase of LLM inference typically memory-bandwidth bound rather than compute-bound?
Practice: KV-Cache Sizing & Concurrency Capacity
Warmup — KV-cache memory calculator
Write calculate_kv_cache_gb(num_layers, kv_dim, seq_len, precision_bytes=2) that returns the total KV-cache memory in gigabytes (1 GB = 10^9 bytes), rounded to 3 decimal places.
Show hint
Multiply 2 * precision_bytes * num_layers * kv_dim * seq_len, then divide by 10^9 and round to 3 decimals.
Solution available after 3 attempts
Practice — Max concurrent streams on GPU
Write max_concurrent_streams(gpu_vram_gb, weights_gb, kv_cache_per_stream_gb) that returns the integer number of concurrent streams the GPU can host without exceeding VRAM.
Show hint
Calculate remaining headroom = gpu_vram_gb - weights_gb, then integer divide by kv_cache_per_stream_gb.
Solution available after 3 attempts
Challenge — Sliding-window KV cache eviction
Write simulate_sliding_kv_cache(stream_tokens, window_size) that simulates a sliding window KV-cache buffer. For each token in stream_tokens, append it to the cache; if cache length exceeds window_size, evict the oldest token. Return a tuple (cached_tokens, num_evicted).
Show hint
Loop through stream_tokens. If len(cache) >= window_size, pop(0) and increment evicted, then append the new token.
Solution available after 3 attempts