Blame

12d21f lugonthier 2026-07-24 11:49:19
Remove unused SVG files and update Markdown content for clarity and accuracy in MLOps and Machine Learning modules. Adjust references to optimization techniques and activation functions, and enhance explanations in the mathematical refresher section.
1
# 10. Transformers
36084c lugonthier 2026-07-02 14:39:19
Add new content and images for Linear Models, Regularization, SVMs, and Decision Trees - Added images for linear regression, logistic regression, and perceptron. - Introduced a new section on Regularization and High-Dimensional Inference with detailed explanations and images. - Added content on Support Vector Machines, including definitions, loss functions, and kernel methods. - Created a new section on Decision Trees and Ensemble Methods, covering CART, bagging, random forests, and boosting. - Included relevant images to illustrate concepts in Decision Trees and Ensemble Methods.
2
12d21f lugonthier 2026-07-24 11:49:19
Remove unused SVG files and update Markdown content for clarity and accuracy in MLOps and Machine Learning modules. Adjust references to optimization techniques and activation functions, and enhance explanations in the mathematical refresher section.
3
The Transformer replaces recurrence with attention alone. It processes a whole sequence of token embeddings in parallel, letting every token attend to every other token through learned queries, keys, and values. This lesson builds the architecture from self-attention, assuming embeddings (lesson 6) and the attention mechanism (lesson 9), and reuses normalization (lesson 4) and residual connections (lesson 5).
36084c lugonthier 2026-07-02 14:39:19
Add new content and images for Linear Models, Regularization, SVMs, and Decision Trees - Added images for linear regression, logistic regression, and perceptron. - Introduced a new section on Regularization and High-Dimensional Inference with detailed explanations and images. - Added content on Support Vector Machines, including definitions, loss functions, and kernel methods. - Created a new section on Decision Trees and Ensemble Methods, covering CART, bagging, random forests, and boosting. - Included relevant images to illustrate concepts in Decision Trees and Ensemble Methods.
4
12d21f lugonthier 2026-07-24 11:49:19
Remove unused SVG files and update Markdown content for clarity and accuracy in MLOps and Machine Learning modules. Adjust references to optimization techniques and activation functions, and enhance explanations in the mathematical refresher section.
5
## 10.1 Self-attention and Q, K, V
36084c lugonthier 2026-07-02 14:39:19
Add new content and images for Linear Models, Regularization, SVMs, and Decision Trees - Added images for linear regression, logistic regression, and perceptron. - Introduced a new section on Regularization and High-Dimensional Inference with detailed explanations and images. - Added content on Support Vector Machines, including definitions, loss functions, and kernel methods. - Created a new section on Decision Trees and Ensemble Methods, covering CART, bagging, random forests, and boosting. - Included relevant images to illustrate concepts in Decision Trees and Ensemble Methods.
6
7
A sequence of $n$ tokens is represented by an embedding matrix $X \in \mathbb{R}^{n \times d}$, one row per token. Self-attention lets each token gather information from the others by asking a question (a query), matching it against every token's label (a key), and reading out content (a value).
8
9
From the same input $X$ we form three projections with learned matrices $W^Q, W^K \in \mathbb{R}^{d \times d_k}$ and $W^V \in \mathbb{R}^{d \times d_v}$:
10
11
$$\boxed{ Q = X W^Q, \quad K = X W^K, \quad V = X W^V }$$
12
13
*Remark:* the projections are the only learned parameters here, and the same three matrices are shared across all positions. Because a token is compared against every other token, the operation captures long-range dependencies in a single step, unlike a recurrence that must carry information forward one position at a time.
14
12d21f lugonthier 2026-07-24 11:49:19
Remove unused SVG files and update Markdown content for clarity and accuracy in MLOps and Machine Learning modules. Adjust references to optimization techniques and activation functions, and enhance explanations in the mathematical refresher section.
15
![Self-attention step one, three projections of the same input](/en/Deep%20Learning/10%20Transformers/a/selfattention-step1.svg)
16
17
*From one input matrix (here four tokens, "nous mangeons du pain"), three learned projections give every token its query, key, and value. What they feed is still grayed out.*
18
19
## 10.2 Scaled dot-product attention
36084c lugonthier 2026-07-02 14:39:19
Add new content and images for Linear Models, Regularization, SVMs, and Decision Trees - Added images for linear regression, logistic regression, and perceptron. - Introduced a new section on Regularization and High-Dimensional Inference with detailed explanations and images. - Added content on Support Vector Machines, including definitions, loss functions, and kernel methods. - Created a new section on Decision Trees and Ensemble Methods, covering CART, bagging, random forests, and boosting. - Included relevant images to illustrate concepts in Decision Trees and Ensemble Methods.
20
21
Each query is compared against every key by a dot product, giving an $n \times n$ matrix of raw scores. The scores are scaled, turned into weights by a row-wise softmax, and used to average the values:
22
23
$$\boxed{ \mathrm{Attention}(Q, K, V) = \mathrm{softmax}\!\left( \frac{Q K^{T}}{\sqrt{d_k}} \right) V }$$
24
25
Row $i$ of the softmax is a probability distribution over all tokens, so output row $i$ is a weighted average of the value vectors, weighted by how relevant each token is to token $i$.
26
12d21f lugonthier 2026-07-24 11:49:19
Remove unused SVG files and update Markdown content for clarity and accuracy in MLOps and Machine Learning modules. Adjust references to optimization techniques and activation functions, and enhance explanations in the mathematical refresher section.
27
![Self-attention as matrix products with shapes](/en/Deep%20Learning/10%20Transformers/a/selfattention-matrices.svg)
28
29
*The whole layer as matrix products, shapes included: $QK^T/\sqrt{d_k}$ compares every token with every other ($n \times n$), the row-wise softmax turns scores into weights, and multiplying by $V$ returns one output row per token.*
30
31
### 10.2.1 Why divide by $\sqrt{d_k}$
36084c lugonthier 2026-07-02 14:39:19
Add new content and images for Linear Models, Regularization, SVMs, and Decision Trees - Added images for linear regression, logistic regression, and perceptron. - Introduced a new section on Regularization and High-Dimensional Inference with detailed explanations and images. - Added content on Support Vector Machines, including definitions, loss functions, and kernel methods. - Created a new section on Decision Trees and Ensemble Methods, covering CART, bagging, random forests, and boosting. - Included relevant images to illustrate concepts in Decision Trees and Ensemble Methods.
32
33
If the entries of $q$ and $k$ are independent with zero mean and unit variance, the dot product $q^{T} k = \sum_{j=1}^{d_k} q_j k_j$ has variance $d_k$, so its typical magnitude grows like $\sqrt{d_k}$.
34
35
$$\boxed{ \mathrm{Var}\!\left(q^{T} k\right) = d_k \quad\Rightarrow\quad \frac{q^{T} k}{\sqrt{d_k}} \text{ has unit variance} }$$
36
37
Large scores push the softmax into a saturated regime where one weight is near $1$ and the rest are near $0$, and the softmax gradient there is tiny. Dividing by $\sqrt{d_k}$ keeps the logits at a moderate scale, which keeps the softmax gradients healthy and stabilizes training.
38
12d21f lugonthier 2026-07-24 11:49:19
Remove unused SVG files and update Markdown content for clarity and accuracy in MLOps and Machine Learning modules. Adjust references to optimization techniques and activation functions, and enhance explanations in the mathematical refresher section.
39
![The Transformer block with one attention head highlighted](/en/Deep%20Learning/10%20Transformers/a/transformer-step1.svg)
40
41
*The unit so far: one scaled dot-product attention head, sitting where it will live. The rest of the block is still grayed out.*
42
43
## 10.3 Multi-head attention
36084c lugonthier 2026-07-02 14:39:19
Add new content and images for Linear Models, Regularization, SVMs, and Decision Trees - Added images for linear regression, logistic regression, and perceptron. - Introduced a new section on Regularization and High-Dimensional Inference with detailed explanations and images. - Added content on Support Vector Machines, including definitions, loss functions, and kernel methods. - Created a new section on Decision Trees and Ensemble Methods, covering CART, bagging, random forests, and boosting. - Included relevant images to illustrate concepts in Decision Trees and Ensemble Methods.
44
45
A single attention computation forces every relationship to be read through one $d_k$-dimensional subspace. Multi-head attention runs $h$ attention operations in parallel, each with its own projections, so different heads can specialize (one on syntax, another on coreference, and so on).
46
47
Head $i$ projects the inputs with its own matrices $W_i^{Q}, W_i^{K}, W_i^{V}$ and applies scaled dot-product attention:
48
49
$$\boxed{ \mathrm{head}_i = \mathrm{Attention}\!\left(Q W_i^{Q}, K W_i^{K}, V W_i^{V}\right) }$$
50
51
The heads are concatenated along the feature axis and mixed by an output projection $W^{O}$:
52
53
$$\boxed{ \mathrm{MultiHead}(Q, K, V) = \mathrm{Concat}(\mathrm{head}_1, \dots, \mathrm{head}_h)\, W^{O} }$$
54
55
*Remark:* the per-head width is usually set to $d_k = d_v = d / h$, so the concatenation returns to width $d$ and the total cost matches a single full-width head. The heads are independent and computed in parallel, which is one reason Transformers train efficiently on modern hardware.
56
12d21f lugonthier 2026-07-24 11:49:19
Remove unused SVG files and update Markdown content for clarity and accuracy in MLOps and Machine Learning modules. Adjust references to optimization techniques and activation functions, and enhance explanations in the mathematical refresher section.
57
![The Transformer block with the multi-head sublayer highlighted](/en/Deep%20Learning/10%20Transformers/a/transformer-step2.svg)
58
59
*Step 2: several heads run in parallel on their own projections, and their outputs are concatenated and mixed by $W^O$. The multi-head sublayer is complete.*
60
61
## 10.4 Positional encoding
36084c lugonthier 2026-07-02 14:39:19
Add new content and images for Linear Models, Regularization, SVMs, and Decision Trees - Added images for linear regression, logistic regression, and perceptron. - Introduced a new section on Regularization and High-Dimensional Inference with detailed explanations and images. - Added content on Support Vector Machines, including definitions, loss functions, and kernel methods. - Created a new section on Decision Trees and Ensemble Methods, covering CART, bagging, random forests, and boosting. - Included relevant images to illustrate concepts in Decision Trees and Ensemble Methods.
62
63
Attention treats its input as a set: permuting the rows of $X$ permutes the output the same way, so the operation is order-agnostic. Language is not, therefore position must be supplied explicitly. The original Transformer adds a fixed sinusoidal encoding to the embeddings, using a different frequency per feature dimension:
64
65
$$\boxed{ PE_{(pos,\, 2i)} = \sin\!\left(\frac{pos}{10000^{2i/d}}\right), \quad PE_{(pos,\, 2i+1)} = \cos\!\left(\frac{pos}{10000^{2i/d}}\right) }$$
66
67
Here $pos$ is the token position and $i$ indexes the feature dimension. Low dimensions vary quickly with position and high dimensions vary slowly, so the vector encodes position across many scales. The encoding is added to the token embedding before the first block.
68
12d21f lugonthier 2026-07-24 11:49:19
Remove unused SVG files and update Markdown content for clarity and accuracy in MLOps and Machine Learning modules. Adjust references to optimization techniques and activation functions, and enhance explanations in the mathematical refresher section.
69
![Sinusoidal positional encoding heatmap](/en/Deep%20Learning/10%20Transformers/a/positional-encoding.png)
36084c lugonthier 2026-07-02 14:39:19
Add new content and images for Linear Models, Regularization, SVMs, and Decision Trees - Added images for linear regression, logistic regression, and perceptron. - Introduced a new section on Regularization and High-Dimensional Inference with detailed explanations and images. - Added content on Support Vector Machines, including definitions, loss functions, and kernel methods. - Created a new section on Decision Trees and Ensemble Methods, covering CART, bagging, random forests, and boosting. - Included relevant images to illustrate concepts in Decision Trees and Ensemble Methods.
70
71
*Sinusoidal positional encodings vary quickly in low dimensions and slowly in high dimensions, giving each position a unique multi-scale signature.*
72
73
*Remark:* sinusoids let a relative shift $PE_{pos+k}$ be written as a linear function of $PE_{pos}$, so the model can learn to attend by relative offset. The encodings are fixed (not learned) and extend to sequence lengths unseen during training. Many later models replace them with learned or relative position schemes.
74
12d21f lugonthier 2026-07-24 11:49:19
Remove unused SVG files and update Markdown content for clarity and accuracy in MLOps and Machine Learning modules. Adjust references to optimization techniques and activation functions, and enhance explanations in the mathematical refresher section.
75
![The Transformer block with the input side highlighted](/en/Deep%20Learning/10%20Transformers/a/transformer-step3.svg)
76
77
*Step 3: the input side. Token embeddings enter through an addition with the positional encoding, which gives attention its sense of order.*
78
79
## 10.5 The Transformer block
36084c lugonthier 2026-07-02 14:39:19
Add new content and images for Linear Models, Regularization, SVMs, and Decision Trees - Added images for linear regression, logistic regression, and perceptron. - Introduced a new section on Regularization and High-Dimensional Inference with detailed explanations and images. - Added content on Support Vector Machines, including definitions, loss functions, and kernel methods. - Created a new section on Decision Trees and Ensemble Methods, covering CART, bagging, random forests, and boosting. - Included relevant images to illustrate concepts in Decision Trees and Ensemble Methods.
80
81
Each sublayer is wrapped in a residual connection followed by layer normalization, which keeps gradients flowing through deep stacks and stabilizes the activation scale:
82
83
$$\boxed{ x \leftarrow \mathrm{LayerNorm}\!\left(x + \mathrm{Sublayer}(x)\right) }$$
84
12d21f lugonthier 2026-07-24 11:49:19
Remove unused SVG files and update Markdown content for clarity and accuracy in MLOps and Machine Learning modules. Adjust references to optimization techniques and activation functions, and enhance explanations in the mathematical refresher section.
85
![The assembled Transformer block](/en/Deep%20Learning/10%20Transformers/a/transformer-block.svg)
36084c lugonthier 2026-07-02 14:39:19
Add new content and images for Linear Models, Regularization, SVMs, and Decision Trees - Added images for linear regression, logistic regression, and perceptron. - Introduced a new section on Regularization and High-Dimensional Inference with detailed explanations and images. - Added content on Support Vector Machines, including definitions, loss functions, and kernel methods. - Created a new section on Decision Trees and Ensemble Methods, covering CART, bagging, random forests, and boosting. - Included relevant images to illustrate concepts in Decision Trees and Ensemble Methods.
86
12d21f lugonthier 2026-07-24 11:49:19
Remove unused SVG files and update Markdown content for clarity and accuracy in MLOps and Machine Learning modules. Adjust references to optimization techniques and activation functions, and enhance explanations in the mathematical refresher section.
87
*The assembled block: multi-head self-attention, then the position-wise feed-forward network, each wrapped in a residual connection and layer normalization. Stacked $N$ times, this is the Transformer.*
36084c lugonthier 2026-07-02 14:39:19
Add new content and images for Linear Models, Regularization, SVMs, and Decision Trees - Added images for linear regression, logistic regression, and perceptron. - Introduced a new section on Regularization and High-Dimensional Inference with detailed explanations and images. - Added content on Support Vector Machines, including definitions, loss functions, and kernel methods. - Created a new section on Decision Trees and Ensemble Methods, covering CART, bagging, random forests, and boosting. - Included relevant images to illustrate concepts in Decision Trees and Ensemble Methods.
88
12d21f lugonthier 2026-07-24 11:49:19
Remove unused SVG files and update Markdown content for clarity and accuracy in MLOps and Machine Learning modules. Adjust references to optimization techniques and activation functions, and enhance explanations in the mathematical refresher section.
89
A block chains two sublayers in this pattern. The first is multi-head self-attention (tokens exchange information). The second is a position-wise feed-forward network, a two-layer MLP applied independently to each position, using the notation of lesson 1:
36084c lugonthier 2026-07-02 14:39:19
Add new content and images for Linear Models, Regularization, SVMs, and Decision Trees - Added images for linear regression, logistic regression, and perceptron. - Introduced a new section on Regularization and High-Dimensional Inference with detailed explanations and images. - Added content on Support Vector Machines, including definitions, loss functions, and kernel methods. - Created a new section on Decision Trees and Ensemble Methods, covering CART, bagging, random forests, and boosting. - Included relevant images to illustrate concepts in Decision Trees and Ensemble Methods.
90
91
$$\boxed{ \mathrm{FFN}(x) = g\!\left(x W_1 + b_1\right) W_2 + b_2 }$$
92
93
with a nonlinearity $g$ (ReLU or GELU) and an inner width several times larger than $d$.
94
12d21f lugonthier 2026-07-24 11:49:19
Remove unused SVG files and update Markdown content for clarity and accuracy in MLOps and Machine Learning modules. Adjust references to optimization techniques and activation functions, and enhance explanations in the mathematical refresher section.
95
*Remark:* the residual reuses the identity shortcut of lesson 5, so the sublayer only has to learn a correction to its input. Layer normalization (lesson 4) normalizes across the feature dimension per token, which suits variable-length sequences better than batch normalization. The form above is the original post-norm placement. Many modern implementations use pre-norm, $x \leftarrow x + \mathrm{Sublayer}(\mathrm{LayerNorm}(x))$, which trains more stably at great depth.
36084c lugonthier 2026-07-02 14:39:19
Add new content and images for Linear Models, Regularization, SVMs, and Decision Trees - Added images for linear regression, logistic regression, and perceptron. - Introduced a new section on Regularization and High-Dimensional Inference with detailed explanations and images. - Added content on Support Vector Machines, including definitions, loss functions, and kernel methods. - Created a new section on Decision Trees and Ensemble Methods, covering CART, bagging, random forests, and boosting. - Included relevant images to illustrate concepts in Decision Trees and Ensemble Methods.
96
97
| Component | Role | Acts across |
98
| --- | --- | --- |
99
| Multi-head attention | mix information between tokens | the sequence |
100
| Feed-forward network | transform each token nonlinearly | the features |
101
| Residual connection | preserve a gradient path | the depth |
102
| Layer normalization | stabilize the activation scale | the features per token |
103
12d21f lugonthier 2026-07-24 11:49:19
Remove unused SVG files and update Markdown content for clarity and accuracy in MLOps and Machine Learning modules. Adjust references to optimization techniques and activation functions, and enhance explanations in the mathematical refresher section.
104
## 10.6 The encoder-decoder architecture
36084c lugonthier 2026-07-02 14:39:19
Add new content and images for Linear Models, Regularization, SVMs, and Decision Trees - Added images for linear regression, logistic regression, and perceptron. - Introduced a new section on Regularization and High-Dimensional Inference with detailed explanations and images. - Added content on Support Vector Machines, including definitions, loss functions, and kernel methods. - Created a new section on Decision Trees and Ensemble Methods, covering CART, bagging, random forests, and boosting. - Included relevant images to illustrate concepts in Decision Trees and Ensemble Methods.
105
106
The full Transformer stacks $N$ identical blocks in an encoder and $N$ in a decoder. The encoder maps the input sequence to a set of context vectors. Each decoder block has three sublayers: masked self-attention over the tokens generated so far (the mask blocks attention to future positions), cross-attention whose queries come from the decoder and whose keys and values come from the encoder output, and a feed-forward network. A final linear layer plus softmax turns the top decoder states into a distribution over the vocabulary.
107
12d21f lugonthier 2026-07-24 11:49:19
Remove unused SVG files and update Markdown content for clarity and accuracy in MLOps and Machine Learning modules. Adjust references to optimization techniques and activation functions, and enhance explanations in the mathematical refresher section.
108
![Transformer encoder-decoder stack](/en/Deep%20Learning/10%20Transformers/a/transformer-stack.svg)
36084c lugonthier 2026-07-02 14:39:19
Add new content and images for Linear Models, Regularization, SVMs, and Decision Trees - Added images for linear regression, logistic regression, and perceptron. - Introduced a new section on Regularization and High-Dimensional Inference with detailed explanations and images. - Added content on Support Vector Machines, including definitions, loss functions, and kernel methods. - Created a new section on Decision Trees and Ensemble Methods, covering CART, bagging, random forests, and boosting. - Included relevant images to illustrate concepts in Decision Trees and Ensemble Methods.
109
110
*The full Transformer: a stack of encoder blocks and a stack of decoder blocks joined by cross-attention.*
111
12d21f lugonthier 2026-07-24 11:49:19
Remove unused SVG files and update Markdown content for clarity and accuracy in MLOps and Machine Learning modules. Adjust references to optimization techniques and activation functions, and enhance explanations in the mathematical refresher section.
112
### 10.6.1 Variants
36084c lugonthier 2026-07-02 14:39:19
Add new content and images for Linear Models, Regularization, SVMs, and Decision Trees - Added images for linear regression, logistic regression, and perceptron. - Introduced a new section on Regularization and High-Dimensional Inference with detailed explanations and images. - Added content on Support Vector Machines, including definitions, loss functions, and kernel methods. - Created a new section on Decision Trees and Ensemble Methods, covering CART, bagging, random forests, and boosting. - Included relevant images to illustrate concepts in Decision Trees and Ensemble Methods.
113
114
Not every task needs both halves. Two families dominate practice:
115
116
| Variant | Structure | Attention | Typical use |
117
| --- | --- | --- | --- |
118
| Encoder-only (BERT) | encoder stack | bidirectional | understanding, classification, embeddings |
119
| Decoder-only (GPT) | decoder stack | masked (causal) | generation, autoregressive prediction |
120
| Encoder-decoder (T5) | both stacks | bidirectional plus masked | translation, summarization |
121
122
*Remark:* an encoder-only model sees the whole sequence at once, which suits labelling and retrieval. A decoder-only model masks the future so it can predict the next token, which is exactly the setup for text generation.
123
0ad9b6 lugonthier 2026-07-10 12:03:30
Remove "07 Regularization and high-dimensional inference" chapter and add "07 Support Vector Machines" and "08 Decision trees and ensemble methods" chapters with corresponding images.
124
*With attention and the Transformer in hand, the arc of this course is complete: from a single perceptron to the architecture behind today's foundation models. To take a trained model from a notebook to a reliable production service, continue with the [MLOps](/en/MLOps) course.*
36084c lugonthier 2026-07-02 14:39:19
Add new content and images for Linear Models, Regularization, SVMs, and Decision Trees - Added images for linear regression, logistic regression, and perceptron. - Introduced a new section on Regularization and High-Dimensional Inference with detailed explanations and images. - Added content on Support Vector Machines, including definitions, loss functions, and kernel methods. - Created a new section on Decision Trees and Ensemble Methods, covering CART, bagging, random forests, and boosting. - Included relevant images to illustrate concepts in Decision Trees and Ensemble Methods.
125
126
---
0ad9b6 lugonthier 2026-07-10 12:03:30
Remove "07 Regularization and high-dimensional inference" chapter and add "07 Support Vector Machines" and "08 Decision trees and ensemble methods" chapters with corresponding images.
127
Next: [Course overview](/en/Deep%20Learning)