SeeingML
Neural Networks & Deep Learning Guide 4 of 6 · tap to switch
✦ Interactive Visual Guide 9 min · 4 hands-on labs · Beginner friendly

Gradient Descent, Learning Rate & Adam Optimizer

Master the engine that trains every deep model: tune learning rates, race SGD vs. Momentum vs. Adam, pick mini-batches, and schedule cosine decay.

Picture standing on a foggy hillside at night trying to reach the lowest valley floor. Backpropagation hands you a compass pointing straight downhill. Now you face the single most important knob in Deep Learning: how big a stride should you take? Stepping downhill again and again to shrink prediction error is gradient descent, powered in modern deep learning by well-chosen step sizes and the Adam optimizer.

That stride size is called the Learning Rate (often written with the Greek letter η, pronounced “eta”). Take tiny shuffling steps and sunrise arrives before you move halfway down. Take giant leaps past the bowl’s safe speed limit and you sail straight over the valley floor onto an even higher opposite cliff until the error overflows and crashes into NaN (“Not a Number”)!

Slide the Step Size / Learning Rate (η) dial below (or tap the 4 presets) to watch all four behaviors unfold live on a simple U-shaped error bowl, L(w) = (w - 3)², where error hits zero at w = 3.

Interactive Lab 1: The Step Size (Learning Rate) Dial
Overshooting (Ping-Pong)
0204060Error (Loss)w=-4w=0w=3w=6w=10Lowest Error (w = 3)Start123Start at w = -2.2 · True Minimum at w = 3.0 · Final Error after 14 steps = 0.75
Tap a preset (or drag the slider) and follow the numbered hops (Start -> 1 -> 2 -> 3):
Step Size (η) = 0.94
At Step Size (η) = 0.94, each step leaps completely across the bottom onto the opposite wall (follow Start -> 1 -> 2 -> 3)! It wastes time bouncing back and forth before slowly settling.

In real training, checking every single row of a massive dataset before taking one step is painfully slow. Instead, networks almost always estimate the downhill slope from small random batches of data, a method called Stochastic Gradient Descent (SGD) (“stochastic” simply means random). Plain, unassisted downhill steps are known as Vanilla SGD.


Adam Optimizer vs. Vanilla SGD & Momentum

Real neural networks do not sit inside neat round bowls: their error landscapes resemble steep, skinny mountain canyons, sloping 60 times steeper across the canyon walls than lengthwise down the valley floor!

Watch what happens when we drop three classic optimizers onto the exact same canyon ridge below for 26 steps (press Play Race or drag the Step slider to watch every bounce unfold):

  • Vanilla SGD only looks at the slope right under its feet, so it slams back and forth across the steep walls while barely inching sideways toward the goal.
  • SGD + Momentum keeps a rolling memory of past steps like a heavy bowling ball rolling downhill: opposite up-and-down bounces cancel each other out while steady forward pushes build speed!
  • Adam combines two superpowers at once: Momentum (rolling memory that smooths zig-zags) plus Automatic Per-Knob Braking (watching how steep each individual weight has been recently, slowing down steep directions while speeding up flat ones)!
Interactive Lab 2: Racing Vanilla SGD vs. Momentum vs. Adam Down a Narrow Canyon
High Error (Steep Wall)High Error (Steep Wall)StartValley Bottom (Lowest Error)● Vanilla SGD● SGD + Momentum● AdamTop-Down Map of a Steep Narrow Canyon (Step 26 of 26)
Step 26 / 26
Vanilla SGDError 0.60
MomentumError 0.06
AdamError 0.03
Step 26 of 26 from the exact same ridge: Coral Vanilla SGD is still bouncing wildly up and down (Error 0.60), Amber Momentum glides smoothly through (0.06), and Green Adam steers right into the valley bottom (0.03)!

Stochastic Gradient Descent (SGD) vs. Mini-Batch vs. Full-Batch

Suppose your training dataset has 1 million photos. Showing the model all 1 million photos once is called one Epoch (one full pass through the entire dataset).

Before taking a single downhill step, how many photos should you check? You have three choices:

  • Full-Batch Gradient Descent: average the slope over all 1 million photos before taking just one slow step per epoch. It overflows GPU memory on big datasets and can settle into narrow dead-end traps.
  • Single Example (Batch = 1): update weights after every individual photo. One mislabeled photo yanks the weights sideways, and it leaves almost all of the GPU’s parallel math lanes idle.
  • Mini-Batch (32 to 256 photos): grab tidy random chunks of 64 photos at a time. Mini-batches fit inside GPU memory, keep parallel GPU math running at full speed, update weights thousands of times per epoch, and add just enough gentle random wobble to shake loose from narrow dead-end traps!

Compare all three trajectories below on the exact same GPU time budget!

Interactive Lab 3: Full Batch vs. Mini-Batch vs. Single Example
0255075100Training ErrorFull BatchMini-Batch (64)Single Example (1)Training Time on the Same GPU (Dashed Lines = Other Strategies)
Tap Full Batch, Mini-Batch (64), and Single Example (1) above to compare speed and smoothness on the same GPU clock:
Steps per Full Pass (Epoch)
Just 1 slow step per full pass (epoch)
GPU Memory & Speed
Overflows GPU memory on large datasets
Full Batch averages the slope over every single photo before taking ONE slow step per full pass (epoch). The line is glass-smooth, yet on the same GPU clock it crawls far behind Mini-Batch (dashed green) and can settle into narrow dead-end traps.

Why one fixed learning rate is never enough (Warmup + Cosine Decay)

Early in training, you want brisk strides to cover big distance quickly, yet not on Step 1 when freshly randomized weights and Adam’s first few speed estimates can jump wildly. Late in training, you want to ease off the throttle like a landing aircraft, taking tiny, delicate adjustments so weights touch down softly at the lowest floor without rattling off the valley walls.

That two-stage speed plan is called Warmup + Cosine Decay: ramp the step size up gently over the first few passes (Warmup), then curve it smoothly down along a gentle wave (Cosine Decay) toward zero.

Switch between Constant, Step Decay, and Warmup + Cosine below and drag the Pass (Epoch) slider to inspect the exact schedule used to train modern language and vision models!

Interactive Lab 4: Learning Rate Schedules (Warmup + Cosine Decay)
0.0000.0010.0020.003Step SizePass 0Pass 25Pass 50Pass 75Pass 100Pass (Epoch) 0 to 100WarmupCosine DecayPass (Epoch) 6 · Step Size = 0.00150
Pass (Epoch) 6
Warmup Stage (Pass 6 of 12, Step Size 0.00150): ramps up gently while freshly randomized weights and Adam's first few speed estimates settle down, preventing wild early jumps! Drag the slider past Pass 12 to watch Cosine Decay kick in.
See Momentum, Adam & Decoupled AdamW Update EquationsThesis / Reference

1. Convex Step-Size Stability Bound: On an LL-smooth quadratic bowl 12w⊤Hw\frac{1}{2} \mathbf{w}^\top \mathbf{H} \mathbf{w} with largest Hessian eigenvalue λmax⁡\lambda_{\max}, vanilla Gradient Descent converges if and only if 0<η<2λmax⁡0 < \eta < \frac{2}{\lambda_{\max}}. In our Lab 1 bowl L(w)=(w−3)2L(w) = (w-3)^2, λmax⁡=L′′(w)=2\lambda_{\max} = L''(w) = 2, yielding the exact divergence threshold η=1.0\eta = 1.0!

2. Polyak Momentum & Adam (Kingma & Ba, 2015): Given mini-batch gradient gt=∇θLt\mathbf{g}_t = \nabla_{\boldsymbol{\theta}} \mathcal{L}_t, Adam tracks exponentially decayed moving averages of the 1st moment (mean direction) and 2nd raw moment (uncentered variance) with bias correction for early steps:

mt=β1mt−1+(1−β1)gt,vt=β2vt−1+(1−β2)gt2\mathbf{m}_t = \beta_1 \mathbf{m}_{t-1} + (1 - \beta_1)\mathbf{g}_t, \qquad \mathbf{v}_t = \beta_2 \mathbf{v}_{t-1} + (1 - \beta_2)\mathbf{g}_t^2
m^t=mt1−β1t,v^t=vt1−β2t,θt=θt−1−ηm^tv^t+ε\hat{\mathbf{m}}_t = \frac{\mathbf{m}_t}{1 - \beta_1^t}, \qquad \hat{\mathbf{v}}_t = \frac{\mathbf{v}_t}{1 - \beta_2^t}, \qquad \boldsymbol{\theta}_t = \boldsymbol{\theta}_{t-1} - \eta \frac{\hat{\mathbf{m}}_t}{\sqrt{\hat{\mathbf{v}}_t} + \varepsilon}

Standard defaults are β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999 (or 0.950.95 for LLMs), and ε=10−8\varepsilon = 10^{-8}.

3. Why Modern Practice Uses AdamW (Loshchilov & Hutter, 2019): Classic L2 regularization adds λθ\lambda \boldsymbol{\theta} inside gt\mathbf{g}_t, which Adam mistakenly rescales by 1/v^t1 / \sqrt{\hat{\mathbf{v}}_t}, weakening regularization on large-gradient weights. AdamW decouples weight decay directly onto the parameter update: θt←(1−ηλ)θt−1−η m^t/(v^t+ε)\boldsymbol{\theta}_t \leftarrow (1 - \eta\lambda)\boldsymbol{\theta}_{t-1} - \eta\,\hat{\mathbf{m}}_t / (\sqrt{\hat{\mathbf{v}}_t} + \varepsilon).

See AdamW + Cosine Annealing Schedule in PyTorchOptional Code
python
import torch

# Modern Deep Learning default: AdamW (decoupled weight decay) + Cosine Decay
optimizer = torch.optim.AdamW(
  model.parameters(),
  lr=3e-4,              # Andrej Karpathy's classic AdamW starting sweet spot
  weight_decay=0.01,    # decoupled L2 shrinkage
)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
  optimizer,
  T_max=100,            # total epochs
  eta_min=1e-5,         # gentle landing floor
)

for epoch in range(100):
  train_one_epoch(model, train_loader, optimizer)
  scheduler.step()

Fast optimization creates a new danger: memorizing the training set!

With activation functions like ReLU and GELU, Backpropagation, and Adam (plus its weight-shrinking variant, AdamW) working together, a deep neural network is so powerful that it can memorize every single training photo or sentence cleanly in minutes.

How do deep learning engineers keep million-parameter networks stable AND force them to generalize to unseen data?

Next up: Dropout, Batch Norm & Weight Decay.

✓ Self-Check

Quick Intuition Check

Four quick real-world scenarios. No scores, just test your intuition.

1

You launch training and notice the error jumps from 2.4 -> 18.7 -> 410.5 -> NaN within 5 steps. What is the very first lever you should check?

Pick an option first, or peek anytime
2

Why does Adam navigate steep, narrow canyons dramatically faster than plain Vanilla SGD?

Pick an option first, or peek anytime
3

Why do almost all deep learning models train on Mini-Batches (such as 32, 64, or 256 examples) instead of Full-Batch Gradient Descent?

Pick an option first, or peek anytime
4

Warmup + Cosine Decay starts with a gently rising learning rate to prevent wild early jumps on fresh random weights, then smoothly lowers the step size toward zero late in training so weights settle softly at the bottom.

Pick an option first, or peek anytime
Quick Reference

Common Questions

What is Stochastic Gradient Descent (SGD) vs Mini-Batch Gradient Descent?
Batch Gradient Descent averages the gradient over the entire dataset before taking one slow step. Stochastic Gradient Descent (SGD) updates weights after a single example (fast but noisy), while Mini-Batch Gradient Descent averages 32 to 256 examples per step for GPU speed plus healthy exploration noise.
What does the Adam optimizer do, and does it change the learning rate?
Adam combines Momentum (a smoothed velocity of past gradients) with RMSProp (dividing each weight's update by its recent squared gradient magnitude). That automatically gives every individual parameter its own adaptive effective step size, letting shallow axes speed up while steep walls stay calm.
Does gradient descent always find the global minimum?
Only on convex bowl-shaped losses like Linear or Logistic Regression. Deep neural networks have non-convex surfaces with many valleys and saddle points, where mini-batch noise, Momentum, and Adam help escape flat saddles and settle into broad, well-generalizing minima.
What is Gradient Descent in simple terms?
Gradient Descent is an iterative algorithm that shrinks prediction error by repeatedly computing the slope (gradient) of the loss function and taking a small step in the opposite downhill direction: w_new = w_old - learning_rate * gradient.
Why does a learning rate that is too large make training explode?
When the learning rate exceeds twice the inverse curvature of the loss bowl, each step overshoots the bottom and lands even higher up the opposite wall than where it began, causing loss to bounce exponentially toward infinity (NaN).
Why is Adam (or AdamW) the default optimizer in modern Deep Learning?
Adam combines two ideas at once: Momentum (smooths out noisy zig-zags using a moving average of past gradients) and adaptive per-weight scaling (divides steep directions by their running gradient magnitude while boosting gentle directions), converging rapidly out of the box with far less tuning than plain SGD.
Why do neural networks train on mini-batches (32 to 256) instead of the entire dataset at once?
Mini-batches fit cleanly inside GPU memory, saturate parallel matrix hardware, perform thousands of weight updates per epoch, and introduce gentle stochastic noise that helps escape sharp, poorly generalizing local minima.
Why do modern LLMs and vision models use Learning Rate Warmup + Cosine Decay?
At step 0, weights are random and Adam's running variance estimates are still noisy, so starting at a high learning rate causes violent spikes; a brief linear Warmup stabilizes early steps, and Cosine Decay gradually shrinks steps late in training so parameters settle cleanly into the valley floor.

Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference

https://seeingml.com/learn/gradient-descent/ Open GitHub issue Suggest an edit
Cite this guide in a paper, thesis, or course (BibTeX & APA)
BibTeX
@misc{irshad2026gradientdescent,
  author       = {Irshad, Muhammad Aashir},
  title        = {Gradient Descent, Learning Rate & Adam Optimizer: Interactive Visual Guide},
  howpublished = {SeeingML},
  year         = {2026},
  month        = {dec},
  url          = {https://seeingml.com/learn/gradient-descent/},
  note         = {Interactive visual guide}
}
APA

Irshad, M. A. (2026). Gradient Descent, Learning Rate & Adam Optimizer: Interactive Visual Guide. SeeingML. https://seeingml.com/learn/gradient-descent/