Gradient Descent Variants and Constrained Optimization
Prerequisite Knowledge
This lecture builds on the following concepts from earlier lectures. If any feel unfamiliar, review the linked notes before proceeding.
Previously Covered in This Subject
- Gradient descent and the update rule — covered in Lecture 11
- Constrained optimization and Lagrange multipliers — covered in Lecture 12
- Gradients, the Jacobian, and the Hessian — covered in Lectures 8–10
14.1 Standard Gradient Descent and Its Problems
Hook. You have a function with millions of knobs to turn, and you want the setting that gives the lowest possible value. You cannot solve it with pen and paper. How do you find the bottom of a landscape you cannot even see?
Intuition + Analogy. Picture yourself on a foggy hill at midnight. You cannot see the valley floor below. The only thing you know is which way your feet slope right here, right now. Your strategy: feel the slope under your boots, take a small step downhill, feel again, step again. That is gradient descent. a blind walker who trusts their feet.
Here is how the mapping works:
- You are the parameter vector . the current set of weights or coefficients you are tuning.
- The slope under your boots is the gradient . it tells you which direction is steepest upward.
- The size of your step is the learning rate . too small and you crawl forever, too large and you might overshoot and tumble.
- The valley floor is the minimum of the loss function .
The analogy breaks because a real hiker can eventually see the valley. Gradient descent never sees the whole landscape. It stays blind forever. It only knows the slope at its feet and nothing else.
In short: "The algorithm is blind. It doesn't understand where it has reached. It just knows the point that it has reached and what is the loss at that point."
14.1.1 Vanilla Gradient Descent Update Rule
The update rule. Standard gradient descent. also called vanilla gradient descent. is the simplest iterative optimization algorithm. You use it to find the minimum of a loss function by taking steps proportional to the negative gradient.
Here is what every symbol means:
| Symbol | Meaning | LaTeX | Type |
|---|---|---|---|
| Parameter vector at step — your current guess | vector in | ||
| Learning rate (step size) — how large each step is | scalar, typically | ||
| Gradient of the loss at — the steepest-uphill arrow | vector in |
Why subtract the gradient? The gradient points in the direction of steepest increase. To go downhill. which is what you want when minimizing. you move in the opposite direction. So you subtract from the current point.
The algorithm moves by only two things: the learning rate and the gradient. It has no memory of where it came from. It does not know whether it is at the global minimum, a local minimum, or a flat plateau. It only knows the current position and the current slope.
14.1.2 Why Simple Gradient Descent Can Fail
Assumptions &. Scope. Gradient descent assumes your loss function is differentiable (smooth, no sharp kinks) and. for guaranteed convergence. convex (a bowl shape with a single bottom). It also assumes you pick a reasonable learning rate. When these assumptions break, gradient descent hits four well-known problems.
1. The large valley problem. When the loss surface has a long, narrow valley, the gradient along the valley floor is nearly zero. Picture a stretched-out bowl. If you start anywhere in that valley, your steps become tiny because the slope is tiny. You inch toward the minimum painfully slowly. Think about it this way: "When you have a large valley, the surface is flat. The gradient becomes small. So it would take many steps to reach the minimum."
2. The plateau problem. A plateau is a nearly flat region. The gradient there is close to zero. The updates become so small that you might wrongly conclude you have reached the optimum. Once the iterations stop improving, you might think you hit the minimum. But you may not have. you may just be stuck on a flat patch.
3. The oscillation problem. When you crank up the learning rate to fix slow convergence, the algorithm starts zigzagging. It swings violently from one side of the valley to the other. It might escape the valley altogether. or oscillate forever between two points without settling. Think about it this way: "When we increase the learning rate, you'll see a lot of oscillation. The gradient descent iterations could escape outside the entire valley."
4. The local minimum trap. If the loss surface has multiple basins, gradient descent can get stuck in any of them. The algorithm does not know whether the minimum it found is local or global. The only practical remedy: run the algorithm from multiple random starting points, compare the final losses, and pick the best one. Start at point A, find loss . Start at point B, find loss . Start at point C, find loss . If is much lower, take the result from point C.
Visual intuition. Plot the loss on the vertical axis against on the horizontal. For a convex bowl (like a parabola), the gradient descent path is a smooth curve that slides steadily to the bottom. For a surface with valleys and plateaus, the path looks like a ball rolling through sticky terrain. it goes fast on steep slopes, crawls on flats, and zigzags in narrow ravines. If there are multiple basins, the ball might stop in a shallow dip and never reach the deepest hole. The takeaway: the shape of the loss surface controls everything. Bad shape, bad convergence.
14.1.3 Worked Example: One Step to Minimum
Consider the simple convex loss function:
This is a perfect bowl in three dimensions. The minimum is at exactly .
Take the partial derivatives:
So the gradient at any point is the point itself: . The halves and squares cancel cleanly. this function was chosen precisely because the point and its gradient are identical, making hand calculations easy.
Run standard gradient descent with learning rate , starting from .
Iteration 1:
In a single step, gradient descent reached the exact minimum . This is only possible because the point equals the gradient and .
Iteration 2:
Now , so the gradient is also .
The parameters do not change. The loss is zero. But the algorithm itself does not stop. it just keeps computing the same update forever.
Sense-check: For this special function, the gradient equals the point, and makes each step exactly cancel the current position. The result (0,0) is the minimum because both squared terms must be non-negative.
14.1.4 Stopping Criteria
Pitfall: The algorithm is blind. The algorithm does not know it has reached the minimum. It only knows the current position and the current loss. It keeps computing the next update using the same equation. Think of driving a car. the car does not know it arrived home. The human driver applies the brakes. The algorithm is the car. you are the driver.
Two common stopping criteria:
- No improvement over several iterations. If the parameters sit still for five or six steps and the loss is flat, declare convergence. The guideline: if the parameter value does not change for five or six steps, take this as the optimal point.
- Maximum number of iterations. Set a hard cap and stop when you hit it. Then check the final loss and decide if it is acceptable.
Do NOT stop when the loss hits zero. The loss might not be zero at the optimum. Some functions have negative minima. You cannot hardcode "if loss equals 0, jump out of the loop" as a stopping condition. You must first prove analytically that zero is the true minimum. In general, you do not know the minimum loss in advance.
How do you know whether you are stuck at a plateau, a local minimum, or the global minimum? You start from a different random initialization in the next run. If the new run finds a much lower loss, the previous run was stuck. Run from several different starting points and keep the best result.
Q: At a local minimum, we also get a near-zero gradient. The algorithm cannot tell local from global. How do we fix this? A: You cannot fix this inside the algorithm itself. The practical approach is to run gradient descent multiple times from different random starting points. Each run may land in a different minimum. Compare the final loss values across runs. The run with the lowest loss is your best guess at the global minimum.
Several students asked variations of this same question. it is a common confusion point.
Q: Can we use the Hessian matrix to identify whether a point is a local minimum? A: The Hessian approach. taking second derivatives, setting first derivatives to zero, solving a system of equations via RREF, then checking the Hessian. involves a huge amount of computation. For many variables, you would compute all partial derivatives, set each to zero, solve the system, and find candidate points. Then compute and evaluate the Hessian at each one. The compute is much, much larger than what gradient descent requires. That is exactly why we switched to iterative methods like gradient descent. the closed-form solution is computationally infeasible.
14.1.5 Visual Intuition
Describe a 3D plot of with the vertical axis as the loss value. The surface is a perfect upward-facing bowl. The point sits on the side of the bowl, high above the floor. The gradient at that point is an arrow that points radially outward. straight up the side. Gradient descent takes the exact opposite arrow, moving straight to the center in one step when . For a non-circular loss like , the contours are ellipses and the gradient never points directly at the minimum. The descent path zigzags. overshooting in the steep direction () while crawling in the shallow direction (). This is the differential curvature problem that motivates momentum and adaptive methods.
14.1.6 Real-World & Domain Connection
In industry, when training large neural networks, practitioners monitor the loss curve. If it flattens, they check whether the model has converged or is stuck on a plateau. They often increase the learning rate temporarily or restart from a different random seed. The oscillation problem is a major reason why Adam and RMSprop are the standard optimizers today. they adapt the learning rate per parameter, dampening zigzagging. Gradient descent itself is the foundation of every modern deep learning system. Understanding its failure modes is the first step to understanding why those fancier algorithms exist.
14.1.7 Recap and Bridge
Vanilla gradient descent takes steps downhill using only the local slope. It is simple and foundational. But it suffers badly from valleys (slow progress), plateaus (false convergence), oscillation (zigzagging), and local minima (getting stuck in shallow basins). The next three sections introduce momentum, adaptive learning rates, and Adam. each designed to fix one or more of these problems.
Exam note: Computing iterations of gradient descent for a simple convex function. like . is commonly asked in examinations. Expect to be given a loss function, a starting point, and a learning rate, and asked to compute two or three iterations. Give extra attention to this section.
---
14.2 Momentum-Based Gradient Descent
Hook. What if your optimizer could remember how it was moving before it hit a flat patch? A rolling ball carries speed. it does not freeze just because the ground briefly levels out. Standard gradient descent has no memory at all. Momentum gives it one.
Intuition + Analogy. Roll a heavy marble down a bumpy hill. On a steep slope, it speeds up. When the hill flattens, the marble keeps rolling. it does not stop dead. That is momentum. The marble's current speed is a blend of where it came from (past gradients) and what it feels right now (current gradient). Now map this to the formulas:
- The marble's velocity is the direction and speed of movement.
- The marble's weight/inertia is . how much of the old velocity it keeps.
- The new push from the current slope is . scaled by the learning rate.
- The next position is the current position minus the velocity.
The analogy breaks because a real marble loses energy to friction and settles at the bottom. Momentum in optimization often overshoots the minimum, oscillates back, and takes time to settle. the marble has no natural friction unless you design it in.
Think about it this way: "This acts as a memory. We are giving a very high weightage to recent few gradients. We are trying to memorize what has been our recent few gradients."
14.2.1 Velocity Term and Update Rule
Momentum fixes gradient descent's slow convergence by adding a velocity term. The velocity accumulates past gradients. A heavy ball keeps rolling even when the slope momentarily flattens.
The momentum update has two equations:
Here is what every symbol means:
| Symbol | Meaning | LaTeX | Type |
|---|---|---|---|
| Velocity at step — the accumulated momentum | vector in | ||
| Momentum coefficient (decay factor) — how much of the old velocity you keep | scalar, typically | ||
| Parameter vector at step | vector in | ||
| Learning rate — scales the contribution of the current gradient | scalar | ||
| Gradient of loss at | vector in |
Why two equations? The first equation builds the velocity. a running blend of old velocity and new gradient. The second equation uses that velocity to update the parameters. This split is what gives momentum its memory: the velocity persists across steps.
When , momentum collapses to standard gradient descent because . When is high (say ), the velocity carries forward most of its previous value, adding only a small fraction of the current gradient.
14.2.2 Exponential Decay Interpretation
Expand the velocity recurrence to see what it really does. Write for brevity.
Substitute :
Keep expanding:
This is a weighted sum of past gradients with exponentially decaying weights. The current gradient gets weight . The previous one gets . The one before that gets , and so on. For , the weights are
The ball gets "heavier" because of the accumulated past gradient contributions. That is why it is called momentum. The heavy ball does not stop exactly at the minimum. it overshoots, rolls up the opposite side, comes back, oscillates a bit, and settles.
Q: From the expansion, can we say we are assigning weights to the ball. like . increasing the weight of the ball as we roll? A: Yes, that is exactly the right intuition. The velocity term gives weight to all past gradients, decaying by a factor of each step back.
Q: In a previous session, the formula was written as multiplied by the derivative. Here and seem separate. Are they dependent or independent? A: Both formulations exist. In one version, the learning rate is absorbed into the momentum term so that . In the other, and are treated as independent hyperparameters. People use both conventions. Either is valid. it depends on the formulation you adopt.
14.2.3 Worked Example: Two Iterations of Momentum
Use the same convex loss function . Start from . Learning rate . Momentum coefficient .
Iteration 1:
The initial velocity is . a cold start with no prior history.
This first step is identical to standard gradient descent because . Both land at .
Iteration 2:
Now , so the gradient at this point is . But the previous velocity is not zero.
The momentum carried the ball past the minimum. It overshot from to . In the next iteration, the velocity will point the other way and pull it back. Momentum makes the ball overshoot, fly past the bottom, climb the other side, come back, oscillate, and settle.
Sense-check: The overshoot is expected. With , half of the previous velocity survives. Since the gradient at the minimum is zero, the velocity at step 2 is purely the carried-forward value . The parameter moves in that direction, landing at . The loss at is , worse than the 0 at the minimum. But future iterations will correct this.
Visual intuition. Plot the two iterations on the - plane. The starting point is at . A straight arrow shoots to . that is step 1, identical to vanilla GD. Then a second arrow shoots from to . that is the overshoot caused by the leftover velocity. The trajectory forms a "V" shape: down to the minimum and straight out the other side. On a real loss surface, the ball would oscillate back and forth across the minimum. The amplitude shrinks each time as the velocity decays.
14.2.4 Assumptions, Scope & Pitfalls
Assumptions. Momentum assumes the gradient direction stays roughly consistent across steps. It works best when the loss surface has a clear downhill direction with gentle curves. like long valleys. It has two hyperparameters ( and ) that need tuning.
Pitfalls:
- Overshooting. The whole point of momentum is to carry speed. But too much speed means you sail past the minimum repeatedly. High (close to 1) makes the ball too heavy. It oscillates for many steps before settling.
- Divergence with large . If the learning rate is already high and you add momentum, the combined effect can explode. The velocity accumulates large gradients, making each step bigger than the last. This is why is typically set lower with momentum than without.
- Cold start. The first step has no history (). Momentum behaves exactly like vanilla GD on step 1. It takes a few iterations before the velocity builds up meaningful memory.
- Not a fix for local minima. Momentum helps you roll through shallow local minima better than vanilla GD. But a deep enough basin will still trap it. It is not a global optimization method.
Comparison: Vanilla GD vs. Momentum. On the same loss function starting from with :
| Aspect | Vanilla GD | Momentum () |
|---|---|---|
| Step 1 | Reaches — exact minimum | Reaches — same as GD (cold start) |
| Step 2 | Stays at — zero gradient | Overshoots to — carried by velocity |
| Behavior on plateaus | Stalls — no gradient, no movement | Keeps moving — velocity carries forward |
| Behavior in valleys | Tiny steps along the floor | Faster progress — velocity accumulates along consistent direction |
| Settling | Stops immediately at minimum | Oscillates, then settles |
When to use momentum: choose it when the landscape has long, consistent slopes and flat patches, and you can afford some oscillation for faster overall convergence. If overshoot is unacceptable (e.g., you need a precise minimum), use vanilla GD with a smaller learning rate instead.
14.2.5 Real-World & Domain Connection
SGD with momentum remains widely used for computer vision models like ResNet and Vision Transformers. With carefully scheduled learning rates (starting high, decaying over time), momentum-based SGD can sometimes outperform even Adam in final accuracy. The reason: momentum's simplicity gives it less bias than adaptive methods on certain architectures. In deep learning, the choice of optimizer is a design decision. momentum is the reliable workhorse. Adam is the convenient default.
14.2.6 Recap and Bridge
Momentum adds a velocity term that accumulates past gradients with exponential decay. This gives the optimizer memory. it keeps moving through flat patches and speeds up in consistent-gradient valleys. The trade-off is overshoot: the ball may swing past the minimum and oscillate before settling. Next, adaptive learning rate algorithms tackle the problem from a different angle. they adjust the step size per parameter instead of adding velocity.
Exam note: Two iterations of momentum on a simple convex function. with a given , starting point, and learning rate. are very likely on the exam. Know both equations: the velocity update and the parameter update. Remember that always.
---
14.3 Adaptive Learning Rate Algorithms
Hook. Every parameter in your model needs a different step size. Some dimensions are steep cliffs. one wrong step and you tumble. Others are nearly flat. you crawl so slowly you might as well be stuck. A single learning rate cannot serve both. What if each parameter could learn its own pace?
Intuition + Analogy. Imagine walking through a landscape where the ground changes texture. On loose gravel, you take small, careful steps. On smooth pavement, you stride confidently. Your brain adjusts stride length without you thinking about it. That is what adaptive optimizers do. They adjust the effective step size per parameter based on how "rough" or "smooth" the past gradients have been in each direction.
Map this to the math:
- The roughness of the ground for parameter is the accumulated squared gradient in that direction.
- The effective step size is . when past gradients were large, the denominator is large, so the step shrinks. When past gradients were tiny, the step grows.
- The different algorithms (Adagrad, RMSprop, Adam) differ only in how they accumulate that history.
The key idea: "If you are having a very high gradient in a slope situation, you say, algorithm, I do not take long steps. When the gradient is high, the algorithm adapts. It makes the learning rate smaller."
14.3.1 Conceptual Motivation
In standard gradient descent, the learning rate is the same for every parameter and every step. But the loss landscape is not uniform. some directions are steep, others nearly flat. A single learning rate cannot serve both well.
All adaptive algorithms follow this template:
where is an accumulation factor. a running statistic of squared gradients. and denotes element-wise (Hadamard) multiplication. The core idea: divide the learning rate by a factor that tracks gradient magnitude per parameter.
- When the gradient is very high (steep slope) → large denominator → small effective step → no overshoot.
- When the gradient is very small (flat region) → small denominator → large effective step → faster movement.
The algorithms differ only in how they compute .
14.3.2 Adagrad (Adaptive Gradient)
Adagrad accumulates all past squared gradients with equal weight. No decay. every gradient in the entire history counts equally.
Accumulation factor:
Update rule:
The square root is taken element-wise. The operator means element-wise multiplication: multiply the first element of by the first element of the gradient, the second by the second, and so on.
| Symbol | Meaning | LaTeX | Type |
|---|---|---|---|
| Accumulated sum of squared gradients up to step | vector in | ||
| Gradient at step | vector in | ||
| Global learning rate | scalar | ||
| Element-wise (Hadamard) multiplication | binary operator |
Why it adapts. When the terrain has been steep, is large, so is small. The effective learning rate shrinks. When the terrain is flat, stays small, so the effective learning rate stays large.
Why it breaks. The accumulation never forgets. If you start on a steep cliff and later enter a flat valley, remains large from the cliff memory. Your effective learning rate stays small forever. Even though the current gradient is tiny, you cannot speed up. The denominator grows monotonically, and eventually learning grinds to a halt.
Worked Example. Adagrad, two iterations
Same setup: , start , .
Iteration 1:
(no prior accumulation).
Started at , reached . Compare: vanilla GD jumped directly to . Adagrad took a much smaller step because the gradient was high, so reduced the effective movement.
Iteration 2:
, so .
, .
After two iterations: . The progress is steady but slow. Adagrad is more cautious than both vanilla GD and momentum. The effective learning rate decreases every step because only grows.
Sense-check: The step sizes shrink predictably. At step 1, the effective rate was . At step 2, it became . The denominator grew monotonically as expected.
14.3.3 RMSprop
RMSprop fixes Adagrad's monotonically growing denominator by adding a decay factor. Instead of accumulating all squared gradients equally, RMSprop applies an exponentially weighted moving average.
Accumulation factor:
Update rule:
The structure is identical to Adagrad. The only difference is . it uses a moving average, so it can increase or decrease based on current gradients.
| Symbol | Meaning | LaTeX | Type |
|---|---|---|---|
| Exponentially weighted moving average of squared gradients | vector in | ||
| Decay factor for the moving average | scalar, typically or | ||
| Gradient at step | vector in | ||
| Global learning rate | scalar |
is typically high, around . A high biases the accumulation toward past squared gradients. The current gradient gets only a small weight, . Think about it this way: "We would put more weightage to the past gradients than what your current gradient is. We keep track of my history and are more biased towards history than the present."
Why RMSprop is faster than Adagrad. Because is a moving average, old large gradients are gradually forgotten. If you leave a steep region and enter a flat valley, will decay, lowering the denominator and allowing larger steps again. Adagrad would be permanently penalized by old steep gradients.
Worked Example. RMSprop, two iterations
Same setup: , start , , .
Iteration 1:
.
RMSprop reached . further than Adagrad's from the same starting point. RMSprop takes a larger step because the factor gives less weight to the current squared gradient, making the denominator smaller.
Iteration 2:
, so .
.
After two iterations: . RMSprop moves notably faster than Adagrad.
Sense-check: The effective learning rates at step 1 were . at step 2 they were . Unlike Adagrad, the first component's rate did not shrink. it stayed at because the decaying memory balanced the new gradient contribution.
Q: How do we write element-wise division as a column vector. like and in a column? A: Mathematically you cannot write element-wise operations as regular scalar-vector operations. For calculation purposes, you can write the results side by side. In an exam, write element-wise operations step by step for each component, or use a shorthand vector notation. Either approach is acceptable.
14.3.4 Adam (Adaptive Moment Estimation)
Adam combines momentum and RMSprop. It maintains two running averages:
- . a momentum-like running average of gradients (first moment).
- . an RMSprop-like running average of squared gradients (second moment).
Momentum term (first moment):
Velocity term (second moment):
controls momentum decay (typically ). controls the squared-gradient moving average (typically in implementations, though the text used for hand calculations). Both are close to 1, meaning the optimizer is heavily biased toward its history.
Expanded interpretation. Expand the recurrences the same way as momentum:
So is a weighted sum of past gradients, and is a weighted sum of past squared gradients.
Bias correction. Both and start at zero (). This biases early iterations toward zero. the cold start problem. Adam compensates with bias correction:
Adam uses this simplified form where you divide by once. The original Adam paper (Kingma &. Ba, 2014) uses and , where is the iteration index. This provides a per-step correction that gradually disappears as grows. For the first iteration (), the two forms give the same result since . For later iterations, this simplified form somewhat over-corrects. But it works reasonably and is what you will see on the exam.
Update rule:
where denotes element-wise division. The update uses both corrected factors: the momentum term divided by the square root of the velocity term.
Why take the square root of ? Because tracks squared gradients. Taking the square root brings it back to the same order as the gradient, making the ratio unit-consistent. It is like root mean squared (RMS): square the values, average them, take the square root to return to the original scale.
| Symbol | Meaning | LaTeX | Type |
|---|---|---|---|
| First moment (running average of gradients) | vector in | ||
| Second moment (running average of squared gradients) | vector in | ||
| Decay factor for first moment | scalar, | ||
| Decay factor for second moment | scalar, | ||
| Bias-corrected first moment | vector in | ||
| Bias-corrected second moment | vector in | ||
| Element-wise division | binary operator |
Worked Example. Adam, one iteration
Same setup: , start , , .
Step 1. Compute raw moments:
, .
Step 2. Bias correction:
Step 3. Parameter update:
Adam reached in one step. the same as Adagrad's first step for this example. This coincidence is specific to this function and parameter choice. On real problems, Adam typically outperforms both Adagrad and RMSprop.
Sense-check: After bias correction, and . So . The update subtracts from , giving . The dimensions are consistent: a 2D gradient produces a 2D update.
Q: Where does the bias-corrected get used in the update formula? A: appears in the denominator under the square root: . is the numerator, is the denominator. They combine through element-wise division.
14.3.5 The Cold Start Problem
Pitfall: The Cold Start. Every adaptive algorithm suffers from one shared problem. the cold start. When you initialize, there is no history. , , , and are all zero. The first step uses only the current gradient. The first few iterations are biased toward zero. You will have a very slow start. Once history begins accumulating, progress improves.
Think about it this way: "All of them suffer from one thing. the cold start problem. When you start, you have no accumulation history. The first step is almost very small. Since we initialize to zero, early steps are biased towards zero. But once it starts learning, it progresses well."
Adam addresses this explicitly with bias correction. Adagrad and RMSprop have no formal bias correction. they simply live with a slow start. Things improve as gradients accumulate.
Q: We initialized the velocity as zero. that is the cold start problem, right? A: Yes, exactly. The first velocity is zero because there is no prior history. The first step is small. Bias correction in Adam compensates for this. it scales up the early moments to counter the zero-initialization bias.
14.3.6 Assumptions, Scope & Visual Intuition
Assumptions &. Scope.
- RMSprop / Adagrad / Adam assume differentiable loss. Like all gradient-based methods, they fail at sharp kinks where the gradient is undefined.
- The denominator must not approach zero. In practice, a small epsilon (like ) is added under the square root to prevent division by zero: .
- Hyperparameter sensitivity. Adam has three: . Typical defaults are , , . Deviating from these often hurts. Adam is robust but not immune to bad settings.
- Adagrad's scope is narrow. It works well on sparse features (where some parameters rarely update). But its monotonically decreasing rate makes it unsuitable for non-convex deep networks.
- RMSprop and Adam work well on non-stationary objectives (RNNs, RL) where the loss landscape shifts during training. Adagrad would fail here because old cliff gradients would permanently slow it.
Visual intuition. Imagine a 2D contour plot where the vertical axis is , the horizontal axis is , and the contours are ellipses of the loss . Each algorithm traces a different path from toward :
- Vanilla GD: a zigzag line. long strides in the direction, tiny nudges in .
- Momentum: a smoother curve that swings past the center and circles back.
- Adagrad: a cautious, steadily slowing curve. almost a straight line but at half the speed.
- RMSprop: a faster version of Adagrad's curve, adjusting stride length as the terrain changes.
- Adam: combines the smoothness of momentum with the adaptive stride of RMSprop. typically the most direct path to the minimum.
14.3.7 Algorithm Comparison
| Algorithm | Accumulation | Decay? | Cold start fix? | Behavior |
|---|---|---|---|---|
| GD | None | — | — | Constant step size; struggles on plateaus |
| Momentum | Velocity (gradient sum) | Exponential, | No | Overshoots, oscillates, faster in valleys |
| Adagrad | Sum of squared gradients | No decay | No | Monotonically decreasing step size; eventually stalls |
| RMSprop | Moving avg of squared gradients | Exponential, | No | Adaptive; can accelerate after leaving steep regions |
| Adam | Both gradient sum + squared gradient moving avg | (both ) | Yes (bias correction) | Combines momentum with adaptive rates; generally the default |
When to pick which. For most deep learning problems: Adam is the default. it requires the least tuning. For RNNs or RL: RMSprop often works better. For computer vision with careful scheduling: SGD + momentum can beat both in final accuracy. Adagrad is mostly historical. use it only for sparse features or as a teaching step.
14.3.8 Real-World & Domain Connection
Adam is the default optimizer in TensorFlow and PyTorch, used to train everything from image classifiers to large language models. It requires minimal tuning. set the learning rate and go. RMSprop is common in sequence models (RNNs, LSTMs) and reinforcement learning where the loss surface is non-stationary. SGD with momentum remains the gold standard in computer vision (ResNet, ViT) when combined with learning rate schedules. Each optimizer occupies a slightly different ecological niche in the deep learning ecosystem.
14.3.9 Recap and Bridge
Adaptive optimizers adjust the effective learning rate per parameter by dividing by the square root of an accumulated gradient statistic. Adagrad accumulates everything and eventually stalls. RMSprop uses a moving average, so it can forget and speed up again. Adam combines momentum with RMSprop and adds bias correction. it is the most capable of the three. All three suffer from cold start. But Adam addresses it explicitly.
Exam note: Expect two iterations of Momentum, Adagrad, RMSprop, or Adam on the exam. Adam is the heaviest. it needs raw moments, bias correction, and element-wise division. A helpful tip: "you just pray you don't get Adam." In the example, was used for hand calculation. Real implementations use and with . Just plug in whatever values the question gives you.
---
14.4 Introduction to Constrained Optimization
Hook. So far, your optimizer could wander anywhere. But what if you are told: "Minimize the cost. But do not spend more than your budget. Do not use negative amounts. And stay inside this box." Suddenly, the optimizer has walls it cannot cross. Gradient descent. born for smooth, open landscapes. has no idea what to do with walls.
Intuition + Analogy. You are walking through a room looking for the lowest spot on the floor. Normally, you follow the slope under your feet. But now someone puts up walls. a rectangle you cannot leave. The lowest spot might be in the middle of the room. But it might also be pressed right against a wall. And the slope at the wall makes no sense. the floor just stops. That is constrained optimization: find the best you can while staying inside a fence.
Map this to the math:
- The room is the feasible region. the set of points that satisfy all constraints.
- The walls are the constraint boundaries where .
- The Lagrangian turns hard walls into soft penalties. cross them and you pay, so you learn to stay inside.
- The primal/dual game is about who moves first: you (picking parameters) or the penalties (knowing the rules). Going second is better.
14.4.1 Gradient Limitations on Non-Smooth Functions
Gradient-based methods need the loss function to be smooth and continuous. The gradient. being a derivative. is only defined where the function has no sharp edges, corners, or walls. If the function has breaks, you cannot compute the gradient at those points.
In constrained optimization, the constraints themselves introduce hard boundaries. The feasible region. the set of points that satisfy all constraints. has edges. The optimum often lies on one of those edges, exactly where the gradient is not defined. Think of a ball rolling and hitting a wall: the trajectory is broken.
The key idea: "Gradient is a derivative. It is only defined for a smooth, continuous function. If the function has edges, you cannot compute the gradient at a point like this."
14.4.2 Feasible Regions and Linear Programming
Consider an optimization problem with box constraints:
Objective: Minimize
Subject to: ,
The constraints carve out a rectangular feasible region. all points with between 0 and 4, between 0 and 2. You are only allowed to search within this rectangle.
Consider a linear programming problem:
Worked Example. Linear Program Feasible Region
Minimize subject to:
Draw these constraints on the - plane. shades everything left of the vertical line at . shades everything below the horizontal line at . shades everything below the diagonal line from to . The feasible region is the polygon formed by the intersection of all three shaded regions. Its vertices are at , , , and .
The objective is a plane tilted upward. Its minimum over this polygon sits at the origin . If the constraints were absent, the minimum would be unbounded. Constraints define the battleground.
Sense-check: At each vertex: , , , . The origin wins.
A fundamental result from linear programming: the optimum of a linear objective with linear constraints always lies at a corner point. It is never in the interior. This is why the simplex method only checks vertices.
Visual intuition. Plot the - plane. Shade the three constraint regions. The feasible polygon has vertices at , , , and . The objective is a plane tilted upward. its minimum over this polygon sits at the origin .
Why the optimum sits on the edge. Imagine rolling a ball on a constrained surface. If there is a hard wall (a constraint), the ball gets pushed against it. The gradient spikes at the boundary. The ball cannot pass through the wall. It naturally rests against an edge. In multi-dimensional problems, walls appear everywhere. Direct gradient-based optimization becomes very difficult because the gradients blow up at boundaries.
Think about it this way: "The optimal values only lie at the edges. Though this is a feasible region, the optimal value of this function would only lie at these corner points. If you start rolling a ball from here, you are going to stick at a point which is almost edgy. The gradient increases hugely at this particular point."
14.4.3 Lagrangian Formulation
Rather than working with hard constraints directly, we convert the constrained problem into an unconstrained one using the Lagrangian. This is done by adding penalty terms for constraint violations.
Step 1: Write constraints in standard form ().
Every constraint must be rewritten as . If a constraint says , multiply by to get . If a constraint says , rewrite as .
The rule: "Wherever you have greater-than-or-equal-to constraints, you multiply by minus one and convert it into less-than-or-equal-to."
For the box-constraint problem with , :
Worked Example. Lagrangian Construction
Problem: Minimize subject to , .
Step 1: Convert constraints to form.
Step 2: Build the Lagrangian. Introduce multipliers :
Plug in:
The hard walls have become soft penalties. Violate and you pay . violate and you pay . and so on. The multipliers are the price of transgression.
Sense-check: At the origin , all constraints are satisfied strictly: , , , . The Lagrangian reduces to . If we move to , then and the penalty term kicks in. The Lagrangian penalizes the violation.
| Symbol | Meaning | LaTeX | Type |
|---|---|---|---|
| Objective function to minimize | scalar function | ||
| The -th constraint, in form | scalar function | ||
| Lagrange multiplier (penalty) for constraint | scalar, | ||
| Lagrangian function | scalar function |
14.4.4 Primal and Dual Problems
The Lagrangian converts a constrained problem into an unconstrained one that depends on both the original variables and the multipliers . This creates a minimax game. a zero-sum contest between two players:
- Player 1 (Minimizer): chooses to minimize .
- Player 2 (Maximizer): chooses to maximize . effectively punishing constraint violations.
The order of play matters enormously.
The primal problem : you pick the variables first, then the adversary picks penalties. Since you moved first without knowing the penalties, you might wander into forbidden regions. The penalty explodes. You lose.
The dual problem : the penalties are set first, then you optimize the variables knowing what is forbidden. You stay safely inside. Going second gives you an advantage. you see what the first player did and can react.
The analogy: "When you know there is a gate and a danger mark, you will not enter. If there is no sign and dynamite in the ground, you step on it. Then you realize the mistake."
T-shirt bargaining analogy. You go to a shop. If the price is set (penalties fixed), you. the buyer. choose the best T-shirt your budget allows. If the seller sets the price after seeing you want it, they can charge more. The one who moves second has the advantage.
Machine learning interpretation. Let be model parameters and be noise. If you know the noise level ( set first), you can choose the best model. that is the dual. If you choose a model first without knowing the noise, you risk a bad fit. that is the primal.
14.4.5 Min-Max Inequality and Zero-Sum Games
The min-max inequality formalizes the idea that planning second is never worse than planning first:
- Left side (primal): first minimize over variables, then maximize over penalties. Think: pick model first, then face the data.
- Right side (dual): first maximize over penalties, then minimize over variables. Think: know the noise first, then pick the model.
The inequality says the dual value is always at least as large as the primal value. When equality holds. . we call it strong duality. For convex problems (like the ones in this lecture), strong duality holds. The dual gives the same answer as the primal, and the dual is often much easier to solve.
Why the inequality? The minimizer on the left has to protect against any penalty the maximizer could choose. a worst-case mindset. The minimizer on the right gets to see the penalties first. an informed choice. Information cannot hurt you, so the informed minimum is never worse (i.e., never larger) than the uninformed one.
Connection to SVM. The SVM companion document shows this exact structure. The primal SVM problem minimizes subject to . The Lagrangian converts these constraints into penalties . The dual SVM problem. which is what you actually solve. maximizes over after minimizing over . The dual reveals the kernel trick and the support vectors. This is Lagrangian duality in action.
Pitfalls:
- Constraints must be in form. Many students lose marks by forgetting to flip the sign for constraints. becomes . Always convert before building the Lagrangian.
- Lagrange multipliers are non-negative for inequality constraints (). A negative multiplier would reward constraint violations, which defeats the purpose.
- Strong duality is not guaranteed for non-convex problems. If the objective or any constraint is non-convex, the primal and dual solutions may differ. The techniques in this lecture assume convexity.
- The dual is easier. But it is still an optimization problem. it may itself need gradient descent. Duality trades hard constraints for more variables.
14.4.6 Nash Equilibrium and Game Theory
The min-max framework was pioneered by John von Neumann and extended by John Nash (subject of the film A Beautiful Mind). A Nash equilibrium describes a situation where each player, knowing the other's strategy, has no incentive to change their own. The zero-sum game. two players, opposing objectives, sequential moves. is the mathematical foundation of duality in optimization.
Real-world applications:
- GANs (Generative Adversarial Networks): a generator minimizes loss while a discriminator maximizes it. a literal zero-sum game trained by alternating optimization.
- Robust optimization: design systems that perform well under worst-case conditions. the dual formulation captures this naturally.
- Portfolio optimization: maximize returns subject to risk constraints, solved via Lagrangian duality.
- Support Vector Machines: the dual formulation reveals support vectors and enables the kernel trick.
- Operations research / linear programming: the simplex method exploits the corner-point principle to solve massive industrial problems in supply chains, logistics, and scheduling.
14.4.7 Student Questions
Q: You mentioned that solving the dual is easier than solving the primal. Why exactly? A: The primal may have too many hard constraints and variables mixed together. The dual separates them into two stages. first choose penalties, then optimize variables. which can be solved sequentially. For SVMs, the primal has variables (dimension of ) while the dual has variables (number of data points). But the dual's structure is simpler and reveals the kernel trick. The next session demonstrates this with worked examples.
14.4.8 Recap and Bridge
Constrained optimization handles problems where the solution must stay inside a feasible region. The Lagrangian converts hard constraints into soft penalties via Lagrange multipliers . The resulting minimax game. primal vs. dual. trades constraint difficulty for additional variables. The dual is always a lower bound. when convexity holds (strong duality), the dual gives the exact solution, often more easily than the primal.
Exam note: Primal-to-dual conversion has appeared in recent exams. Know the three steps. (1) Convert all constraints to form by flipping signs where needed, (2) build the Lagrangian , (3) express the dual as . Convert constraints to standard form, build the Lagrangian, write the dual.
---
Exam Guidance Summary
Exam note: Standard GD with convex functions. Computing 2–3 iterations on a simple convex function like is a common exam problem. You will be given a loss function, a starting point, and a learning rate. Know the update rule cold.
Exam note: Momentum, Adagrad, RMSprop, Adam. Two iterations of any one of these four is very likely on the exam. Know all formulas. the velocity/moment accumulation AND the parameter update. For each algorithm, here is the minimum you must memorize:
- Momentum: , then
- Adagrad: , then
- RMSprop: , then
- Adam: then bias-correct , then
Adam is the heaviest calculation. bias correction, two moments, and element-wise division. The advice: you just pray you do not get Adam. That said, always plug in whatever values the question gives you.
Exam note: Primal-to-dual conversion. "I have seen in the last few years they have given a primal and asked to write down the dual." Know the three steps:
- Convert all constraints to standard form (flip signs for constraints).
- Build the Lagrangian with .
- Express the dual as .
Problem types expected. Two kinds:
- Numerical computation. iterate through GD, momentum, Adagrad, RMSprop, or Adam steps with given numbers.
- Symbolic manipulation. write the Lagrangian, convert primal to dual.
Practice problems. Request has been made for exam-like problems from previous mid-semester exams covering momentum through Adam iterations. A mathematics textbook recommendation covering Jacobians, gradient descent, and constrained optimization will be shared later.
---
Key Industry Applications
- Adam is the default optimizer in PyTorch and TensorFlow. It trains everything from image classifiers (ResNet, EfficientNet) to large language models (GPT family). Its appeal: plug-and-play. set the learning rate and go. Minimal hyperparameter tuning needed.
- RMSprop is the go-to for recurrent neural networks (RNNs, LSTMs, GRUs) and reinforcement learning. In these settings, the loss landscape shifts during training (non-stationary objectives). Adagrad would fail because old steep gradients permanently slow it down. RMSprop's moving average forgets and adapts.
- SGD with momentum remains the gold standard in computer vision. ResNet, Vision Transformers, and many ImageNet-winning architectures were trained with momentum + learning rate schedules (e.g., cosine annealing). With careful tuning, momentum can sometimes beat Adam in final accuracy. its simplicity gives it less bias on certain problems.
- Lagrangian duality / constrained optimization is the mathematical engine behind Support Vector Machines. The SVM primal has hard-margin constraints. the dual reveals support vectors and enables the kernel trick. Beyond SVMs, duality is used in portfolio optimization (maximize returns subject to risk budgets), control theory (stay within safe operating bounds), and resource allocation (meet demand without exceeding capacity).
- Zero-sum games / min-max power Generative Adversarial Networks (GANs), where a generator minimizes loss while a discriminator maximizes it. trained by alternating optimization. The same framework appears in robust optimization (worst-case design), adversarial training (defending against attacks), and game theory for economics and auction design.
- Linear programming drives operations research at scale. The simplex method, which exploits the corner-point principle, solves problems in supply chain logistics, airline crew scheduling, production planning, and network flow optimization. Every major shipping company and airline runs LP solvers daily to plan routes and allocate resources.
---
MFML Lecture 14 notes · Gradient Descent Variants and Constrained Optimization
Sections Breakdown
Vanilla update rule, valleys, plateaus, oscillation, local minima, and stopping criteria.
Velocity term, exponential decay of past gradients, and overshoot behaviour.
Adagrad, RMSprop, Adam, and the shared cold start problem.
Lagrangians, primal/dual problems, min-max duality, and linear programming.
What to prepare for an exam question on gradient descent variants and constrained optimization.
Where these optimizers and duality ideas are used in practice.
Exam Revision Notes
Below is the distilled, exam-ready core of this lecture. Every entry is built from the full textbook notes above. Use this section for rapid review — but if something doesn't make sense, go back to the full explanation in the main content.
Standard (Vanilla) Gradient Descent
Must know: Update moves opposite the gradient. It has no memory and is blind to the landscape beyond its current slope.
Common pitfall: Stopping when the loss hits zero. A real optimum need not have zero loss, so a zero-loss cutoff can exit early or never trigger.
Self-check: Why do we subtract the gradient instead of adding it?
Connects to: Momentum, Stopping criteria, Local minima
Momentum
Must know: A velocity term accumulates past gradients with exponential decay, giving the optimizer memory. Beta near 0.9 makes it heavy.
Common pitfall: Cold start: v_0 = 0, so step 1 is identical to vanilla GD. Too high a beta also causes long oscillation before settling.
Self-check: Why does momentum take a few steps before it kicks in?
Connects to: Vanilla GD, RMSprop, Adam
Adagrad
Must know: Divides the learning rate by the root of all past squared gradients. The denominator only grows, so progress eventually stalls.
Common pitfall: Monotonically shrinking step size. After a steep region the old gradients keep the rate small forever, so it never speeds up.
Self-check: Why does Adagrad slow down and never recover?
Connects to: RMSprop, Adam, Adaptive learning rates
RMSprop
Must know: Like Adagrad but uses an exponentially weighted moving average of squared gradients, so old steep gradients are forgotten.
Common pitfall: Still suffers the cold start (no bias correction), so early steps are biased toward zero.
Self-check: How does RMSprop differ from Adagrad, and why does that matter?
Connects to: Adagrad, Adam, Momentum
Adam
Must know: Combines momentum (first moment m_t) with RMSprop (second moment v_t) and adds bias correction. The default optimizer for deep learning.
Common pitfall: Heaviest to compute by hand, and the simplified bias-correction form over-corrects compared with the paper's per-step version.
Self-check: What do the bias-corrected terms hat{m}_t and hat{v}_t fix?
Connects to: Momentum, RMSprop, Cold start problem
Cold Start Problem
Must know: All adaptive methods begin with zero history (m_0, v_0, G_0, S_0 = 0), biasing early steps toward zero. Adam fixes this with bias correction.
Common pitfall: Assuming the first step already represents the data. It is far too small and only becomes reliable once history accumulates.
Self-check: Why is the very first momentum or Adam step so small?
Connects to: Adam, Adagrad, RMSprop
Lagrangian Formulation
Must know: Turns hard constraints into soft penalties using non-negative Lagrange multipliers lambda_i.
Common pitfall: Forgetting to flip greater-than-or-equal constraints into less-than-or-equal-to (multiply by minus one) before building L.
Self-check: Why must every constraint be written as g_i(x) <= 0?
Connects to: Primal and dual problems, Min-max duality, Feasible regions
Primal and Dual Problems
Must know: Primal moves first (worse); dual sets penalties first then optimizes (better). Going second is an advantage.
Common pitfall: Mixing up which player moves first, or thinking the primal is always at least as good as the dual.
Self-check: Why is the dual never worse than the primal?
Connects to: Lagrangian formulation, Min-max inequality, Support Vector Machines
Min-Max Inequality and Strong Duality
Must know: The dual value is always a lower bound on the primal. For convex problems equality (strong duality) holds.
Common pitfall: Assuming strong duality for non-convex problems, where the primal and dual can diverge.
Self-check: When does the min-max inequality become an equality?
Connects to: Primal and dual, Lagrangian formulation, Support Vector Machines
Feasible Regions and Linear Programming
Must know: The optimum of a linear objective with linear constraints always sits at a corner (vertex), never in the interior.
Common pitfall: Searching inside the region instead of just evaluating the vertices, which is where the optimum must lie.
Self-check: Where does the optimum of a linear program always sit?
Connects to: Lagrangian formulation, Constrained optimization, Min-max duality
Was this lecture useful?
BitsNotes AI Assistant
Subject Notes AssistantConfigure AI Chat
Choose how to access the chatbotSigned in as
Powered by BitsNotes — 20 messages per day. No API key needed. Want unlimited access? Use "Bring Your Own Key" mode.
Sign in to use AI Chat
Get 20 free AI messages per day to ask questions about your lecture notes. Sign in with Google or GitHub — it takes 5 seconds.
Sign In to BitsNotesSwitch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.