Understanding the Transformer

Understanding the building blocks and design choices of the Transformer architecture.

This article explains the landmark paper Attention Is All You Need by Vaswani et al. (2017), which introduced the Transformer architecture that powers GPT, BERT, and nearly every modern language model. All interactive numbers below are small toy values chosen for illustration, not weights from a trained model.

Key Takeaways

1
Every token reads from every other token in one step. There is no left-to-right chain, so training runs in parallel and distant words connect directly.
2
Attention is a soft lookup: compare, normalize, blend. A query is scored against every key, softmax turns scores into weights, and the output mixes the values.
3
Dividing scores by $\sqrt{d_k}$ keeps attention trainable. Unscaled scores grow with vector size until softmax picks one token and almost no learning signal flows back.
4
Eight small heads see more than one big head. Eight 64-number heads cost about the same as one 512-number head, and each can learn a different relationship.
5
A mask is what separates reading from writing. Hiding future positions lets a decoder train on whole sentences yet generate one token at a time, as GPT does.

Introduction

How do you teach a model to relate any two words in a sentence, no matter how far apart they sit? For years the answer was to walk the sentence left to right and hope the signal survived the trip. The Transformer threw that assumption out.

Its single idea fits in one sentence: every token looks at every other token and decides how much to take from each. That operation is called attention. Stack it with a small per-token network, repeat a few times, and you have the Transformer.

The roadmap: why the old sequential models hurt, how text becomes vectors, attention as a soft lookup, the scaled formula, where queries, keys and values come from, multiple heads, masking, the full block, word order, and finally why it won.

The Sequential Bottleneck

Before the Transformer, sequence tasks such as translation were dominated by recurrent neural networks (RNNs), especially LSTMs and GRUs. An RNN reads one token at a time and carries a running summary, the hidden state:

$$h_t = f(h_{t-1}, x_t)$$

In words: the state at position $t$ is computed from the previous state and the current token. Position $t$ cannot start until position $t-1$ has finished.

Token:
x₁ → x₂ → x₃ → x₄ → x₅
Hidden:
h₁ → h₂ → h₃ → h₄ → h₅
↑ must wait for previous
RNNs process tokens sequentially. Each hidden state depends on the previous one, preventing parallel computation.

That chain causes two problems.

Key question: can every position reach every other position directly, with no chain in between? The Transformer's answer is yes.

From Words to Vectors

A network cannot read letters, so the first step turns text into numbers. The sentence is split into tokens: whole words or common word pieces. Each token has an ID in a fixed vocabulary (the paper used about 37,000 shared tokens for English-German). Each ID then picks one row from a learned table, the embedding: a list of $d_{\text{model}} = 512$ numbers that the model is free to tune during training.

tokenIDembedding (first 8 of 512 numbers)
The464
…
animal5044
…
was373
…
tired10032
…
Text becomes a list of vectors: one row of 512 numbers per token. Blue cells are positive, orange negative, darker means larger. IDs and values are made up for illustration.

From here on, “a token” means its vector. Everything the Transformer does is arithmetic on this stack of vectors, one per position.

Attention as a Soft Lookup

Attention lets each token ask a question of the whole sentence. It works like a fuzzy dictionary lookup with three roles:

The query is compared with every key to give a score. Scores can be any real number, so they pass through softmax: raise $e$ to each score, then divide by the total. The results are positive and add up to 1, and a larger score always gets a larger share. These shares are the attention weights. The output is the values mixed in those proportions.

Try it on a classic example from Google’s 2017 announcement of the Transformer. Who does “it” refer to?

Interactive A. Click any word to make it the query. Chip shading and the bars show how much weight it gives each word. Switch the last word to "wide" and "it" moves from "animal" to "street". Toy 6-number vectors chosen for illustration, not a trained model.

Two things to notice. Every word gets some weight: attention is a soft blend, not a hard pick. And “it” reaches “animal” six positions away in one step, with no chain of hidden states in between.

Scaled Dot-Product Attention

Now the precise version. Stack all queries into a matrix $Q$, all keys into $K$ and all values into $V$, one row per token. The paper computes attention for every query at once:

Scaled Dot-Product Attention
$$\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right) V$$
Query $Q$: one row per token, what that token is looking for
Key $K$: one row per token, what that token offers for matching
Value $V$: one row per token, the content that gets mixed
Scaling $\sqrt{d_k}$: square root of the key length; keeps scores in a workable range

Read it right to left in four steps:

  1. Score. $QK^T$ holds every dot product $q \cdot k$: multiply matching entries and add them up. A large dot product means the two vectors point the same way.
  2. Scale. Divide every score by $\sqrt{d_k}$, where $d_k$ is the length of each key.
  3. Normalize. Softmax each row, so each query’s weights add up to 1.
  4. Blend. Multiply by $V$: each output row is the weighted mix of the value rows.

The interactive below runs exactly these steps for one query, three tokens and $d_k = 2$, small enough to draw on paper.

Interactive B. Drag the orange query arrow. Left: the query is compared with three fixed keys by dot product. Right: the output (ring) is the weighted mix of the three values; each value's dot grows with its weight. The output always lands inside the dashed triangle, because weights are positive and sum to 1. Toy numbers.

Drag the query onto the key for “the”, at $[1, 0]$. The scores are $1, 0.5, -1$; divided by $\sqrt{2}$ they become $0.71, 0.35, -0.71$; softmax gives weights $0.51, 0.36, 0.12$; and the output is $0.51 \cdot [3, 0.5] + 0.36 \cdot [1, 3] + 0.12 \cdot [0, 0] = [1.90, 1.34]$. Point the query toward “cat” and the cat row takes over. That is the whole mechanism; everything else in the Transformer repeats it at scale.

Why scale the scores?

Suppose each entry of $q$ and $k$ is a random number with mean 0 and variance 1. A dot product adds up $d_k$ such products, so its variance is $d_k$ and its typical size (standard deviation) is $\sqrt{d_k}$. With $d_k = 512$ scores spread over roughly $\pm 22$. Softmax of numbers that far apart gives almost all the weight to the largest one.

That is bad for learning. When one weight is nearly 1 and the rest nearly 0, nudging a score barely changes any weight, so the gradient through softmax is close to zero and the query and key matrices stop learning. Dividing by $\sqrt{d_k}$ brings the spread back to about 1 at every size.

Interactive C. Slide $d_k$ from 2 to 512. One query and eight keys with random unit-variance entries (fixed seed, so the numbers are repeatable). Left: softmax of raw scores collapses onto one key as $d_k$ grows. Right: scaled scores keep a usable spread. "Learning signal" is $\sum_i w_i(1-w_i)$, the sum of softmax's own slopes; near 0 means almost no gradient.
Scaled Dot-Product Attention
Figure 2 (left) from the paper: the same four steps as a diagram. MatMul scores queries against keys, Scale divides by $\sqrt{d_k}$, the optional Mask is covered below, SoftMax normalizes, and the last MatMul blends the values.

Where Queries, Keys and Values Come From

So far the queries, keys and values were given. In the Transformer they all come from the same token vector $x$, multiplied by three learned matrices:

$$q = x W^Q, \qquad k = x W^K, \qquad v = x W^V$$

In words: one vector, three different learned views of it. $W^Q$ learns what a token should ask for, $W^K$ how it should advertise itself, and $W^V$ what it should hand over. None of these roles is programmed; they emerge from training.

token vector $x$ ("it")
…
× $W^Q$ →
query $q$
…
× $W^K$ →
key $k$
…
× $W^V$ →
value $v$
…
Every token is projected three ways. The same three matrices are shared by all positions, so the model learns one way to ask and one way to answer, applied everywhere. Cell values are illustrative.

When queries, keys and values all come from the same sequence, it is self-attention: the sentence reads itself. When the queries come from one sequence and the keys and values from another, it is cross-attention; the decoder uses it to read the source sentence during translation.

Multi-Head Attention

One attention pattern can only blend in one way per token. But “it” needs to know who it refers to, the verb needs its subject, and every word benefits from knowing its neighbour. Multi-head attention runs several attentions side by side, each with its own $W^Q$, $W^K$, $W^V$, so each can learn a different relationship.

Interactive D. Pick a head; hover or tap a row to read it. The three patterns are hand-drawn illustrations of the kinds of behaviour real heads show. For evidence from a trained model, see the paper's Figures 3 to 5 further down.
Multi-Head Attention
$$\text{MultiHead}(Q, K, V) = \text{Concat}(\text{head}_1, \ldots, \text{head}_h)\, W^O$$ $$\text{head}_i = \text{Attention}(QW_i^Q,\; KW_i^K,\; VW_i^V)$$
$W_i^Q, W_i^K, W_i^V$ ($512 \times 64$ each): head $i$'s own learned projections
$W^O$ ($512 \times 512$): mixes the concatenated head outputs back into one vector

In words: each head projects the tokens down to a small space, runs attention there, and the head outputs are glued together and mixed by $W^O$.

The arithmetic is what makes this cheap. The paper uses $d_{\text{model}} = 512$ and $h = 8$ heads, so each head works in $d_k = 512 / 8 =$ 64 dimensions. Eight heads of 64 cost about the same as one head of 512, so the model gets eight views of the sentence for the price of one.

Multi-Head Attention
Figure 2 (right) from the paper: $h$ parallel attention layers, each with its own linear projections of V, K and Q, then Concat and a final Linear ($W^O$).

Masking: No Peeking Ahead

The encoder reads a sentence that already exists, so every token may look at every other token. The decoder writes a sentence, one token at a time. When it predicts word 3 it must not see word 3 or anything after it, or training would teach it to copy the answer.

The fix is a causal mask. Before softmax, every score where the key comes after the query is set to $-\infty$. Since $e^{-\infty} = 0$, those positions get exactly zero weight, and softmax spreads the full weight over the positions that remain.

Interactive E. Rows are the token asking, columns the token being read. Switch to the decoder mask: everything above the diagonal is blocked, and each row's weights are re-shared over what it can still see. Toy scores.

The mask also explains a phrase in the paper’s Figure 1: “outputs (shifted right)”. During training the decoder is fed the target sentence moved one place to the right, with a start symbol in front. Position $i$ then sees the target up to word $i-1$ and is trained to predict word $i$. Thanks to the mask, all positions train in parallel on one forward pass.

At inference time there is no target, so the decoder generates in a loop, feeding each prediction back in:

StepDecoder input so farPredicts
1<start>The
2<start> Thecat
3<start> The catsat
4<start> The cat satdown
5<start> The cat sat down<end>
Generation, one token per step. Training sees all five rows at once; the causal mask guarantees each row only uses the tokens to its left.

The Transformer Block

Attention mixes information across positions. Each block pairs it with a second sub-layer that works on each position on its own, and wraps both in two pieces of plumbing.

A useful picture is a residual stream: each token’s vector flows straight up through the stack, and each sub-layer reads from it and adds its result back.

Multi-head self-attention + LayerNorm Feed-forward (each token alone) + LayerNorm to the next block token vectors in read add back read add back residual stream
One encoder block, as in the paper: each sub-layer reads the stream, its output is added back, and the sum is normalized, $\text{LayerNorm}(x + \text{Sublayer}(x))$. Many later models move LayerNorm inside the branch, before the sub-layer ("pre-norm"), which trains more stably when stacks get deep.

The second sub-layer is a small two-layer network applied to every position separately:

$$\text{FFN}(x) = \max(0,\; xW_1 + b_1)\,W_2 + b_2$$

In words: widen each token’s vector from 512 to 2,048 numbers, zero out the negatives (the ReLU, $\max(0, \cdot)$), and project back to 512. Attention moves information between tokens; the feed-forward network processes what each token has gathered.

Encoder and decoder

The paper stacks six blocks on each side.

A final linear layer and softmax turn each decoder output vector into a probability for every token in the vocabulary.

Transformer Architecture — original paper figure
Figure 1 from the paper: the full Transformer. Left, the encoder block (×N, N = 6). Right, the decoder block with masked self-attention, cross-attention whose keys and values arrow in from the encoder, and feed-forward. Every sub-layer is followed by "Add & Norm", the residual plus LayerNorm above.

Positional Encoding

Attention treats its input as a set: shuffle the tokens and each output just moves with its token, unchanged. That is a problem, since “dog bites man” and “man bites dog” would look identical. So before the first block, the Transformer adds a positional encoding to each embedding, giving every position a distinct fingerprint.

$$PE_{(pos, 2i)} = \sin\left(\frac{pos}{10000^{2i/d_{\text{model}}}}\right)$$ $$PE_{(pos, 2i+1)} = \cos\left(\frac{pos}{10000^{2i/d_{\text{model}}}}\right)$$

Think of each pair of dimensions as a clock hand turning at its own speed. Fast hands change from one position to the next and pin down fine position; slow hands barely move and give coarse position. Reading all the hands together tells you exactly where you are, the way hours, minutes and seconds together give the time.

Interactive: Drag the slider or click on the grid to explore how positional encodings change. Each row is a position, each column is a dimension. Orange = sin (even dims), blue = cos (odd dims). Lower dimensions vary quickly; higher dimensions vary slowly.

For any fixed offset $k$, $PE_{pos+k}$ is a rotation of $PE_{pos}$, a linear function of it. The authors chose sinusoids hoping this would make relative positions easy to attend to.

Why It Won

The paper compares one layer of each type on three costs, for a sequence of $n$ tokens with vectors of size $d$.

Layer type Work per layer Steps that must run in order Longest path between two tokens
Self-attention $O(n^2 \cdot d)$ $O(1)$ $O(1)$
Recurrent $O(n \cdot d^2)$ $O(n)$ $O(n)$
Convolutional $O(k \cdot n \cdot d^2)$ $O(1)$ $O(\log_k n)$

Darker cells mean more sequential work or a longer path. Self-attention wins both: no chain of steps, and any two tokens are one hop apart. The work column is a trade-off. When the sentence is shorter than the vector size ($n < d$, true for most 2017 translation sentences with $d = 512$), $n^2 d$ is smaller than $n d^2$.

The cost: the attention matrix has $n^2$ entries, so memory and compute grow with the square of the length. Doubling the context quadruples it. Much later work (FlashAttention, sparse and linear attention) targets exactly this term.

The paper trained on WMT 2014 English-German (4.5M sentence pairs) and English-French (36M pairs) using 8 NVIDIA P100 GPUs. The base model trained in 12 hours, the big model in 3.5 days.

Model (paper Table 2) EN-DE BLEU EN-FR BLEU
ConvS2S ensemble (previous best) 26.36 41.29
Transformer (base) 27.3 38.1
Transformer (big) 28.4 41.8

BLEU measures overlap with human reference translations; higher is better. Shading is relative within each column. A single big Transformer beat the best previous ensemble (several models averaged) on both language pairs, and did it with far less compute:

Training cost, English-German (FLOPs, paper Table 2)
ConvS2S ensemble
7.7 × 10¹⁹
Transformer (big)
2.3 × 10¹⁹
Transformer (base)
0.33 × 10¹⁹
The base model beat the previous best ensemble using about 1/23 of its training compute.

What Attention Heads Learn

Interactive D drew head patterns by hand. The paper shows real ones from its trained model. None of this structure is programmed; it emerges from training on translation.

Long-range attention dependency
Figure 3 from the paper: encoder self-attention in layer 5 following a long-distance dependency. Many heads link "making" to the distant words that complete the phrase "making ... more difficult". Colors are different heads.
Anaphora resolution head 1 Anaphora resolution head 2
Figure 4 from the paper: two heads in layer 5 that appear to do anaphora resolution, linking the pronoun "its" back to the noun it refers to. This is the real counterpart of head 2 in Interactive D.
Sentence structure attention 1 Sentence structure attention 2
Figure 5 from the paper: two heads whose behaviour tracks sentence structure. Different heads clearly learned different jobs.

The Lineage: One Block, Three Descendants

The paper shipped a full encoder-decoder for translation. What followed took the stack apart. The block turned out to be reusable on its own, and the field split along the seam between encoder and decoder.

Family Uses Self-attention mask Best at
Encoder-only (BERT) Encoder stack None: bidirectional Understanding: embeddings, retrieval, rerankers, classification
Decoder-only (GPT) Decoder stack, no cross-attention Causal Generation: chat, code, autocompletion
Encoder-decoder (T5, original) Both Encoder none, decoder causal Sequence-to-sequence: translation, summarization

The mask is the main difference. Remove the causal mask and every position sees the full sentence: that is BERT, built for understanding. Keep the mask so each position sees only its past, and the model can generate one token at a time: that is GPT. Same block, one switch flipped, the same switch as in Interactive E.

Encoders never went away. Even in the age of large decoder-only chat models, encoder-style Transformers remain the workhorse for text embeddings and for reranking search results, jobs that need one strong bidirectional read rather than token-by-token generation.

References

  1. Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, Ł., & Polosukhin, I. (2017). Attention Is All You Need. NeurIPS 2017.

  2. Bahdanau, D., Cho, K., & Bengio, Y. (2014). Neural Machine Translation by Jointly Learning to Align and Translate. ICLR 2015.

  3. Ba, J. L., Kiros, J. R., & Hinton, G. E. (2016). Layer Normalization.