Blame

6b31d5 lugonthier 2026-07-15 12:37:13
feat: Update "Decision trees and ensemble methods" module with new content and visuals - Revamped the introduction to ensemble methods, emphasizing the benefits of combining models. - Expanded sections on decision trees, bagging, and boosting, including detailed explanations and formulas. - Added new SVG diagrams illustrating the bagging process, the transition from stumps to trees, and variance reduction. - Introduced new images for AdaBoost rounds and variance reduction to enhance understanding.
1
# 15. Transformeurs
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
3
Le Transformeur remplace la récurrence par la seule attention. Il traite en parallèle une séquence entière de plongements de tokens, ce qui permet à chaque token de porter attention à tous les autres au moyen de requêtes, de clés et de valeurs apprises. Cette leçon construit l'architecture à partir de l'auto-attention, en supposant connus les plongements (leçon 12) et le mécanisme d'attention (leçon 15), et elle réutilise la normalisation (leçon 8) et les connexions résiduelles (leçon 11).
4
5
**Objectifs**
6
- Projeter les plongements de tokens en requêtes $Q$, clés $K$ et valeurs $V$ à l'aide de matrices apprises.
7
- Définir l'attention par produit scalaire mis à l'échelle et expliquer le facteur d'échelle $1/\sqrt{d_k}$.
8
- Exécuter plusieurs têtes d'attention en parallèle et les combiner par l'attention multi-têtes.
9
- Injecter l'ordre dans une opération ensembliste au moyen d'encodages positionnels.
10
- Assembler un bloc de Transformeur à partir de connexions résiduelles et de la normalisation par couche.
11
- Placer le bloc dans la pile encodeur-décodeur et nommer ses variantes encodeur seul et décodeur seul.
12
6b31d5 lugonthier 2026-07-15 12:37:13
feat: Update "Decision trees and ensemble methods" module with new content and visuals - Revamped the introduction to ensemble methods, emphasizing the benefits of combining models. - Expanded sections on decision trees, bagging, and boosting, including detailed explanations and formulas. - Added new SVG diagrams illustrating the bagging process, the transition from stumps to trees, and variance reduction. - Introduced new images for AdaBoost rounds and variance reduction to enhance understanding.
13
## 15.1 Auto-attention et 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.
14
15
Une séquence de $n$ tokens est représentée par une matrice de plongements $X \in \mathbb{R}^{n \times d}$, une ligne par token. L'auto-attention permet à chaque token de recueillir de l'information auprès des autres en posant une question (une requête), en la comparant à l'étiquette de chaque token (une clé) et en en lisant le contenu (une valeur).
16
17
À partir de la même entrée $X$, nous formons trois projections à l'aide de matrices apprises $W^Q, W^K \in \mathbb{R}^{d \times d_k}$ et $W^V \in \mathbb{R}^{d \times d_v}$ :
18
19
$$\boxed{ Q = X W^Q, \quad K = X W^K, \quad V = X W^V }$$
20
21
*Remarque :* les projections sont ici les seuls paramètres appris, et les trois mêmes matrices sont partagées entre toutes les positions. Comme un token est comparé à tous les autres, l'opération capture les dépendances à longue portée en une seule étape, contrairement à une récurrence qui doit propager l'information une position à la fois.
22
6b31d5 lugonthier 2026-07-15 12:37:13
feat: Update "Decision trees and ensemble methods" module with new content and visuals - Revamped the introduction to ensemble methods, emphasizing the benefits of combining models. - Expanded sections on decision trees, bagging, and boosting, including detailed explanations and formulas. - Added new SVG diagrams illustrating the bagging process, the transition from stumps to trees, and variance reduction. - Introduced new images for AdaBoost rounds and variance reduction to enhance understanding.
23
## 15.2 Attention par produit scalaire mis à l'échelle
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.
24
25
Chaque requête est comparée à toutes les clés par un produit scalaire, ce qui donne une matrice $n \times n$ de scores bruts. Les scores sont mis à l'échelle, transformés en poids par un softmax appliqué ligne par ligne, puis utilisés pour moyenner les valeurs :
26
27
$$\boxed{ \mathrm{Attention}(Q, K, V) = \mathrm{softmax}\!\left( \frac{Q K^{T}}{\sqrt{d_k}} \right) V }$$
28
29
La ligne $i$ du softmax est une distribution de probabilité sur tous les tokens, si bien que la ligne $i$ de la sortie est une moyenne pondérée des vecteurs de valeurs, pondérée par la pertinence de chaque token vis-à-vis du token $i$.
30
6b31d5 lugonthier 2026-07-15 12:37:13
feat: Update "Decision trees and ensemble methods" module with new content and visuals - Revamped the introduction to ensemble methods, emphasizing the benefits of combining models. - Expanded sections on decision trees, bagging, and boosting, including detailed explanations and formulas. - Added new SVG diagrams illustrating the bagging process, the transition from stumps to trees, and variance reduction. - Introduced new images for AdaBoost rounds and variance reduction to enhance understanding.
31
### 15.2.1 Pourquoi diviser par $\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
Si les composantes de $q$ et $k$ sont indépendantes, de moyenne nulle et de variance unité, le produit scalaire $q^{T} k = \sum_{j=1}^{d_k} q_j k_j$ a une variance $d_k$, de sorte que sa magnitude typique croît comme $\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{ a une variance unité} }$$
36
37
Des scores élevés poussent le softmax dans un régime saturé où un poids est proche de $1$ et les autres proches de $0$, régime dans lequel le gradient du softmax est minuscule. Diviser par $\sqrt{d_k}$ maintient les logits à une échelle modérée, ce qui garde les gradients du softmax en bonne santé et stabilise l'entraînement.
38
6b31d5 lugonthier 2026-07-15 12:37:13
feat: Update "Decision trees and ensemble methods" module with new content and visuals - Revamped the introduction to ensemble methods, emphasizing the benefits of combining models. - Expanded sections on decision trees, bagging, and boosting, including detailed explanations and formulas. - Added new SVG diagrams illustrating the bagging process, the transition from stumps to trees, and variance reduction. - Introduced new images for AdaBoost rounds and variance reduction to enhance understanding.
39
## 15.3 Attention multi-têtes
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.
40
41
Un unique calcul d'attention contraint chaque relation à être lue à travers un seul sous-espace de dimension $d_k$. L'attention multi-têtes exécute $h$ opérations d'attention en parallèle, chacune avec ses propres projections, de sorte que différentes têtes peuvent se spécialiser (l'une sur la syntaxe, une autre sur la coréférence, et ainsi de suite).
42
43
La tête $i$ projette les entrées avec ses propres matrices $W_i^{Q}, W_i^{K}, W_i^{V}$ et applique l'attention par produit scalaire mis à l'échelle :
44
45
$$\boxed{ \mathrm{head}_i = \mathrm{Attention}\!\left(Q W_i^{Q}, K W_i^{K}, V W_i^{V}\right) }$$
46
47
Les têtes sont concaténées le long de l'axe des caractéristiques et mélangées par une projection de sortie $W^{O}$ :
48
49
$$\boxed{ \mathrm{MultiHead}(Q, K, V) = \mathrm{Concat}(\mathrm{head}_1, \dots, \mathrm{head}_h)\, W^{O} }$$
50
51
*Remarque :* la largeur par tête est habituellement fixée à $d_k = d_v = d / h$, si bien que la concaténation revient à la largeur $d$ et que le coût total égale celui d'une seule tête de pleine largeur. Les têtes sont indépendantes et calculées en parallèle, ce qui explique en partie pourquoi les Transformeurs s'entraînent efficacement sur le matériel moderne.
52
6b31d5 lugonthier 2026-07-15 12:37:13
feat: Update "Decision trees and ensemble methods" module with new content and visuals - Revamped the introduction to ensemble methods, emphasizing the benefits of combining models. - Expanded sections on decision trees, bagging, and boosting, including detailed explanations and formulas. - Added new SVG diagrams illustrating the bagging process, the transition from stumps to trees, and variance reduction. - Introduced new images for AdaBoost rounds and variance reduction to enhance understanding.
53
## 15.4 Encodage positionnel
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.
54
55
L'attention traite son entrée comme un ensemble : permuter les lignes de $X$ permute la sortie de la même manière, l'opération est donc indifférente à l'ordre. Le langage ne l'est pas, la position doit donc être fournie explicitement. Le Transformeur original ajoute aux plongements un encodage sinusoïdal fixe, en utilisant une fréquence différente par dimension de caractéristique :
56
57
$$\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) }$$
58
59
Ici, $pos$ est la position du token et $i$ indexe la dimension de caractéristique. Les dimensions basses varient rapidement avec la position et les dimensions hautes varient lentement, de sorte que le vecteur encode la position à travers de nombreuses échelles. L'encodage est ajouté au plongement du token avant le premier bloc.
60
6b31d5 lugonthier 2026-07-15 12:37:13
feat: Update "Decision trees and ensemble methods" module with new content and visuals - Revamped the introduction to ensemble methods, emphasizing the benefits of combining models. - Expanded sections on decision trees, bagging, and boosting, including detailed explanations and formulas. - Added new SVG diagrams illustrating the bagging process, the transition from stumps to trees, and variance reduction. - Introduced new images for AdaBoost rounds and variance reduction to enhance understanding.
61
![Carte de chaleur de l'encodage positionnel sinusoïdal](/fr/Deep%20Learning/15%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.
62
63
*Les encodages positionnels sinusoïdaux varient rapidement dans les dimensions basses et lentement dans les dimensions hautes, donnant à chaque position une signature multi-échelle unique.*
64
65
*Remarque :* les sinusoïdes permettent d'écrire un décalage relatif $PE_{pos+k}$ comme une fonction linéaire de $PE_{pos}$, de sorte que le modèle peut apprendre à porter attention par décalage relatif. Les encodages sont fixes (non appris) et s'étendent à des longueurs de séquence non vues pendant l'entraînement. De nombreux modèles ultérieurs les remplacent par des schémas de position appris ou relatifs.
66
6b31d5 lugonthier 2026-07-15 12:37:13
feat: Update "Decision trees and ensemble methods" module with new content and visuals - Revamped the introduction to ensemble methods, emphasizing the benefits of combining models. - Expanded sections on decision trees, bagging, and boosting, including detailed explanations and formulas. - Added new SVG diagrams illustrating the bagging process, the transition from stumps to trees, and variance reduction. - Introduced new images for AdaBoost rounds and variance reduction to enhance understanding.
67
## 15.5 Le bloc de Transformeur
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.
68
69
Chaque sous-couche est enveloppée dans une connexion résiduelle suivie d'une normalisation par couche, ce qui maintient la circulation des gradients à travers des piles profondes et stabilise l'échelle des activations :
70
71
$$\boxed{ x \leftarrow \mathrm{LayerNorm}\!\left(x + \mathrm{Sublayer}(x)\right) }$$
72
6b31d5 lugonthier 2026-07-15 12:37:13
feat: Update "Decision trees and ensemble methods" module with new content and visuals - Revamped the introduction to ensemble methods, emphasizing the benefits of combining models. - Expanded sections on decision trees, bagging, and boosting, including detailed explanations and formulas. - Added new SVG diagrams illustrating the bagging process, the transition from stumps to trees, and variance reduction. - Introduced new images for AdaBoost rounds and variance reduction to enhance understanding.
73
![Bloc de Transformeur avec connexions résiduelles](/fr/Deep%20Learning/15%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.
74
75
*Un bloc de Transformeur enveloppe une attention multi-têtes et un réseau à propagation avant, chacun dans une connexion résiduelle suivie d'une normalisation par couche.*
76
77
Un bloc enchaîne deux sous-couches selon ce motif. La première est l'auto-attention multi-têtes (les tokens échangent de l'information). La seconde est un réseau à propagation avant appliqué par position, un MLP à deux couches appliqué indépendamment à chaque position, avec la notation utilisée depuis la leçon 12 :
78
79
$$\boxed{ \mathrm{FFN}(x) = g\!\left(x W_1 + b_1\right) W_2 + b_2 }$$
80
81
avec une non-linéarité $g$ (ReLU ou GELU) et une largeur interne plusieurs fois plus grande que $d$.
82
83
*Remarque :* la connexion résiduelle réutilise le raccourci identité de la leçon 11, de sorte que la sous-couche n'a qu'à apprendre une correction de son entrée. La normalisation par couche (leçon 8) normalise selon la dimension des caractéristiques pour chaque token, ce qui convient mieux aux séquences de longueur variable que la normalisation par lot. La forme ci-dessus correspond au placement post-norm original. De nombreuses implémentations modernes utilisent le pré-norm, $x \leftarrow x + \mathrm{Sublayer}(\mathrm{LayerNorm}(x))$, qui s'entraîne de façon plus stable à grande profondeur.
84
85
| Composant | Rôle | Agit selon |
86
| --- | --- | --- |
87
| Attention multi-têtes | mélanger l'information entre les tokens | la séquence |
88
| Réseau à propagation avant | transformer chaque token de façon non linéaire | les caractéristiques |
89
| Connexion résiduelle | préserver un chemin de gradient | la profondeur |
90
| Normalisation par couche | stabiliser l'échelle des activations | les caractéristiques par token |
91
6b31d5 lugonthier 2026-07-15 12:37:13
feat: Update "Decision trees and ensemble methods" module with new content and visuals - Revamped the introduction to ensemble methods, emphasizing the benefits of combining models. - Expanded sections on decision trees, bagging, and boosting, including detailed explanations and formulas. - Added new SVG diagrams illustrating the bagging process, the transition from stumps to trees, and variance reduction. - Introduced new images for AdaBoost rounds and variance reduction to enhance understanding.
92
## 15.6 L'architecture encodeur-décodeur
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.
93
94
Le Transformeur complet empile $N$ blocs identiques dans un encodeur et $N$ dans un décodeur. L'encodeur associe la séquence d'entrée à un ensemble de vecteurs de contexte. Chaque bloc décodeur comporte trois sous-couches : une auto-attention masquée sur les tokens générés jusqu'ici (le masque bloque l'attention vers les positions futures), une attention croisée dont les requêtes proviennent du décodeur et dont les clés et les valeurs proviennent de la sortie de l'encodeur, et un réseau à propagation avant. Une dernière couche linéaire suivie d'un softmax transforme les états du sommet du décodeur en une distribution sur le vocabulaire.
95
6b31d5 lugonthier 2026-07-15 12:37:13
feat: Update "Decision trees and ensemble methods" module with new content and visuals - Revamped the introduction to ensemble methods, emphasizing the benefits of combining models. - Expanded sections on decision trees, bagging, and boosting, including detailed explanations and formulas. - Added new SVG diagrams illustrating the bagging process, the transition from stumps to trees, and variance reduction. - Introduced new images for AdaBoost rounds and variance reduction to enhance understanding.
96
![Pile encodeur-décodeur du Transformeur](/fr/Deep%20Learning/15%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.
97
98
*Le Transformeur complet : une pile de blocs encodeurs et une pile de blocs décodeurs reliées par l'attention croisée.*
99
6b31d5 lugonthier 2026-07-15 12:37:13
feat: Update "Decision trees and ensemble methods" module with new content and visuals - Revamped the introduction to ensemble methods, emphasizing the benefits of combining models. - Expanded sections on decision trees, bagging, and boosting, including detailed explanations and formulas. - Added new SVG diagrams illustrating the bagging process, the transition from stumps to trees, and variance reduction. - Introduced new images for AdaBoost rounds and variance reduction to enhance understanding.
100
### 15.6.1 Variantes
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.
101
102
Toutes les tâches n'ont pas besoin des deux moitiés. Deux familles dominent la pratique :
103
104
| Variante | Structure | Attention | Usage typique |
105
| --- | --- | --- | --- |
106
| Encodeur seul (BERT) | pile d'encodeurs | bidirectionnelle | compréhension, classification, plongements |
107
| Décodeur seul (GPT) | pile de décodeurs | masquée (causale) | génération, prédiction autorégressive |
108
| Encodeur-décodeur (T5) | les deux piles | bidirectionnelle plus masquée | traduction, résumé |
109
110
*Remarque :* un modèle encodeur seul voit toute la séquence d'un coup, ce qui convient à l'étiquetage et à la recherche d'information. Un modèle décodeur seul masque le futur afin de pouvoir prédire le token suivant, ce qui correspond exactement au cadre de la génération de texte.
111
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.
112
*L'attention et le Transformeur étant maintenant acquis, l'arc du cours est complet : du simple perceptron à l'architecture derrière les modèles de fondation d'aujourd'hui. Pour faire passer un modèle entraîné du notebook à un service de production fiable, poursuivez avec le cours [MLOps](/fr/MLOps).*
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
---
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.
115
Suivant : [Vue d'ensemble du cours](/fr/Deep%20Learning)