Level 3 In-Depth AI · Transformers and Language Models
The Transformer
The architecture behind every modern language model. A stack of identical blocks, each letting tokens exchange information through attention and then process it with a small neural network, held together by residual connections and layer normalisation.
- Level
- ●●●●● Intermediate
- Reading
- 12 min
- To learn it well
- 1.5 hours to read, an afternoon to practise
- Builds on
- 27 concepts →
- Quiz
- 5 questions ↓
Read first
Self-Attention and Multi-Head AttentionPositional EncodingsResidual ConnectionsNormalization Layers: BatchNorm and LayerNormThe full path from zero — 27 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Dot Product, Norms and Similarity
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Recurrent Neural Networks
- Backpropagation
- Activation Functions
- Vanishing and Exploding Gradients
- Normalization Layers: BatchNorm and LayerNorm
- LSTMs and GRUs
- Residual Connections
- Sequence-to-Sequence Models
- Attention
- Self-Attention and Multi-Head Attention
- Positional Encodings
- The Transformer
Read them roughly in this order. See it on the concept map →
Why it matters
In June 2017 eight researchers at Google published Attention Is All You Need, introducing an architecture for machine translation they called the Transformer. Within five years it had taken over almost all of AI. GPT-4, Claude, Gemini and Llama are Transformers. So are BERT and the search-ranking models built on it, Whisper for speech, the Vision Transformers for images, AlphaFold 2's core, and the backbones of many image and video generators.
The surprise is how simple it is. A Transformer is the same block repeated many times. Each block does two things: let the tokens talk to each other (Self-Attention and Multi-Head Attention), then let each token think on its own (a small feed-forward network). Residual connections and normalisation keep the stack trainable. If you understand one block, you understand the architecture of a 400-billion-parameter model; the big one just has wider vectors and more blocks.
This chapter assembles the full block, traces the shape of every tensor through it, and builds a working one in PyTorch.
The intuition
Think of a team of specialists working on a document, one specialist per word, sitting round a table. The work happens in rounds:
- Meeting (attention): everyone looks around the table and gathers notes from the colleagues whose words are relevant to their own. "It" consults "animal"; "bank" consults "river" or "money".
- Desk work (feed-forward network): everyone goes back to their own desk and thinks privately about what they gathered, using a large store of general knowledge.
- Keep the notes (residual connection): nobody throws away their old notes. Each round's insights are added to a running file that every round reads and writes.
Repeat for a few dozen rounds. By the end, the specialist for the last word has a file rich enough to predict what comes next.
That running file is called the residual stream: one vector per token that flows from the bottom of the network to the top, with each block reading from it and adding to it.
Key idea A Transformer block = attention (tokens exchange information) + MLP (each token processes it), each wrapped as
x = x + f(norm(x)). Stack N blocks. The vector for each token, the residual stream, is gradually refined from "which word am I" to "what comes next".
How it works
We follow a decoder-only Transformer like GPT, the design of nearly all modern LLMs. Sizes in brackets are for GPT-2 small: width , 12 blocks, 12 heads, vocabulary . is the batch size and the number of tokens.
1. From tokens to vectors
The input is a batch of token ids, shape . Each id selects a row of a learned token embedding table of shape , and each position selects a row of a position table (or, in RoPE models, positions enter inside attention; see Positional Encodings). The two are added:
Now we have the residual stream: shape , one 768-number vector per token.
2. The block
Each block applies two sub-layers, each in the same pattern: normalise, transform, add back.
Multi-head causal self-attention (Self-Attention and Multi-Head Attention) is the only place where information moves between positions. Inside it, queries, keys and values have shape and the score table is . Its output is back to .
The MLP, or feed-forward network, is two linear layers with a nonlinearity between them, applied to each token's vector independently:
expands the vector from to numbers (768 → 3,072), the GELU activation bends it, and projects it back to . The MLP holds about two thirds of each block's parameters. Interpretability research suggests that much of a model's factual knowledge is stored here, with the first layer acting like a set of pattern detectors and the second writing the associated information back into the stream.
Residual connections (Residual Connections) are the x + .... Each sub-layer only has to compute a change to the stream, not a whole new representation. This gives gradients a direct path from the loss to the earliest layers, which is what lets models stack 100 or more blocks without the signal dying (Vanishing and Exploding Gradients).
3. Layer normalisation
Deep stacks become unstable if the size of the vectors drifts from layer to layer. Batch normalisation fixes this in CNNs by normalising each feature across the batch, but that works badly for sequences of varying length and for generating one token at a time. Layer normalisation instead normalises each token's vector on its own, across its features: subtract the vector's mean, divide by its standard deviation, then apply a learned scale and shift :
Here and are the mean and variance of the entries of , is a tiny number (like ) that prevents division by zero, and means element-by-element multiplication.
Worked example. Take . The mean is . The deviations are , so the variance is and the standard deviation is . Dividing gives : mean 0, spread 1. With and (their starting values) that is the output.
Where the normalisation goes matters. The original Transformer normalised after adding the residual (post-norm). GPT-2 and nearly every model since normalise the input to each sub-layer, as in the formulas above (pre-norm), which trains more stably and needs less learning-rate warm-up. Many recent models use RMSNorm, which skips the mean subtraction and the shift and just divides by the root-mean-square; it is slightly cheaper and works as well.
4. From vectors to predictions
After the last block comes one more layer norm, then a linear layer that turns each -vector into scores, one per vocabulary token. These raw scores are called logits, shape . A softmax over the last axis turns them into next-token probabilities. Because attention was causal, the prediction at position only used tokens , so one forward pass trains predictions at once. Many models tie this output matrix to the input embedding table, saving parameters.
Counting parameters
Per block, ignoring the small biases and norms:
| Part | Matrices | Parameters |
|---|---|---|
| Attention | , each | |
| MLP | and | |
| Block total |
For GPT-2 small, per block, about 85 million for 12 blocks. The token embeddings add million and positions million, for a total of about 124 million. The same formula gives about 175 billion for GPT-3's largest model (, 96 blocks).
Encoder, decoder, or both
The original Transformer had two stacks. The encoder read the source sentence with full (unmasked) self-attention. The decoder generated the translation with causal self-attention plus a third sub-layer, cross-attention, whose queries come from the decoder and whose keys and values come from the encoder output. Its base model had 6 encoder and 6 decoder blocks, , an MLP width of 2,048 and 8 heads, and the larger version trained in 3.5 days on eight GPUs.
Since then three families have emerged:
- Encoder-only (BERT): bidirectional attention, trained to fill in masked words. Great for classification, search and embeddings.
- Decoder-only (GPT, Claude, Llama): causal attention, trained to predict the next token. One stack does everything by treating every task as text continuation. This is the dominant design for LLMs.
- Encoder-decoder (original Transformer, T5, Whisper): best when there is a clear input to transform, as in translation or speech recognition.
Why it replaced recurrent networks
An Recurrent Neural Networks processes tokens one after another, so training on a 1,000-token sequence takes 1,000 sequential steps, and information from token 1 must survive 999 updates to reach token 1,000. The Transformer paper compared the two per layer:
| Layer type | Work per layer | Sequential steps | Longest path between two tokens |
|---|---|---|---|
| Self-attention | |||
| Recurrent |
means "grows in proportion to". Self-attention does more total work on long sequences, but all of it in parallel, which GPUs love, and any two tokens are one step apart. That parallelism is what made it possible to train on trillions of tokens, and scale turned out to matter more than anything else (Scaling Laws).
In code
A complete pre-norm Transformer block in PyTorch, the same design as GPT-2:
import torch
import torch.nn as nn
import torch.nn.functional as F
class CausalSelfAttention(nn.Module):
def __init__(self, d_model, n_heads):
super().__init__()
self.n_heads = n_heads
self.qkv = nn.Linear(d_model, 3 * d_model) # W_Q, W_K, W_V in one matrix
self.proj = nn.Linear(d_model, d_model) # W_O
def forward(self, x): # x: (B, T, d)
B, T, d = x.shape
q, k, v = self.qkv(x).split(d, dim=-1) # each (B, T, d)
# split d into heads: (B, T, d) -> (B, h, T, d/h)
q, k, v = (z.view(B, T, self.n_heads, d // self.n_heads).transpose(1, 2)
for z in (q, k, v))
y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
y = y.transpose(1, 2).reshape(B, T, d) # concatenate heads
return self.proj(y)
class Block(nn.Module):
def __init__(self, d_model, n_heads):
super().__init__()
self.ln1 = nn.LayerNorm(d_model)
self.attn = CausalSelfAttention(d_model, n_heads)
self.ln2 = nn.LayerNorm(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):
x = x + self.attn(self.ln1(x)) # tokens talk to each other
x = x + self.mlp(self.ln2(x)) # each token thinks on its own
return x
torch.manual_seed(0)
block = Block(d_model=768, n_heads=12) # GPT-2 small sizes
x = torch.randn(2, 10, 768) # batch of 2 sequences, 10 tokens each
print(block(x).shape)
print(sum(p.numel() for p in block.parameters()))
# causal check: changing the last token must not change earlier outputs
y1 = block(x); x2 = x.clone(); x2[:, -1] = 0; y2 = block(x2)
print(torch.allclose(y1[:, :-1], y2[:, :-1], atol=1e-6), torch.allclose(y1[:, -1], y2[:, -1]))
# torch.Size([2, 10, 768])
# 7087872
# True False
The block maps to , which is why blocks can be stacked. Its 7,087,872 parameters are the from the table plus about 10,000 biases and layer-norm weights. The last check proves the mask works: changing token 10 leaves outputs 1 to 9 untouched. Stack 12 of these between an embedding layer and an output layer and you have GPT-2 small. Build a GPT from Scratch does exactly that and trains it.
PyTorch also ships nn.TransformerEncoderLayer and nn.TransformerDecoderLayer (pass norm_first=True for pre-norm), and Hugging Face's transformers library has ready-made, pretrained versions of nearly every published model (The Hugging Face Ecosystem).
Common pitfalls
- Shape bugs. The head split is the classic one:
view(B, T, h, d/h)must be followed bytranspose(1, 2)so the heads become a batch dimension. Reshaping straight to(B, h, T, d/h)scrambles tokens and heads together without any error. - Broken causal mask. If the training loss drops far faster than expected, check the mask with the test above.
- Post-norm instability. Deep post-norm stacks diverge without careful learning-rate warm-up. Use pre-norm unless you are reproducing a specific older model.
- Memory. Activations, not weights, usually fill GPU memory in training: the attention scores alone are numbers per layer. Use fused attention (
scaled_dot_product_attention), Mixed Precision Training and smaller batches with gradient accumulation. - Forgetting the final layer norm. Pre-norm models need one more LN after the last block, or the output scale drifts.
Watch out Attention cost grows with the square of the context length. Doubling the context from 4,096 to 8,192 tokens quadruples the score computation in every layer. Budget memory and time for the longest inputs you'll actually use.
Variations
Modern LLMs keep the block's shape but swap in improved parts. The LLaMA recipe (2023) became the template for open models:
- Pre-norm with RMSNorm instead of post-norm LayerNorm.
- SwiGLU MLP: a gated feed-forward layer, , which works slightly better than GELU for the same compute.
- RoPE positions inside attention (Positional Encodings), and often no bias terms at all.
- Grouped-query attention, where several query heads share one key and value head to shrink the The KV Cache and Fast Inference.
- Mixture of Experts: many MLPs per block with a router that sends each token to only a few, giving more parameters for the same compute.
Alternatives to attention, such as State Space Models and Mamba like Mamba, are being explored and sometimes mixed into Transformer stacks, but as of late 2026 the Transformer remains the dominant architecture.
A bit of history
The Transformer was introduced in 2017 by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan Gomez, Łukasz Kaiser and Illia Polosukhin, mostly at Google Brain and Google Research. It beat recurrent models on English–German and English–French translation at a fraction of the training cost. In 2018 OpenAI's GPT used only the decoder stack and Google's BERT only the encoder, and both showed that a Transformer pretrained on unlabelled text could be adapted to many tasks. GPT-2 (2019) moved layer normalisation to the input of each sub-layer, and the pre-norm design became standard. In 2020 the Vision Transformer applied it to images, and GPT-3 showed what happened at 175 billion parameters.
Try it
- Compute by hand the layer norm of . Check it with
nn.LayerNorm(3)(torch.tensor([1., 1., 4.])).- Using the rule, estimate the parameter count of a model with and 32 blocks (the shape of Llama 2 7B). Why is your answer a bit lower than 7 billion?
- In the code, remove the two residual connections (
x = self.attn(...)instead ofx = x + ...), stack 24 blocks, and compare the standard deviation of the output for random input with and without residuals.Hint for 2: billion. The rest is mostly the input embedding table and the separate output layer, each billion. The real total is about 6.7 billion.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
The Illustrated Transformer
The famous picture-by-picture walk through the Transformer architecture.
Let's build GPT: from scratch, in code, spelled out
Two hours of live-coding a Transformer language model, explaining every line.
Transformer Explainer
An interactive visualisation of GPT-2 running in your browser. Type text and watch every step.
LLM Visualization
A 3D walk-through of every computation inside a GPT model, step by step.
The Annotated Transformer
The original Transformer paper, line by line, with working PyTorch code beside each paragraph.
Attention Is All You Need
Introduced the Transformer, the architecture behind every modern LLM.
On Layer Normalization in the Transformer Architecture
Explains why putting layer norm before each sub-layer (pre-LN) trains more stably than the original post-LN design.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/llm/transformer.md