Search

Search papers and lessons

Transformer

Level 4 · 11 min read

A transformer is a network built from attention, small feedforward layers, residual connections and layer normalization, which lets every position in a sequence read every other position at once.

On this page

  • Colour = topic mix
  • Calculus
  • Probability
  • Neural network basics
  • Linear algebra
  • Architectures
  • Discrete math
  • Sign in to see your progress

TL;DR

A transformer is a neural network that processes a sequence by repeatedly letting every position look at every other position through attention, and then passing each position through a small feedforward network. It uses no recurrence and no convolution. Because all positions are handled at the same time, training parallelises well on modern hardware, and stacking many of these blocks gives the large language and vision models in use today.

Where you'll see it: inside chat models such as GPT, encoder models such as BERT used for search and classification, machine translation systems, and vision transformers that treat image patches as tokens.

Intuition

A meeting where everyone can hear everyone

Older sequence models read a sentence one word at a time and carry a memory forward, like a relay where each runner hands a baton to the next. A word near the end of a long paragraph has to survive many hand-offs to influence the words at the start, and details fade on the way. Recurrent networks work this way.

A transformer works more like a meeting. Every word gets to speak, and every word listens to every other word at the same moment, deciding how much attention to pay to each. After one round, each word's representation contains a blend of the context it needs. A word like "bank" can pull in "river" or "money" depending on the sentence. Several rounds of this, each followed by a small private computation per word, build up meaning layer by layer.

Why it exists

A recurrent model must compute position t before position t plus 1, so the work cannot be spread across positions on a GPU. Information between distant words also has to travel through many steps, which makes long-range dependencies hard to learn. In 2017 Vaswani and colleagues asked whether attention alone was enough, with no recurrence at all. For machine translation the answer was yes: the model trained faster, scored higher, and every position could be computed in parallel.

One block

Each block has the same shape. The input is a set of vectors, one per token. Attention mixes information between positions. A feedforward network then transforms each position separately. Residual connections and layer normalization wrap both steps so that deep stacks stay trainable.

flowchart TB
  X[Input vectors] --> A[Multi-head self-attention]
  A --> R1[Add and layer norm]
  X --> R1
  R1 --> F[Feedforward network, same for each position]
  F --> R2[Add and layer norm]
  R1 --> R2
  R2 --> Y[Output vectors, same shape as input]

The original paper placed layer normalization after each residual addition. Many later models move it before the sublayer, which often trains more smoothly at large depth.

The math

Setup

Suppose a sequence has nn tokens, and each token is represented by a vector of size dd. The paper uses d=512d = 512. Stack the vectors as the rows of a matrix X∈Rn×dX \in \mathbb{R}^{n \times d}. Every operation below takes a matrix like this and returns one of the same shape.

Scaled dot-product attention

The core operation is the one from Attention Mechanism. Three learned projections turn XX into queries, keys and values:

Q=XWQ,K=XWK,V=XWV.Q = X W^Q, \qquad K = X W^K, \qquad V = X W^V.

Here WQW^Q, WKW^K and WVW^V are weight matrices learned during training. Attention is then

Attention(Q,K,V)=softmax ⁣(QK⊤dk)V,\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\!\left(\frac{Q K^\top}{\sqrt{d_k}}\right) V,

where dkd_k is the size of each query and key vector. The softmax is applied row by row, so each row of weights sums to 1. The division by dk\sqrt{d_k} keeps the scores from growing with the dimension, as explained in the attention lesson, and keeps Softmax out of its flat, low-gradient regime.

Multi-head attention

One attention pattern is rarely enough. A transformer runs hh attention operations in parallel, each with its own projections of size dk=d/hd_k = d / h. The paper uses h=8h = 8, so dk=64d_k = 64. The outputs are concatenated and mixed by one more matrix:

MultiHead(X)=Concat(head1,…,headh) WO,headi=Attention(XWiQ,XWiK,XWiV).\mathrm{MultiHead}(X) = \mathrm{Concat}(\mathrm{head}_1, \ldots, \mathrm{head}_h)\, W^O, \qquad \mathrm{head}_i = \mathrm{Attention}(X W_i^Q, X W_i^K, X W_i^V).

Each head is free to specialise. In trained models some heads track the previous word, some track matching brackets, and some track the subject of a verb. This is a pattern seen in analysis, not a rule built into the design.

Position-wise feedforward network

After attention, each position passes through the same two-layer network on its own:

FFN(x)=max⁡(0, xW1+b1) W2+b2.\mathrm{FFN}(x) = \max(0, \, x W_1 + b_1) \, W_2 + b_2.

The inner width is dff=2048d_{ff} = 2048 in the base model. The feedforward step holds about two thirds of each layer's parameters (2d dff≈2.12 d\, d_{ff} \approx 2.1 million, against 4d2≈1.054 d^2 \approx 1.05 million for attention in the base model), and interpretability work suggests it stores much of the factual knowledge in large models. Attention moves information between positions; this step processes the information at each position.

Residual connections and layer normalization

Each sublayer, attention or feedforward, is wrapped the same way:

output=LayerNorm(x+Sublayer(x)).\mathrm{output} = \mathrm{LayerNorm}\big(x + \mathrm{Sublayer}(x)\big).

The x+x + term is the residual connection. The gradient can flow straight through the addition, so deep stacks train. The layer norm rescales each token's vector to mean 0 and variance 1, then applies a learned scale and shift.

Positional encoding

Attention on its own treats its input as a set. Shuffling the tokens shuffles the outputs in the same way, so word order is invisible. The original paper fixes this by adding a sinusoidal vector pposp_{pos} to each token embedding before the first block:

ppos, 2i=sin⁡ ⁣(pos100002i/d),ppos, 2i+1=cos⁡ ⁣(pos100002i/d).p_{pos,\,2i} = \sin\!\left(\frac{pos}{10000^{2i/d}}\right), \qquad p_{pos,\,2i+1} = \cos\!\left(\frac{pos}{10000^{2i/d}}\right).

Each pair of dimensions is a sine and cosine at a different frequency, so every position gets a distinct pattern. Many later models learn the position vectors instead. See Positional Encoding for the details and the trade-offs.

Encoder and decoder stacks

The base model has N=6N = 6 encoder layers and N=6N = 6 decoder layers. An encoder layer is one multi-head self-attention step followed by the feedforward step. A decoder layer has three steps: masked self-attention, where position ii may only attend to positions up to ii, then cross-attention over the encoder output, then the feedforward step. The mask sets the scores for future positions to negative infinity before the softmax, so their weights become 0. This is what lets a decoder generate text one token at a time without peeking. The overall shape is the one described in Encoder-Decoder Architecture.

Worked examples

Example
Layer normalization on one token

Take the token vector x=(1,2,3,4)x = (1, 2, 3, 4) and ignore the small constant that is added in practice for numerical safety.

  1. Mean: μ=(1+2+3+4)/4=2.5\mu = (1 + 2 + 3 + 4) / 4 = 2.5.
  2. Deviations from the mean: (−1.5,−0.5,0.5,1.5)(-1.5, -0.5, 0.5, 1.5).
  3. Variance: σ2=(2.25+0.25+0.25+2.25)/4=1.25\sigma^2 = (2.25 + 0.25 + 0.25 + 2.25) / 4 = 1.25.
  4. Standard deviation: σ=1.25≈1.1180\sigma = \sqrt{1.25} \approx 1.1180.
  5. Normalised vector: (−1.3416,−0.4472,0.4472,1.3416)(-1.3416, -0.4472, 0.4472, 1.3416).
  6. Check: the mean is 0, and the variance is (1.8+0.2+0.2+1.8)/4=1(1.8 + 0.2 + 0.2 + 1.8) / 4 = 1.

The result depends only on this token's four numbers. A learned scale and shift would follow in a real layer.

Example
Self-attention on two tokens

Two tokens have embeddings x1=(1,0)x_1 = (1, 0) and x2=(0,1)x_2 = (0, 1). To keep the arithmetic visible, set WQ=WK=WV=IW^Q = W^K = W^V = I, the identity matrix, so queries, keys and values equal the inputs. The divisor is dk=2≈1.4142\sqrt{d_k} = \sqrt{2} \approx 1.4142.

  1. Token 1, query (1,0)(1, 0). Scores against the keys: q⋅k1/2=0.7071q \cdot k_1 / \sqrt{2} = 0.7071 and q⋅k2/2=0q \cdot k_2 / \sqrt{2} = 0.
  2. Exponentials: e0.7071≈2.0281e^{0.7071} \approx 2.0281 and e0=1e^0 = 1. Sum ≈3.0281\approx 3.0281.
  3. Weights: 0.66980.6698 and 0.33020.3302.
  4. Output: 0.6698⋅(1,0)+0.3302⋅(0,1)=(0.6698,0.3302)0.6698 \cdot (1, 0) + 0.3302 \cdot (0, 1) = (0.6698, 0.3302).
  5. Token 2, query (0,1)(0, 1). Scores: 00 and 0.70710.7071. Weights: 0.33020.3302 and 0.66980.6698.
  6. Output: 0.3302⋅(1,0)+0.6698⋅(0,1)=(0.3302,0.6698)0.3302 \cdot (1, 0) + 0.6698 \cdot (0, 1) = (0.3302, 0.6698).

Each token moved toward the other one, and neither output equals its original input. That mixing is the whole job of the attention step. The residual connection then adds the original input back, so token 1 becomes (1.6698,0.3302)(1.6698, 0.3302).

Example
What the score matrix costs in memory

Attention builds an n×nn \times n matrix of scores. Consider a realistic model with h=8h = 8 heads and a sequence of n=512n = 512 tokens, stored as 4-byte floats.

  1. Entries per head: 512×512=262,144512 \times 512 = 262{,}144.
  2. Entries for all 8 heads: 8×262,144=2,097,1528 \times 262{,}144 = 2{,}097{,}152.
  3. Bytes: 2,097,152×4=8,388,6082{,}097{,}152 \times 4 = 8{,}388{,}608, about 8 MB for one layer.

Now take a single head and a document of n=50,000n = 50{,}000 tokens.

  1. Entries: 50,0002=2.5×10950{,}000^2 = 2.5 \times 10^9.
  2. Bytes: 2.5×109×4=10102.5 \times 10^9 \times 4 = 10^{10}, about 10 GB for one head in one layer, before any other memory.

Doubling the length quadruples this cost. That is why long-context models use memory-efficient attention such as FlashAttention or other approximations.

Tradeoffs and failure modes

SituationProblemBetter choice
Very long inputs, hundreds of thousands of tokensScore matrix grows with the square of lengthMemory-efficient exact attention, sparse or linear attention, or a state-space model
Small dataset, strong local patterns (for example, short sensor signals)Transformers are data hungry and can overfitA convolutional or recurrent model, or gradient-boosted trees for tabular data
Streaming input on a tiny deviceAttention needs the whole context to be keptA recurrent or state-space model with constant memory per step
Any task with a pretrained model availableTraining from scratch is expensiveFine-tune a pretrained transformer

Other failure modes are worth knowing:

  • Length generalisation. Sinusoidal or learned positions trained on short sequences often degrade on much longer ones. Methods such as rotary position embeddings were designed to help.
  • Training instability. Post-layer-norm stacks at large depth need careful learning-rate warmup. Pre-layer-norm placement is more forgiving.
  • Quadratic cost in practice. Even when the math fits, the memory traffic dominates speed, so the bottleneck is often moving data rather than arithmetic.
  • Attention is not an explanation. High weight on a token does not prove the model relied on it, as the attention lesson notes.

History

In 2014 Bahdanau, Cho and Bengio added an attention step to a recurrent encoder-decoder for machine translation, so the decoder could look back at the source words it needed. The problem was that the encoder still ran one word at a time.

In 2017 Vaswani and colleagues at Google published "Attention Is All You Need" at NeurIPS. They removed recurrence entirely and built the encoder-decoder from attention and feedforward layers. On the WMT 2014 English-to-German and English-to-French translation tasks the large model reached BLEU scores of 28.4 and 41.8 (the paper's abstract and results table; its running text gives 41.0 for English-to-French), above the best prior systems at the time, at a small fraction of their training cost. The base model trained for about 12 hours on eight GPUs and the large one for 3.5 days.

The design caught on quickly. In 2018 BERT used only the encoder stack, trained to fill in masked words, and became a standard tool for language understanding. The same year GPT used only the decoder stack, trained to predict the next word, which led to the generative line of models. Vision transformers, from about 2020, applied the same block to image patches. Most of the work since has been about scale, efficient attention, and training stability rather than changing the basic block.

Check yourself

QuestionIn one sentence, what does the attention step compute for each position, and what replaces recurrence as the way information moves between positions?Show answer

For each position, attention computes a weighted average of the value vectors of all positions, with weights from the softmax of scaled query-key scores. Information moves between positions in one step through these weighted averages, rather than being passed from one position to the next through a hidden state over many steps.

QuestionA query is (2,0)(2, 0) and two keys are (1,0)(1, 0) and (0,1)(0, 1). The dimension is dk=4d_k = 4, so the divisor is 4=2\sqrt{4} = 2. What are the two attention weights?Show answer

Scores: q⋅k1/2=2/2=1q \cdot k_1 / 2 = 2 / 2 = 1 and q⋅k2/2=0q \cdot k_2 / 2 = 0. Exponentials: e1≈2.7183e^1 \approx 2.7183 and e0=1e^0 = 1. Sum ≈3.7183\approx 3.7183. Weights: 2.7183/3.7183≈0.73112.7183 / 3.7183 \approx 0.7311 and 1/3.7183≈0.26891 / 3.7183 \approx 0.2689. The two weights sum to 1, as they must.

QuestionWhy does the decoder need a causal mask during training, and what would go wrong without it?Show answer

When the decoder is trained to predict token ii from the tokens before it, the target tokens are all known in advance. Without the mask, position ii could attend to token i+1i + 1 and simply copy the answer, so the training loss would be very low but the model would learn nothing usable for generation. The mask sets the scores for future positions to negative infinity, so they get weight 0 and the model has to predict from the past.

QuestionA model with a single attention head processes 20,000 tokens with 4-byte floats. Roughly how large is the score matrix for one layer, and how does it change if the length doubles to 40,000?Show answer

The matrix has 20,0002=4×10820{,}000^2 = 4 \times 10^8 entries, so about 1.6×1091.6 \times 10^9 bytes, or 1.6 GB. Doubling the length to 40,000 gives 1.6×1091.6 \times 10^9 entries and about 6.4 GB. The cost grows with the square of the length, so doubling the length multiplies it by four.

Sources