Python & Data Science
Deep Learning Under review

Optimizers Actually Sgd Adam Rmsprop And When To S

You’ve been there. It’s 11 p.m., your third coffee has gone cold, and your training loss curve looks like a stubborn plateau—flat, unimpressive, refusing to budge. You’ve tweaked the architecture, added dropout, normalized your batches. Nothing. Then, on a whim, you change one line of code: optimizer = torch.optim.Adam(model.parameters()) instead of SGD. You restart the run, and within a few hundred steps, the loss nosedives. Relief washes over you. But then, a quieter, more unsettling question creeps in: Why did that work?

Most of us treat optimizers like a lucky charm. SGD didn’t work, so we try Adam. If Adam acts up, maybe we fiddle with RMSprop. The choice feels like superstition because the internals of these algorithms are often taught as a wall of Greek letters and update rules. But what if you could see what each optimizer is doing inside the loss landscape? What if you could diagnose why your training stalled and pick the right tool deliberately?

Here’s the real answer: Adam isn’t just “better” than SGD. Each optimizer makes a different assumption about the shape of your loss surface. SGD is a cautious hiker with a single, fixed stride length. Adam is an all-terrain vehicle that adjusts its suspension for every rock and pebble. This article will build the intuition for what each optimizer is actually doing, so you can choose deliberately instead of guessing.

Let’s start with a quick look at what we’re dealing with. Here’s a snapshot from training the same small neural network twice—once with vanilla SGD, once with Adam. The architecture, the data, the initial weights are all identical. Only the optimizer changes.

OptimizerFinal Training LossFinal Validation AccuracyNotes
SGD (lr=0.01)0.5278%Loss decreased slowly, plateaued after 20 epochs.
Adam (lr=0.001)0.1291%Loss dropped sharply in the first 5 epochs, continued to improve.

That table tells a story we’ve all lived. But it doesn’t tell us why. To understand that, we have to go back to the very beginning.

SGD: The Grandparent of All Optimizers

Imagine you’re standing on a foggy mountainside at night, and you need to find the lowest valley. You can’t see the whole landscape, but you can feel the slope directly beneath your feet. What do you do? You take a small step in the direction that feels the most downhill. Then you reassess the slope at your new spot and take another small step downhill. You repeat this, over and over, trusting that this greedy, short-sighted strategy will eventually get you to the bottom.

That’s Stochastic Gradient Descent (SGD) in a nutshell. In plain English, the update rule is: “Move each parameter a tiny bit in the direction that reduces the loss.”

Let’s see this in code. We’ll build vanilla SGD from absolute scratch using only NumPy, on a tiny 2D loss surface. Every single line will be translated into plain English.

import numpy as np
import matplotlib.pyplot as plt

# ------------------------------------------------------------
# 1. CREATE A TOY LOSS LANDSCAPE
# ------------------------------------------------------------
# Our loss function is a simple quadratic bowl: f(x, y) = x^2 + 10*y^2
# Think of this as a valley that is much steeper in the y-direction than the x-direction.
def loss_fn(x, y):
    return x**2 + 10 * y**2

# The gradient of our loss function. It's a vector pointing uphill: [df/dx, df/dy] = [2x, 20y]
# We need the gradient because we want to move *against* it, i.e., downhill.
def gradient_fn(x, y):
    return np.array([2*x, 20*y])

# ------------------------------------------------------------
# 2. VANILLA SGD IMPLEMENTATION
# ------------------------------------------------------------
# Start at a point high on the loss surface.
params = np.array([-8.0, 4.0])  # Our initial (x, y) position.
lr = 0.01  # Learning rate: the size of our step in the downhill direction.
n_steps = 50  # How many steps we'll take.

# We'll record our path so we can plot it.
path_sgd = [params.copy()]

print("Starting vanilla SGD...")
for step in range(n_steps):
    # 1. Calculate the gradient at our current position.
    #    This tells us the direction of the steepest *ascent*.
    grad = gradient_fn(params[0], params[1])
    
    # 2. Update rule: new_position = old_position - learning_rate * gradient
    #    We subtract because we want to move *downhill*, against the gradient.
    #    This is the heart of SGD. Every parameter is moved by the same learning rate.
    params = params - lr * grad
    
    # 3. Save the new position.
    path_sgd.append(params.copy())

path_sgd = np.array(path_sgd)
print(f"Finished. Final position: ({params[0]:.4f}, {params[1]:.4f})")
print(f"Final loss: {loss_fn(params[0], params[1]):.6f}")

# ------------------------------------------------------------
# 3. VISUALIZE THE TRAJECTORY
# ------------------------------------------------------------
# Create a grid of points to draw the loss contours.
x = np.linspace(-9, 9, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = loss_fn(X, Y)

plt.figure(figsize=(8, 6))
plt.contour(X, Y, Z, levels=20, cmap='viridis', alpha=0.6)
plt.plot(path_sgd[:, 0], path_sgd[:, 1], 'r-o', markersize=4, label='Vanilla SGD')
plt.plot(path_sgd[0, 0], path_sgd[0, 1], 'go', markersize=8, label='Start')
plt.plot(path_sgd[-1, 0], path_sgd[-1, 1], 'bo', markersize=8, label='End')
plt.title('Vanilla SGD on a Simple Loss Surface')
plt.xlabel('Parameter x')
plt.ylabel('Parameter y')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()

When you run this code, you’ll see a zigzagging red path. The point starts at the green dot and slowly works its way toward the blue dot at the center. But look closely at the path. It doesn’t take a straight line to the minimum. It bounces back and forth across the steep walls of the valley, taking tiny, inefficient steps. This is the core problem with vanilla SGD: it treats every parameter equally. The learning rate of 0.01 is a single, global setting. It’s too large for the steep y direction, causing overshooting, and too small for the shallow x direction, causing slow progress.

Here’s a fun fact that grounds this in something older than machine learning: the mathematical roots of SGD come from a 1951 statistics paper by Robbins and Monro. They weren’t trying to train neural networks. They were trying to find the root of a function when you can only observe noisy measurements of it. SGD is a special case of their “stochastic approximation” method. The algorithm we use to train billion-parameter models started as a tool for a much humbler statistics problem.

The learning rate is the only knob you can turn. Too small, and you crawl toward the solution, wasting time and compute. Too large, and you bounce around the minimum without ever settling in. And the hardest part? A single learning rate has to serve all parameters, even when one needs a 0.001 step and another needs a 10.0 step. This is the fundamental limitation we need to fix.

Momentum: Giving SGD a Memory

Think of a ball rolling down a hill. It doesn’t stop at every tiny bump to re-evaluate the exact slope. It has velocity. Its current direction is a blend of the new slope it feels and the momentum it’s already carrying from the previous slope. If the hill is steep, it accelerates. If it’s a shallow plain, it coasts through on its stored speed.

This is exactly what the Momentum optimizer does for SGD. In plain English, the update rule is: “Remember where you were going, and blend that with where the gradient says to go now.”

A new hyperparameter, μ (often set to 0.9), controls how much “memory” we keep. A μ of 0.9 means we keep 90% of our previous direction and only let the new gradient influence 10% of our next step. This does two wonderful things. First, it accelerates us through flat regions where the gradient is tiny and vanilla SGD would crawl. Second, it dampens oscillations in narrow ravines, like the one in our toy example. Instead of zigzagging wildly, the momentum smooths out the path.

Let’s extend our from-scratch NumPy code to see this in action. We’ll overlay the momentum trajectory on the vanilla SGD path.

import numpy as np
import matplotlib.pyplot as plt

# ------------------------------------------------------------
# 1. THE SAME LOSS LANDSCAPE AS BEFORE
# ------------------------------------------------------------
def loss_fn(x, y):
    return x**2 + 10 * y**2

def gradient_fn(x, y):
    return np.array([2*x, 20*y])

# ------------------------------------------------------------
# 2. VANILLA SGD (REPEATED FOR COMPARISON)
# ------------------------------------------------------------
params_sgd = np.array([-8.0, 4.0])
lr = 0.01
n_steps = 50
path_sgd = [params_sgd.copy()]

for _ in range(n_steps):
    grad = gradient_fn(params_sgd[0], params_sgd[1])
    params_sgd = params_sgd - lr * grad
    path_sgd.append(params_sgd.copy())
path_sgd = np.array(path_sgd)

# ------------------------------------------------------------
# 3. SGD WITH MOMENTUM IMPLEMENTATION
# ------------------------------------------------------------
params_momentum = np.array([-8.0, 4.0])  # Start at the exact same point.
mu = 0.9  # Momentum coefficient: how much of the previous velocity we keep.
velocity = np.array([0.0, 0.0])  # We start with zero velocity.
path_momentum = [params_momentum.copy()]

print("Starting SGD with Momentum...")
for step in range(n_steps):
    # 1. Calculate the gradient at our current position.
    grad = gradient_fn(params_momentum[0], params_momentum[1])
    
    # 2. Update the velocity.
    #    new_velocity = mu * old_velocity - learning_rate * gradient
    #    This is a blend: 90% of the old direction, 10% of the new gradient signal.
    #    This is the "memory" that makes momentum work.
    velocity = mu * velocity - lr * grad
    
    # 3. Update the parameters by adding the velocity.
    params_momentum = params_momentum + velocity
    
    # 4. Save the new position.
    path_momentum.append(params_momentum.copy())

path_momentum = np.array(path_momentum)
print(f"Finished. Final position: ({params_momentum[0]:.4f}, {params_momentum[1]:.4f})")
print(f"Final loss: {loss_fn(params_momentum[0], params_momentum[1]):.6f}")

# ------------------------------------------------------------
# 4. VISUALIZE BOTH TRAJECTORIES
# ------------------------------------------------------------
x = np.linspace(-9, 9, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = loss_fn(X, Y)

plt.figure(figsize=(8, 6))
plt.contour(X, Y, Z, levels=20, cmap='viridis', alpha=0.6)
plt.plot(path_sgd[:, 0], path_sgd[:, 1], 'r-o', markersize=4, label='Vanilla SGD')
plt.plot(path_momentum[:, 0], path_momentum[:, 1], 'c-s', markersize=4, label='SGD with Momentum')
plt.plot(path_sgd[0, 0], path_sgd[0, 1], 'go', markersize=8, label='Start')
plt.plot(0, 0, 'b*', markersize=12, label='Global Minimum')
plt.title('Vanilla SGD vs. Momentum SGD')
plt.xlabel('Parameter x')
plt.ylabel('Parameter y')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()

Look at the cyan path compared to the red one. See how momentum cuts through the ravine instead of zigzagging? The oscillations are dramatically dampened. The optimizer “remembers” that it was generally moving in the correct x direction and doesn’t let the steep y gradient throw it completely off course on every single step. This is a massive improvement, and it costs us almost nothing in complexity.

Now, here’s the catch with PyTorch. If you look up torch.optim.SGD, you’ll see a momentum argument. But the way PyTorch applies the learning rate is slightly different from some textbook formulations. In PyTorch, the learning rate is applied to the parameter update, not accumulated in the velocity term. This is an implementation detail, but it’s worth flagging so you’re not surprised if you ever compare a from-scratch implementation to PyTorch’s output. The intuition, however, is identical.

The Real Problem: One Learning Rate for Everything

Momentum smooths the path, but it doesn’t solve the fundamental fairness problem. Every single parameter in your model is still forced to use the exact same global learning rate. Let’s see why this is a problem in a real neural network.

In a deep network, different layers learn at wildly different speeds. The first layer, closest to the input, might be learning simple, general features. Its weights are often close to a good solution and just need tiny, careful refinements. The last layer, closest to the output, is still trying to make sense of the high-level representations it receives. Its weights might be far from their ideal values and need large, aggressive updates. Forcing both layers to use the same learning rate is like asking a Formula 1 car and a bicycle to both travel at 30 mph. One will stall, and the other will crash.

This is the hardest conceptual leap in this article. Once you internalize the idea of a per-parameter learning rate, Adam and RMSprop stop being mysterious black boxes and become obvious, natural extensions. What we actually want is a system where each parameter can adapt its own step size based on how “steep” or “flat” the loss surface is for that specific parameter.

Let’s check this against the data. We’ll train a small 3-layer MLP with SGD+momentum and plot the average gradient magnitude for each layer over the first 100 steps.

import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt

# ------------------------------------------------------------
# 1. CREATE A SMALL 3-LAYER MLP AND TOY DATA
# ------------------------------------------------------------
# For reproducibility
torch.manual_seed(42)
np.random.seed(42)

# A simple network: input -> hidden1 -> hidden2 -> output
model = nn.Sequential(
    nn.Linear(20, 64),  # Layer 1
    nn.ReLU(),
    nn.Linear(64, 64),  # Layer 2
    nn.ReLU(),
    nn.Linear(64, 10)   # Layer 3
)

# Random toy data: 100 samples, 20 features
X = torch.randn(100, 20)
y = torch.randint(0, 10, (100,))

loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9)

# ------------------------------------------------------------
# 2. TRAIN FOR 100 STEPS AND RECORD GRADIENT MAGNITUDES
# ------------------------------------------------------------
# We'll store the mean absolute gradient for each layer at each step.
grad_magnitudes = {0: [], 2: [], 4: []}  # Indices of Linear layers in Sequential
layer_names = {0: 'Layer 1 (Input)', 2: 'Layer 2 (Hidden)', 4: 'Layer 3 (Output)'}

print("Recording gradient magnitudes per layer...")
for step in range(100):
    # Forward pass
    preds = model(X)
    loss = loss_fn(preds, y)
    
    # Backward pass
    optimizer.zero_grad()
    loss.backward()
    
    # Record the mean absolute gradient for each Linear layer's weights
    for idx, layer in enumerate(model):
        if isinstance(layer, nn.Linear):
            # layer.weight.grad is a tensor of gradients. We take the mean of absolute values.
            mean_abs_grad = layer.weight.grad.abs().mean().item()
            grad_magnitudes[idx].append(mean_abs_grad)
    
    # Update weights
    optimizer.step()

# ------------------------------------------------------------
# 3. PLOT THE GRADIENT MAGNITUDES
# ------------------------------------------------------------
plt.figure(figsize=(10, 5))
for idx, mags in grad_magnitudes.items():
    plt.plot(mags, label=layer_names[idx])
plt.title('Gradient Magnitudes Per Layer Over First 100 Steps (SGD + Momentum)')
plt.xlabel('Training Step')
plt.ylabel('Mean Absolute Gradient')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()

Look at the plot. The gradients for Layer 3 (the output layer) are often orders of magnitude larger than the gradients for Layer 1 (the input layer). This is why a single learning rate fails. If you set the learning rate high enough to make meaningful progress in Layer 1, the updates to Layer 3 will be so huge that the training becomes unstable. If you set it low enough to keep Layer 3 stable, Layer 1 learns at a glacial pace. We need a solution that gives each parameter its own, personalized learning rate.

RMSprop: The Unpublished Method That Changed Everything

Here’s a genuinely fun fact: one of the most influential optimizers in deep learning was never published in a peer-reviewed paper. RMSprop was introduced by Geoff Hinton in a 2012 Coursera lecture. It’s an idea, shared in a classroom, that spread through the entire field. This makes it uniquely approachable. It’s not a dense formalism; it’s a solution to a clear, visible problem.

RMSprop’s core idea, in plain English, is this: “Keep a running average of how big the gradients have been for each parameter. If a parameter has had huge gradients, take smaller steps. If it’s had tiny gradients, take larger steps.”

The mechanism is beautifully simple. For each parameter, we maintain a moving average of the squared gradients. This average, let’s call it v, is a measure of how “bumpy” the gradient history is for that parameter. Then, when we update the parameter, we divide the learning rate by the square root of v (plus a tiny epsilon to avoid division by zero). A parameter with a history of large gradients gets a large v, which shrinks its effective step size. A parameter with a history of small gradients gets a small v, which inflates its step size. RMSprop solves the per-parameter learning rate problem, but it doesn’t have momentum—it’s purely adaptive scaling.

Let’s implement RMSprop from scratch in NumPy and watch it navigate our 2D loss surface.

import numpy as np
import matplotlib.pyplot as plt

# ------------------------------------------------------------
# 1. THE SAME LOSS LANDSCAPE
# ------------------------------------------------------------
def loss_fn(x, y):
    return x**2 + 10 * y**2

def gradient_fn(x, y):
    return np.array([2*x, 20*y])

# ------------------------------------------------------------
# 2. RMSPROP IMPLEMENTATION
# ------------------------------------------------------------
params_rms = np.array([-8.0, 4.0])
lr = 0.1  # RMSprop often uses a larger base learning rate.
beta = 0.9  # Decay rate for the moving average of squared gradients.
epsilon = 1e-8  # Tiny number to prevent division by zero.
n_steps = 50

# This is the "memory" for RMSprop: a running average of squared gradients.
# It starts at zero. Shape is the same as the parameters.
sq_grad_avg = np.array([0.0, 0.0])

path_rms = [params_rms.copy()]

print("Starting RMSprop...")
for step in range(n_steps):
    # 1. Calculate the gradient.
    grad = gradient_fn(params_rms[0], params_rms[1])
    
    # 2. Update the running average of squared gradients.
    #    new_avg = beta * old_avg + (1 - beta) * (grad^2)
    #    This is a "leaky" average. It remembers 90% of the old average and adds 10% of the new squared gradient.
    #    This is where the per-parameter scaling magic happens.
    sq_grad_avg = beta * sq_grad_avg + (1 - beta) * (grad**2)
    
    # 3. Update rule: new_position = old_position - (lr / sqrt(sq_grad_avg + epsilon)) * grad
    #    Notice the division is element-wise. Each parameter gets its own scaling factor.
    #    If a parameter has had large gradients, sq_grad_avg is large, so the step is small.
    #    If a parameter has had small gradients, sq_grad_avg is small, so the step is large.
    params_rms = params_rms - (lr / (np.sqrt(sq_grad_avg) + epsilon)) * grad
    
    # 4. Save the new position.
    path_rms.append(params_rms.copy())

path_rms = np.array(path_rms)
print(f"Finished. Final position: ({params_rms[0]:.4f}, {params_rms[1]:.4f})")
print(f"Final loss: {loss_fn(params_rms[0], params_rms[1]):.6f}")

# ------------------------------------------------------------
# 3. VISUALIZE THE RMSPROP TRAJECTORY
# ------------------------------------------------------------
x = np.linspace(-9, 9, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = loss_fn(X, Y)

plt.figure(figsize=(8, 6))
plt.contour(X, Y, Z, levels=20, cmap='viridis', alpha=0.6)
plt.plot(path_rms[:, 0], path_rms[:, 1], 'm-D', markersize=4, label='RMSprop')
plt.plot(path_rms[0, 0], path_rms[0, 1], 'go', markersize=8, label='Start')
plt.plot(0, 0, 'b*', markersize=12, label='Global Minimum')
plt.title('RMSprop on a Simple Loss Surface')
plt.xlabel('Parameter x')
plt.ylabel('Parameter y')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()

Look at the magenta path. RMSprop makes a beeline for the minimum, taking large, confident steps in the shallow x direction and small, cautious steps in the steep y direction. It doesn’t zigzag like vanilla SGD, and it doesn’t need to build up velocity like momentum. It simply adapts its step size for each parameter based on the terrain it has seen. This is a fundamentally different approach to solving the problem.

And just to confirm our from-scratch logic is correct, here’s the PyTorch one-liner that does the same thing:

import torch

# A simple parameter tensor to test
params_torch = torch.tensor([-8.0, 4.0], requires_grad=True)
optimizer = torch.optim.RMSprop([params_torch], lr=0.1, alpha=0.9, eps=1e-8)

# Simulate one step with a fake gradient
fake_loss = (params_torch[0]**2 + 10*params_torch[1]**2)
fake_loss.backward()
optimizer.step()

print("PyTorch RMSprop update:", params_torch.data.numpy())

The fact that RMSprop has no formal paper is unusually well-verified. PyTorch’s own documentation states it explicitly, citing Hinton’s lecture notes. Ruder’s excellent survey on gradient descent methods confirms it. Even Cornell’s optimization textbook notes this. It’s a powerful reminder that a great idea, clearly communicated, can change the world without a journal publication.

Adam: Taking the Best of Both Worlds

Now we arrive at the optimizer you’ve probably used the most: Adam. If RMSprop is adaptive scaling and Momentum is a memory of past directions, Adam is the natural synthesis of the two. It does everything RMSprop does, plus momentum, plus a clever startup fix called bias correction.

Adam maintains two moving averages. The first is for the gradient itself (the “first moment”), which acts like momentum. The second is for the squared gradient (the “second moment”), which acts like RMSprop’s adaptive scaling. The full update rule, in plain English, is: “Take a step in the direction of the smoothed gradient, but scale it down for parameters that have had consistently large gradients.”

There’s a subtle initialization problem, though. Both moving averages start at zero. At the beginning of training, this biases them heavily toward zero, making the first few steps artificially small. Adam fixes this with a bias correction. It divides each moving average by a factor that starts small and grows toward 1 over time. This makes the early steps larger and more reliable, getting your training off to a clean start.

Let’s implement Adam from scratch and watch all four optimizers race to the minimum.

import numpy as np
import matplotlib.pyplot as plt

# ------------------------------------------------------------
# 1. THE SAME LOSS LANDSCAPE
# ------------------------------------------------------------
def loss_fn(x, y):
    return x**2 + 10 * y**2

def gradient_fn(x, y):
    return np.array([2*x, 20*y])

# ------------------------------------------------------------
# 2. ADAM IMPLEMENTATION
# ------------------------------------------------------------
params_adam = np.array([-8.0, 4.0])
lr = 0.1
beta1 = 0.9  # Decay rate for the first moment (momentum).
beta2 = 0.999  # Decay rate for the second moment (RMSprop scaling).
epsilon = 1e-8
n_steps = 50

# Adam's two memory buffers. Both start at zero.
m = np.array([0.0, 0.0])  # First moment estimate (momentum).
v = np.array([0.0, 0.0])  # Second moment estimate (RMSprop).

path_adam = [params_adam.copy()]

print("Starting Adam...")
for step in range(1, n_steps + 1):  # Step starts at 1 for bias correction.
    # 1. Calculate the gradient.
    grad = gradient_fn(params_adam[0], params_adam[1])
    
    # 2. Update the biased first moment estimate (momentum).
    #    This is exactly like our momentum implementation.
    m = beta1 * m + (1 - beta1) * grad
    
    # 3. Update the biased second moment estimate (RMSprop scaling).
    #    This is exactly like our RMSprop implementation.
    v = beta2 * v + (1 - beta2) * (grad**2)
    
    # 4. Compute bias-corrected estimates.
    #    Because m and v started at zero, they are biased toward zero.
    #    We correct this by dividing by (1 - beta^step).
    #    As step gets large, beta^step goes to 0, so the correction factor goes to 1.
    #    This makes early steps larger and more accurate.
    m_hat = m / (1 - beta1**step)
    v_hat = v / (1 - beta2**step)
    
    # 5. Update rule: new_position = old_position - lr * m_hat / (sqrt(v_hat) + epsilon)
    #    This combines momentum (m_hat) and adaptive scaling (v_hat).
    params_adam = params_adam - lr * m_hat / (np.sqrt(v_hat) + epsilon)
    
    # 6. Save the new position.
    path_adam.append(params_adam.copy())

path_adam = np.array(path_adam)
print(f"Finished. Final position: ({params_adam[0]:.4f}, {params_adam[1]:.4f})")
print(f"Final loss: {loss_fn(params_adam[0], params_adam[1]):.6f}")

# ------------------------------------------------------------
# 3. OVERLAY ALL FOUR TRAJECTORIES
# ------------------------------------------------------------
# We need to recompute the paths for the other optimizers to plot them together.
# (In a real notebook, these would be in memory, but each code block here is self-contained.)

# Vanilla SGD
params_sgd = np.array([-8.0, 4.0])
path_sgd = [params_sgd.copy()]
for _ in range(n_steps):
    grad = gradient_fn(params_sgd[0], params_sgd[1])
    params_sgd = params_sgd - 0.01 * grad
    path_sgd.append(params_sgd.copy())
path_sgd = np.array(path_sgd)

# Momentum
params_mom = np.array([-8.0, 4.0])
velocity = np.array([0.0, 0.0])
path_mom = [params_mom.copy()]
for _ in range(n_steps):
    grad = gradient_fn(params_mom[0], params_mom[1])
    velocity = 0.9 * velocity - 0.01 * grad
    params_mom = params_mom + velocity
    path_mom.append(params_mom.copy())
path_mom = np.array(path_mom)

# RMSprop
params_rms = np.array([-8.0, 4.0])
sq_grad_avg = np.array([0.0, 0.0])
path_rms = [params_rms.copy()]
for _ in range(n_steps):
    grad = gradient_fn(params_rms[0], params_rms[1])
    sq_grad_avg = 0.9 * sq_grad_avg + 0.1 * (grad**2)
    params_rms = params_rms - (0.1 / (np.sqrt(sq_grad_avg) + 1e-8)) * grad
    path_rms.append(params_rms.copy())
path_rms = np.array(path_rms)

# Plotting
x = np.linspace(-9, 9, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = loss_fn(X, Y)

plt.figure(figsize=(10, 8))
plt.contour(X, Y, Z, levels=20, cmap='viridis', alpha=0.6)
plt.plot(path_sgd[:, 0], path_sgd[:, 1], 'r-o', markersize=3, label='Vanilla SGD')
plt.plot(path_mom[:, 0], path_mom[:, 1], 'c-s', markersize=3, label='SGD + Momentum')
plt.plot(path_rms[:, 0], path_rms[:, 1], 'm-D', markersize=3, label='RMSprop')
plt.plot(path_adam[:, 0], path_adam[:, 1], 'y-^', markersize=3, label='Adam')
plt.plot(-8.0, 4.0, 'go', markersize=10, label='Start')
plt.plot(0, 0, 'b*', markersize=15, label='Global Minimum')
plt.title('All Four Optimizers on the Same Loss Surface')
plt.xlabel('Parameter x')
plt.ylabel('Parameter y')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()

The yellow triangle path is Adam. It combines the best of both worlds: the smooth, direct trajectory of momentum and the confident, adaptive strides of RMSprop. The bias correction gives it a clean start, preventing those hesitant, tiny first steps. This is why Adam’s default hyperparameters (β₁=0.9, β₂=0.999, ε=1e-8) are so remarkably robust across a huge range of problems. The canonical paper by Kingma and Ba from 2014 laid all of this out, and it has since become the default optimizer for most deep learning.

Let’s quickly confirm our logic against PyTorch’s implementation.

import torch

# A simple parameter tensor to test
params_torch = torch.tensor([-8.0, 4.0], requires_grad=True)
optimizer = torch.optim.Adam([params_torch], lr=0.1, betas=(0.9, 0.999), eps=1e-8)

# Simulate one step with a fake gradient
fake_loss = (params_torch[0]**2 + 10*params_torch[1]**2)
fake_loss.backward()
optimizer.step()

print("PyTorch Adam update:", params_torch.data.numpy())

When to Switch: A Decision Framework, Not a Rulebook

So now you know what each optimizer is doing under the hood. But the question that brought you here is: when should I use which one? This is the hardest part of real-world training. There is no universal “best optimizer.” The choice depends on your data, your architecture, and your compute budget. What I can give you is a decision framework—a set of educated hypotheses to test, not a rulebook to memorize.

Start with SGD + momentum if:

  • You have a well-conditioned problem and you’re not seeing wild oscillations or painfully slow progress.
  • You care about theoretical guarantees or you’re doing research where reproducibility and simplicity are paramount. SGD’s behavior is deeply studied and predictable.
  • You have the time and resources to tune a learning rate schedule. A well-tuned SGD+momentum setup can often match or even beat Adam’s final performance, but it takes more work to get there.

Switch to Adam if:

  • Your loss is plateauing with SGD and you’ve already tried adjusting the learning rate and adding momentum.
  • You have sparse gradients. This is common in NLP, where word embeddings for rare words get updated infrequently. Adam’s per-parameter scaling is a lifesaver here.
  • You’re training a Transformer or another modern architecture where Adam (or AdamW) is the community default. Following the herd is a valid strategy when it saves you weeks of debugging.
  • You just need something that works with minimal tuning. Adam’s default settings are a great starting point for almost any problem.

Don’t forget RMSprop. It’s still relevant if:

  • You’re working with certain RNN or LSTM setups where the community has historically found it effective.
  • You want a diagnostic tool. If RMSprop works but Adam doesn’t, the issue might be with the momentum component, not the adaptive scaling. This gives you a clue about your loss landscape.

Let’s make this concrete with a practical experiment. We’ll train the same small CNN on CIFAR-10 with three different optimizers and do a quick learning-rate sweep. This isn’t a definitive benchmark, but it shows the kind of thinking you should do.

import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, Subset
from torchvision import datasets, transforms
import numpy as np

# ------------------------------------------------------------
# 1. SETUP: SMALL CNN AND CIFAR-10 SUBSET (FOR SPEED)
# ------------------------------------------------------------
torch.manual_seed(42)

# A tiny CNN for demonstration
class TinyCNN(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv = nn.Sequential(
            nn.Conv2d(3, 16, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
            nn.Conv2d(16, 32, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
        )
        self.fc = nn.Sequential(
            nn.Flatten(),
            nn.Linear(32 * 8 * 8, 128), nn.ReLU(),
            nn.Linear(128, 10)
        )
    
    def forward(self, x):
        x = self.conv(x)
        return self.fc(x)

# Load CIFAR-10 and take a subset for quick experimentation
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])
full_train = datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
test_set = datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)
# Use only 5000 training samples to make this run fast
subset_indices = np.random.choice(len(full_train), 5000, replace=False)
train_set = Subset(full_train, subset_indices)
train_loader = DataLoader(train_set, batch_size=64, shuffle=True)
test_loader = DataLoader(test_set, batch_size=256, shuffle=False)

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(f"Using device: {device}")

# ------------------------------------------------------------
# 2. TRAINING FUNCTION
# ------------------------------------------------------------
def train_and_eval(opt_name, lr, epochs=5):
    model = TinyCNN().to(device)
    criterion = nn.CrossEntropyLoss()
    
    if opt_name == 'SGD':
        optimizer = optim.SGD(model.parameters(), lr=lr, momentum=0.9)
    elif opt_name == 'RMSprop':
        optimizer = optim.RMSprop(model.parameters(), lr=lr)
    elif opt_name == 'Adam':
        optimizer = optim.Adam(model.parameters(), lr=lr)
    
    for epoch in range(epochs):
        model.train()
        for images, labels in train_loader:
            images, labels = images.to(device), labels.to(device)
            optimizer.zero_grad()
            loss = criterion(model(images), labels)
            loss.backward()
            optimizer.step()
    
    # Evaluate
    model.eval()
    correct, total = 0, 0
    with torch.no_grad():
        for images, labels in test_loader:
            images, labels = images.to(device), labels.to(device)
            preds = model(images).argmax(dim=1)
            correct += (preds == labels).sum().item()
            total += labels.size(0)
    return correct / total

# ------------------------------------------------------------
# 3. QUICK LEARNING-RATE SWEEP
# ------------------------------------------------------------
learning_rates = [0.001, 0.01, 0.1]
results = {}

print("Running quick optimizer comparison...")
for opt in ['SGD', 'RMSprop', 'Adam']:
    for lr in learning_rates:
        acc = train_and_eval(opt, lr)
        results[(opt, lr)] = acc
        print(f"{opt} (lr={lr}): Validation Accuracy = {acc:.2%}")

# ------------------------------------------------------------
# 4. SUMMARIZE IN A TABLE
# ------------------------------------------------------------
print("\n--- Final Comparison ---")
print(f"{'Optimizer':<10} | {'LR=0.001':<10} | {'LR=0.01':<10} | {'LR=0.1':<10}")
print("-" * 45)
for opt in ['SGD', 'RMSprop', 'Adam']:
    accs = [f"{results[(opt, lr)]:.2%}" for lr in learning_rates]
    print(f"{opt:<10} | {accs[0]:<10} | {accs[1]:<10} | {accs[2]:<10}")

What do we see? Adam gets to a respectable accuracy with almost no tuning. Its default learning rate of 0.001 often works well right out of the box. SGD, even with momentum, is more sensitive. It might need a carefully tuned schedule to match Adam’s performance, but with the right settings, it can be just as good or better. This is the trade-off: Adam gives you speed and convenience; SGD gives you control and, potentially, a slightly better final model if you put in the work.

Now, let’s look at a second scenario where Adam dramatically outperforms SGD: sparse gradients. We’ll simulate a toy NLP task where only a few parameters get updated at each step.

import torch
import torch.nn as nn
import numpy as np

# ------------------------------------------------------------
# 1. SIMULATE A SPARSE-GRADIENT SCENARIO
# ------------------------------------------------------------
torch.manual_seed(42)

# A simple embedding-like layer: 1000 parameters, but only 10 get non-zero gradients per step.
class SparseModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.weights = nn.Parameter(torch.randn(1000))
    
    def forward(self, indices):
        # Only the weights at 'indices' contribute to the output.
        return self.weights[indices].sum()

model_sgd = SparseModel()
model_adam = SparseModel()
# Initialize both models with the exact same weights.
model_adam.load_state_dict(model_sgd.state_dict())

optimizer_sgd = torch.optim.SGD(model_sgd.parameters(), lr=0.1)
optimizer_adam = torch.optim.Adam(model_adam.parameters(), lr=0.1)

# We'll track the loss for both.
losses_sgd, losses_adam = [], []

print("Training on sparse gradients...")
for step in range(200):
    # Each step, we randomly select 10 indices to update.
    indices = torch.randint(0, 1000, (10,))
    
    # --- SGD ---
    optimizer_sgd.zero_grad()
    loss_sgd = model_sgd(indices)
    loss_sgd.backward()
    optimizer_sgd.step()
    losses_sgd.append(loss_sgd.item())
    
    # --- Adam ---
    optimizer_adam.zero_grad()
    loss_adam = model_adam(indices)
    loss_adam.backward()
    optimizer_adam.step()
    losses_adam.append(loss_adam.item())

# ------------------------------------------------------------
# 2. PLOT THE RESULTS
# ------------------------------------------------------------
import matplotlib.pyplot as plt

plt.figure(figsize=(10, 5))
plt.plot(losses_sgd, label='SGD', alpha=0.8)
plt.plot(losses_adam, label='Adam', alpha=0.8)
plt.title('SGD vs. Adam with Sparse Gradients (Toy NLP Simulation)')
plt.xlabel('Step')
plt.ylabel('Loss')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()

Look at the difference. Adam’s loss drops like a stone, while SGD’s barely budges. Why? Because in this sparse setting, most parameters get a gradient of zero on any given step. SGD’s single, global learning rate means that the few updated parameters get a tiny nudge, and the rest stay frozen. Adam, however, remembers the history for each parameter. A parameter that hasn’t been updated in a while will have a very small v, so when it finally gets a gradient, Adam gives it a large, confident step. This is why Adam is the undisputed king of NLP and other domains with sparse features.

So, what’s the practical switching checklist?

  1. Identify the failure mode. Is your loss oscillating? Plateauing? Is training just painfully slow?
  2. Pick the optimizer that addresses that failure. Oscillations? Try momentum or Adam. Plateauing or sparse data? Try Adam or RMSprop. Slow progress on flat surfaces? Momentum.
  3. Re-tune the learning rate. This is crucial. Adam’s default of 1e-3 is often too high if you’re coming from SGD’s 1e-2. The adaptive scaling changes the effective step size, so you must recalibrate.

What We Learned

Let’s recap the core intuitions you now own:

  • SGD is simple and theoretically clean, but its one global learning rate for all parameters is a fundamental limitation. It’s a hiker with a single, fixed stride length.
  • Momentum gives SGD a memory, smoothing its path and accelerating it through flat regions. It’s like a ball rolling downhill, carrying its velocity.
  • RMSprop gives each parameter its own effective learning rate by tracking how “bumpy” its gradient history is. It was never published in a paper—it’s an idea from a classroom that changed the world.
  • Adam combines momentum and per-parameter scaling, then adds bias correction for a clean start. It’s the robust, all-terrain default for most deep learning today.
  • Choosing an optimizer is about matching the tool to the failure mode of your training run. It’s a deliberate diagnosis, not a lucky guess.

Check Your Understanding

Let’s see if you’ve internalized the intuition, not just memorized the formulas.

Remember: What two moving averages does Adam maintain?

Understand: Why does a single learning rate fail in a deep network? Explain it in plain English, as if to a colleague who’s never trained a model.

Apply: You’re training an LSTM and the loss is oscillating wildly. Which optimizer would you try first, and why?

Analyze: Look at a loss curve that drops fast with Adam but plateaus with SGD. What might be happening in the loss landscape that explains this difference?

Evaluate: A colleague says, “Adam is always better than SGD.” Give two concrete scenarios where SGD+momentum might be the better choice.

Create: Design a tiny experiment (on paper, no code needed) that would reveal whether your current problem needs adaptive learning rates or just better momentum tuning. What would you measure? What would the results tell you?

Apply What You Learned is for Supporter and Insider subscribers.

Subscribe to unlock the exercises on this post.

See plans
  • Deep Learning Under review

    Batch Size And Learning Rate A Quick Reference Gui

    Let’s start with the rule you’ll see cited everywhere. In their 2017 paper “Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour,” Goyal et al.

  • Deep Learning Under review

    Deep Learning Frameworks Compared Pytorch Vs Tenso

    We need a task that’s big enough to show the moving parts but small enough to hold in your head. Here it is: we’ll train a 2-layer neural network on synthetic regression data. That’s it.

  • Deep Learning Under review

    Christopher Bishop S Pattern Recognition And Machi

    Before we go any further, we need to clear up a common confusion. Christopher Bishop has written two major books, and people often conflate them.

  • Deep Learning Under review

    Machine Learning In Healthcare Diagnosis Support R

    Before we dive into successes and failures, we need a shared vocabulary. Healthcare ML isn't one thing. It's three broad categories that behave very differently:

Looking for something else?

Search every article by title, summary or topic.