12 The Infinite Memory Scratching Post
LLM Architecture, KV Cache, RoPE, MoE
⏳ 2026 Edition: reflects current state-of-the-art. Last verified: 2026-11-26
Prerequisites: Chapter 11 Technical Keywords: Large Language Models (LLMs), Autoregressive Generation, Prefill vs. Decode, KV Cache, FlashAttention, Rotary Position Embeddings (RoPE), Grouped Query Attention (GQA), Mixture of Experts (MoE)
🧭 Advanced Track Navigation Core Track completion is defined by Checkpoints 1-4. This chapter is Core Track with optional advanced subsections. Read
12.1and12.2first (core inference concepts). Sections12.3to12.6are safe to skim on first pass and are not required for checkpoints.
In Chapter 11, we built the Transformer—the engine that powers modern AI. Pixel learned to use the Attention Mechanism to look at an entire sentence all at once, rather than reading it painfully left-to-right like an RNN.
But there is a catch.
If Pixel wants to read a prompt (like “Write a poem about tuna”), the Transformer splits it into subword tokens (Chapter 10) and processes all of those input tokens simultaneously. But when Pixel has to write the poem, he can’t output every token at once. He generates the first token (“Oh”), looks at everything so far, generates the next token (“sweet”), looks again, and generates the next token (“fish”).
This token-by-token writing process is called Autoregressive Generation.
If we scale Pixel’s brain up to 100 billion parameters (creating a modern frontier or open-weights Large Language Model, or LLM), this token-by-token process becomes a computational nightmare.Let’s look at the cutting-edge engineering required to make a massive AI run efficiently.
12.1 The Two Phases of Thought: Prefill and Decode
In chat assistants such as ChatGPT, the model experiences two different phases of computation:
1. The Prefill Phase: Pixel reads your entire prompt at once. Because Transformers process inputs in parallel, Pixel’s GPU crunches all the math for your prompt in one massive, highly efficient matrix multiplication. This is incredibly fast.
2. The Decode Phase: Now Pixel has to generate the answer. He outputs token 1. To output token 2, he has to run the entire prompt, plus token 1, through the network again. To output token 3, he runs the prompt, token 1, and token 2 through the network again.
Catastrophic Failure: The Autoregressive Quadratic Wall
For a prompt of length P and N generated tokens, decode step t with a KV cache attends over P + t tokens, so total cached dense decode attention scales roughly as O(NP + N^2) (which simplifies to O(N^2) when P is treated as fixed).
Without a KV cache, a naive implementation must re-run the entire forward pass over the growing text prefix each step. Because attention for length t costs O(t^2) work, summing this across N generated tokens yields roughly O(N^3) total attention work. In practice, modern frameworks avoid this through caching, reducing the total attention work to O(N^2).
12.2 The KV Cache: Saving the Scent
To fix the Decode bottleneck, engineers invented the KV Cache (Key-Value Cache).
Remember the Attention formula from Chapter 11? Each token generates three vectors: a Query (Q, “what I’m looking for”), a Key (K, “what I have”), and a Value (V, “my actual meaning”).
When Pixel generates token 1, he calculates the K and V vectors for every token in the prompt. Instead of throwing them away and recalculating them for token 2, he saves them in GPU memory (VRAM/HBM).
When it’s time to generate token 2, Pixel only calculates the Q, K, V for the brand-new token. He takes his new Query (Q) and compares it against the saved Keys (K) sitting in his memory vault (the KV Cache).
This removes most redundant recomputation of old Keys/Values. Decode gets much faster in practice, but total decode still scales roughly quadratically with generated length because each new Query still attends over a growing history. This complexity simplification treats prompt length as fixed: if prompt length is P and the number of generated tokens is N, total decode attention computation with a KV Cache scales roughly as O(NP + N^2).
Analogy
The KV Cache is a massive scratching post. When Pixel reads a token, he leaves its exact scent (K and V) on the post. When he needs to remember the context later, he doesn’t re-read past tokens—he just sniffs the post.

12.3 [Advanced Track] RoPE: The Rotating Collars of Time
Safe to skim on first pass; not required for checkpoints.
We have a new problem. A Transformer processes all tokens simultaneously. If you feed it “The dog chased the cat” or “The cat chased the dog”, the raw Attention math looks identical! The model has no concept of order.
Originally, engineers added “Position Embeddings”—a static vector added to each token’s representation to say “I am at position 3.”
But modern LLMs use Rotary Position Embeddings (RoPE) (Su et al., 2021). Instead of adding a vector, RoPE uses trigonometry (sines and cosines) to rotate each token’s Query and Key vectors in high-dimensional space based on its position in the sequence.
When the Attention Mechanism calculates the dot product between two tokens, the math naturally captures the relative distance between them from the angle between their rotations.
12.4 [Advanced Track] FlashAttention: IO-Awareness
Safe to skim on first pass; not required for checkpoints.
Even with the KV Cache, calculating the Attention Matrix requires moving massive amounts of data from the GPU’s main VRAM (HBM) into its much faster, tiny on-chip working memory (SRAM), then writing it all back. This back-and-forth data movement causes a huge memory bottleneck.
FlashAttention is a hardware-aware algorithm that mathematically breaks the Attention calculation into tiny blocks (Dao et al., 2022). It loads a block into SRAM, computes the final softly-maxed values, and never writes the massive intermediate matrices back to main memory. It computes the exact same math while reducing HBM/SRAM memory traffic and intermediate memory overhead (O(N) for attention intermediates rather than materializing the full O(N^2) attention matrix). Compute is still O(N^2), and FlashAttention mitigates—rather than eliminating—memory bottlenecks and OOM risk (KV cache and model weights still consume VRAM).
12.5 [Advanced Track] Grouped Query Attention (GQA): Sharing the Toys
Safe to skim on first pass; not required for checkpoints.
As models got larger, the KV Cache (the saved scents) got so massive that it physically could not fit inside the GPU’s memory (VRAM).
In a standard Transformer (Multi-Head Attention, MHA), every query head in a layer keeps its own Key and Value head—storing separate K and V vectors per token position. In an aggressive alternative (Multi-Query Attention, MQA), all query heads in a layer are forced to share one single Key/Value head (still storing one K and V vector per token in that layer).
Grouped Query Attention (GQA) is the sweet spot (Ainslie et al., 2023). Instead of giving every query head its own KV head, we group the query heads in each layer into pods of 4 or 8 that share a single Key/Value head. Note that GQA still stores cached K and V vectors for every token position in the sequence per layer—it just avoids duplicating them across every query head.
This shrinks the KV Cache by 4\times or 8\times, allowing the model to handle much longer contexts without running out of GPU VRAM, while preserving accuracy much better than MQA.
Rosetta Stone
| Kitten World | Math/Concept | Engineering Impact |
|---|---|---|
| “Save the scent on the post” | KV Cache | Trades GPU Memory (VRAM) to save Compute (FLOPs). |
| “Rotate the token’s vector” | RoPE | Allows the model to understand token order and relative distance. |
| “Lightning fast SRAM math” | FlashAttention | Reduces HBM/SRAM memory traffic and intermediate memory overhead. |
| “Kittens share the memory” | Grouped Query Attention | Massively reduces VRAM usage for long contexts. |
12.6 [Advanced Track] Mixture of Experts (MoE): The Stadium Sleeps
Safe to skim on first pass; not required for checkpoints.
If you have a 100-billion-parameter model, running every single parameter for every single token costs an enormous amount of compute.
Do all parameters need to activate for every token? No.
Enter Mixture of Experts (MoE) (Fedus et al., 2022). Instead of one massive, dense feedforward network per layer, each layer contains multiple smaller “Expert” sub-networks (e.g., 8 experts). When a token enters a layer, a learned Router Network inspects that token’s hidden state and selects the top-k experts (for example, Expert 2 and Expert 5) while skipping the rest. Crucially, the router does not classify prompts by human labels like “history” or “Python”—routing weights are learned automatically per-token and per-layer during training.
If a model has 50 billion total parameters but activates only 2 experts per token, it might spend only ~12 billion parameters of compute per token—running much faster than a 50B dense model. However, all experts’ weights still have to reside in GPU VRAM/HBM (or be sharded across GPUs), so MoE saves compute (FLOPs), not total parameter memory.
Micro-notebook (optional): micro-notebooks/phase03_ch12_prefill_decode_timing.ipynb
Time: ~15 minutes. Goal: simulate prefill vs decode compute patterns and compare toy latency trends.
12.7 Removing the Training Wheels
The Real Engineering
We talked about scratching posts and sleeping experts. In a modern LLM serving engine, the KV Cache explicitly stores the computed Key and Value tensors for all past tokens to prevent O(N^3) redundant recomputation during autoregressive decode. RoPE uses complex number arithmetic to inject relative positional information into the Attention score. Mixture of Experts (MoE) uses a learned per-token, per-layer routing gate to activate only the top-k expert MLPs per token, saving massive amounts of compute (FLOPs)—though all experts must still fit in VRAM.
12.8 Paws and Reflect: Chapter Quiz
Work through these conceptually before checking the answers.
Your LLM reads a 5,000-token document almost instantly, but takes 30 seconds to write a 100-token summary. Why is there a speed difference?
You try to generate a very long story, but your code crashes with an “Out of Memory” (OOM) error on the GPU, even though the model weights themselves easily fit in VRAM. What filled up the memory?
How does Grouped Query Attention (GQA) fix the issue in question 2?
True or False: In a Mixture of Experts (MoE) model with 8 experts, all 8 experts process every token, and then they vote on the best answer.
Reveal answers
- Reading the document happens in the Prefill Phase (parallel, fast). Writing the summary happens in the Decode Phase (autoregressive, one token at a time, slow).
- The KV Cache! As the sequence grows, the model stores Key and Value vectors for every generated token across every layer until VRAM overflows.
- GQA shares one Key/Value head across a group of Query heads in each layer, shrinking the KV Cache by the group factor.
- False! That is an Ensemble (like a Random Forest from Chapter 5). In MoE, the per-token router skips the unselected experts to save compute (FLOPs).
12.9 Chapter 12 Summary
You’ve learned the engineering hacks required to run massive Language Models:
- Prefill vs. Decode: The difference between quickly reading a prompt in parallel and slowly generating an answer token-by-token.
- The KV Cache: Saving previously computed Keys and Values in GPU VRAM/HBM to avoid recomputing the entire prefix for every generated token.
- RoPE (Rotary Position Embeddings): Using trigonometry to rotate Query and Key vectors so Attention captures token order and relative distance.
- FlashAttention: Reducing HBM/SRAM memory traffic and intermediate attention memory overhead by tiling computations in fast SRAM.
- Grouped Query Attention (GQA): Having groups of Query heads in each layer share a KV head, shrinking the KV Cache for long contexts.
- Mixture of Experts (MoE): Using a learned per-token, per-layer router to activate only a subset of experts per token, cutting active compute (FLOPs) while still requiring VRAM for all expert weights.
AI Safety Thread: Chapter 12
The “Lost in the Middle” Phenomenon: In Chapter 12, we learned how the KV Cache and RoPE allow models to read massive 100,000-token documents. But there is a dangerous architectural quirk in the Attention Mechanism.
Researchers discovered that if you hide a specific fact (or a crucial safety constraint) in the exact middle of a massive prompt, the Attention Mechanism can underweight it. Models often over-index on the very first few paragraphs and the very last few paragraphs, skimming the middle just like a lazy human reader. If your company’s AI safety guardrails (“Do not generate harmful code”) are buried in the middle of a massive system prompt, the LLM might forget them and comply with a malicious user’s request at the end of the prompt. Massive context windows are not a silver bullet for safety.