Gradient descent on the whole data set is exact but slow, and one learning rate for every weight is crude. Almost all deep learning replaces the first with a cheap random estimate and the second with a step size that adapts to each weight. This lesson pairs with Lectures 7 and 8 of CMU's 11-785 (Fall 2026), linked under Watch & read. You build the shuffler that cuts an epoch into mini-batches and one Adam update, and you match that update against torch.optim.Adam.
An epoch visits every example once, in a fresh random order. Shuffle the indices, cut them into consecutive pieces of the batch size, and let the last piece be shorter. Each piece gives one gradient estimate and one update.
A mini-batch gradient is the average of the per-example gradients in the batch. If the batch is drawn at random, its expected value is the full gradient: the estimate is unbiased. Its noise shrinks like 1/√B for batch size B, so quadrupling the batch halves the spread. That is a poor return on computation: four times the work buys only half the noise.
import numpy as np
rng = np.random.default_rng(0)
x = rng.normal(size=1024)
y = 2.0 * x + rng.normal(scale=0.5, size=1024)
per_example = x * (x * 0.0 - y) # gradient of 0.5 (x w - y)² at w = 0
print("full", per_example.mean().round(4))
for B in (1, 4, 16, 64):
est = [per_example[rng.choice(1024, B, replace=False)].mean() for _ in range(2000)]
print(B, np.mean(est).round(3), np.std(est).round(3))The averages stay near the full gradient, while the spread falls from 2.97 at B = 1 to 1.54, 0.74 and 0.35. When every batch has the same size and the epoch covers each example once, the batch gradients average to the full gradient exactly. A shorter last batch must be weighted by its size to keep that true.
Now the step size. With one learning rate, a weight whose gradient is a thousand times smaller than another's moves a thousand times less. RMSProp keeps a running average of each weight's squared gradient, s = ρ·s + (1 − ρ)·g², and divides the step by √s. Every weight then moves by about the learning rate, whatever the size of its gradient.
import numpy as np
g = np.array([1e-3, 10.0]) # two weights, gradients 10⁴ apart
s, w_sgd, w_rms = np.zeros(2), np.zeros(2), np.zeros(2)
for t in range(200):
s = 0.9 * s + 0.1 * g * g
w_sgd -= 0.01 * g
w_rms -= 0.01 * g / (np.sqrt(s) + 1e-8)
print(w_sgd.round(5).tolist(), w_rms.round(3).tolist())After 200 steps plain SGD has moved the weights by 0.002 and 20.0. RMSProp has moved both by 2.091.
Adam adds momentum. It keeps m, an average of the gradient, and v, an average of the squared gradient. With g = grad + weight_decay · w, one step is:
- m = β₁·m + (1 − β₁)·g
- v = β₂·v + (1 − β₂)·g²
- m̂ = m / (1 − β₁ᵗ) and v̂ = v / (1 − β₂ᵗ)
- w = w − lr · m̂ / (√v̂ + ε)
Both averages start at zero, so early on they sit far below the values they are averaging. With a constant gradient, m is only (1 − β₁ᵗ) of that gradient and v only (1 − β₂ᵗ) of its square. Dividing by those factors, the bias correction, undoes the zero start. After the correction a constant gradient gives m̂ = g and v̂ = g², so every step has size lr, whatever the scale of g. Count from t = 1: at t = 0 the divisor would be zero.
Leave the correction out and the effect does not point where you might expect. With the default betas, m starts at 0.1 g, one tenth of the target, but v starts at 0.001 g², one thousandth, and its square root is only 0.0316 of the target. The ratio is 0.1 / 0.0316, so the first step is about 3.16 times lr, and it keeps growing for a while.
import numpy as np
for g in (1e-3, 1.0, 1e3):
m, v = 0.1 * g, 0.001 * g * g # after the first update, from zero
raw = m / (np.sqrt(v) + 1e-8)
fixed = (m / 0.1) / (np.sqrt(v / 0.001) + 1e-8)
print(g, round(raw, 3), round(fixed, 3))The peak is 6.57 times lr at step 12. After 1000 steps the uncorrected step is still 1.26 times lr.
Two details follow PyTorch. First, ε is added after the square root, so the denominator is √v̂ + ε. Second, weight_decay is L2 regularization: weight_decay · w is added to the gradient before the averages, so the decay is divided by √v̂ like everything else. AdamW decays the weights directly instead, which is a different update and is not built here.
Adam is not a second-order method. Newton's method divides the gradient by the curvature. On f(w) = ½·h·w² the gradient is h·w, so the step g / h lands on the minimum in one move, but for n weights it needs an n × n matrix of second derivatives. Adam's v is the average of squared gradients. It is a cheap per-weight scale, not a Hessian.
Four mistakes to avoid:
- Correcting v with β₁ instead of β₂, a copy of the line above. The first step becomes 10 times lr.
- Putting ε inside the root. For gradients near 10⁻⁶ the denominator becomes about 10⁻⁴ and the step comes out 99 times too small.
- Dropping the short last batch. It silently discards up to batch_size − 1 examples every epoch, and returns no batches at all when n is smaller than the batch size.
- Reading t before increasing it, or changing the old state in place.
The tests check three ways: a first step you can compute by hand, five consecutive steps against torch.optim.Adam at 1e-12 with and without weight decay and with tiny gradients, and the mean of equal-size batch gradients against the full gradient. Agreement with PyTorch shows that you implemented the update rule. It does not show that Adam suits your problem, or that your learning rate is a good one.