Gradient descent
How does a machine find the right numbers without being told?
Lesson complete
If you like:
We now have a model with one number to adjust, the weight, and a way to measure how wrong it is. The key part is still missing: how do we find the weight that is least wrong?
No voice: the lesson advances on its own with subtitles.
The voice for this lesson is being recorded: for now it advances on its own with subtitles.
Review modeComment on this stepI finished the lesson
What you will achieve
- Explain what the slope of the error curve at a point is (its derivative) and what its sign tells you.
- Compute one step of gradient descent with the rule new weight = current weight − rate × slope.
- Predict the effect of a very small or very large learning rate, and recognize the gradient as the list of slopes, one per weight.
Key ideas
- Training means searching for the weight that leaves the error lowest. The machine cannot see the whole curve: it only knows the error and the slope where it stands.
- The slope, or derivative, says how much the error changes when the weight moves a little. Negative: it goes down to the right. Positive: it goes up. Zero: it is the bottom.
- The rule is new weight = current weight − η × slope. The minus sign leads downhill from either side, and the steps shorten on their own as the slope flattens.
- The learning rate η sets the size of the step: too small is slow; too large bounces or diverges.
- With many weights, the gradient is the list of slopes, one per weight. The same loop, with variants such as Adam, trains models with hundreds of billions of weights, with no guarantee of reaching the best valley.
What many people believe
Common belief The AI “sees” the whole error landscape and jumps straight to the best point.
What is true It only knows the slope right where it stands. It reaches the bottom by feeling its way, step by step, and can end up in a different valley depending on where it starts.
Check yourself
Four questions. No grade, no account: they just show whether the idea stuck.
Under the hoodFor those who want the math and the code. You do not need it to follow the course.
The slope and the derivative
To measure the slope of a curve at a point, you move the weight by a small amount and divide the change in the error by that move:
The derivative is the value that ratio approaches as gets smaller and smaller. That is why : the derivative says how to scale a small change in the weight to get the change in the error, and it is the slope of the tangent line at that point (Goodfellow et al., 2016, §4.3).
In the lesson, , so . At , with the error goes from 9 to 8.605 and the ratio is ; with , ; in the limit, . On this curve the ratio is exactly . At weight 6 the derivative is , and at 3, the bottom, it is .
A word on names: in lesson 3, the weight was the slope of the model’s line. Here the slope is a different one: that of the error curve with respect to the weight. And in practice nobody probes with an : the derivative is computed with exact formulas and, in a deep network, with backpropagation (lesson 8).
The update rule
With one weight, gradient descent repeats
where is the learning rate. Since is less than for small enough , moving in small steps with the opposite sign of the derivative brings the error down (Goodfellow et al., 2016, §4.3). In the lesson, with : The distance to the bottom halves at every step, and the steps (2, 1, 0.5, 0.25, …) shorten on their own because the slope flattens.
With many weights, , each partial derivative measures how the error changes when only increases, and the gradient is the vector that contains them all:
The gradient points uphill because, among all directions of length 1, it is the one that makes grow fastest; that is why we subtract it (Goodfellow et al., 2016, §4.3).
The method is credited to Cauchy, who presented it at the 18 October 1847 session of the Paris Academy of Sciences to solve systems of equations: he replaced the system with a single equation, the sum of the squares set to zero, and made that function go down step by step. He set the step size by solving an equation in one variable or by taking a “sufficiently small” value (Cauchy, 1847; Lemaréchal, 2012).
Why there is a threshold for the rate
For a one-variable quadratic error, with curvature , the gradient is and the distance to the bottom is multiplied by a constant factor at each step:
- if , the weight approaches the bottom without crossing it;
- if , it reaches the bottom in one jump;
- if , it crosses at every step but converges (it oscillates);
- if , it bounces between two points at the same distance from the bottom, without getting closer;
- if , the distance grows at every step: it diverges.
This is the classic analysis of LeCun et al. (1998, §5.1): the optimal one-variable rate is , and it diverges if the rate exceeds twice the optimal one. In the lesson . The four rates in the scene are a slow case (0.05: after 12 steps it is still 2.16 from the bottom, which was 4 away), one that oscillates (1.7: it crosses the bottom at every step but gets closer), one that diverges (2.05: each jump lands farther away and the error goes from 9 to 12.82 in 4 steps), and a good one (0.8: within 0.03 of the bottom in 3 steps). The interactive turn asks you to get within 0.08 of the bottom in ten steps or fewer without crossing it: rates from 0.33 to 1 do it.
A very small rate is not entirely harmless in a real network: besides being slow, it can leave training stuck at a high error, an effect that would not happen with a convex function and that is poorly understood (Goodfellow et al., 2016, §11.4.1).
Several dimensions: conditioning
In several dimensions the curvature is the Hessian matrix . For a quadratic, : along each eigendirection the distance is multiplied by . Convergence needs (LeCun et al., 1998), but progress along the flattest direction depends on . With a large condition number , the error falls slowly and the path zigzags, as in the figure. With the best fixed rate () the distance to the bottom shrinks by a factor of per step (Goh, 2017).
In the figure, and (), and : along the flat direction the distance is multiplied by at every step, and along the steep one by (it switches sides: the zigzag). The best fixed rate would be , with factor . At the starting point, , the two slopes are and : the gradient points up and to the left, uphill, and the path heads down and to the right.
Real landscapes
The curves in the lesson are toys: , the two-weight bowl with curvatures 1 and 7, and , with two valleys whose minimum errors are 0.38 and 1.35. The error of a real network is not convex: it has local minima, plateaus, and saddle points (zero gradient, but it goes down in one direction and up in another). In large networks it is now suspected that most local minima have an error close to the best one, and that plateaus and saddle points get in the way more than bad minima do (Goodfellow et al., 2016, §8.2; Dauphin et al., 2014). The starting point matters: it can decide whether training converges, at what cost, and with what ability to generalize (Goodfellow et al., 2016, §8.4), and changing only the random seed can give very different results, as when fine-tuning BERT (Dodge et al., 2020).
In code
def descent(slope, w0, eta, steps):
w = w0
history = [w]
for _ in range(steps):
w = w - eta * slope(w) # new weight = current weight − rate × slope
history.append(w)
return history
# error L(w) = 0.5 * (w - 3)**2 + 1 -> slope (derivative): w - 3
print(descent(lambda w: w - 3, w0=-1.0, eta=0.5, steps=5))
# [-1.0, 1.0, 2.0, 2.5, 2.75, 2.875]
What comes next
In real models the gradient is computed on a subset of the data (stochastic gradient descent; Bottou et al., 2018) and optimizers such as Adam are used (Kingma and Ba, 2015); both appear in lesson 9. This is how GPT-3 (175 billion weights) was trained: with Adam, batches of up to 3.2 million tokens and, for the large model, a learning rate of with warm-up and gradual decay (Brown et al., 2020, table 2.1 and appendix B). The efficient computation of in deep networks is backpropagation (lesson 8).
Decision lens
What this idea means if your job is to decide, not to code.
- Training is iterative optimization: compute grows with the number of steps, the size of the model, and the batch size. Every extra step is compute money.
- If a team says “training does not converge,” the first question is about the learning rate (perhaps the most important hyperparameter) and the data, not about “more GPUs.”
- The outcome depends on the starting point and on training decisions: two runs with the same recipe can yield different models. Ask for that variability to be reported.
- There is no guarantee of having reached the best possible point: “good enough” is checked with data the model has not seen (lesson 10).
Terms in this lesson
- Gradient descent A method that adjusts the weights step by step, always against the slope of the error (the gradient), until it reaches a bottom.
- Gradient The list of the slopes of the error, one for each weight. Seen as an arrow, it points to where the error rises fastest.
- Derivative The mathematical name for the slope of a curve at a point: how much one quantity changes for each small change in another.
- Learning rate A number (η) that multiplies the slope and sets the size of each step. Too small is slow; too large bounces or diverges.
- Weight (w) In a linear model, the number that multiplies the input: the slope of the line. It tells how much the prediction rises for each unit the input grows.
- Loss function A single number that summarizes how wrong a model is on its data. Training is the search for the parameters that make it as small as possible.
- Model A form of rule with adjustable numbers. Once trained, it is the learned rule.
- Parameter Each of the numbers a model adjusts while training and in which it stores what it learned.
Full transcript
Sources
- Cauchy, A. (1847). Méthode générale pour la résolution des systèmes d’équations simultanées (Comptes rendus de l’Académie des sciences, t. 25, pp. 536–538; sesión del 18 de octubre de 1847)
- Lemaréchal, C. (2012). Cauchy and the gradient method (Documenta Mathematica, Extra Volume ISMP, pp. 251–254)
- LeCun, Y., Bottou, L., Orr, G. B., Müller, K.-R. (1998). Efficient BackProp (Neural Networks: Tricks of the Trade, LNCS 1524, pp. 9–50; §5.1: convergencia del descenso del gradiente)
- Goh, G. (2017). Why Momentum Really Works (Distill 2(4); mejor tasa fija y factor (κ−1)/(κ+1) en una cuadrática)
- Goodfellow, I., Bengio, Y., Courville, A. (2016). Deep Learning, capítulo 4: Numerical Computation (§4.3: la derivada como pendiente, el gradiente y el descenso del gradiente)
- Goodfellow, I., Bengio, Y., Courville, A. (2016). Deep Learning, capítulo 8: Optimization for Training Deep Models (§8.2: mínimos locales, mesetas y puntos de silla; §8.4: inicialización)
- Goodfellow, I., Bengio, Y., Courville, A. (2016). Deep Learning, capítulo 11: Practical Methodology (§11.4.1: la tasa de aprendizaje)
- Dauphin, Y., Pascanu, R., Gulcehre, C., Cho, K., Ganguli, S., Bengio, Y. (2014). Identifying and attacking the saddle point problem in high-dimensional non-convex optimization
- Dodge, J., Ilharco, G., Schwartz, R., Farhadi, A., Hajishirzi, H., Smith, N. (2020). Fine-Tuning Pretrained Language Models: Weight Initializations, Data Orders, and Early Stopping
- Bottou, L., Curtis, F. E., Nocedal, J. (2018). Optimization Methods for Large-Scale Machine Learning
- Kingma, D. P., Ba, J. (2015). Adam: A Method for Stochastic Optimization
- Brown, T. B., et al. (2020). Language Models are Few-Shot Learners (GPT-3: 175 mil millones de parámetros; tabla 2.1 y apéndice B)
- Grattafiori, A., et al. (Llama Team, Meta) (2024). The Llama 3 Herd of Models (el mayor, de 405 mil millones de parámetros)
- Kaplan, J., McCandlish, S., Henighan, T., et al. (2020). Scaling Laws for Neural Language Models (el cómputo de entrenamiento ≈ 6·N·B·S)
CommentsThis lesson’s public conversation: questions, facts to check, ideas.
Comments live in GitHub Discussions, in the course’s public repository; writing one requires a GitHub account. They load from giscus.app when you open this section. The course reviewers read them, and if a change is accepted, it is applied in both languages. Open the thread on GitHub