Comparing Optimizers and Checking Them Against torch.optim
The previous four lessons built nine optimizers. Two questions remain. Which one should you use? A fair answer needs the same problem, the same compute budget and a learning rate tuned for each, because an optimizer with a badly chosen learning rate tells you nothing. Are our implementations right? Library optimizers have conventions (where goes, how the momentum buffer starts, what weight_decay means) that change the numbers. This lesson runs all nine on one problem with a learning-rate sweep, then checks our NumPy updates against torch.optim to the last digit.
Nine optimizers, one interface
Every optimizer is a function (w, g, state, lr) -> new w; the dictionary state holds whatever it remembers (velocity, sums, moments). The problem is logistic regression on 1000 examples with 8 features, three of which have been rescaled (by 5 and by 0.2) so the loss surface is not perfectly round, the usual situation with unscaled data. Each optimizer gets exactly 10 epochs, so all of them compute the same 10,000 example-gradients, and runs at seven learning rates. The number reported is the excess training loss: the loss minus its minimum (found by Newton's method), so 0 is perfect. This is an optimisation benchmark, so the training loss is the right thing to measure; for model selection you would look at validation loss instead.
import numpy as np
from sklearn.datasets import make_classification
X, y = make_classification(n_samples=1000, n_features=8, n_informative=5, n_redundant=0,
flip_y=0.1, random_state=0)
X = X * np.array([1, 1, 1, 1, 5, 5, 0.2, 0.2]) # unscaled features on purpose: curvatures differ
X = np.column_stack([X, np.ones(len(y))]) # bias column
n, d = X.shape
def loss(w):
z = X @ w
return np.mean(np.logaddexp(0, z) - y * z)
def grad(w, idx):
p = 1 / (1 + np.exp(-(X[idx] @ w)))
return X[idx].T @ (p - y[idx]) / len(idx)
# every optimizer is one function: (w, g, state, lr) -> new w
def sgd(w, g, s, lr):
return w - lr * g
def momentum(w, g, s, lr, beta=0.9):
s["v"] = beta * s.get("v", 0) + g
return w - lr * s["v"]
def nesterov(w, g, s, lr, beta=0.9):
s["v"] = beta * s.get("v", 0) + g
return w - lr * (g + beta * s["v"])
def adagrad(w, g, s, lr, eps=1e-10):
s["G"] = s.get("G", 0) + g ** 2
return w - lr * g / (np.sqrt(s["G"]) + eps)
def rmsprop(w, g, s, lr, alpha=0.99, eps=1e-8):
s["E"] = alpha * s.get("E", 0) + (1 - alpha) * g ** 2
return w - lr * g / (np.sqrt(s["E"]) + eps)
def adam(w, g, s, lr, b1=0.9, b2=0.999, eps=1e-8, wd=0.0):
s["t"] = s.get("t", 0) + 1
s["m"] = b1 * s.get("m", 0) + (1 - b1) * g
s["v"] = b2 * s.get("v", 0) + (1 - b2) * g ** 2
w = w - lr * wd * w # decoupled decay (AdamW); 0 for Adam
mh, vh = s["m"] / (1 - b1 ** s["t"]), s["v"] / (1 - b2 ** s["t"])
return w - lr * mh / (np.sqrt(vh) + eps)
def adamw(w, g, s, lr):
return adam(w, g, s, lr, wd=0.01)
def run(step, batch, lr, epochs=10, seed=0):
r, w, s = np.random.default_rng(seed), np.zeros(d), {}
for _ in range(epochs):
order = r.permutation(n)
for i in range(0, n, batch):
w = step(w, grad(w, order[i:i + batch]), s, lr)
if not np.all(np.isfinite(w)):
return np.inf
return loss(w)
# reference: the minimum, by many full-batch Newton steps
w = np.zeros(d)
for _ in range(30):
p = 1 / (1 + np.exp(-(X @ w)))
w -= np.linalg.solve((X.T * (p * (1 - p))) @ X / n, X.T @ (p - y) / n)
best = loss(w)
print(f"minimum training loss {best:.4f}")
lrs = [0.001, 0.003, 0.01, 0.03, 0.1, 0.3, 1.0]
print("excess training loss after 10 epochs, by learning rate")
print("optimizer batch " + "".join(f"{lr:>8}" for lr in lrs))
for name, step, batch in [("batch GD", sgd, n), ("SGD", sgd, 1), ("mini-batch SGD", sgd, 32),
("momentum", momentum, 32), ("Nesterov", nesterov, 32), ("Adagrad", adagrad, 32),
("RMSprop", rmsprop, 32), ("Adam", adam, 32), ("AdamW", adamw, 32)]:
row = [run(step, batch, lr) - best for lr in lrs]
# an excess above 1 means the run is bouncing around far from the minimum: its exact value is chaotic
print(f"{name:14s} {batch:5d} " + "".join(" div." if not np.isfinite(e) else " > 1" if e > 1 else f"{e:8.4f}" for e in row))minimum training loss 0.3267
excess training loss after 10 epochs, by learning rate
optimizer batch 0.001 0.003 0.01 0.03 0.1 0.3 1.0
batch GD 1000 0.3541 0.3364 0.3056 0.2611 0.1667 0.1164 0.5436
SGD 1 0.0149 0.0032 0.0191 0.0435 0.2611 > 1 > 1
mini-batch SGD 32 0.2581 0.1728 0.0681 0.0157 0.0073 0.0314 > 1
momentum 32 0.0678 0.0176 0.0066 0.0054 0.1646 0.7598 > 1
Nesterov 32 0.0679 0.0168 0.0034 0.0034 0.1169 > 1 > 1
Adagrad 32 0.3198 0.2658 0.1690 0.0605 0.0030 0.0008 0.0089
RMSprop 32 0.1407 0.0359 0.0008 0.0039 0.0205 0.1798 0.9519
Adam 32 0.1778 0.0705 0.0054 0.0082 0.0123 0.0787 0.6433
AdamW 32 0.1779 0.0710 0.0060 0.0082 0.0115 0.0801 0.0840
How to read the table:
- Batch GD gets only 10 updates in 10 epochs. Its best entry (0.1164 at ) is the worst in the table: exact gradients are a poor use of compute.
- SGD (batch size 1) does well (0.0032 at ) but is the most sensitive: one step size up and it is six times worse. Mini-batch SGD needs a larger (0.1) and reaches 0.0073; on real hardware its 320 vectorised updates are also far faster than SGD's 10,000.
- Momentum and Nesterov improve on mini-batch SGD (0.0054 and 0.0034) at a learning rate 3 to 10 times smaller, as expected from the factor.
- Adagrad and RMSprop are the best here (0.0008): per-feature scaling undoes the rescaled features. Note how far apart their best learning rates are (0.3 against 0.01), because Adagrad's accumulator keeps shrinking the step.
- Adam reaches 0.0054 and, more important in practice, stays within a factor of 2.3 of its best over from 0.01 to 0.1. AdamW is close; its decay () pulls the weights slightly away from the unregularised minimum, so a tiny excess is expected.
> 1marks a learning rate too large for the method: the weights bounce around far from the minimum, and the exact loss they end at is chaotic (it changes with the last bits of floating-point rounding), so the table does not print it.
Do not turn this into a ranking. On a convex, 9-parameter problem the differences are small, and one data set and one seed decide them; a different scaling or batch size would reorder the middle of the table. What does generalise: the learning rate matters more than the choice of optimizer, adaptive methods are less sensitive to feature scaling and to , and every optimizer must be compared at its own best learning rate, on the same budget. Large benchmark studies of deep networks (e.g. Schmidt, Schneider and Hennig, 2021) came to the same conclusion: with tuning, many optimizers perform similarly, and Adam is a strong default.
Practical defaults
| Situation | Start with | Typical |
|---|---|---|
| transformers, language models, most new architectures | AdamW, warm-up + cosine decay, 0.01 to 0.1 | to |
| convolutional image classifiers trained from scratch | SGD + momentum 0.9 (Nesterov), step or cosine decay, about | 0.1 for batch 256 |
| fine-tuning a pretrained model | AdamW with a small | to |
| sparse linear models, embeddings | Adagrad | 0.01 to 0.1 |
| small convex problems (logistic regression on tables) | a second-order method such as L-BFGS (scikit-learn's default) | none to tune |
Checking against torch.optim
PyTorch is not available in your browser, so the next example is recorded: it ran with PyTorch on a CPU, and the output below is that run's. It minimises the quadratic for 20 steps with each torch.optim class and with our NumPy update written to the same conventions, in float64 so the comparison can be exact. The comments mark each convention.
import numpy as np
import torch
torch.manual_seed(0)
A = np.array([[3.0, 0.5, 0.0], [0.5, 1.0, 0.2], [0.0, 0.2, 0.1]]) # f(w) = 1/2 w^T A w - b^T w
b = np.array([1.0, -2.0, 0.5])
w0 = np.array([0.5, -1.0, 2.0])
grad = lambda w: A @ w - b
# NumPy updates written with PyTorch's conventions
def np_sgd(w, g, s, lr=0.1, momentum=0.9, nesterov=False, wd=0.0):
g = g + wd * w # weight_decay in SGD is L2 added to the gradient
s["buf"] = g.copy() if "buf" not in s else momentum * s["buf"] + g # first step: buf = g
return w - lr * (g + momentum * s["buf"] if nesterov else s["buf"])
def np_adagrad(w, g, s, lr=0.1, eps=1e-10):
s["sum"] = s.get("sum", 0.0) + g * g # initial_accumulator_value = 0
return w - lr * g / (np.sqrt(s["sum"]) + eps)
def np_rmsprop(w, g, s, lr=0.01, alpha=0.99, eps=1e-8):
s["sq"] = alpha * s.get("sq", 0.0) + (1 - alpha) * g * g
return w - lr * g / (np.sqrt(s["sq"]) + eps) # eps outside the square root, no bias correction
def np_adam(w, g, s, lr=0.01, b1=0.9, b2=0.999, eps=1e-8, wd=0.0, decoupled=False):
if decoupled:
w = w * (1 - lr * wd) # AdamW: p <- p - lr * wd * p, before the Adam step
elif wd:
g = g + wd * w # Adam(weight_decay=...) is plain L2
s["t"] = s.get("t", 0) + 1
s["m"] = b1 * s.get("m", 0.0) + (1 - b1) * g
s["v"] = b2 * s.get("v", 0.0) + (1 - b2) * g * g
mh = s["m"] / (1 - b1 ** s["t"])
vh = s["v"] / (1 - b2 ** s["t"])
return w - lr * mh / (np.sqrt(vh) + eps)
cases = [
("SGD momentum", lambda p: torch.optim.SGD(p, lr=0.1, momentum=0.9), lambda w, g, s: np_sgd(w, g, s)),
("SGD Nesterov", lambda p: torch.optim.SGD(p, lr=0.1, momentum=0.9, nesterov=True), lambda w, g, s: np_sgd(w, g, s, nesterov=True)),
("Adagrad", lambda p: torch.optim.Adagrad(p, lr=0.1), np_adagrad),
("RMSprop", lambda p: torch.optim.RMSprop(p, lr=0.01), np_rmsprop),
("Adam", lambda p: torch.optim.Adam(p, lr=0.01), np_adam),
("Adam + L2", lambda p: torch.optim.Adam(p, lr=0.01, weight_decay=0.1), lambda w, g, s: np_adam(w, g, s, wd=0.1)),
("AdamW", lambda p: torch.optim.AdamW(p, lr=0.01, weight_decay=0.1), lambda w, g, s: np_adam(w, g, s, wd=0.1, decoupled=True)),
]
At, bt = torch.tensor(A), torch.tensor(b)
for name, make_opt, np_step in cases:
p = torch.tensor(w0, requires_grad=True) # float64, so the comparison is exact
opt = make_opt([p])
w, s = w0.copy(), {}
for _ in range(20):
opt.zero_grad()
loss = 0.5 * p @ At @ p - bt @ p
loss.backward()
opt.step()
w = np_step(w, grad(w), s)
diff = np.abs(p.detach().numpy() - w).max()
print(f"{name:13s} torch after 20 steps {np.round(p.detach().numpy(), 4)} same as NumPy: {diff < 1e-12}")
# a common mistake: momentum as a moving average, v = beta v + (1 - beta) g
w, v = w0.copy(), np.zeros(3)
for _ in range(20):
v = 0.9 * v + 0.1 * grad(w)
w = w - 0.1 * v
print("EMA-style momentum after 20 steps", np.round(w, 4), " (not what torch.optim.SGD computes)")SGD momentum torch after 20 steps [ 0.9826 -3.9718 10.3241] same as NumPy: True
SGD Nesterov torch after 20 steps [ 1.0407 -4.3541 10.5054] same as NumPy: True
Adagrad torch after 20 steps [ 0.6152 -1.7073 2.7775] same as NumPy: True
RMSprop torch after 20 steps [ 0.6174 -1.7199 2.7913] same as NumPy: True
Adam torch after 20 steps [ 0.5314 -1.1989 2.2005] same as NumPy: True
Adam + L2 torch after 20 steps [ 0.5106 -1.1986 2.2 ] same as NumPy: True
AdamW torch after 20 steps [ 0.5293 -1.1773 2.1589] same as NumPy: True
EMA-style momentum after 20 steps [ 0.6799 -2.505 2.6939] (not what torch.optim.SGD computes)
All seven agree to better than , so the update rules of the previous lessons are exactly PyTorch's. The conventions that had to be matched:
| Optimizer | PyTorch's convention |
|---|---|
SGD(momentum=β) |
buffer , set to on the first step; step (no factor) |
SGD(nesterov=True) |
step |
Adagrad |
accumulator starts at initial_accumulator_value=0; added after the square root |
RMSprop |
; after the square root; no bias correction |
Adam(weight_decay=λ) |
L2: added to the gradient before the moments |
AdamW(weight_decay=λ) |
first, then the Adam step |
The last line shows why the check is worth doing: "momentum" written as a moving average, , gives instead of SGD's , because its steps are ten times smaller. Both are called momentum in papers, and hyperparameters copied between them are off by a factor of 10. The quadratic's minimum is about ; its smallest curvature (about 0.054) makes the third coordinate slow, so 20 steps of any method are still far from it, which does not matter for a check of the update rules.
To run a check like this for your own code, use float64, a deterministic loss, more than one step (so the state is exercised) and parameters with different gradient scales (so elementwise operations are tested).
Pitfalls
- Comparing optimizers at one shared learning rate. Each needs its own; at a single you are measuring the learning rate, not the optimizer.
- Comparing per update instead of per compute. Batch GD's update costs 1000 times an SGD update here.
- Trusting one seed. Repeat a comparison with several seeds before believing a gap of a few per cent.
- Re-implementing an optimizer from a paper and assuming it matches the library. Check where goes, whether there is bias correction and what
weight_decaymeans.
Practice
- In the table, what is the ratio between Nesterov's and mini-batch SGD's best learning rates, and why is it roughly what momentum theory predicts?
Answer
0.01 (or 0.03, tied at 0.0034) against 0.1: 3 to 10 times smaller. With momentum multiplies the effective step by , so a learning rate about 10 times smaller gives a similar effective step.
- Write PyTorch's
SGD(momentum=0.9, dampening=0.9)update and compare it with the EMA-style momentum in the example.
Answer
With dampening the buffer is (after the first step; PyTorch sets without dampening). With it is the EMA form from step 2 on, so its iterates differ from the example's EMA only by the first buffer value, instead of .
Test yourself
What is the fair way to compare two optimizers?
- Same learning rate, same number of updates
- Each at its own tuned learning rate, on the same compute budget, over several seeds
- Whichever finishes first
- Same learning rate, same number of epochs
In PyTorch, torch.optim.RMSprop…
- applies bias correction like Adam
- adds after taking the square root and has no bias correction
- adds inside the square root
- uses by default
Which statement about the lesson's learning-rate table is supported by the numbers?
- Adam is always best
- Batch GD with 10 updates was the worst at its best learning rate
- SGD is insensitive to the learning rate
- All optimizers share the same best learning rate
Why did the torch check use float64 tensors?
- PyTorch requires it
- So both implementations do the same arithmetic and an exact match is meaningful
- float64 is faster
- To use less memory