Optimization Techniques
Your Challenge: The Valley of Deceit
Standard Gradient Descent is like walking downhill blindfolded. It works great on a smooth, simple hill. But real-world loss landscapes are treacherous.- Local Minima: Small dips that look like the bottom but aren’t.
- Saddle Points: Flat areas where you get stuck.
- Ravines: Steep walls where you bounce back and forth.
Momentum: The Heavy Ball
The Intuition
Imagine rolling a ping-pong ball down a bumpy hill. It gets stuck in every little pothole (Local Minimum). Now imagine rolling a heavy bowling ball.- It gains speed.
- When it hits a small pothole, its momentum carries it right through.
- It eventually settles in the deepest valley.
The Math
Instead of just following the gradient, we keep a “velocity” () that accumulates speed.- : Friction (usually 0.9). Retains 90% of speed.
- : Velocity.
The Code
RMSprop & Adam: Adaptive Shoes
The Problem with Ravines
Imagine a narrow ravine.- Steep walls (High gradient in direction).
- Gentle slope towards the sea (Low gradient in direction).
- If the ground is steep (), take tiny steps.
- If the ground is flat (), take huge steps.
Adam (Adaptive Moment Estimation)
Adam combines both ideas:- Momentum (first moment): Keep moving forward by tracking the exponential moving average of the gradient.
- RMSprop (second moment): Adapt step size by tracking the exponential moving average of the squared gradient.
lr=0.001, beta1=0.9, beta2=0.999, eps=1e-8) work for the vast majority of problems.
The Full Adam Update (Step by Step)
Here is what Adam does on every training step, in plain language:- Compute the gradient for the current batch
- Update the momentum estimate: (moving average of gradients)
- Update the variance estimate: (moving average of squared gradients)
- Correct for initialization bias: , (without this, early estimates are biased toward zero)
- Update the weight:
The Code (Using PyTorch)
You rarely implement Adam from scratch. You use a library.Comparison: Who Wins?
Visual Comparison
- SGD: Stumbles, gets stuck.
- Momentum: Overshoots but eventually settles.
- Adam: Beelines straight for the goal.
Practice Exercise: Escape the Trap
The Scenario
You are training a model that keeps getting stuck at 80% accuracy.- Loss isn’t going down.
- Gradients are small but not zero.
🎯 Practice Exercises & Real-World Applications
Exercise 1: Optimizer Shootout 🏁
Race different optimizers on the same problem:💡 Solution
💡 Solution
Exercise 2: Learning Rate Scheduling 📅
Implement and compare learning rate schedules:💡 Solution
💡 Solution
Exercise 3: Batch Size Trade-offs ⚖️
Explore the relationship between batch size and training:💡 Solution
💡 Solution
Exercise 4: Adam from Scratch 🔧
Implement the Adam optimizer and understand each component:💡 Solution
💡 Solution
What’s Next?
You have mastered the core math of learning!- Derivatives: How things change.
- Gradients: The direction of change.
- Chain Rule: How changes propagate.
- Gradient Descent: How to learn.
- Optimization: How to learn fast.
Quick Reference: Optimizer Selection Guide
Hyperparameter Tuning Priority
Interview Questions: Optimizers
Why is Adam preferred over SGD for many tasks?
Why is Adam preferred over SGD for many tasks?
- Handle sparse gradients well
- Converge faster with less tuning
- Adapt to each parameter’s needs
What's the difference between Adam and AdamW?
What's the difference between Adam and AdamW?
How do you debug a model that's not training?
How do you debug a model that's not training?
- First, verify the model can overfit a tiny subset (10 examples). If not, there’s a bug.
- Check for NaN/Inf in gradients and activations
- Try different learning rates (10x higher and 10x lower)
- Check data preprocessing (normalization, labels)
- Verify loss function is correct for the task
- Plot gradient norms over time (should be stable, not exploding/vanishing)
Final Project
Interview Deep-Dive
Adam is often called the 'default optimizer.' But SGD with momentum still outperforms Adam on ImageNet for CNNs. Explain why, and how you decide which optimizer to use for a new project.
Adam is often called the 'default optimizer.' But SGD with momentum still outperforms Adam on ImageNet for CNNs. Explain why, and how you decide which optimizer to use for a new project.
- Adam adapts the learning rate per parameter using running averages of first and second gradient moments. This makes it excellent at handling sparse gradients, noisy objectives, and landscapes with wildly different curvatures per parameter. It converges quickly and requires minimal tuning — which is why it is the default.
- However, there is strong empirical evidence (Wilson et al., 2017) that SGD with momentum generalizes better than Adam for computer vision tasks. The leading theory is that Adam’s adaptive rates effectively give each parameter its own loss landscape, and these individual trajectories can converge to sharper minima compared to SGD’s “one learning rate for all” approach. SGD’s uniform step size forces all parameters through the same optimization dynamics, which acts as an implicit regularizer.
- My decision framework for a new project: Start with Adam (lr=1e-3) to get a quick baseline — it will converge fast and tell you if the architecture and data pipeline are working. Then, if the task is well-established (like ImageNet classification), switch to SGD with momentum for the final model because the generalization benefit is worth the extra tuning effort. For transformers and NLP, use AdamW (Adam with decoupled weight decay) because the adaptive rates are essential for the highly heterogeneous gradient landscape of attention mechanisms. For fine-tuning pretrained models, always Adam or AdamW at a low learning rate (1e-5 to 5e-5).
- A nuance most people miss: Adam and AdamW are different in a meaningful way. Vanilla Adam applies weight decay to the gradient before the adaptive scaling, which means the actual regularization strength depends on the gradient magnitude — parameters with large gradients get less effective regularization. AdamW applies weight decay directly to the weights, decoupled from the gradient computation. Loshchilov and Hutter (2019) showed this decoupling is critical for proper regularization in transformers.
Walk me through the Adam optimizer update rule step by step. What does each component do, and what happens if you remove it?
Walk me through the Adam optimizer update rule step by step. What does each component do, and what happens if you remove it?
- Adam maintains two running averages per parameter. The first moment estimate m tracks the exponential moving average of gradients: m_t = beta1 * m_(t-1) + (1 - beta1) * g_t, where beta1 is typically 0.9. This is momentum — it smooths out gradient noise and builds up velocity in consistent directions.
- The second moment estimate v tracks the exponential moving average of squared gradients: v_t = beta2 * v_(t-1) + (1 - beta2) * g_t^2, where beta2 is typically 0.999. This captures per-parameter gradient variance — how much the gradient fluctuates for each parameter.
- Bias correction is critical in early steps. Since m and v are initialized to zero, they are biased toward zero for the first several iterations. The correction divides by (1 - beta^t): m_hat = m_t / (1 - beta1^t), v_hat = v_t / (1 - beta2^t). Without this, the first few updates would be artificially small, causing a slow start.
- The parameter update is: theta_t = theta_(t-1) - lr * m_hat / (sqrt(v_hat) + epsilon). The division by sqrt(v_hat) is the adaptive learning rate — parameters with large historical gradients get smaller steps, and vice versa. Epsilon (typically 1e-8) prevents division by zero.
- If you remove momentum (m): you get RMSprop. It still adapts per-parameter but lacks the smoothing effect. This makes it more sensitive to noisy gradients and more likely to oscillate.
- If you remove the adaptive rate (v): you get SGD with momentum. You lose per-parameter adaptation, so you need a single global learning rate that works for all parameters — harder to tune.
- If you remove bias correction: early training steps use the heavily biased m and v estimates, leading to tiny initial updates. For short training runs or when warm-starting from a checkpoint, this can significantly slow convergence.
- If you change epsilon from 1e-8 to something larger (like 1e-3): you reduce the adaptive effect. Parameters with small gradients no longer get dramatically larger effective learning rates. This can be useful when the adaptive behavior is too aggressive and causes training instability.
Explain saddle points. Why are they more problematic than local minima in high-dimensional optimization, and how do modern optimizers handle them?
Explain saddle points. Why are they more problematic than local minima in high-dimensional optimization, and how do modern optimizers handle them?
- A saddle point is a critical point (gradient = 0) where the surface curves upward in some directions and downward in others. Think of a mountain pass: if you stand at the top of the pass, the terrain goes up toward the peaks on either side but down into the valleys on either end.
- In high dimensions, saddle points vastly outnumber local minima. The intuition: at a critical point, each eigenvalue of the Hessian is independently likely to be positive or negative. For a random critical point in N dimensions, the probability that ALL N eigenvalues are positive (true minimum) is about 2^(-N). For N = 1000, that is astronomically unlikely. Almost all critical points are saddle points.
- Why they are problematic: the gradient is zero (or very small near the saddle), so gradient-based optimizers stall. The optimizer does not know which direction to move because the landscape looks flat locally. Unlike a local minimum where you are at least at a low point, a saddle point might have you at a high-loss region with a clear escape route — but the gradient cannot “see” it because the first-order information is zero.
- How modern optimizers handle them: SGD with mini-batch noise naturally perturbs the optimizer away from exact saddle points. The stochastic gradient is almost never exactly zero even at a saddle. Momentum accumulates velocity from past gradients, so even if the current gradient is small, the optimizer keeps moving based on its history. Adam further helps because its adaptive rates can amplify steps in flat directions (where v is small, the effective learning rate is large), which is often exactly the escape direction from a saddle.
- More sophisticated approaches include negative curvature exploitation: if you can identify directions where the Hessian has negative eigenvalues (the “downhill” directions of the saddle), you move along those directions. Cubic regularization methods and trust-region methods do this systematically. In practice, the combination of SGD noise + momentum + adaptive rates handles saddle points well enough for most deep learning tasks.
A colleague says: 'Just use Adam with lr=0.001 for everything, it always works.' What is wrong with this advice, and when does it fail?
A colleague says: 'Just use Adam with lr=0.001 for everything, it always works.' What is wrong with this advice, and when does it fail?
- This advice works surprisingly often for getting something to train, which is why it persists. But “something trains” and “trains optimally” are very different. There are several well-documented failure modes.
- First, Adam can fail to generalize as well as SGD for certain architectures. On ImageNet with ResNets, SGD with momentum and a carefully tuned schedule consistently achieves 0.5-1% better top-1 accuracy than Adam. At production scale, that difference matters.
- Second, lr=0.001 is wrong for fine-tuning. If you fine-tune a BERT or GPT model with lr=0.001, you will catastrophically overwrite the pretrained weights in the first few steps. Fine-tuning requires lr in the range 1e-5 to 5e-5, typically 20-100x smaller than training from scratch.
- Third, Adam’s adaptive rates can cause unstable training with certain loss landscapes. In GANs, the adversarial dynamics create a non-stationary objective, and Adam’s second moment can lag behind rapid loss surface changes. The recommended Adam settings for GANs use beta1=0.5 instead of 0.9 and beta2=0.999, which is quite different from the default.
- Fourth, for reinforcement learning, Adam with lr=0.001 often destabilizes training. The standard RL learning rate is 3e-4 (PPO default) or lower, and the nonstationarity of RL objectives means Adam’s moment estimates are frequently stale.
- Fifth, vanilla Adam (not AdamW) applies weight decay incorrectly, as discussed earlier. Using Adam when you should use AdamW results in weaker regularization for parameters with large gradients, which hurts generalization.
- My recommendation: Adam with lr=0.001 is a great starting point for prototyping. But for any model going to production, treat the optimizer and its hyperparameters as tunable. At minimum, tune the learning rate on a log scale (1e-5, 1e-4, 1e-3, 1e-2) and compare Adam versus AdamW versus SGD+momentum for your specific task.