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.

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.

Earlier sequence models—for translation, language modeling, generation—were built on recurrent or convolutional networks, usually with an encoder, a decoder, and an attention link between them. The Transformer keeps the attention link and discards everything else: no recurrence, no convolution. The result is a model that trains faster, parallelizes cleanly, and reaches higher quality.

The rest of this article builds the architecture one constraint at a time: first why sequential models hurt, then attention as the fix, then the full encoder-decoder stack.

The Sequential Bottleneck

Before the Transformer, the dominant approach to sequence tasks—machine translation, language modeling, text generation—was the recurrent neural network (RNN), particularly LSTMs and GRUs.

RNNs process sequences one token at a time. To compute the hidden state at position $t$, you need the hidden state at position $t-1$:

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

Read it plainly: the state at position $t$ is a function of the previous state and the current token. Position $t$ cannot start until position $t-1$ finishes. This creates two fundamental problems:

Lack of Parallelization

Because each step depends on the previous step, you cannot parallelize computation within a single sequence. Training is inherently sequential in time. For long sequences, this becomes a severe bottleneck.

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.

Long-Range Dependencies

Information from early tokens must survive many sequential steps to influence later processing. Gradients must flow backward through all those steps. In practice, this makes learning long-range dependencies difficult, even with gating mechanisms like LSTM.

Key question: Can we design an architecture where every position can directly attend to every other position—without sequential dependencies?

The answer is the Transformer.

Attention as a Lookup

The core idea of attention is surprisingly simple: it’s a soft lookup into a set of values, where the lookup key determines how much weight to give each value.

Think of it like a database query:

The attention mechanism compares your query to each key, computes a relevance score, and returns a weighted combination of the values.

Query: "What information is relevant here?"
Keys:
k₁ k₂ k₃ k₄ k₅
Values:
v₁ v₂ v₃ v₄ v₅
Scores:
0.1 0.7 0.05 0.1 0.05
Output: 0.1·v₁ + 0.7·v₂ + 0.05·v₃ + 0.1·v₄ + 0.05·v₅
Attention computes a weighted sum of values, where weights come from comparing a query to keys. Here, key k₂ matches the query best, so v₂ dominates the output.
Key insight: Attention connects any two positions in constant time. There's no sequential path that information must traverse.

Scaled Dot-Product Attention

The Transformer uses a specific form of attention called Scaled Dot-Product Attention.

Given:

The attention output is:

Scaled Dot-Product Attention
$$\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right) V$$
Query $Q$: what information does this position need?
Key $K$: what information does this position offer?
Value $V$: the actual content to retrieve
Scaling $\sqrt{d_k}$: prevents dot products from growing too large

Step by step

  1. Compute compatibility scores: $QK^T$ gives an $n \times m$ matrix of dot products. Entry $(i, j)$ measures how much query $i$ matches key $j$.

  2. Scale: Divide by $\sqrt{d_k}$. Without scaling, large $d_k$ values push dot products into regions where softmax has very small gradients.

  3. Normalize: Apply softmax row-wise. Each query now has a probability distribution over keys.

  4. Retrieve: Multiply by $V$. Each output is a weighted combination of values.

Why scale?

For large $d_k$, the dot products $q \cdot k$ tend to have large magnitude (variance roughly $d_k$). This pushes softmax into saturated regions where gradients vanish. Scaling by $\sqrt{d_k}$ keeps the variance at 1.

A worked example with real numbers

Abstractions land cold, so let one query attend over three tokens with $d_k = 2$. The query is $q = [1,\ 0]$, and the three keys and values are:

One attention step, three tokens

TokenKey $k\_j$$q\cdot k\_j$÷ $\sqrt{2}$softmaxValue $v\_j$
the[1, 0]1.000.710.51[2, 0]
cat[0.5, 1]0.500.350.36[0, 3]
sat[-1, 0.5]-1.00-0.710.13[1, 1]

Weighted sum of values: $0.51\,[2,0] + 0.36\,[0,3] + 0.13\,[1,1] = [1.15,\ 1.21]$.

The query matched “the” most strongly, so its value dominates the output—but every token still contributes. Attention is a soft blend, not a hard pick. Swap in a query that points toward “cat” and the second row would dominate instead. That is the entire mechanism; multi-head attention and the full stack just repeat it at scale.

Scaled Dot-Product Attention
Figure 2 (left) from the paper: The Scaled Dot-Product Attention computation. Queries and Keys are dot-product scored, optionally masked, softmax-normalized, and used to weight the Values.

Multi-Head Attention

A single attention function can only focus on one type of relationship at a time. Multi-Head Attention runs multiple attention functions in parallel, each with its own learned projections.

Multi-Head Attention
$$\text{MultiHead}(Q, K, V) = \text{Concat}(\text{head}_1, \ldots, \text{head}_h) W^O$$

$$\text{where } \text{head}_i = \text{Attention}(QW_i^Q, KW_i^K, VW_i^V)$$
$W_i^Q, W_i^K, W_i^V \in \mathbb{R}^{d_{\text{model}} \times d_k}$: learned projections
$W^O \in \mathbb{R}^{hd_v \times d_{\text{model}}}$: output projection

Each head can learn to attend to different things:

The paper uses $h = 8$ heads with $d_k = d_v = 64$ (for $d_{\text{model}} = 512$). Each head works in a smaller 64-dimensional subspace, so eight heads cost about the same as one full-width head—the model gets several views of the sequence for the price of one.

Heads are not assigned roles; they discover them. Nothing tells head 3 to track syntax or head 7 to resolve pronouns. The projections $W\_i^Q, W\_i^K, W\_i^V$ are learned, and the division of labor emerges from training—shown in the attention maps later.
Multi-Head Attention
Figure 2 (right) from the paper: Multi-Head Attention runs multiple single-head attentions in parallel, each with its own learned projections, then concatenates and linearly projects the outputs.

The Transformer Architecture

The Transformer follows the encoder-decoder structure, but built entirely from attention and feed-forward layers.

Encoder
Multi-Head
Self-Attention
Add & Norm
Feed Forward
Add & Norm
×6
Input Embedding
+
Positional Encoding
Inputs
K, V
Decoder
Masked Multi-Head
Self-Attention
Add & Norm
Multi-Head
Cross-Attention
Add & Norm
Feed Forward
Add & Norm
×6
Output Embedding
+
Positional Encoding
Outputs (shifted right)
The Transformer architecture (simplified). The encoder (left) processes the input sequence. The decoder (right) generates the output, attending to both itself and the encoder output.
Transformer Architecture — original paper figure
Figure 1 from the paper: The full Transformer architecture as presented in Vaswani et al. The left side is the encoder stack; the right side is the decoder, which includes both masked self-attention and cross-attention to the encoder output.

Encoder

Each encoder layer has two sub-layers:

  1. Multi-head self-attention: Every position attends to every position
  2. Feed-forward network: Applied independently to each position
$$\text{FFN}(x) = \max(0, xW_1 + b_1)W_2 + b_2$$

In words: project each position up to a wider hidden size, apply a ReLU, project back down. Attention mixes information across positions; the feed-forward network then transforms each position on its own. The two sub-layers split the work: attention routes, the FFN thinks.

Residual connections and layer normalization wrap each sub-layer, which keeps gradients flowing through the deep stack.

Decoder

Each decoder layer has three sub-layers:

  1. Masked self-attention: Each position attends only to earlier positions
  2. Cross-attention: Queries from decoder; keys/values from encoder
  3. Feed-forward network: Same as encoder

Positional Encoding

Attention treats its input as a set: shuffle the tokens and the output shuffles with them, unchanged. That is a problem—“dog bites man” and “man bites dog” would look identical. So before the first layer, the Transformer adds positional encodings to the input embeddings, giving each 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)$$

Each dimension $i$ is a sine or cosine wave of a different wavelength. Low dimensions oscillate slowly (they encode coarse position); high dimensions oscillate quickly (fine position). Together the waves form a unique code for every position—like the digits of a binary clock, but continuous.

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 slowly; higher dimensions vary quickly.

For any fixed offset $k$, $PE_{pos+k}$ can be written as a linear function of $PE_{pos}$. This allows the model to learn to attend by relative position.

Why Self-Attention?

Layer Type Complexity Sequential Ops Max Path Length
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)$

Self-attention connects all positions in $O(1)$ sequential operations, enabling full parallelization. It also provides a direct path between any two positions, making long-range dependencies easier to learn.

Trade-off: Self-attention has $O(n^2)$ memory complexity. For very long sequences, this can become prohibitive.

What Attention Heads Learn

The paper visualizes what individual attention heads learn in a trained Transformer. Different heads spontaneously specialize for different linguistic patterns—none of this structure is hard-coded.

Long-range attention dependency
Figure 3 from the paper: Self-attention following a long-distance dependency in encoder layer 5. The word "it" attends strongly to "The animal," resolving the coreference across the sentence.
Anaphora resolution head 1 Anaphora resolution head 2
Figure 4 from the paper: Two attention heads in layer 5 that appear to perform anaphora resolution—linking pronouns back to the nouns they refer to.
Sentence structure attention 1 Sentence structure attention 2
Figure 5 from the paper: Attention heads exhibiting behaviour related to sentence structure. Different heads learn to attend to different syntactic roles and positional patterns.

Training and Results

Setup:

Model EN-DE BLEU EN-FR BLEU Training Cost
Previous SOTA 26.36 41.29 $7.7 \times 10^{19}$ FLOPs
Transformer (big) 28.4 41.8 $2.3 \times 10^{19}$ FLOPs

The Transformer achieves state-of-the-art results at a fraction of the training cost.

The Lineage: One Block, Three Descendants

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

Family Uses Attention Best at
Encoder-only (BERT) Encoder stack Bidirectional Understanding: embeddings, retrieval, rerankers, classification
Decoder-only (GPT) Decoder stack Causal (masked) Generation: chat, code, autocompletion
Encoder-decoder (T5, original) Both Bi + causal Sequence-to-sequence: translation, summarization

The masking rule is the whole difference. Remove the causal mask and every position sees the full sentence—that is BERT, tuned for understanding. Keep the mask so each position sees only its past, and you can generate one token at a time—that is GPT. Same block, one flag flipped.

Encoders never went away. Even in the age of large decoder-only chat models, encoder-style Transformers remain the workhorse for producing text embeddings and for reranking search results—jobs that need one strong bidirectional read, not 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.