◆ AI All-in-One

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
↗ Plan a path here

Read first

Self-Attention and Multi-Head AttentionPositional EncodingsResidual ConnectionsNormalization Layers: BatchNorm and LayerNorm

This leads to

Diffusion TransformersBERT and Encoder ModelsGPT and Decoder-Only ModelsMixture of ExpertsState Space Models and MambaThe Hugging Face EcosystemMechanistic InterpretabilityOCR and Document AISpeech RecognitionVision Transformers
The full path from zero — 27 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. The Chain Rule
  9. Dot Product, Norms and Similarity
  10. Supervised, Unsupervised and Reinforcement Learning
  11. Gradient Descent
  12. Supervised Learning
  13. Linear Regression
  14. The Perceptron
  15. Logistic Regression
  16. Neural Networks
  17. Recurrent Neural Networks
  18. Backpropagation
  19. Activation Functions
  20. Vanishing and Exploding Gradients
  21. Normalization Layers: BatchNorm and LayerNorm
  22. LSTMs and GRUs
  23. Residual Connections
  24. Sequence-to-Sequence Models
  25. Attention
  26. Self-Attention and Multi-Head Attention
  27. Positional Encodings
  28. 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:

  1. 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".
  2. 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.
  3. 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.

A decoder-only (GPT-style) Transformer, with the shape of every tensor Sizes for GPT-2 small: batch B, length T ≤ 1024, width d = 768, h = 12 heads, vocabulary V = 50,257 token ids (B, T) integers token embedding + position lookup tables V×d and T×d (B, T, d) × N blocks (12 in GPT-2 small) same shapes in and out LayerNorm multi-head causal self-attention Q, K, V: (B, h, T, d/h) scores: (B, h, T, T) out: (B, T, d) + LayerNorm MLP: Linear → GELU → Linear d → 4d → d hidden: (B, T, 4d = 3072) + residual residual (B, T, d) final LayerNorm linear to vocabulary logits: (B, T, V) softmax → probabilities (B, T, V), rows sum to 1 Attention: the only place where tokens exchange information (T × T scores). MLP: applied to each token separately; holds about 2/3 of the weights.
Fig. 1 A GPT-style Transformer from token ids to next-token probabilities, with the shape of every tensor. The dashed box is one block, repeated N times. Tokens only exchange information inside attention; everything else works on each token separately.

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 d=768d = 768, 12 blocks, 12 heads, vocabulary V=50,257V = 50{,}257. BB is the batch size and TT the number of tokens.

1. From tokens to vectors

The input is a batch of token ids, shape (B,T)(B, T). Each id selects a row of a learned token embedding table of shape V×dV \times d, 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:

xt=E[idt]+P[t]\mathbf{x}_t = \mathbf{E}[\text{id}_t] + \mathbf{P}[t]

Now we have the residual stream: shape (B,T,d)(B, T, d), one 768-number vector per token.

2. The block

Each block applies two sub-layers, each in the same pattern: normalise, transform, add back.

x←x+MultiHeadAttention(LN(x))\mathbf{x} \leftarrow \mathbf{x} + \text{MultiHeadAttention}(\text{LN}(\mathbf{x}))
x←x+MLP(LN(x))\mathbf{x} \leftarrow \mathbf{x} + \text{MLP}(\text{LN}(\mathbf{x}))

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 (B,h,T,d/h)=(B,12,T,64)(B, h, T, d/h) = (B, 12, T, 64) and the score table is (B,h,T,T)(B, h, T, T). Its output is back to (B,T,d)(B, T, d).

The MLP, or feed-forward network, is two linear layers with a nonlinearity between them, applied to each token's vector independently:

MLP(x)=W2 GELU(W1x+b1)+b2\text{MLP}(\mathbf{x}) = \mathbf{W}_2\, \text{GELU}(\mathbf{W}_1 \mathbf{x} + \mathbf{b}_1) + \mathbf{b}_2

W1\mathbf{W}_1 expands the vector from dd to 4d4d numbers (768 → 3,072), the GELU activation bends it, and W2\mathbf{W}_2 projects it back to dd. 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 dd features: subtract the vector's mean, divide by its standard deviation, then apply a learned scale γ\boldsymbol{\gamma} and shift β\boldsymbol{\beta}:

LN(x)=γ⊙x−μσ2+ϵ+β\text{LN}(\mathbf{x}) = \boldsymbol{\gamma} \odot \frac{\mathbf{x} - \mu}{\sqrt{\sigma^2 + \epsilon}} + \boldsymbol{\beta}

Here μ\mu and σ2\sigma^2 are the mean and variance of the entries of x\mathbf{x}, ϵ\epsilon is a tiny number (like 10−510^{-5}) that prevents division by zero, and ⊙\odot means element-by-element multiplication.

Worked example. Take x=(2,4,6)\mathbf{x} = (2, 4, 6). The mean is μ=4\mu = 4. The deviations are (−2,0,2)(-2, 0, 2), so the variance is (4+0+4)/3=2.667(4 + 0 + 4)/3 = 2.667 and the standard deviation is 1.6331.633. Dividing gives (−1.225,0,1.225)(-1.225, 0, 1.225): mean 0, spread 1. With γ=1\boldsymbol{\gamma} = 1 and β=0\boldsymbol{\beta} = 0 (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 dd-vector into VV scores, one per vocabulary token. These raw scores are called logits, shape (B,T,V)(B, T, V). A softmax over the last axis turns them into next-token probabilities. Because attention was causal, the prediction at position tt only used tokens 1,…,t1, \dots, t, so one forward pass trains TT predictions at once. Many models tie this output matrix to the input embedding table, saving V×dV \times d parameters.

Counting parameters

Per block, ignoring the small biases and norms:

Part Matrices Parameters
Attention WQ,WK,WV,WO\mathbf{W}_Q, \mathbf{W}_K, \mathbf{W}_V, \mathbf{W}_O, each d×dd \times d 4d24d^2
MLP d×4dd \times 4d and 4d×d4d \times d 8d28d^2
Block total ≈12d2\approx 12 d^2

For GPT-2 small, 12×7682=7,077,88812 \times 768^2 = 7{,}077{,}888 per block, about 85 million for 12 blocks. The token embeddings add 50,257×768≈38.650{,}257 \times 768 \approx 38.6 million and positions 1,024×768≈0.81{,}024 \times 768 \approx 0.8 million, for a total of about 124 million. The same formula gives about 175 billion for GPT-3's largest model (d=12,288d = 12{,}288, 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, d=512d = 512, 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:

Three ways to use Transformer blocks Encoder-only BERT, RoBERTa, ModernBERT the [MASK] sat encoder blocks cat fill in / classify sees both directions best for understanding Decoder-only GPT, Llama, Claude the cat sat decoder blocks on predict the next token sees only the past best for generation Encoder-decoder original Transformer, T5, Whisper encoder decoder cross-attention the cat le chat noir translate, transcribe input fully visible, output generated Small grids show each model's attention mask: orange = allowed. Full for encoders, lower-triangular (causal) for decoders.
Fig. 2 Encoder-only models see the whole input and are used for understanding tasks. Decoder-only models see only the past and generate text. Encoder-decoder models read an input fully and generate an output that attends to it.
  • 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 O(n2⋅d)O(n^2 \cdot d) O(1)O(1) O(1)O(1)
Recurrent O(n⋅d2)O(n \cdot d^2) O(n)O(n) O(n)O(n)

O(⋅)O(\cdot) 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 (B,T,d)(B, T, d) to (B,T,d)(B, T, d), which is why blocks can be stacked. Its 7,087,872 parameters are the 12d2=7,077,88812d^2 = 7{,}077{,}888 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 by transpose(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 B×h×T×TB \times h \times T \times T 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, W2 (SiLU(W1x)⊙W3x)\mathbf{W}_2\,(\text{SiLU}(\mathbf{W}_1\mathbf{x}) \odot \mathbf{W}_3\mathbf{x}), 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

  1. Compute by hand the layer norm of (1,1,4)(1, 1, 4). Check it with nn.LayerNorm(3)(torch.tensor([1., 1., 4.])).
  2. Using the 12d212d^2 rule, estimate the parameter count of a model with d=4096d = 4096 and 32 blocks (the shape of Llama 2 7B). Why is your answer a bit lower than 7 billion?
  3. In the code, remove the two residual connections (x = self.attn(...) instead of x = x + ...), stack 24 blocks, and compare the standard deviation of the output for random input with and without residuals.

Hint for 2: 12×40962×32≈6.412 \times 4096^2 \times 32 \approx 6.4 billion. The rest is mostly the input embedding table and the separate output layer, each 32,000×4,096≈0.1332{,}000 \times 4{,}096 \approx 0.13 billion. The real total is about 6.7 billion.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. In a Transformer block, where does information move between different token positions?

  2. Using the rule of about 12d² parameters per block, roughly how many parameters do 12 blocks with d = 768 hold?

  3. What does layer normalisation produce for the vector (2, 4, 6), with scale 1 and shift 0?

  4. Why do residual connections (x = x + f(x)) matter so much in deep Transformer stacks?

  5. You need to translate speech into text where there is a clear input to transform. Which Transformer family fits best?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Article

The Illustrated Transformer

Jay Alammar · Beginner · Free

The famous picture-by-picture walk through the Transformer architecture.

Interactive

Transformer Explainer

Georgia Tech Polo Club · Beginner · Free

An interactive visualisation of GPT-2 running in your browser. Type text and watch every step.

Interactive

LLM Visualization

Brendan Bycroft · Intermediate · Free

A 3D walk-through of every computation inside a GPT model, step by step.

Tutorial

The Annotated Transformer

Harvard NLP · Advanced · Free

The original Transformer paper, line by line, with working PyTorch code beside each paragraph.

Paper

Attention Is All You Need

Vaswani et al. · 2017 · Advanced · Free

Introduced the Transformer, the architecture behind every modern LLM.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/llm/transformer.md