Skip to main content
Module 1 · Lesson 2 of 42/48 in the course~15 min
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:

Text
KV_Cache_Bytes = 2 * precision_bytes * num_layers * num_heads * head_dim * seq_len

Where:

  • 2 accounts for Key and Value matrices.
  • precision_bytes is 2 for FP16/BF16, or 1 for FP8 quantization.
  • num_layers is the number of transformer blocks.
  • num_heads * head_dim is the hidden size (or Key-Value dimension in Grouped-Query Attention).
Model ArchitectureLayersKV DimensionFP16 Memory per 1,000 Tokens128k Context Memory
Llama-3-8B (GQA: 8 KV)321,024~0.13 GB~16.8 GB
Llama-3-70B (GQA: 8 KV)801,024~0.33 GB~42.0 GB
Dense 70B (64 heads MHA)808,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

Quiz#ai-engineering.m1.l2.q1

Why is the decode phase of LLM inference typically memory-bandwidth bound rather than compute-bound?

Answer options

Practice: KV-Cache Sizing & Concurrency Capacity

Practice Stage

Warmup — KV-cache memory calculator

Exercise#ai-engineering.m1.l2.e1
Attempts: 0Loading…

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.

Loading editor…
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 Stage

Practice — Max concurrent streams on GPU

Exercise#ai-engineering.m1.l2.e2
Attempts: 0Loading…

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.

Loading editor…
Show hint

Calculate remaining headroom = gpu_vram_gb - weights_gb, then integer divide by kv_cache_per_stream_gb.

Solution available after 3 attempts

Practice Stage

Challenge — Sliding-window KV cache eviction

Exercise#ai-engineering.m1.l2.e3
Attempts: 0Loading…

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).

Loading editor…
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