Gradient Descent
Iterative first-order optimisation algorithm for differentiable loss functions.
Overview
In the most general sense, training a model usually means choosing parameters that make a loss function small. In Linear Regression, for example, we choose weights and a bias to minimise the mean-squared error between predictions and labels.
There are, of course, many ways to minimise said loss, as exemplified by Linear Regression:
- We could solve the normal equation with a least-squares method, which yields a closed-form solution, assuming the data has full column rank (i.e. there are enough data points to determine the parameters, and the features are independent).
- We could also use gradient descent, which is the topic of this article.
How do we do Gradient Descent?
For Gradient Descent, the name of the game is to start with arbitrary parameters and iteratively improve them by moving opposite to the gradient of our loss function (thus, roughly speaking, the loss function is assumed differentiable with respect to the parameters).
An Analogy for Gradient Descent
We can intuitively understand this process by likening it to hikers descending a mountain in fog so thick they can only see a few steps ahead.
So the story goes:
The hikers cannot see the bottom of the mountain, so they can only rely on their immediate surroundings to feel their way down. They can feel the slope of the ground, or measure it with instruments, and determine the locally steepest downhill direction. They then discuss how far to move before stopping to measure the slope again. As the fog is too thick, they cannot know whether they have reached the lowest point of the mountain. They might instead stop in a local valley, make very slow progress across a nearly flat region, or repeatedly overshoot a narrow valley by taking steps that are too large.
This analogy captures a few key recurring themes of Gradient Descent that are worth highlighting:
| Gradient Descent | Hiker Analogy |
|---|---|
| Global optimum is unknown | Hikers cannot see the bottom of the mountain |
| Slope at current point is known | Hikers can feel or measure how the ground slopes where they are standing |
| Loss function is differentiable | Hikers can feel/measure the slope of the ground |
| Best-effort updates based on local information | Hikers move in their perceived direction of steepest descent |
| Step size is chosen by the learning rate | Hikers discuss how far to move before measuring again |
| Convergence to global optima not guaranteed | Hikers may never reach the bottom of the mountain |
and it should also reveal that Gradient Descent is actually a pretty crass algorithm (after all, real-life hikers would be quite cooked if they actually encountered such a scenario).
Yet, gradient descent is one of the most widely used optimisation algorithms in machine learning. We will explore how it works, and why this is the case in the next few sections.
Algorithm
To go into further details, let’s assume we are dealing with a regression task, and write some (extremely sloppy) math down:
- Suppose we had a model , accepting as its input and being parameterised by .
- We wish to train the model on an indeterminate dataset , where we are trying to discover such that for all (i.e. we are “fitting” to ).
In Gradient Descent (for regression tasks):
- We start by defining a loss function , which measures how far off our model’s predictions are from the true labels.
- Aside from being differentiable w.r.t. , it is mandatory for to be minimized whenever .
- We then arbitrarily select as our initial parameters, and a learning rate
- For every timestep (repeating until we are satisfied):
- We compute , the gradient of the loss function w.r.t. the parameters
- Indeed, is a vector of partial derivatives of w.r.t. each parameter in .
- We then collectively update our parameters using the update rule .
- In calculus, this is a first-order approximation of our loss function, as .
- Notice how it always reduces our approximated loss whenever (i.e. whenever we are not at a stationary point), but is not guaranteed to reduce the true loss.
- We compute , the gradient of the loss function w.r.t. the parameters
Worked Example
Consider a toy loss where and .
- This loss function satisfies , so it is special and has a unique global minimum at . More on that later.
With , , and , the update rule becomes
You can trace out the first few updates and check against the table below.
| Iteration | Current | Gradient | Update | Next |
|---|---|---|---|---|
| 0 | 0 | -3 | 1.5 | 1.5 |
| 1 | 1.5 | -1.5 | 0.75 | 2.25 |
| 2 | 2.25 | -0.75 | 0.375 | 2.625 |
Baby’s First Training Dynamics Analysis
Mechanically tracing how updates evolve can familiarize us with the procedure of gradient descent, but it is arguably more useful to study how the updates change as training goes on (“training dynamics”).
Continuing with our toy example, we can observe from the above that every update moves (ever more slowly) towards 3. In fact, rearranging gives
so (at least when we have a nice loss like this), the multiplier completely determines HOW the weights evolve, as summarized below:
| Learning rate | Behaviour on this example |
|---|---|
| Approaches 3 from the same side; very small values make slow progress. | |
| Reaches 3 in one step. | |
| Oscillates back and forth around 3, but eventually settles down. | |
| Oscillates around 3 without getting closer. | |
| Overcorrects and diverges to . |
This shows something treated as quite obvious by ML practitioners: that learning rate is a hyperparameter that must be carefully tuned.
Convergence, Convexity, and Polyak-Lojasiewicz
Typically, we do not run gradient descent indefinitely. We stop when we are satisfied with the solution, and we then call the model “converged” (onto a set of parameters ).
What “satisfied” means varies quite wildly depending on who you ask:
- (From Boyd and Vandenberghe) It could be , where is a true global minimizer of the loss function.
- (From Polyak) It could also be , where is a true global minimum of the loss function.
- (From Nocedal and Wright) It could be ; that is, we reach a stationary point of the loss function, NOT even a local minimum.
- “satisfied” can also mean that the model performs “well enough” on some (optionally) held-out validation data.
However, if we are willing to put up some strong assumptions on the loss function and assume it is convex, we can guarantee every local minimum must be a global minimum.
Unfortunately, many loss functions are non-convex, so most practitioners default to the last option, and use convergence as a vague conceptual tool to guide their training process instead.
Advanced: Links to Proofs of Convergence
Note: All three results below assume the objective is -smooth on the region being analysed, meaning its gradient is -Lipschitz continuous:
For their strongly convex result, Boyd and Vandenberghe assume on the initial sublevel set, so plays the role of the smoothness constant. Karimi, Nutini, and Schmidt state the PL result using an -Lipschitz continuous gradient.
Convex Functions
- Without assuming strong convexity or PL, Theorem L12.6 in MIT’s gradient descent notes proves that gradient descent on a convex, -smooth objective with a minimizer has a sublinear objective-gap rate of when .
Strongly Convex Functions
- Boyd and Vandenberghe prove in section 9.3.1 that the objective gap under gradient descent converges linearly when the objective is strongly convex and its Hessian is bounded above, provided the learning rate is chosen appropriately. Strong convexity is stronger than ordinary convexity and guarantees a unique global minimizer.
Polyak-Lojasiewicz Functions
- A differentiable objective satisfies the Polyak-Lojasiewicz (PL) condition if there is some such that . Strong convexity implies the PL condition, but the PL condition does not require convexity. For an objective that is both PL and smooth and has a minimizer, Karimi, Nutini, and Schmidt show that gradient descent with an appropriate learning rate makes the objective gap converge linearly to zero.
Batch, Stochastic, and Mini-Batch Gradients
Up to this point, we’ve discussed gradient descent (GD) as if we had access to the true gradient of the loss function at every step.
In this regime, we typically break up the loss function into an aggregate of per-example losses (such as “average”), then compute the gradient of this aggregate loss at every step. This is called batch GD:
This is rarely the case in practice, and with finite (or even small) datasets (relative to a presumed infinite population), we are forced to work with noisy estimates of our loss (and therefore, its gradient) at every step. We often express the gradient as
where is a random variable with mean and variance (and, if the batch size is big enough, is approximately Gaussian by the Central Limit Theorem).
Using a single, truly-randomly selected sample (i.e. n = 1) gives us stochastic GD (SGD, not to be confused with the optimizer of the same name), while using a small, truly-randomly selected subset of samples (i.e. ) gives us mini-batch GD.
In the vaguest of senses, here are some considerations when using these three variants of GD (which essentially vary ):
- Increasing reduces the mean noise variance (with variance ) but makes each update susceptible to overfitting
- Decreasing and increasing the noise of the gradient update can help in common non-convex loss landscapes (in escaping local minima, and saddle points, and high-loss basins), but can also hurt convergence.
- However, on modern hardware (especially GPUs) where parallelism is cheap, increasing can reduce wall-clock time per step, and speed up convergence in practice.
Related Topics
Linear Regression provides a concrete convex loss on which the update and convergence ideas are easiest to see. In Neural Networks, backpropagation computes the gradient and a gradient-based optimiser applies the parameter update. Transformers inherit this training loop from neural networks, usually with mini-batches and an extension of plain gradient descent.
Learning Path
What should I learn before Gradient Descent?
Start with linear-regression before studying Gradient Descent.
How does Gradient Descent connect to other AI topics?
Gradient Descent belongs to Classical ML and connects to optimisation, calculus, optimisation, calculus, learning-rate, convergence.
Further Reading
- Convex Optimization – Boyd & Vandenberghe
- Optimization Methods for Large-Scale Machine Learning – Bottou, Curtis & Nocedal
- A Stochastic Approximation Method – Robbins & Monro
- Some Methods of Speeding Up the Convergence of Iteration Methods – Polyak
- Gradient Descent and Descent Lemmas – MIT 6.7220/15.084