The central idea
Vaswani et al. (2017) proposed an architecture that drops recurrence and convolution altogether and relies on self-attention: each word computes its new representation by looking directly at all the words in the sentence. The result: a path of length one between any two words, and fully parallel computation across positions during training. The architecture achieved the best translation results of its time (WMT 2014 English–German and English–French) at a much lower training cost.
Encoder: multi-head self-attention followed by a feed-forward network, with residual connections and normalization. Decoder: masked self-attention, then cross-attention over the encoder outputs, then feed-forward. The blocks repeat N times.
Query, key and value
Each token has a representation \mathbf{x}_i \in \mathbb{R}^{d_{\text{model}}}. We project the matrix X \in \mathbb{R}^{n \times d_{\text{model}}} with three learned matrices:
A useful analogy is a soft database lookup: each word poses a query (what am I looking for?), and each word offers a key (what do I hold?) and a value (what information do I give if chosen?). The match score between the query and the key decides how much of the value we take.
Scaled dot-product attention
- QK^\top is an n \times n matrix of scores: row i measures the relevance of word i to every word.
- The softmax on each row turns it into weights that sum to 1.
- Multiplying by V gives each word a weighted average of the values of all words.
Why divide by \sqrt{d_k}?
If the components of \mathbf{q} and \mathbf{k} are independent variables with mean 0 and variance 1, then \mathbf{q} \cdot \mathbf{k} = \sum_{i=1}^{d_k} q_i k_i has variance d_k. With d_k = 64 the standard deviation is 8, so some scores come out very large, the softmax saturates (a weight close to 1 for a single item), and its gradients become almost zero. Dividing by \sqrt{d_k} brings the variance back to 1.
A small example
Two words with d_k = 2: \mathbf{q}_1 = (1, 0), \mathbf{k}_1 = (1, 0), \mathbf{k}_2 = (0, 1), \mathbf{v}_1 = (1, 2), \mathbf{v}_2 = (3, 4).
- Scores: \mathbf{q}_1 \cdot \mathbf{k}_1 = 1, \mathbf{q}_1 \cdot \mathbf{k}_2 = 0, and after dividing by \sqrt{2}: (0.707,\ 0).
- Softmax: \frac{(e^{0.707}, 1)}{e^{0.707} + 1} = \frac{(2.028, 1)}{3.028} \approx (0.670,\ 0.330).
- Output: 0.670(1, 2) + 0.330(3, 4) = (1.66,\ 2.66).
Multi-head attention
A single head gives one kind of average. So we run h heads in parallel, each with its own projections of dimension d_k = d_{\text{model}} / h:
In the base transformer: d_{\text{model}} = 512, h = 8, d_k = 64. Analysis studies showed that different heads specialize: one head follows the previous word, one links a verb to its subject, and one links a pronoun to its antecedent. But caution is needed: attention weights are not always a faithful explanation of the model's decision.
Positional encoding
Attention does not know order: if we swap two words, the outputs are only swapped in the same way. So a vector representing the position is added to each token's embedding. In the original paper, with sinusoidal functions:
Each dimension is a wave with a different frequency, and a relative offset is represented by a linear transformation. BERT and GPT-2 used learned positional embeddings. Modern models mostly use rotary encoding (RoPE) (Su et al., 2021), which rotates the query and key vectors by an angle proportional to the position, so their dot product depends only on the relative distance, which makes it easier to extend the context window.
The feedforward network
After attention, each word passes independently through a two-layer network:
with inner dimension usually d_{ff} = 4 \times d_{\text{model}} (2048 in the original). Attention mixes information across positions, and the feedforward network processes each position; it is thought to store a large part of the factual "knowledge". Modern models mostly use SwiGLU (Shazeer, 2020) instead of ReLU.
Residual connections and layer normalization
Each sublayer (attention or feedforward) is wrapped in:
The residual connection lets the gradient pass directly through dozens of layers. Layer normalization (Ba et al., 2016) normalizes the vector components of each token separately. Xiong et al. (2020) showed that Pre-LN makes training more stable and reduces the need for a long learning-rate warm-up phase. Many modern models use the simpler RMSNorm.
The encoder and the decoder
- The encoder: N blocks (6 in the original), with bidirectional self-attention (every word sees everything).
- The decoder: N blocks, each with three sublayers:
- Causally masked self-attention: position i sees only positions \le i. This is done by adding -\infty to the scores above the diagonal before the softmax.
- Cross-attention: the queries come from the decoder, and the keys and values from the encoder's outputs; it is the heir of Bahdanau attention.
- A feedforward network.
- Then a linear layer and a softmax over the vocabulary.
Three families grew out of this design: encoder-only (BERT) for understanding, decoder-only (GPT) for generation, and encoder–decoder (T5, BART) for transformation.
Number of parameters
For one block (ignoring biases and normalization):
- Attention: 4\, d_{\text{model}}^2 (the matrices W^Q, W^K, W^V, W^O).
- Feedforward network: 2\, d_{\text{model}}\, d_{ff} = 8\, d_{\text{model}}^2 when d_{ff} = 4 d_{\text{model}}.
- The total is about 12\, d_{\text{model}}^2 per block.
Check: BERT-Base has 12 layers and d_{\text{model}} = 768: 12 \times 12 \times 768^2 \approx 85 million, plus the vocabulary embedding 30{,}522 \times 768 \approx 23 million, the positional embeddings and the rest, so the total approaches the announced 110 million.
Computational complexity
| Layer | Complexity per layer | Sequential operations | Longest path |
|---|---|---|---|
| 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) |
(The table is based on the table in the original paper.) Attention is faster when n < d, which is usually the case for sentences, but being quadratic in n becomes the obstacle with long contexts (tens of thousands of tokens). Solutions include:
- FlashAttention (Dao et al., 2022): computes the same exact attention but with clever tiling that reduces memory reads and writes, so it is faster and uses less memory without approximation.
- Sparse and windowed attention: each token attends to local neighbors and global tokens.
- The key–value cache (KV Cache) during generation: storing K and V for previous tokens instead of recomputing them, and multi-query attention (MQA/GQA) to reduce the size of this cache.
Training in the original paper
- The Adam optimizer with a learning-rate schedule that rises linearly during warm-up (4000 steps) and then decreases with the inverse square root of the step number.
- Label smoothing of 0.1, and dropout of 0.1.
- Beam search with width 4 for translation.
To go deeper: read Jay Alammar's "The Illustrated Transformer" (in the references), then re-derive the parameter count of the small GPT-2 (12 layers, 768 dimensions, 50,257 tokens) and compare it with the announced figure of about 124 million.
