Gradient Descent
Your Challenge: Lost in the Mountains
Imagine you are dropped onto a random spot in a vast, foggy mountain range at night.- You can’t see the bottom (the valley).
- You can’t see more than 3 feet in front of you.
- You have no map.
- You feel the slope under your feet.
- You take a small step downhill.
- You repeat this thousands of times.
The Algorithm Visualized
- The Mountain: Your Loss Function (Error).
- Your Position: The current weights of your model.
- The Slope: The Gradient.
- The Step Size: The Learning Rate.
- The Bottom: The Optimal Weights (Best Model).
The Core Intuition
Why We Need It
In high school math, you found the minimum by setting the derivative to zero: That works for simple parabolas like . But in Deep Learning, your function looks like a crumpled piece of paper in 1,000,000 dimensions. You cannot solve algebraically. It is impossible. Think of the difference like this. Finding where the derivative equals zero analytically is like solving a Sudoku puzzle by reasoning through every constraint — elegant, but only feasible for small puzzles. Gradient descent is like a GPS navigation system: you do not need a complete map of the terrain. You just need to know which direction is downhill from where you are right now, and you take one step at a time. GPS works in any city, no matter how complex the road network. Gradient descent works for any differentiable function, no matter how many variables. So instead of solving for the answer directly, we search for it iteratively.The Code: A Simple Descent
Let’s implement the “blind hiker” logic for a simple valley: .The Algorithm
Mathematical Formulation
Update rule: Where:- = learning rate (step size)
- = gradient (direction of steepest ascent)
- We subtract because we want to go downhill
Pseudocode
Example 1: Training Your First Model
The Problem
You want to predict house prices based on square footage. Your Goal: Find the best (weight) and (bias) that minimize the error.The Data
Gradient Descent Training
Example 2: Optimizing Your Prices
The Scenario
You run an e-commerce site. You control two things:- = Ad spend ($1000s)
- = Discount percentage
Gradient Descent Optimization
Example 3: Training Your Neural Network
The Challenge
You want to train a simple neural network to solve a problem.- Input:
- Target:
- Model:
The Code
Learning Rate: The “Goldilocks” Problem
Choosing the step size () is the most important decision you make.1. Too Small (The Turtle)
- Symptom: Loss decreases veeeery slowly.
- Result: You run out of time/patience before reaching the bottom.
2. Too Large (The Grasshopper)
- Symptom: Loss bounces around or even INCREASES.
- Result: You overshoot the valley and never converge.
3. Just Right (Goldilocks)
- Symptom: Loss decreases steadily and quickly.
- Result: You reach the minimum efficiently.
How to Find It?
Start with 0.01 or 0.001. If loss is slow, increase it (0.1). If loss explodes, decrease it (0.0001).Variants of Gradient Descent
The Survey Analogy
To understand the three variants, think about conducting a political survey to decide your campaign strategy. Batch Gradient Descent is like surveying every single voter in the country before making any decision. You get a perfectly accurate picture, but it takes forever and costs a fortune. Stochastic Gradient Descent (SGD) is like asking one random person on the street and immediately adjusting your entire strategy based on their opinion. Cheap and fast, but wildly noisy — one grumpy respondent could send you in the wrong direction. Mini-Batch Gradient Descent is like polling a focus group of 32-256 people. Not perfect, but a reasonable estimate that you can act on quickly. This is what everyone uses in practice.Batch Gradient Descent
Uses all data points to compute gradient:Cons: Slow for large datasets; must fit all data in memory
Stochastic Gradient Descent (SGD)
Uses one data point at a time:Cons: Noisy, unstable; poor GPU utilization (GPUs want parallel work)
Mini-Batch Gradient Descent
Uses small batches of data:Cons: Need to choose batch size (32-256 is usually a safe range) This is what everyone uses in practice. When someone says “SGD” in a deep learning context, they almost always mean mini-batch SGD, not true single-sample SGD.
Convergence Criteria
When to Stop?
Option 1: Gradient is smallPractice Exercises
Exercise 1: Implement Gradient Descent
🎯 Practice Exercises & Real-World Applications
Exercise 1: Train a Linear Model by Hand 📈
Implement gradient descent to fit a line to data:💡 Solution
💡 Solution
LinearRegression.fit() works under the hood (though it uses closed-form solution when possible for speed).Exercise 2: Learning Rate Experiments 🎛️
Explore how learning rate affects convergence:💡 Solution
💡 Solution
Exercise 3: Escaping Local Minima 🕳️
Navigate a function with multiple minima:💡 Solution
💡 Solution
Exercise 4: Mini-Batch Gradient Descent 📦
Implement mini-batch training on a larger dataset:💡 Solution
💡 Solution
🎯 Optimizer Selection Guide: Which One Should You Use?
Decision Flowchart
Optimizer Comparison Table
Learning Rate Guidelines
🚨 Real-World Challenge: Messy Training Data
Handling Noisy Labels
Handling Missing Features
Handling Class Imbalance
Key Takeaways
✅ Gradient descent = iterative optimization algorithm✅ Follow gradient downhill = move opposite to gradient
✅ Learning rate = critical hyperparameter
✅ Mini-batch = best practice for large datasets
✅ Powers all ML = from linear regression to GPT
Learning Rate Schedulers: Advanced Techniques
Popular Schedulers
When Training Gets Stuck: Debugging Checklist
🔴 Loss not decreasing
🔴 Loss not decreasing
- Learning rate too high? Try 10x smaller
- Learning rate too low? Try 10x larger
- Data issue? Check for NaN/Inf values
- Bug in loss function? Verify on toy data
🔴 Loss oscillating wildly
🔴 Loss oscillating wildly
- Reduce learning rate by 2-10x
- Add gradient clipping
- Check for exploding gradients
- Increase batch size for smoother gradients
🔴 Loss decreases then plateaus
🔴 Loss decreases then plateaus
- Use learning rate scheduler
- Add momentum or switch to Adam
- Check if you’ve converged (that’s good!)
- Try data augmentation
🔴 Training loss good, validation bad
🔴 Training loss good, validation bad
- Overfitting - add regularization
- Reduce model complexity
- Add dropout
- Get more data
What’s Next?
Gradient descent is powerful, but basic. Can we do better? Can we converge faster? Can we escape local minima? Yes! Advanced optimization techniques like Momentum, Adam, and RMSprop!Next: Optimization Techniques
Interview Deep-Dive
You set the learning rate to 0.1 and training diverges. You set it to 0.0001 and training takes days to converge. How do you systematically find the right learning rate?
You set the learning rate to 0.1 and training diverges. You set it to 0.0001 and training takes days to converge. How do you systematically find the right learning rate?
- The most practical technique is the learning rate range test (also called the LR finder), popularized by Leslie Smith. You start with a very small learning rate (say 1e-7), train for a few hundred steps, and exponentially increase the learning rate at each step up to a large value (say 10). Plot loss versus learning rate on a log scale. The optimal learning rate is typically at the steepest descent of the curve — just before the loss starts increasing or oscillating. In my experience, this takes about 5 minutes of compute and saves hours of trial-and-error.
- A rough heuristic that works surprisingly often for Adam: start with 3e-4. For SGD with momentum, start with 0.1 and decay. For fine-tuning pretrained models, use 10-100x smaller than the original training rate, typically 1e-5 to 5e-5.
- The deeper understanding: the maximum stable learning rate is related to the curvature of the loss landscape. Specifically, for a quadratic loss with maximum eigenvalue of the Hessian equal to lambda_max, the learning rate must be less than 2/lambda_max for gradient descent to converge. In practice, you do not compute the Hessian, but the LR finder empirically discovers this boundary.
- For production systems, I use learning rate schedules rather than a single fixed rate. Warmup (start small, ramp up over 1000-5000 steps) stabilizes early training when the loss surface is poorly conditioned. Then cosine decay or linear decay reduces the rate as training progresses. The combination of warmup + cosine decay has become the default for transformer training (GPT, BERT, and most LLMs use this pattern).
Compare and contrast batch gradient descent, stochastic gradient descent (SGD), and mini-batch SGD. What are the mathematical and practical trade-offs?
Compare and contrast batch gradient descent, stochastic gradient descent (SGD), and mini-batch SGD. What are the mathematical and practical trade-offs?
- Batch gradient descent computes the gradient over the entire training set before making one update. The gradient is the exact average gradient, so updates are smooth and stable. But for a dataset of N samples, every single step costs N forward-backward passes. For ImageNet with 1.2 million images, that is prohibitively slow — one step might take hours.
- Stochastic gradient descent (SGD with batch size 1) updates after every single sample. This is extremely noisy — the gradient from one sample is a very rough approximation of the true gradient. But you make N updates per epoch instead of 1, so convergence in wall-clock time is often faster. The noise is actually beneficial: it helps escape sharp local minima and acts as an implicit regularizer.
- Mini-batch SGD is the practical sweet spot. You compute the gradient over B samples (typically 16-512) and update. The gradient variance decreases as 1/B, so larger batches give smoother updates. But there are diminishing returns: doubling the batch size halves the variance but doubles the compute per step. The optimal batch size balances gradient quality with compute efficiency.
- A critical practical consideration: GPU utilization. GPUs are massively parallel — processing 32 samples costs barely more than processing 1 because the matrix multiplications are parallelized. So increasing batch size from 1 to 32 gives 32x more gradient information at maybe 2x the wall-clock time. Beyond some threshold (often 256-1024 depending on model and hardware), the GPU saturates and larger batches give diminishing throughput.
- The generalization trade-off: Keskar et al. (2017) showed that large-batch training tends to converge to sharp minima that generalize poorly, while small-batch training finds flatter minima that generalize better. This has been partially addressed by learning rate scaling rules (linear scaling by Goyal et al. 2017: multiply LR by batch_size/base_batch_size) and LARS/LAMB optimizers designed for very large batch training.
Your model converges to 85% accuracy on both train and validation. You suspect it is stuck in a local minimum. How do you diagnose this, and what do you do about it?
Your model converges to 85% accuracy on both train and validation. You suspect it is stuck in a local minimum. How do you diagnose this, and what do you do about it?
- First, I would challenge the assumption. Equal train and validation accuracy at 85% means the model is not overfitting — it is underfitting. The issue might not be a local minimum at all. It could be that the model lacks capacity (too small), the features are insufficiently expressive, or the data itself has an 85% accuracy ceiling (label noise, inherently ambiguous examples).
- To diagnose whether optimization is the bottleneck versus model capacity: overfit a tiny subset. Take 100 examples and train until the loss is near zero. If the model can memorize 100 examples perfectly, then capacity is not the issue — the problem is optimization or data. If it cannot even memorize 100 examples, the architecture needs to change.
- If the model overfits the tiny subset but plateaus at 85% on the full dataset, optimization is likely the bottleneck. I would check: (1) gradient norms — if they are near zero, you are at a critical point. (2) Loss landscape visualization — project the loss along random directions to see if you are in a flat region versus a true minimum. (3) Try different learning rates — a larger rate might push you out of a local minimum. (4) Switch optimizers — Adam with its adaptive rates might navigate the landscape differently than SGD.
- Specific interventions for escaping local minima: learning rate restarts (cyclical learning rates or warm restarts, as in SGDR by Loshchilov and Hutter), which periodically spike the learning rate to “shake” the optimizer out of basins. Increasing batch size during training (reverse of the typical schedule) can also sharpen the gradient signal and push toward different basins. Finally, adding noise to parameters (shaking the weights directly) or using stochastic weight averaging (SWA) to average weights across multiple points in the optimization trajectory can find wider, more generalizable basins.
- In my experience, the most common fix for plateauing models is not fancy optimization tricks but rather: better data augmentation, larger models, or longer training. The optimization landscape of modern neural networks is surprisingly benign — most local minima have similar loss values. Plateaus are more often caused by data or architecture limitations than by optimization failure.
Explain the mathematical relationship between learning rate and batch size. Specifically: if I double my batch size, should I change my learning rate, and why?
Explain the mathematical relationship between learning rate and batch size. Specifically: if I double my batch size, should I change my learning rate, and why?
- The linear scaling rule says: if you multiply batch size by k, multiply learning rate by k. The intuition is that with a batch k times larger, your gradient estimate has k times less variance (standard error scales as 1/sqrt(B), but you are taking one step instead of k steps, so the net effect on expected weight change per epoch should be preserved).
- More precisely: with batch size B and learning rate eta, the expected weight change per epoch is proportional to eta * (N/B) * g_bar, where N is dataset size, N/B is steps per epoch, and g_bar is the average gradient. If you double B to 2B, steps per epoch halves to N/(2B), so to maintain the same expected weight change, you double eta to 2*eta.
- This works well up to a point. Goyal et al. (2017) at Facebook successfully trained ImageNet with batch sizes up to 8192 using linear scaling. But beyond a critical batch size (which is problem-dependent), the linear scaling rule breaks down. With extremely large batches, you need sublinear scaling (like square root scaling: LR proportional to sqrt(B)), or specialized optimizers like LARS (layer-wise adaptive rate scaling) and LAMB.
- The reason it breaks down: very large batches reduce gradient noise so much that the optimizer converges to sharp minima that generalize poorly. The noise from small batches is not just an annoyance — it serves as a regularizer. Killing that noise with huge batches can hurt test accuracy even when training accuracy improves.
- A practical consideration: the learning rate warmup period should also scale with batch size. Larger batches need longer warmup because the initial gradient statistics are noisier relative to the larger step sizes. The BERT training recipe uses warmup proportional to total training steps, which implicitly accounts for batch size.