Lesson 4 · Optimization II
⏱ 19 min read
Subgradient descent · AdaGrad · Adam
Where we are right now
First, let's look a second back. In Lecture 2 we dealt with linear regression:
objects → features → model parameters → prediction → error → loss function → optimization.
We got acquainted with MSE and saw that training a model can be framed as searching for the parameters at which the loss function becomes small.
And in Lecture 3 we already went through the optimization process itself in detail:
Gradient Descent → SGD → mini-batch → Momentum → adaptive learning rate → AdaGrad → Adam.
So we already have the basic picture. Now we won't ask again:
"What is Gradient Descent?"
We already know that. Now let's ask a more grown-up question:
Where do ordinary gradient optimization methods start running into trouble?
And here new ideas gradually appear.
1. The first problem: what if there is no derivative at all?
Until now our logic has been roughly this:
There is a loss function → we take its derivative → we see where it grows → we go the opposite way.
For example:
The derivative:
At the point \(x=2\):
All is well. But a question arises:
Does a derivative always exist?
No. And this is a very important point.
2. First: what even is a function?
Before going further, let's nail this down literally. A function is a rule that takes some value as input and produces a value as output.
For example:
You can picture a function as a little machine:
flowchart TD
N1["x"] --> N2["[ square it ]"] --> N3["f(x)"]
If:
then:
If:
then:
That is, a function links input and output.
3. What does "a function is differentiable" mean?
The word is scary, but the idea is quite simple.
Differentiable means, roughly:
at a given point the function has an unambiguous slope that can be described by a derivative.
Picture the graph of a road. If the road is smooth:
/
/
/
____/
then at every point we can say:
"Here the road is sloped roughly like this."
That slope is what the derivative describes.
And if the road has a sharp corner?
For example:
\ /
\ /
\ /
\/
This is the graph of the function
The absolute value. And right here there is a very interesting point:
At it, the graph has a kink. This is exactly where the ordinary derivative does not exist.
4. Why does \(|x|\) have no derivative at zero?
We won't just memorize this fact. Let's look at what happens on the left and on the right.
The function:
By the definition of absolute value:
That is, to the left of zero:
And to the right:
Now let's look at the slope.
On the left
For
the derivative is:
So on the left the slope is:
On the right
For
the derivative is:
So on the right the slope is:
We get:
left right slope -1 slope +1
\ /
\ /
\ /
\ /
\ /
\ /
\ /
\/
0
At the point \(0\) itself we would like to get one specific slope. But on the left it is:
and on the right:
They don't match. That is why there is no ordinary derivative at this point.
5. And here a problem arises for Gradient Descent
Let me recall the formula for ordinary gradient descent:
Here:
- \(w\) is a model parameter;
- \(L(w)\) is the loss function;
- \(\nabla L(w)\) is the gradient;
- \(\eta\) is the learning rate, that is, the step size.
But to compute the gradient we need derivatives. Now imagine that our function has a kink.
For example:
And we have ended up here:
What do we do? The ordinary derivative says:
"At this point there is no single specific value."
And Gradient Descent finds itself in an unpleasant situation.
6. But we still want to move
And here a very elegant idea appears:
If the ordinary derivative does not exist, maybe we don't have to insist on exactly the ordinary derivative.
We can try to define a set of admissible directions. This is how we arrive at the subgradient.
7. The subgradient — intuitively
First, with no formula at all. Picture a function with a kink:
/
/
/
/
/
/\
/ \
At a smooth point we have one exact slope. But at the kink we can say:
"There is no single exact slope here, but there are admissible values that can be used instead of the ordinary derivative."
Those values are called subgradients. For \(|x|\) at the point:
the subgradients are all the numbers in the interval:
That is:
For example:
can be subgradients. This is a very important difference:
Ordinary derivative
usually gives us one value.
Subgradient
can give us a set of admissible values.
8. Why exactly from −1 to +1?
Let's feel this on the graph. For \(|x|\):
the slope on the left is:
on the right:
And at the kink the admissible subgradients become the values between them:
That is:
-1 ─────────────── 0 ─────────────── +1
↑
│
possible
subgradients
This is exactly why a subgradient is not just "a derivative that for some reason is called differently". It is a more general concept.
9. Formally: what is a subgradient?
Now that the intuition is in place, we can look at the mathematical notation. For a convex function \(f\), a number \(g\) is called a subgradient at the point \(x_0\) if for every \(x\):
There is no need to be frightened by this formula. Let's go through every piece literally.
\(f(x)\)
the value of the function at an arbitrary point \(x\).
\(f(x_0)\)
the value of the function at the point \(x_0\) we care about.
\(g\)
the subgradient.
\(x-x_0\)
how far we have moved away from the point \(x_0\).
The main idea of the formula:
a subgradient defines a line that, for a convex function, turns out to lie below the function itself or touch it.
For an ordinary derivative at a smooth point this will be the familiar tangent line. And at a kink there can be several such admissible lines.
And from here the next concept arises naturally.
10. The subdifferential
The subdifferential is simply the set of all subgradients of a function at a given point. It is denoted, for example, as:
Here the symbol:
does not mean the ordinary derivative. It denotes the subdifferential.
That is:
For:
at the point \(0\):
This means:
the subdifferential is a whole interval of possible subgradients.
11. And what happens away from the kink?
This is where things get even more interesting. For:
if:
then the function is smooth, and its derivative is:
Therefore: \(\partial f(x)=\{-1\}\). And if: \(x>0\) then:
therefore: \(\partial f(x)=\{1\}\). And at zero: \(\partial f(0)=[-1,1]\) We get:
| Point | What happens |
|---|---|
| \(x<0\) | a single subgradient −1 |
| \(x=0\) | a set of subgradients from −1 to 1 |
| \(x>0\) | a single subgradient +1 |
And here we can see an important connection:
For a smooth function, the ordinary gradient can be viewed as a special case of the subgradient.
12. Subgradient descent
Now the idea practically builds itself. Ordinary Gradient Descent:
If the gradient exists, we use it. If the function is non-differentiable, we can use a subgradient:
where
That is:
we take some admissible subgradient and step in the direction opposite to it.
13. A small example
Let's take:
Let:
Then the ordinary derivative exists:
Let the learning rate be:
Then:
We get:
That is, we move toward the minimum:
Now imagine that we have reached:
Here there is no ordinary derivative. But:
We can choose, for example:
Then:
We have taken a step. This is exactly the practical meaning of the subgradient:
the absence of an ordinary derivative does not necessarily mean that optimization has to stop.
14. Why does this matter in ML?
Now let's connect this to what we have already studied. The L1 regularizer is especially interesting.
Let's recall it:
Here:
- \(L_{\text{data}}\) is the model's error on the data;
- \(w_i\) are the model parameters;
- \(\lambda\) is the strength of regularization;
- \(|w_i|\) is the absolute value of a parameter.
And the absolute value has a kink at:
Therefore, when optimizing L1 regularization, we run into non-differentiability. And this is where the concept of a subgradient stops being abstract mathematics and becomes a directly useful tool.
15. But now let's return to adaptive optimizers
The subgradient solves one problem:
what to do when the derivative does not exist?
But we had another big topic. We already know:
Gradient Descent
takes one general type of step. Then came:
which helps to take the direction of movement into account. Then we arrived at the idea:
What if different parameters require different step sizes?
That is how adaptive methods appear. And the first important method here is AdaGrad.
16. AdaGrad: the idea
The name:
That is, literally:
adaptive gradient.
The main idea:
let different parameters have different effective learning rates.
Why can this be useful? Let's picture two parameters:
w₁
w₂
For \(w_1\) the gradients are usually large. For \(w_2\) they are small.
If we use the same learning rate:
for both parameters, that will not necessarily be convenient. AdaGrad says:
let's look at the history of each parameter's gradients and change the step size based on that history.
17. The main idea of AdaGrad
AdaGrad accumulates the squares of past gradients. For a single parameter we can write:
Here:
- \(G_t\) is the accumulated sum of squared gradients;
- \(G_{t-1}\) is the accumulator before the current step;
- \(g_t\) is the current gradient;
- \(g_t^2\) is the square of the current gradient.
The parameter update looks roughly like this:
Now literally.
\(w_t\)
the current value of the parameter.
\(g_t\)
the current gradient.
\(\eta\)
the initial learning rate.
\(G_t\)
the accumulated history of squared gradients.
\(\sqrt{G_t}\)
the square root of the accumulated sum.
\(\varepsilon\)
a small number added for numerical stability.
18. Why the square?
A very good question. If we simply added up the gradients:
positive and negative values could cancel each other out. For example:
But that does not mean there were no gradients. So we take squares:
Now information about the magnitude of the gradients does not disappear because of the sign.
19. What happens to the step size?
Let's look at the formula:
If \(G_t\) becomes large, the denominator becomes large. Which means:
becomes small. That is:
the greater the accumulated history of large gradients, the smaller the effective learning rate becomes for that parameter.
And this is precisely the adaptivity of AdaGrad.
20. A numerical example of AdaGrad
Let's take a single parameter. We start:
Let:
And the gradients:
Step 1
Then:
The effective learning rate is approximately:
Step 2
Now:
The effective learning rate:
It has decreased.
Step 3
The effective learning rate:
It decreased a little again. That is, we can literally see:
step accumulator effective LR 1 4 0.0500
2 5 0.0447
3 5.25 0.0436
21. And here the problem with AdaGrad appears
Let's recall:
What happens to \(G_t\)? It only increases.
Why? Because:
Every time we add something. We never subtract anything.
Consequently:
Which means the denominator:
also grows gradually. And the effective learning rate:
gradually decreases. And if training continues for a very long time, the learning rate can become extremely small.
In the limiting case:
flowchart TD
A1["large accumulator"] --> A2["large denominator"] --> A3["very small step"] --> A4["updates almost vanish"] --> A5["training can practically stop"]
And this is already a serious limitation of AdaGrad.
22. And this is where Adam is born
We have discovered a problem:
AdaGrad remembers the entire history too literally.
Every old squared gradient stays inside:
forever. A natural question arises:
Can we take history into account but gradually forget old values?
This is exactly where we need an exponential moving average. And then Adam will grow out of this idea.
23. Moving average
Imagine we have the values:
The ordinary average:
But sometimes we want the most recent values to have more influence than the old ones. For example:
"What is happening now matters more than what happened very long ago."
Then we can use a moving average.
24. Why "exponential"?
We use the formula:
Here:
- \(s_t\) is the new smoothed value;
- \(s_{t-1}\) is the old smoothed value;
- \(x_t\) is the new observation;
- \(\beta\) is the memory coefficient.
Let's look at the weights. If:
then:
That is:
90% — old information
10% — new information
But the old information itself consists of even older information. So when the formula is unrolled, powers appear:
That is why the average is called exponential. Old values are gradually forgotten.
25. What does β do?
This can be remembered very intuitively. If:
then the memory is long. We say:
"We trust the history strongly."
If:
then the memory is short. We say:
"We orient almost entirely toward the new value."
That is:
| β | Behavior |
|---|---|
| small | reacts quickly to the new |
| large | smooths more, remembers history longer |
And now we are ready for Adam.
26. Adam: two memories instead of one
Adam can be understood as a combination of two ideas:
Momentum + adaptive scaling
But now we can understand this much more deeply. Adam stores two quantities: \(m_t\) and \(v_t\). Very roughly:
flowchart TD
A["m"] --> B["where and roughly how far we are moving"]
flowchart TD
C["v"] --> D["how large the gradients are"]
The first quantity is related to the first moment. The second to the second moment.
27. The first moment of Adam
The formula:
Let's break it down.
\(m_t\)
the current estimate of the average direction of the gradients.
\(m_{t-1}\)
the previous estimate.
\(\beta_1\)
how strongly we preserve the old information.
\(g_t\)
the current gradient.
\(t\)
the step number. We get:
old information
+
new gradient
↓
new estimate of the direction
This is what connects Adam to Momentum. Momentum also stores information about previous gradients.
28. What happens with a large β₁?
For example:
Then:
The old state gets a weight of 90%. The new gradient is left 10%.
Therefore \(m_t\) comes out smoothed. It does not start jumping sharply after every individual gradient.
29. The second moment of Adam
Now:
A very similar formula. But there is a fundamental difference:
instead of:
we use:
That is, Adam separately tracks the scale of the gradients. If the gradients are large:
is large. If they are small:
is small. And since an exponential average is used here too, old values are gradually forgotten.
And this is an important difference from AdaGrad.
30. AdaGrad vs Adam at the level of memory
AdaGrad:
That is:
we accumulated everything and never forget it.
Adam:
That is:
we take history into account, but gradually forget old values.
This is one of the key ideas that matters here.
31. But why is bias correction needed?
Here another subtlety appears.
At the start of training: \(m_0=0\) and usually: \(v_0=0\). Which means the first values of \(m_t\) and \(v_t\) are artificially pulled toward zero.
For example, if:
and the first gradient is:
then:
But the current gradient was:
And our estimate came out as:
It is too small. Why?
Not because the real gradient is small. But because we initially set the memory to zero.
This is the source of the initial bias.
32. Bias correction
Adam uses:
and:
The "hat" on top:
means the corrected estimate. We compensate for the artificial pull toward zero.
33. The full Adam formula
Now that all the details are individually clear, we can assemble them.
where:
and:
Now the whole chain looks like this:
flowchart TD
A["current gradient g_t"] --> B["ordinary gradient"] --> C["first moment m_t"]
A --> D["square g_t²"] --> E["second moment v_t"]
C --> F["bias correction"]
E --> F
F --> G["corrected estimates"]
G --> H["update size"]
H --> I["w_{t+1}"]
And this is already far more useful than simply remembering:
"Adam is a popular optimizer."
34. Adam on one small step
Let's take an artificial example. Let:
We start:
Then:
Now the second moment:
For now they look very small. That is exactly why correction is needed.
For the first moment:
There we go! We have brought the estimate back to the scale of the original gradient.
For the second:
That is:
And again we see the original scale. This is a very good small example of why bias correction is really needed.
35. Momentum vs AdaGrad vs Adam
Now we can finally compare them not as a list of names, but as an evolution of ideas.
| Method | What does it remember? | Main idea |
|---|---|---|
| Momentum | the direction of past gradients | smooth the movement |
| AdaGrad | the sum of squared gradients | adapt the step |
| Adam | the average of gradients + the average of squares | combine both ideas |
You can picture it as:
flowchart TD
A["Gradient Descent"] --> B["we want to<br/>take the past<br/>into account"] --> C["Momentum"]
A --> D["we want<br/>different<br/>step sizes"] --> E["AdaGrad"] --> F["too much<br/>accumulation"] --> G["Adam"]
36. Adam is not magic
It is very important not to create the wrong impression:
"Adam will tune everything by itself."
No. Adam still has:
a learning rate. There is:
and:
There is:
There is the influence of the scale of the data, the structure of the loss function, and other training conditions. That is:
adaptive learning rate ≠ automatic perfect training.
Adam simply uses additional information about the history of gradients to form the step.
37. A map of the development of optimizers
Now the most important thing is to put the whole story together.
Step 1. Gradient Descent
We have a gradient. We go against it:
But questions arise:
- large datasets;
- the cost of computation;
- different directions of movement;
- different scales of gradients.
Step 2. SGD / mini-batch
Instead of processing the whole dataset at once, we use small portions. We get:
faster and cheaper updates, but noise appears.
Step 3. Momentum
The steps become noisy. So we start taking the history of movement into account.
The idea:
"Don't react fully to every new gradient; remember where we were moving before."
Step 4. AdaGrad
Now we notice:
different parameters can have gradients of completely different scales.
So we make the steps adaptive. But:
accumulates everything. And the learning rate can gradually become too small.
Step 5. Adam
The idea:
let's not keep the whole history for the same length of time.
We use exponential averages. One:
for direction. Another:
for scale. And we get an adaptive update.
A parallel branch: non-differentiability
A completely different problem:
the derivative exists
↓
Gradient Descent
But:
flowchart TD
N1["there is no derivative"] --> N2["the ordinary gradient does not apply"] --> N3["subgradient"] --> N4["subgradient descent"]
That is why the subgradient and AdaGrad/Adam are not just four consecutive algorithms. They answer different problems.
This is very important.
38. The connection to Lecture 2
In Lecture 2 we studied linear regression and loss functions. Now we see a deeper picture:
flowchart TD
A1["Linear regression"] --> A2["loss function"] --> A3["needs to be minimized"]
flowchart TD
B1["optimization"] --> B2["gradient"] --> B3["optimizer"]
And if the function contains:
for example in L1 regularization, non-differentiability becomes possible. So the mathematical details of optimization really are connected to the models we have already studied.
39. The connection to Lecture 3
And here the connection is even stronger. In Lecture 3 we learned about:
- Gradient Descent;
- SGD;
- mini-batch;
- Momentum;
- AdaGrad;
- Adam.
Now we start looking inside these ideas. That is, Lecture 3 mainly answered:
"What are these methods and why are they needed?"
And Lecture 4 answers:
"What mathematics stands behind them, and what problems forced us to invent them?"
This is already a transition from getting acquainted with algorithms to understanding them.
40. The main distinction between the methods
This table is worth keeping as a foundation.
| Method | Main problem/idea |
|---|---|
| Gradient Descent | move against the gradient |
| SGD | don't compute the gradient on the whole dataset |
| Momentum | take the history of the direction of movement into account |
| AdaGrad | adapt the step for different parameters |
| Adam | take both the direction and the scale of gradients into account with fading memory |
| Subgradient Descent | work with non-differentiable convex functions through subgradients |
41. ML interview questions
Now the questions, from simple to complex.
Level 1
1. What is a subgradient?
Answer: a subgradient is a generalization of the derivative for certain non-differentiable convex functions. At a kink point, instead of a single gradient there can be a set of admissible subgradients.
2. Why does \(|x|\) have no derivative at zero?
Because on the left the slope is:
and on the right:
There is no single matching value of the derivative.
3. What is the subdifferential?
The set of all subgradients of a function at a specific point:
Level 2
4. How does subgradient descent work?
Instead of:
we use:
where:
5. Why does AdaGrad use squared gradients?
To measure the magnitude of gradients independently of their sign and to keep positive and negative gradients from cancelling each other out.
6. Why does the learning rate of AdaGrad gradually decrease?
Because:
the accumulator only grows, and it sits in the denominator of the step formula.
Level 3
7. What is the first moment of Adam?
It is an exponentially smoothed estimate of the gradients:
It stores information about the direction and scale of the gradient's movement.
8. What is the second moment?
An exponentially smoothed estimate of squared gradients:
It is used to adapt the step size.
9. Why does Adam use two states?
Because it needs to take into account simultaneously:
- the direction/average of the gradient;
- the magnitude/scale of the gradients.
10. What is bias correction?
The correction of the initial bias of \(m_t\) and \(v_t\), which arises because their initial values are usually set to zero.
42. Problems for self-checking
Answer each task for yourself, then open the answer and compare. You do not have to solve it perfectly — the goal is to see where the gaps are.
Problem 1
Find the derivative \(f(x)=3x^2+2x\)
Show answer
We use:
Therefore:
Problem 2
Does an ordinary derivative exist at the point \(x=0\) for \(f(x)=|x|\). Explain why.
Show answer
For:
on the left:
on the right:
They do not match. Consequently, there is no ordinary derivative at zero.
Problem 3
What is the subdifferential of \(f(x)=|x|\)
at the point \(x=0\)
Show answer
That is, any:
is an admissible subgradient.
Problem 4
Let \(L(w)=|w|\) \(w=2\) \(\eta=0.1\). Take one step of subgradient descent.
Show answer
At:
the subgradient is:
Therefore:
Problem 5
AdaGrad.
Let \(G_0=0\) \(\eta=0.1\). Gradients \(g_1=2,\quad g_2=1\). Find \(G_1\) \(G_2\)
and the effective learning rate after each step.
Show answer
The first step:
The effective learning rate:
The second:
We see the effective learning rate decreasing.
Problem 6
Adam.
Let \(g_1=2\) \(\beta_1=0.9\) \(\beta_2=0.999\) \(m_0=v_0=0\). Find \(m_1\) \(v_1\) \(\hat m_1\) \(\hat v_1\)
Show answer
The first moment:
The second:
Bias correction:
Problem 7
What will happen to Adam's memory if we increase \(\beta_1\)
for example from 0.9 to 0.99?
Answer in words first, without formulas.
Show answer
If we increase:
then we trust the previous history more strongly. The memory becomes longer.
The new gradient has a relatively smaller influence on \(m_t\).
Problem 8
Why is bias correction especially important at the start of training?
Show answer
Because \(m_0\) and \(v_0\) are usually equal to zero. At the start of training this artificially underestimates the estimates.
Bias correction compensates for this effect.
Problem 9
There are two situations:
A: the function has a sharp kink.
B: the function is smooth, but different parameters have gradients of very different scales.
Which problem are we trying to solve in each case?
Show answer
In situation A the problem is:
the derivative does not exist.
Therefore the subgradient arises. In situation B the problem is:
different parameters may require different step scales.
Here adaptive methods such as AdaGrad and Adam appear. And these are two different problems.
44. The most important map of this lecture
This part is really worth saving.
flowchart TD
O["OPTIMIZATION"] --> Q1["how to<br/>compute the<br/>gradient?"]
Q1 --> S["is the function smooth?"]
S -->|yes| G["gradient"]
S -->|no| SB["subgradient"] --> SBD["Subgradient Descent"]
G --> GD["Gradient Descent"]
SBD --> GD
flowchart TD
O["OPTIMIZATION"] --> Q2["how to<br/>take a better<br/>step?"]
Q2 --> GD["Gradient Descent"] --> SG["SGD / mini-batch"] --> MM["Momentum"] --> AG["AdaGrad"] --> TA["too much<br/>accumulation"] --> AD["Adam"]
45. Final cheat sheet
-
Derivative
Shows the local slope of a function at a smooth point.
-
Gradient
In the multidimensional case, a vector of partial derivatives.
-
Subgradient
A generalization of the gradient for certain non-differentiable convex functions.
-
Subdifferential
The set of all subgradients \(\partial f(x)\)
-
Subgradient descent
\[ w\leftarrow w-\eta g \]where \(g\in\partial L(w)\)
-
AdaGrad
Accumulates squared gradients \(G_t=G_{t-1}+g_t^2\)
and decreases the effective learning rate \(\frac{\eta}{\sqrt{G_t}+\varepsilon}\). The main problem:
the accumulator never forgets the past and keeps growing.
-
Adam
The first moment \(m_t=\beta_1m_{t-1}+(1-\beta_1)g_t\). The second moment \(v_t=\beta_2v_{t-1}+(1-\beta_2)g_t^2\). The correction \(\hat m_t=\frac{m_t}{1-\beta_1^t}\) \(\hat v_t=\frac{v_t}{1-\beta_2^t}\). The update:
\[ w_{t+1} = w_t- \eta \frac{\hat m_t} {\sqrt{\hat v_t}+\varepsilon} \]The main idea:
remember the direction of the gradient + remember its scale, but gradually forget the old information.
And one thought worth taking away from this lecture
Don't try to memorize all of Adam's formulas right now. It is far more important to see the logic of how the methods were invented:
Gradient Descent:
"There is a gradient → we go against it." Momentum:
"Let's take the history of movement into account." AdaGrad:
"Let's take the history of gradient magnitudes into account and adapt the step." The problem with AdaGrad:
"But we never forget the old history." Adam:
"Let's use a smoothed history: direction separately, scale separately."
And a completely separate branch:
There is no derivative:
"Let's use a subgradient instead of the ordinary derivative."
This is no longer a list of names. It is the history of how optimization developed. And that is the kind of story that is much easier to tell later at an interview.
🧪 Practice
- Optimizer race — SGD, Momentum, and Adam: you can see how adaptive methods change the trajectory.
- Descent along the loss function — what the loss landscape looks like and what the gradient does on it.
Check yourself
📚 Further reading
- Loss functions — an overview of loss functions.