Modern AI & LLMs Guide 3 of 7 · tap to switch
Transformer Architecture & KV Cache
Step inside the complete blueprint powering GPT, Claude, and Gemini: Pre-Norm blocks, RoPE positional encoding, Encoder vs. Decoder families, and KV Caching.
When you open the famous 2017 paper “Attention Is All You Need”, the architecture diagram can look like a spaceship wiring schematic. Yet peel away the jargon, and a modern Transformer (powering ChatGPT, Claude, Gemini, and Llama) is just one clean Lego block stacked 32 to 96 times tall.
Think of each block as a two-desk assembly line that every word in your sentence passes through:
- Desk 1, the Group Meeting: Words compare notes with each other across the sentence so an ambiguous word like “bank” picks up clues from neighbors like “river” or “flooded”. The official name for this desk is Self-Attention, and it is the only place in the block where different words talk to each other.
- Desk 2, the Private Thinking Booth: Each word steps away alone into a mini neural network to digest those clues and pull up factual knowledge stored in the model’s learned weights. The official name is the Feed-Forward Network, or MLP (modern models often use a gated style called SwiGLU).
To stack dozens of these blocks without losing the plot, every block adds two simple safety rails:
- Steady Signal Volume (Pre-Norm / RMSNorm): Before entering either desk, the model gently levels each word’s numbers so signals never blow up or fade away. Doing this before each desk is called Pre-Norm, commonly implemented with RMSNorm.
- Keep Your Original Notes (
+Skip Highway): Instead of erasing a word’s old meaning and rewriting it from scratch, each desk simply adds its new insight onto a clean copy of the original notes. That bypass lane is called a Residual Skip Connection.
Step through all 4 stages inside one modern Transformer block below and watch what happens to the word "bank" as it moves through the assembly line.
Solving Attention’s blind spot: Positional Encoding & RoPE
Pop quiz: "Dog bites man" and "Man bites dog" contain the exact same three words, yet tell opposite news stories!
Because Self-Attention compares every word against every other word all at once without reading left to right, it has a surprising blind spot: it sees an unordered bag of words. Pouring the words {bites, dog, man} onto a table loses who came first and who came last.
The fix is simple: before words compare notes, stamp every seat in the sentence with a unique position signal (like giving each word its own clock-hand angle or rhythmic wave signature). Early Transformers added smooth wave patterns directly onto each word’s numbers, called Positional Encoding. Modern models like Llama, Gemma, and Mistral instead rotate each word’s matching vectors like hands on a clock, called RoPE (Rotary Position Embedding), so the angle gap between any two words immediately tells the model how far apart they sit.
Start with Position Info: OFF below and click Swap Words to catch the bag-of-words bug in action, then turn Position Info: ON to watch position stamps fix it!
One blueprint, three famous families: BERT vs. T5 vs. GPT/Gemini
Since 2017, engineers split this single Transformer blueprint into three famous families based on one simple choice: which words is each word allowed to look at?
- The Reader (Encoder-Only, e.g., BERT): Every word looks both left and right across the whole sentence at once, making it ideal for understanding meaning in semantic search, review classification, and tagging key facts.
- The Translator (Encoder-Decoder, e.g., T5, Whisper): First reads the entire input in both directions (like an English sentence or an audio clip), then uses a second stack to write out the converted answer word by word (like French text or a transcript).
- The Writer (Decoder-Only, e.g., GPT, Claude, Gemini, Llama): Each word can only look backward at earlier words (never peeking ahead), predicting the next word one at a time. Turning almost any task into next-word prediction let this clean, uniform stack win general-purpose AI!
Click each family below to see how its attention arrows flow across words.
What Is KV Cache? Fixing O(N²) Transformer Memory
Imagine writing a report on a 500-page book. If you threw away all your notes after writing every single word and had to re-read all 500 pages from page 1 just to write the next word, finishing one paragraph would take hours!
That is the exact trap a naive Transformer falls into. When a model reads N words and compares every word with every other word, the number of word pairs grows like N × N (O(N²)). On a 32,000-word prompt, that is over 1 billion comparisons!
Here is the clever shortcut: in a Writer (Decoder-Only) model, earlier words never peek ahead at future words. That means the summary notes for page 1 through page 500 never change once you read them! Instead of re-reading the entire conversation for every new word, the model keeps sticky-note summaries of every past word on its desk. Writing a new word then only takes 1 × N work (O(N)): compare your 1 brand-new word against the N saved sticky notes.
In ML terms, this two-phase trick has three names:
- Prefill (
O(N²)): Reading your entire pasted prompt once up front to build those first sticky notes (this is why a huge prompt pauses briefly before the first word appears). - KV Cache: The memory shelf in GPU RAM that stores each past word’s saved Key (
K) and Value (V) sticky-note vectors. - Decode (
O(N)per word): Streaming the reply one new word at a time by computing just 1 new Query vector and looking up the saved KV Cache. On long conversations, this speeds up typing by over 100×, trading a few gigabytes of GPU memory for silky-smooth real-time speed.
Start with KV Cache: OFF below to see the re-reading bottleneck across short chats and full books, then flip KV Cache: ON to watch sticky notes slash per-word wait time!
See Pre-Norm Residual Blocks, Sinusoidal Waves & Rotary Position Embeddings (RoPE)Thesis / Reference
1. Modern Pre-Norm Decoder Block (Xiong et al., 2020; Touvron et al., 2023): Given hidden state matrix , each layer updates the clean residual stream via:
After blocks, a final normalization and unembedding projection produces next-token logits across the full vocabulary.
2. Sinusoidal Positional Encoding (Vaswani et al., 2017) vs. RoPE (Su et al., 2021): Vaswani et al. added multi-frequency waves and to input embeddings. Modern frontier LLMs instead apply Rotary Position Embeddings (RoPE), rotating each 2D pair of Query/Key coordinates by angle so their inner product depends exclusively on relative token distance :
3. Scaling Laws & MoE (Kaplan et al., 2020; Hoffmann et al., 2022): Chinchilla scaling laws showed compute-optimal pretraining balances model parameters and training tokens roughly at . Frontier models further scale total knowledge capacity without inflating per-token FLOPs using Mixture-of-Experts (MoE), routing each token through only 2 to 8 active MLP experts out of 64 to 128 total experts!
See a Complete Pre-Norm Transformer Block in 15 Lines of PyTorchOptional Code
import torch.nn as nn
import torch.nn.functional as F
class TransformerBlock(nn.Module):
def __init__(self, d_model=512, n_heads=8):
super().__init__()
self.norm1 = nn.RMSNorm(d_model)
self.attn = nn.MultiheadAttention(d_model, n_heads, batch_first=True)
self.norm2 = nn.RMSNorm(d_model)
self.mlp = nn.Sequential(
nn.Linear(d_model, 4 * d_model),
nn.GELU(),
nn.Linear(4 * d_model, d_model),
)
def forward(self, x, causal_mask):
h = self.norm1(x)
x = x + self.attn(h, h, h, attn_mask=causal_mask, is_causal=True)[0]
x = x + self.mlp(self.norm2(x))
return xSo the final Transformer layer spits out 100,000 scores: now what?
You now understand the entire internal engine, from raw text all the way to the final next-word probability scores! Yet ask the exact same prompt twice and an LLM writes two subtly different replies. How do Temperature, Top-K, and Top-P turn those final scores into creative writing, crisp code, or accidental hallucinations?
Next up: How LLMs Generate Text (Temperature, Top-K & Top-P).
Quick Intuition Check
Four quick real-world scenarios. No scores, just test your intuition.
Inside a single Transformer block, how do Self-Attention and the Feed-Forward MLP divide the work?
What happens if you remove Positional Encoding (and RoPE) from a bare Self-Attention layer and feed it 'Dog bites man' vs. 'Man bites dog'?
Why does turning on the KV Cache speed up word-by-word LLM generation by over 100x on long conversations?
A Reader (Encoder-Only) Transformer like BERT lets every word look both left and right at the same time, making it ideal for semantic search and classification rather than streaming open-ended chat replies.
Common Questions
What is KV Cache in an LLM and how does it work?
What is KV cache quantization and why does it matter?
How does a Transformer block work in simple terms?
Why do Transformers need Positional Encoding or RoPE?
What is the difference between BERT, T5, and GPT/Claude/Gemini?
What is a KV Cache in LLM inference?
Why are long context windows (like 128K or 1M tokens) expensive?
Related Visual Guides
Self-Attention & the Attention Mechanism
Understand the exact spotlight powering modern AI: Query, Key, Value dot products, sqrt(d_k) scaling, Multi-Head Attention, and Causal Masks.
LLM Temperature, Top-K & Top-P Sampling
See how next-token prediction turns logits into fluent prose, why Temperature reshapes probabilities, why Top-P beats Top-K, and why hallucinations happen.
Convolutional Neural Networks (CNNs)
See how sliding 3x3 magnifying filters, stride, padding, and pooling let neural networks recognize visual patterns anywhere in an image.
Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference
Cite this guide in a paper, thesis, or course (BibTeX & APA)
@misc{irshad2026transformers,
author = {Irshad, Muhammad Aashir},
title = {Transformer Architecture & KV Cache: Interactive Visual Guide},
howpublished = {SeeingML},
year = {2026},
month = {dec},
url = {https://seeingml.com/learn/transformers/},
note = {Interactive visual guide}
} Irshad, M. A. (2026). Transformer Architecture & KV Cache: Interactive Visual Guide. SeeingML. https://seeingml.com/learn/transformers/