Lesson 2.2 — Gradient-based Optimization
Objective, curvature and parameter space
Neural network training searches for lower loss in parameter space. Backpropagation produces gradients, while the optimizer maintains internal state and updates parameters. A loss landscape is not input data space: each point represents a full parameter vector.
Curvature
For a quadratic model with Hessian diag(1, κ) and κ ≥ 1, the
condition number is κ. The steep axis limits the usable step size while the flat
axis progresses slowly.
Local vs. global
A positive-definite quadratic is convex with a unique global optimum. Real MLPs are typically non-convex: low loss, zero gradient, and global optimality are not equivalent.
Gradient estimates from data
Uniform random sampling yields an unbiased gradient estimate whose variance depends on batch size. One epoch is one pass through the training set, not a single parameter update.
01 · Batch Gradient Sampler
Stable, oscillating or divergent?
Take one principal direction of a quadratic bowl. Write for signed distance from its minimum in that direction and for its curvature. The slope is . A gradient step subtracts a fraction of the current displacement.

Read each plot against the horizontal zero line. The sign of decides whether a step crosses the minimum. Its magnitude decides whether the next point is closer. Crossing zero can be a perfectly convergent step. At one update lands exactly on the minimum.
In several dimensions the same learning rate acts on every principal direction. The steepest direction has the largest , so it reaches the stability boundary first. For fixed-step gradient descent to converge from every initial point on a strictly convex quadratic, . At equality an initial displacement in the steepest direction oscillates indefinitely.
Compare the flat and steep directions at the same learning rate
02 · Curvature & Learning Rate Explorer
Accumulate a direction, not just a gradient
The velocity buffer turns the update into a second-order recurrence, so the plain-GD stability interval no longer applies directly.
The gradient descent and momentum paths use the same quadratic, starting point and step size. Momentum starts with zero velocity. With β = 0 the two updates are identical. When β > 0, past gradients contribute to the direction and can carry a step past the minimum.
03 · Momentum vs. Gradient Descent
Per-coordinate gradient scaling
AdaGrad accumulates all historical squared gradients, causing step sizes to shrink monotonically;
RMSProp uses an exponential moving average so scale estimates adapt to recent gradients (following
PyTorch's convention with ε outside the square root).
04 · Adaptive State Inspector
First moment, second moment and bias correction
The second moment v averages squared gradients, not centered gradient variance.
ε prevents division by zero. AdamW decouples weight decay from the moment estimates.
05 · Adam Moment Player
Separate regularization from step-size policy
06 · Coupled L2 vs. Decoupled Weight Decay (Zero Data Gradient)
Warmup ramps the learning rate up at the start of training; cosine decay smoothly lowers it; step
decay drops it at milestones. Schedulers modify η directly rather than modifying
gradients. In PyTorch, call optimizer.step() before scheduler.step().
07 · Learning-rate Schedule Player
Engineering benchmark · robot dynamics MLP
Default illustrative rates are SGD/Momentum 0.03, AdaGrad/RMSProp 0.02,
and Adam/AdamW 0.01 (or switch to a shared rate). Non-zero decay applies only to
AdamW; at λ = 0, Adam and AdamW coincide. This is a teaching comparison, not a
fully tuned ranking—real research requires per-optimizer tuning, multiple seeds, an independent
test set, and wall-clock measurements.
The browser runs SGD, momentum, Adam and AdamW. The Python example below also runs AdaGrad and RMSProp and checks all six update rules against PyTorch.
08 · Live Optimizer Benchmark (Robot Dynamics MLP)
From scratch + PyTorch verification
import numpy as np
import torch
from torch import nn
# Identical deterministic data and initial parameters as the browser.
def data(n, shift):
i = np.arange(n, dtype=np.float64) + shift
x = 2 * np.sin(i * 1.71 + 0.2)
u = np.cos(i * 2.13 + 0.4)
X = np.stack([x, u], axis=1)
return X, 0.65 * x + 0.5 * np.sin(2 * x) + 0.35 * u
H = 6
X, y = data(64, 0)
V, vy = data(32, 100)
initial = 0.35 * np.sin(np.arange(25) * 1.13 + 0.7)
# Flat layout: W1 (2,H), b1 (H,), W2 (H,), b2 (scalar).
def forward(p, X):
a = np.tanh(X @ p[:2 * H].reshape(2, H) + p[2 * H:3 * H])
return a @ p[3 * H:4 * H] + p[-1], a
def gradient(p, X, y):
pred, a = forward(p, X)
e = 2 * (pred - y) / len(y)
dz = e[:, None] * p[3 * H:4 * H] * (1 - a * a)
return np.r_[(X.T @ dz).ravel(), dz.sum(0), a.T @ e, e.sum()]
# State is persistent across optimizer steps; t starts at 1.
def update(p, g, m, v, t, name, lr, wd=0.0):
if name == "SGD":
d = g
elif name == "Momentum":
m = 0.9 * m + g
d = m
elif name == "AdaGrad":
v = v + g * g
d = g / (np.sqrt(v) + 1e-10)
elif name == "RMSProp":
v = 0.9 * v + 0.1 * g * g
d = g / (np.sqrt(v) + 1e-8)
else:
m = 0.9 * m + 0.1 * g
v = 0.999 * v + 0.001 * g * g
d = (m / (1 - 0.9**t)) / (np.sqrt(v / (1 - 0.999**t)) + 1e-8)
p = p * (1 - lr * wd) if name == "AdamW" else p
return p - lr * d, m, v
rates = {"SGD": 0.03, "Momentum": 0.03, "AdaGrad": 0.02, "RMSProp": 0.02, "Adam": 0.01, "AdamW": 0.01}
def make_optimizer(name, param, lr, wd):
if name == "SGD": return torch.optim.SGD([param], lr=lr)
if name == "Momentum": return torch.optim.SGD([param], lr=lr, momentum=0.9)
if name == "AdaGrad": return torch.optim.Adagrad([param], lr=lr, eps=1e-10)
if name == "RMSProp": return torch.optim.RMSprop([param], lr=lr, alpha=0.9, eps=1e-8)
if name == "Adam": return torch.optim.Adam([param], lr=lr)
return torch.optim.AdamW([param], lr=lr, weight_decay=wd)
def run(name, lr, batch=16, epochs=60, wd=0.0):
p = initial.copy()
m = np.zeros_like(p)
v = m.copy()
q = nn.Parameter(torch.tensor(initial, dtype=torch.float64))
opt = make_optimizer(name, q, lr, wd)
t = 0
max_err = 0.0
for ep in range(epochs):
order = (np.arange(len(y)) + 7 * ep) % len(y)
for start in range(0, len(y), batch):
ids = order[start:start + batch]
xx, yy = X[ids], y[ids]
t += 1
g = gradient(p, xx, yy)
p, m, v = update(p, g, m, v, t, name, lr, wd)
opt.zero_grad(set_to_none=True)
a = torch.tanh(torch.tensor(xx) @ q[:12].reshape(2, 6) + q[12:18])
pred = a @ q[18:24] + q[24]
loss = ((pred - torch.tensor(yy))**2).mean()
loss.backward()
opt.step()
max_err = max(max_err, np.max(np.abs(p - q.detach().numpy())))
tr = np.mean((forward(p, X)[0] - y)**2)
va = np.mean((forward(p, V)[0] - vy)**2)
assert max_err < 1e-8, (name, max_err)
print(f"{name:9s} train={tr:.8f} val={va:.8f} max_parameter_error={max_err:.2e}")
return p, tr, va, max_err
if __name__ == "__main__":
for name, lr in rates.items():
run(name, lr)
run("AdamW", 0.01, wd=0.1)
With wd=0, the decoupled shrinkage factor (1 - lr * wd) equals 1.0, so AdamW's update matches Adam.