Why Transformers Changed Everything

Before transformers (2017), sequence models processed tokens one at a time. Transformers process them all at once.

Before: RNNs / LSTMs

w1
->
w2
->
w3
->
...

Sequential: must finish word 1 before starting word 2. Long-range dependencies fade as the chain grows. Training is slow — can't parallelize.

After: Transformers

w1
w2
w3
w4

Parallel: every token can attend to every other token simultaneously. Long-range dependencies are direct. Training is massively parallel on GPUs.

The breakthrough was both algorithmic (attention replaces recurrence) and practical (scales to modern hardware). This is why every major LLM — GPT, Claude, LLaMA, Gemini — is built on transformers.


Inside a Transformer Block

Every transformer is a stack of identical blocks. Each block has two main stages: self-attention (mix information across tokens) and feed-forward (transform each token independently).

Input Embeddings + Position
|
Repeated N times (6-96 layers)
Multi-Head Self-Attention
|
Add & Layer Norm
skip
|
Feed-Forward Network (FFN)
|
Add & Layer Norm
skip
|
Linear (hidden -> vocab size)
|
Softmax -> probabilities

What each component does:

Multi-Head Self-Attention — Each token looks at all other tokens and decides which ones are relevant. "Who should I pay attention to?" Multiple heads let it look for different types of relationships simultaneously.
Add & Layer Norm — The residual connection (Add) lets the original signal pass through unchanged, so each layer only needs to learn a small refinement. Layer Norm stabilizes the numbers to prevent them from exploding or vanishing.
Feed-Forward Network — A simple two-layer neural network applied to each token independently. This is where individual token representations get transformed. Typically expands to 4x the model dimension, then contracts back. Uses GELU or SwiGLU activation.
Linear + Softmax (output head) — After the final layer, a linear projection maps each token's hidden state (e.g., 4096-dim) to the vocabulary size (e.g., 128,256-dim) — one score per possible next token. Softmax converts these scores into probabilities. In many models, this linear layer shares weights with the input embedding table ("weight tying").
Residual skip connections — The yellow lines in the diagram show the input bypassing each sublayer and being added back at the Add & Norm step. This means the sublayer only needs to learn a delta (refinement), not a complete transformation. Without these, deep networks (80+ layers) can't train — gradients vanish.
Stacking — GPT-2 has 12-48 layers. LLaMA 3 70B has 80 layers. Each layer refines the representation — early layers handle syntax, later layers handle semantics and reasoning.

End-to-End: Watch Vectors Flow Through a Tiny LLM

A 2-layer, 2-head transformer with 8-dimensional vectors. Step through each stage from raw text to predicted next token — every number is real and traceable.


Self-Attention: The Core Mechanism

The single idea that makes transformers work. Best understood through a concrete example.

The problem attention solves

Consider this sentence:

The bank was steep and covered in mud

The word "bank" is ambiguous — financial institution or riverbank? The token embedding for "bank" is the same either way (it's just a lookup table). So how does the model figure out which meaning is intended?

Answer: it looks at the other words. "steep" and "mud" are strong signals for riverbank. "closed" and "account" would signal financial. Attention is the mechanism that lets "bank" look at every other token and absorb the relevant context.

The core idea in one sentence: Each token creates a search query ("what context do I need?"), every other token advertises what it has, the best matches share their information. That's attention.

Q, K, V: The library analogy

Think of attention as a library search. Every token plays two roles simultaneously: it's both a visitor searching for books and a book on the shelf.

Query (Q)

"What am I searching for?"

The visitor's search request. "bank" might generate a query that means "I'm an ambiguous noun — I need context about my environment."

Computed as: Q = token_state * W_Q
A learned projection that extracts "what I need" from each token's current state.

Key (K)

"What's written on my spine?"

The book's label/title. "steep" generates a key that says "I'm an adjective describing physical terrain." The search engine matches queries to keys.

Computed as: K = token_state * W_K
A learned projection that extracts "what I have to offer" from each token.

Value (V)

"Here's the book's actual content."

The full content of the book. Once "bank" finds that "steep" is relevant, it reads the value of "steep" to absorb its meaning. Keys are for matching; values are for reading.

Computed as: V = token_state * W_V
A learned projection that extracts "the content I share" from each token.
Why separate Key from Value? Because what makes a book findable (its title/tags) is different from what you learn by reading it (its content). A book titled "Geography" (Key) might contain detailed information about river formations (Value). The Key helps you find it; the Value is what you take away.

Interactive: Follow "bank" through attention

Click each step to see how "bank" resolves its ambiguity by attending to other tokens.

Where do Q, K, V come from?

Every token produces all three — Q, K, and V — by multiplying its embedding by three different learned weight matrices. Same input, three different projections, three different roles:

"bank"
token embedding
× WQ
Qbank — "what am I looking for?" This token's search query. Used to find relevant context.
× WK
Kbank — "what do I advertise?" How other tokens find me. Matched against their Q's.
× WV
Vbank — "what content do I share?" The actual information read when someone attends to me.
Every token produces all three. But during generation they play different roles — here's how attention works for the sentence "The cat sat on":
How Q, K, V interact during generation

When generating "on" (the current token), the model needs to decide what context is relevant. Q comes from the current token. K and V come from all previous tokens (including the current one):

Qon
current token
×
KThe
VThe
10%
Kcat
Vcat
30%
Ksat
Vsat
50%
Kon
Von
10%
=
outputon
mostly Vsat
Qon · Ksat scores highest (50%) → "on" reads mostly from Vsat. The output is a weighted mix of all V's, dominated by "sat"'s content.
Q = current token only
Each token generates its own Q to ask its own question. Q is used once for this token's attention computation, then discarded. This is why Q is not cached.
K, V = all previous tokens (cached)
Every future token will need to attend back to this token's K and V. So they're stored in the KV cache and reused — never recomputed. This is the key optimization for fast generation.

The formula (now that you have the intuition)

Attention(Q, K, V) = softmax( Q * K^T / sqrt(d_k) ) * V
Q * K^T — Each token's Q is dot-producted with every other token's K. High score = relevant match. This produces an [n × n] score matrix.
/ sqrt(d_k) — Scale down so no single match dominates. Without this, large dot products push softmax to a one-hot distribution. In GPT-2, d_k=64, so we divide by 8.
softmax — Turn scores into weights that sum to 100%. "bank" might put 40% on "steep", 25% on "mud", 15% on itself.
* V — Weighted sum of V vectors. "bank" absorbs 40% of Vsteep + 25% of Vmud + ... The output is "bank" infused with riverbank context.

This shows bidirectional attention (as in BERT-style encoder models). In causal/decoder models (GPT, Claude), tokens can only attend to previous tokens — the upper-right triangle would be masked to zero.


Multi-Head Attention

One attention head can only focus on one type of relationship at a time. Multiple heads let the model look for many patterns simultaneously.

How it works

Instead of one big attention computation, the model splits the embedding into h smaller pieces (heads), runs attention on each independently, then concatenates the results. By convention, d_head = d_model / n_heads so the concat reconstructs the full dimension — but this is a design choice, not a hard requirement.

MultiHead(Q, K, V) = Concat(head_1, ..., head_h) * W_O

where head_i = Attention(Q * W_Qi, K * W_Ki, V * W_Vi)

Each head has its own learned W_Q, W_K, W_V projection matrices, so each head learns to look for different things. Researchers have identified specific head types like induction heads (pattern completion) and copy suppression heads (preventing repetition). See section 10 for the full picture with interactive examples.

WO is the output projection — a learned matrix [d_model × d_model] applied after concatenating all heads. It mixes information across heads, letting the model combine what different heads found. Without WO, heads couldn't share their findings.

Head dimensions across real models

Q headsNumber of query heads — each generates its own Q vector. More heads = more parallel attention patterns. KV headsNumber of key/value heads. In standard MHA, KV heads = Q heads. In GQA, fewer KV heads are shared across groups of Q heads to save memory. d_modelThe model dimension — width of the embedding vector throughout the network. d_headDimensions per head — each head operates on a d_head-sized slice. Q heads × d_head = d_model.
ModelQ headsKV headsd_modeld_head
GPT-2 Small121276864
GPT-2 XL2525160064
LLaMA 3 8B328 (GQA)4096128
LLaMA 3 70B648 (GQA)8192128

Key relationship: Q heads × d_head = d_model always (e.g., 32 × 128 = 4096). In GQA models, KV heads < Q heads — each KV head is shared by a group of Q heads (e.g., 32 Q heads ÷ 8 KV heads = groups of 4), reducing KV cache size by 4×.


Residual Connections & Layer Norm

The unsung heroes that make deep transformers (80+ layers) trainable at all.

Residual Connections

output = LayerNorm(x + SubLayer(x))
LayerNorm(x) = (x - mean) / std_dev * γ + β

LayerNorm subtracts the mean and divides by standard deviation per vector (not per batch), then applies learned scale (γ) and shift (β) parameters. This keeps values in a stable range so deep layers don't explode or collapse.

The residual connection (Add) lets the original signal pass through unchanged, so each layer only needs to learn a small refinement:

1. Gradients flow directly through the residual path (no vanishing)
2. Each layer only needs to learn a small refinement, not a complete transformation
3. You can stack 100+ layers without the signal degrading

Pre-LN vs Post-LN

Post-LN (original)
LN(x + Attn(x))
Normalize after adding. Used in original Transformer. Can be unstable in very deep models — needs careful warmup.
Pre-LN (modern)
x + Attn(LN(x))
Normalize before the sublayer. Much more stable training. Used by GPT-2+, LLaMA, and most modern LLMs.

RMSNorm (Root Mean Square Layer Norm) is a simplified variant used by LLaMA and Mistral — it only normalizes the scale, not the mean, making it ~10-15% faster.


Positional Encoding

Attention is permutation-invariant — "dog bites man" and "man bites dog" look the same without position info. Positional encoding fixes this.

Sinusoidal (original Transformer)

PE(pos, 2i) = sin(pos / 10000^(2i/d))
PE(pos, 2i+1) = cos(pos / 10000^(2i/d))

Fixed, deterministic waves at different frequencies. Each position gets a unique pattern. Can generalize to unseen sequence lengths because sin/cos are continuous functions.

Applied: once, before layer 1. Added per-dimension to the token embedding (same shape: 768 or 4096 dims).

Used by: Original Transformer (Vaswani et al., 2017)

Learned Embeddings

Just add a learnable vector for each position. The model discovers the best position representation during training. Simple but limited to the maximum training sequence length.

output = token_embed + position_embed[pos]

Applied: once, before layer 1. Added per-dimension, same shape as token embedding.

Used by: GPT-2, BERT

RoPE (Rotary Position Embeddings)

Instead of adding position info to the embeddings, RoPE rotates pairs of dimensions in the Q and K vectors based on their position.

Concrete example: How rotation encodes position

Take dimensions d0 and d1 of a Q vector. RoPE treats them as a 2D point and rotates by an angle that depends on the token's position:

q'_d0 = q_d0 × cos(θ) - q_d1 × sin(θ)
q'_d1 = q_d0 × sin(θ) + q_d1 × cos(θ)

where θ = position / 10000^(2i/d)

Say Q has d0=0.5, d1=0.3 at position 5 with θ=0.5 radians:

Before rotation
d0=0.50, d1=0.30
→ rotate 0.5 rad →
After rotation
d0=0.29, d1=0.50

The magic: When Q at position 5 dot-products with K at position 3, the rotation angles partially cancel — the dot product depends only on the difference (5-3=2), not the absolute positions. Two tokens 2 apart always interact the same way, whether they're at positions 5,3 or 100,98.

Each dimension pair rotates at a different frequency (the circles above): low dims rotate fast (fine position detail), high dims rotate slowly (coarse position). Like a clock with second, minute, and hour hands.

Applied: at every layer, inside attention. Rotates dimension pairs (d0-d1, d2-d3, ...) in Q and K before the dot product. Does NOT touch V or the input embedding.

Used by: LLaMA, Mistral, Gemma, most modern LLMs

ALiBi (Attention with Linear Biases)

Doesn't modify embeddings or Q/K vectors at all. Instead, adds a scalar penalty to the attention score based on distance: farther tokens get lower scores. Each head uses a different decay rate.

score(i,j) = q_i * k_j - m * |i - j|

Extremely simple and extrapolates well to longer sequences than seen during training.

Applied: at every layer, as a bias on attention scores. No modification to embeddings or Q/K/V vectors — just a distance penalty added after Q*K^T.

Used by: BLOOM, MPT

Where does each method inject position info?

MethodWhat it modifiesWhenGranularity
SinusoidalInput embeddingOnce (before layer 1)Per dimension (sin/cos wave per dim pair)
LearnedInput embeddingOnce (before layer 1)Per dimension (learned value per dim)
RoPEQ and K vectorsEvery layer (inside attention)Per dimension pair (rotates d0-d1, d2-d3, ...)
ALiBiAttention scoresEvery layer (after Q*K^T)Per token pair (scalar bias by distance)

Interactive: How sinusoidal PE gets added to a token

The token embedding is a vector of numbers. The positional encoding is another vector of the same size. They get added element-wise. Drag the position slider to see how the PE changes — the token stays the same, but the result shifts.

3

Showing first 16 of 64 dimensions. Bar heights represent values. Notice how changing the position shifts the green PE bars (especially the low-frequency left side stays similar for nearby positions) while the blue token embedding stays constant.

Positional encoding visualizations

-1
+1 Blue = negative  |  Dark = near zero  |  Red/orange = positive

Each row is a position (0-39), each column is a dimension. Colors show the sin/cos values — lower dimensions (left) change slowly, higher dimensions (right) change rapidly.


Architectures & Modern Variants

The attention mask controls the architecture. Causal masking → decoder (generation). Bidirectional → encoder (understanding). Plus modern efficiency variants.

Bidirectional (Encoder models)

Every token can attend to every other token — past AND future. The model sees the full context. Used for understanding tasks: classification, NER, retrieval.

Models: BERT, RoBERTa, DeBERTa

Causal / Autoregressive (Decoder models)

Each token can only attend to itself and previous tokens — never the future. The model generates autoregressively: one token at a time, feeding each output back as input for the next step ("The" → "The cat" → "The cat sat" → ...). Auto (self) + regressive (predicting from prior values).

Models: GPT, Claude, LLaMA, Mistral

Encoder-Only

Attention pattern:
The
[MASK]
sat
<-- every token sees every other -->
bidirectional
|
Predict: "cat"

Every token attends to every other token — past AND future. Produces rich representations but can't generate text autoregressively.

Example: Sentiment Classification
In: "The movie was absolutely brilliant"
Out: positive (0.97)
Example: Named Entity Recognition
In: "Tim Cook announced the new iPhone in Cupertino"
Out: [Tim Cook]PERSON  [iPhone]PRODUCT  [Cupertino]LOC
Best for: classification, search, NER, retrieval
Models: BERT, RoBERTa, DeBERTa
Trains by: Masked Language Modeling

Decoder-Only most LLMs today

Attention pattern:
The
cat
sat
each token sees only itself + past -->
causal (left-to-right)
|
Predict next: "on"

Each token can only see tokens before it (causal mask). Generates text one token at a time. This is how ChatGPT, Claude, etc. work.

Example: Chat Completion
In: "Explain quantum entanglement simply"
Out: "Imagine two coins that always land on opposite sides..."
Example: Code Generation
In: "def fibonacci(n):"
Out: "if n <= 1: return n\n return fibonacci(n-1) + ..."
Best for: chat, code, creative writing, reasoning
Models: GPT, Claude, LLaMA, Mistral
Trains by: Next Token Prediction

Encoder-Decoder

Two-stage architecture:
Encoder
bidirectional
--cross-attn-->
Decoder
causal
reads input fully | generates output
|
"Hello" -> "Bonjour"

Encoder reads the full input bidirectionally. Decoder generates output autoregressively but can also attend to the encoder's output via cross-attention — a second attention where Q comes from the decoder but K,V come from the encoder.

Example: Translation
In: "The weather is beautiful today"
Out: "Le temps est magnifique aujourd'hui"
Example: Summarization
In: "Scientists at CERN have discovered a new particle that..." (500 words)
Out: "CERN discovers new subatomic particle confirming..."
Best for: translation, summarization, structured tasks
Models: T5, BART, mBART, Flan-T5
Trains by: Seq2Seq (text-to-text)

Multi-Query Attention (MQA)

All heads share the same K and V projections. Only Q differs per head. Cuts KV cache by ~Nx (where N = number of heads).

Used by: PaLM, Falcon

Grouped-Query Attention (GQA)

A middle ground: heads are divided into groups, and each group shares K and V. Better quality than MQA, smaller cache than full MHA.

Used by: LLaMA 2/3, Mistral, Gemma 2+ — the modern default

Sliding Window Attention

Each token only attends to the last W tokens (e.g., 4096). Reduces O(n^2) to O(n*W). Information still flows across the full sequence through stacked layers.

Used by: Mistral 7B (W=4096)

Flash Attention is not an attention variant — it's a faster implementation of the same math. It reorders the computation to minimize GPU memory reads/writes (IO-aware), running 2-4x faster with much less memory. Supported by PyTorch (built-in since 2.0), HuggingFace, vLLM, TensorRT-LLM, and DeepSpeed.

Interactive: How Q and KV heads connect

Toggle between MHA, GQA, and MQA to see how query heads map to key/value heads. Each Q head needs a K,V pair — the question is whether each Q gets its own K,V or shares.

Mixture of Experts (MoE)

Not an attention variant, but a transformer scaling trick. Replace the single FFN with multiple "expert" FFNs. A router network picks the top-k experts (usually 2) per token. The model has many more parameters but only activates a fraction for each token — better quality at lower compute cost.

Used by: Mixtral (8x7B = 46.7B params, 12.9B active), GPT-4 (rumored), Switch Transformer


Efficiency: KV Cache & Cost

The optimizations that make long-context inference practical — and why they're necessary.

Interactive: Step through generation with KV Cache

Click Generate next token to watch the KV cache grow as the model generates "The cat sat on." At each step, see exactly what gets computed vs reused.

The trade-off: KV cache saves massive compute but costs memory. For LLaMA 2 70B (80 layers, GQA with 8 KV heads, fp16) at 128k context, the KV cache consumes ~40 GB per request. Full MHA (64 KV heads) would require ~320 GB — an 8x blowup. This is why techniques like GQA, MQA, and quantized KV caches are essential.

Attention complexity: O(n^2 * d)

Compute and memory grow quadratically with sequence length. Doubling context from 4k to 8k roughly quadruples attention cost.

Sequence LengthAttention FLOPs (relative)KV Cache (70B, 8 KV heads, fp16)Real-world note
2,0481x~0.6 GBGPT-3 original context
4,0964x~1.2 GBLLaMA 2 default
32,768256x~10 GBMany current models
128,0003,900x~39 GBGPT-4 Turbo, Claude
1,000,000238,000x~305 GBGemini 1.5 Pro

What Do Heads & Neurons Actually Learn?

Mechanistic interpretability: reverse-engineering the circuits inside transformers to understand why they produce specific outputs.

Attention heads specialize

Not all attention heads do the same thing. During training, heads develop distinct roles — some track syntax, some copy tokens, some suppress predictions. Researchers have identified several recurring head types:

Previous Token Heads

Always attend to position i-1. They feed the "what came right before" signal to downstream layers. Found in early layers.

Induction Heads

Pattern-match: if [A][B] appeared before, and [A] appears again, predict [B]. The core mechanism behind in-context learning. Found in mid layers. (Olsson et al., 2022)

Duplicate Token Heads

Detect when the same token has appeared earlier in context. They signal "I've seen this before" to help the model track references and repetition.

Copy Suppression Heads

When an upstream layer naively predicts a token, these heads attend to where that token appeared and write an opposing signal to suppress the prediction. They prevent the model from blindly copying. (e.g., GPT-2 L10H7)

Interactive: See what each head type looks like

Click a head type to see its idealized attention pattern on a sample sentence. These are illustrative patterns showing the characteristic shape of each head type, not outputs from a specific model. The heatmap shows how much each token (row) attends to every other token (column). Bright = high attention.

Interactive: Induction head in action

An induction head learns the pattern: "if [A][B] appeared before, and [A] appears again, predict [B]." Click tokens in the sequence to see which earlier tokens the induction head attends to and why.

Neurons, superposition & polysemanticity

Individual neurons are hard to interpret because of superposition: models pack more concepts than they have dimensions, so a single neuron activates (produces a high output value after the activation function, e.g., GELU or SwiGLU) for multiple unrelated things (polysemanticity). A neuron might activate for both "dog photos" and "the concept of democracy."

The problem: polysemantic neurons

A single neuron might activate for:
dogs
democracy
rivers
jazz
One neuron, many unrelated meanings

One neuron activates for multiple unrelated concepts. You can't point to a single neuron and say "this represents X." The model stores ~100x more features than it has dimensions.

The solution: sparse autoencoders

SAE features (sparse — most are zero):
Golden Gate
travel
bridges
Sparse: 3 of 8 features active, each interpretable

SAEs decompose activations into a sparse, interpretable basis. Anthropic extracted 34M interpretable features from Claude 3 Sonnet — 70% rated genuinely interpretable by humans. (Anthropic, 2024)

How SAEs work

Encode: z = ReLU(W_enc · h + b)   (sparse bottleneck)
Decode: ĥ = W_dec · z   (reconstruction)
Loss: ||h - ĥ||² + λ · ||z||₁   (reconstruct + encourage sparsity)

The key insight: z is sparse — only a few features activate for any given input. Each active feature corresponds to one interpretable concept (a language, a topic, an entity, a syntactic role). Features are multimodal and multilingual: the "Golden Gate Bridge" feature activates for English text, Japanese text, and images of the bridge.

Circuits: how heads & neurons compose

Heads and neurons don't work alone — they form circuits through the residual stream. Information flows: head writes to residual → neuron reads from residual → next head reads the updated residual. Researchers have mapped complete circuits for specific tasks:

Interactive: Indirect Object Identification (IOI) circuit

Given "Mary and John went to the store. Mary gave a book to ___", the model should predict "John." This requires tracking who is who and who already acted. Click the circuit stages to see how information flows:

Why this matters: Understanding circuits lets researchers steer model behavior. By clamping or amplifying specific SAE features during inference, you can increase truthfulness, reduce toxicity, or suppress sycophancy — more targeted than RLHF. This is a core technique for AI safety research.


Transformer Failure Modes

Understanding what can go wrong helps you design better systems around the model.

Attention Dilution

On very long contexts, attention weights spread thin across thousands of tokens. Important tokens may receive too little weight. This is why "lost in the middle" is a real phenomenon — models often perform worse on information placed in the middle of long prompts.

Positional Degradation

Models trained on shorter sequences may perform poorly when extended to longer ones, even with position encoding extrapolation. RoPE NTK-scaling and YaRN help but don't fully solve this.

Hallucination

The model generates plausible-sounding but factually wrong content. This is partly because the training objective (predict next token) rewards fluency, not factual accuracy. RAG and grounding help mitigate this.

Decoding Instability

Temperature, top-k, and top-p settings can dramatically change output quality. Too high = incoherent. Too low = repetitive. The model itself is deterministic; the randomness is in the sampling strategy.