Home/ Deep Learning/ SGD vs Adam: Which Optimizer Should You Actually Use?
Deep Learning

SGD vs Adam: Which Optimizer Should You Actually Use?

SGD vs Adam compared with a decision table, a 60-step ravine race and a PyTorch run. See which optimizer to start with, and when tuning changes the answer.

SGD vs Adam is the most common optimizer question in deep learning, and most answers are opinions. This article gives you a decision table first, then tests it. We race plain gradient descent, SGD with momentum and Adam on the same elongated ravine for 60 steps, then train the same small neural network with SGD, SGD with momentum, Adam and AdamW in PyTorch. Every number comes from a run described here, so you can reproduce it. The honest summary: with a tuned learning rate the optimizers often tie, and the real difference is how much tuning each one demands.

The short answer: which optimizer should you use?

Task type Data size Tuning budget Start with
New problem, quick baseline Any A few runs Adam, learning rate 1e-3 (PyTorch’s default)
Small MLP or tabular-style network Small A few runs Adam; after tuning, SGD with momentum can tie
Transformers and language models Large Moderate AdamW
Image classification, chasing the last bit of accuracy Medium to large Enough to tune the learning rate and its schedule SGD with momentum, compared against AdamW
Memory is tight Any Any SGD, with or without momentum
Sparse or very uneven gradients Any A few runs Adam

The rule behind the table: if you can afford to tune the learning rate and schedule, SGD with momentum is a strong choice. If you cannot, Adam is the safer default, because it works across a wider range of learning rates. These are starting points, not laws. The rows for transformers and image classification reflect common practice and published arguments, not a guarantee for your problem (see the sections on generalization and on when each wins). Our own experiments below agree with the table’s logic: Adam won the ravine race, and on the PyTorch task all four optimizers tied once tuned, while Adam stayed strong untuned.

What actually differs

One global learning rate versus per-parameter rates

Plain SGD updates every weight with the same learning rate η:

w ← w − η · g

where g is the gradient. A weight with a huge gradient takes a huge step, and a weight with a tiny gradient barely moves. Adam adds two running averages per parameter, a mean of gradients m and a mean of squared gradients v, and scales each step by them:

m ← β1·m + (1 − β1)·g
v ← β2·v + (1 − β2)·g²
m̂ = m / (1 − β1^t)      v̂ = v / (1 − β2^t)      (bias correction at step t)
w ← w − η · m̂ / (√v̂ + ε)

The division by √v̂ is the key idea. Parameters with consistently large gradients get smaller effective steps, and parameters with small gradients get larger ones. A concrete case: on the very first step, m̂ = g and v̂ = g², so the step is η · g / |g| = ±η, no matter whether g is 100 or 0.01 (ε is negligible). Plain SGD would take steps of 100η and 0.01η, a ratio of 10,000 to 1. Adam equalises them. Gradient Descent Explained and Adam Optimizer Explained (both coming in this series) cover the derivations; here we focus on the choice.

SGD with momentum versus Adam

Momentum is not unique to Adam. SGD with momentum keeps a velocity: v ← β·v + g, then w ← w − η·v. Past gradients accumulate, so steps along a consistent direction grow and zig-zag components cancel. Adam’s m is also a momentum-like average. What SGD with momentum lacks is Adam’s per-parameter division by √v̂. So the real contrast is not “momentum or not” but “one global step size or an adaptive one”.

Memory cost

Plain SGD stores nothing extra. SGD with momentum stores one extra number per parameter (the velocity). Adam stores two (m and v). As an illustrative example with made-up round numbers, a model with 100 million float32 parameters needs 400 MB for the weights (4 bytes each), and Adam’s states add another 800 MB. For small models this is irrelevant. For very large ones it can decide the question.

The race: both optimizers on one shared problem

Setup. The loss is a quadratic ravine, f(w) = ½ (1·w₀² + 25·w₁²). It has curvature 1 along one axis and 25 along the other, so it is steep across the valley and shallow along it. Every optimizer starts at (−4, 1), where the loss is 20.5, and takes exactly 60 steps. SGD uses learning rate η; momentum uses β = 0.9; Adam uses β1 = 0.9, β2 = 0.999, ε = 1e-8. We give each optimizer the same eight learning rates and report its best, so nobody is handicapped by a single bad choice. Run on Python 3.12.3 with NumPy 2.5.4:

import numpy as np

STEPS = 60
START = np.array([-4.0, 1.0])
CURV = np.array([1.0, 25.0])                 # curvature along w0 and w1: a 25:1 ravine

def make_problem(rotate_deg=0.0):
    th = np.radians(rotate_deg)
    Q = np.array([[np.cos(th), -np.sin(th)], [np.sin(th), np.cos(th)]])
    H = Q @ np.diag(CURV) @ Q.T              # Hessian of f(w) = 0.5 * w.T @ H @ w
    return (lambda w: 0.5 * w @ H @ w), (lambda w: H @ w)

def optimize(kind, lr, loss, grad, beta=0.9, b1=0.9, b2=0.999, eps=1e-8):
    w, m, v = START.copy(), np.zeros(2), np.zeros(2)
    losses = [loss(w)]
    for t in range(1, STEPS + 1):
        g = grad(w)
        if kind == "sgd":
            w = w - lr * g
        elif kind == "momentum":
            m = beta * m + g                  # PyTorch-style momentum buffer
            w = w - lr * m
        elif kind == "adam":
            m = b1 * m + (1 - b1) * g
            v = b2 * v + (1 - b2) * g * g
            w = w - lr * (m / (1 - b1**t)) / (np.sqrt(v / (1 - b2**t)) + eps)
        losses.append(loss(w))
    return np.array(losses)

LRS = [0.001, 0.003, 0.01, 0.03, 0.1, 0.3, 1.0, 3.0]
for label, deg in [("axis-aligned ravine", 0.0), ("same ravine rotated 45 degrees", 45.0)]:
    loss, grad = make_problem(deg)
    print(f"\n== {label}: start loss {loss(START):.2f} ==")
    best = {}
    for lr in LRS:
        row = []
        for k in ["sgd", "momentum", "adam"]:
            L = optimize(k, lr, loss, grad)
            ok = np.isfinite(L[-1]) and L[-1] < 1e6
            row.append(f"{L[-1]:12.4g}" if ok else f"{'div':>12s}")
            if ok and (k not in best or L[-1] < best[k][0]):
                best[k] = (L[-1], lr)
        print(f"{lr:<8}" + "".join(row))
    for k in best:
        L = optimize(k, best[k][1], loss, grad)
        print(k, "best lr", best[k][1], "loss at steps 10/20/40/60:",
              [round(L[i], 4) for i in (10, 20, 40, 60)])

Because the gradients here are exact, “SGD” in this race is plain gradient descent: there is no mini-batch noise. We note this limitation again below.

Results: the axis-aligned ravine

Final loss after 60 steps, by learning rate (div means the loss blew up):

Learning rate SGD SGD + momentum Adam
0.001 7.694 2.676 18.82
0.003 5.579 0.1209 15.8
0.01 2.395 0.02145 8.474
0.03 0.2069 0.01944 2.736
0.1 div 0.01377 0.01501
0.3 div div 0.002407
1.0 div div 0.007
3.0 div div 0.04344

The best learning rate for each optimizer, and its loss along the way:

Optimizer (best learning rate) Loss at step 10 Step 20 Step 40 Step 60
SGD (0.03) 4.35 2.366 0.6996 0.2069
SGD + momentum (0.1) 6.272 1.891 0.1647 0.01377
Adam (0.3) 2.226 0.8689 0.08777 0.002407

At 60 steps Adam’s loss is about 86 times lower than plain gradient descent’s and about 5.7 times lower than momentum’s. Notice three things beyond the ranking.

  1. The stable window. Gradient descent diverges at learning rate 0.1. That matches a standard result: on a quadratic, it is stable only below 2 divided by the largest curvature, here 2 / 25 = 0.08. Momentum survives 0.1 but diverges at 0.3. Adam stayed finite across the whole range from 0.001 to 3.0.
  2. Finite is not the same as good. Adam’s loss at its extremes was 18.82 (learning rate 0.001, far too small) and 0.04344 (3.0, too large, so it bounces around the minimum). Its best was 0.002407. A wide stable range makes Adam forgiving, not tuning-free.
  3. Momentum starts slowly. At step 10 momentum (6.272) was behind plain gradient descent (4.35), because the velocity has to build up. By step 20 it had overtaken it (1.891 against 2.366).

Results: the same ravine, rotated 45 degrees

An axis-aligned ravine is the best case for Adam, because its per-parameter scaling works along each coordinate axis, and the ravine runs along those axes. To check, we rotated the same ravine by 45 degrees, so its valley is diagonal. Same start point and steps (the start loss is now 158.5, because the same start point sits at a different place on the rotated bowl):

Optimizer (best learning rate) Final loss, step 60 Loss at step 10 Step 20 Step 40
SGD (0.03) 0.05818 1.224 0.6654 0.1968
SGD + momentum (0.1) 0.03051 44.52 12.03 0.7431
Adam (1.0) 0.008708 2.886 0.7663 1.166

Adam still finished lowest, but the picture is less one-sided. Plain gradient descent was ahead of Adam at steps 10 and 20, and Adam’s loss went up between steps 20 and 40 (0.7663 to 1.166) as it overshot before settling. Its best learning rate was also a different value (1.0, not 0.3), which is a reminder that the best learning rate depends on the problem’s geometry.

What the race does and does not show

A toy race illustrates behaviour; it does not prove a universal winner. It used exact gradients, a single quadratic, one start point and 60 steps. Real networks have noisy mini-batch gradients, non-convex loss surfaces and millions of parameters. What the race does show is the mechanism: Adam’s per-parameter scaling helps on a ravine, momentum helps SGD but narrows its stable learning-rate window, and the best learning rate differs for each optimizer.

A short PyTorch comparison

Setup. The dataset is scikit-learn’s load_digits: 1,797 images of handwritten digits, 8 × 8 pixels (64 features), 10 classes. We split 80/20 with stratify and random_state=42, giving 1,437 training and 360 test samples. The model is a small network, 64 → 128 → ReLU → 10. All runs use 30 epochs, batch size 64 and cross-entropy loss, with features standardised using training-set statistics. We compare SGD, SGD with momentum 0.9, Adam and AdamW (weight decay 0.01). To avoid tuning on the test set, we choose each optimizer’s learning rate from a five-value grid on a validation split carved out of the training set (1,149 train, 288 validation), using validation loss after 30 epochs at seed 42. Then we retrain on the full training set with the chosen rate and score the test set once. Python 3.12.3, PyTorch 2.15.0, scikit-learn 1.9.1, NumPy 2.5.4, one CPU thread.

import numpy as np, torch, torch.nn as nn
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

torch.set_num_threads(1)
X, y = load_digits(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, stratify=y, random_state=42)
X_tr, X_val, y_tr, y_val = train_test_split(
    X_train, y_train, test_size=0.2, stratify=y_train, random_state=42)

EPOCHS, BATCH = 30, 64

def make_data(Xa, ya, Xb, yb):
    sc = StandardScaler().fit(Xa)
    t = lambda a: torch.tensor(a, dtype=torch.float32)
    return t(sc.transform(Xa)), torch.tensor(ya), t(sc.transform(Xb)), torch.tensor(yb)

def build():
    return nn.Sequential(nn.Linear(64, 128), nn.ReLU(), nn.Linear(128, 10))

def make_opt(name, params, lr):
    if name == "SGD":          return torch.optim.SGD(params, lr=lr)
    if name == "SGD+momentum": return torch.optim.SGD(params, lr=lr, momentum=0.9)
    if name == "Adam":         return torch.optim.Adam(params, lr=lr)
    if name == "AdamW":        return torch.optim.AdamW(params, lr=lr, weight_decay=0.01)

def train_eval(name, lr, data, seed):
    Xa, ya, Xb, yb = data
    torch.manual_seed(seed)
    model = build(); opt = make_opt(name, model.parameters(), lr)
    lossf = nn.CrossEntropyLoss()
    gen = torch.Generator().manual_seed(seed)
    curve = []
    for ep in range(EPOCHS):
        perm = torch.randperm(len(Xa), generator=gen); tot = 0.0
        for i in range(0, len(Xa), BATCH):
            idx = perm[i:i + BATCH]; opt.zero_grad()
            loss = lossf(model(Xa[idx]), ya[idx]); loss.backward(); opt.step()
            tot += loss.item() * len(idx)
        curve.append(tot / len(Xa))
    with torch.no_grad():
        out = model(Xb)
        return curve, lossf(out, yb).item(), (out.argmax(1) == yb).float().mean().item()

GRID = {"SGD": [0.003, 0.01, 0.03, 0.1, 0.3],
        "SGD+momentum": [0.001, 0.003, 0.01, 0.03, 0.1],
        "Adam": [0.0003, 0.001, 0.003, 0.01, 0.03],
        "AdamW": [0.0003, 0.001, 0.003, 0.01, 0.03]}

# 1) choose each learning rate on the validation split (test set untouched)
dsel, best_lr = make_data(X_tr, y_tr, X_val, y_val), {}
for name, lrs in GRID.items():
    best_lr[name] = min((train_eval(name, lr, dsel, 42)[1], lr) for lr in lrs)[1]

# 2) retrain on the full training set; evaluate on the test set once per run
dfin = make_data(X_train, y_train, X_test, y_test)
for name in GRID:
    runs = [train_eval(name, best_lr[name], dfin, seed) for seed in range(5)]
    print(name, best_lr[name], "test acc, seeds 0-4:", [round(r[2], 4) for r in runs])

Chosen learning rates: SGD 0.3, SGD with momentum 0.03, Adam 0.003, AdamW 0.003. SGD’s choice is the largest value in its grid, so a larger rate might have done better; treat the SGD result as a slight underestimate.

Results with tuned learning rates (test set, 360 samples; one sample is 0.28 percentage points):

Optimizer Test accuracy, seed 42 Test accuracy, mean (min to max) over seeds 0 to 4 Mean test loss Train loss at epoch 5 / 30, seed 42
SGD 0.9806 0.9800 (0.9778 to 0.9806) 0.1037 0.0915 / 0.0076
SGD + momentum 0.9806 0.9772 (0.9722 to 0.9806) 0.1029 0.0843 / 0.0073
Adam 0.9806 0.9822 (0.9778 to 0.9889) 0.0812 0.0694 / 0.0019
AdamW 0.9806 0.9822 (0.9778 to 0.9889) 0.0800 0.0697 / 0.0021

At seed 42 all four got 353 of 360 test samples right. Across five seeds the means differ by at most 0.005, under two test samples, which is well inside the seed-to-seed spread. On accuracy, this is a tie. The Adam variants did reach a lower training loss faster (0.0694 against 0.0915 for SGD at epoch 5) and showed a lower average test loss (about 0.08 against about 0.10), but with one small dataset and one architecture we would not generalise that.

Results with untuned defaults (seed 42, no learning-rate search): the case where the optimizers separate.

Optimizer, learning rate Test accuracy Test loss Train loss at epoch 30
SGD, 0.01 0.9306 0.4376 0.4152
SGD + momentum, 0.01 0.9750 0.1220 0.0327
Adam, 0.001 0.9806 0.1063 0.0163
AdamW, 0.001 0.9806 0.1062 0.0166

Here the tuning-effort gap is visible. Plain SGD at 0.01 was still undertrained after 30 epochs (train loss 0.4152), while Adam at its default learning rate matched the tuned results. This matches the decision table: Adam is the low-effort choice, and SGD pays you back for tuning. In the learning-rate search, Adam also showed a cliff at the top: validation loss at 0.03 was 7.0241, far worse than 0.0547 at 0.003.

Flat versus sharp minima, and generalization

A popular argument says SGD generalizes better than Adam because it finds flat minima, where the loss changes little when the weights are nudged, whereas adaptive methods settle in sharp ones. The evidence is real but mixed, so treat it as a tendency, not a law.

  • Keskar et al. (2017) reported that large-batch training tends to converge to sharper minima and generalize worse, which put sharpness on the map.
  • Wilson et al. (2017) argued that adaptive methods, Adam among them, can find solutions that generalize worse than SGD’s, including on a constructed example, and reported cases on real tasks.
  • Dinh et al. (2017) showed that sharpness depends on how the model is parametrised, so flatness alone cannot be a complete explanation.
  • Loshchilov and Hutter (2019) traced part of Adam’s generalization gap to how weight decay is implemented, and proposed AdamW to fix it.

Notice that these findings point in different directions. Part of the reported gap may come from regularization details rather than from the optimizer’s nature, and well-tuned Adam variants are widely used in practice. We did not measure sharpness in our own runs. What we did measure, on the digits task, is that tuned SGD and tuned Adam reached the same test accuracy. If you are chasing the last fraction of accuracy on an image classifier, the published results are a reason to try SGD with momentum. They are not a reason to expect it to win.

Defaults that work

These PyTorch settings are starting points to tune, not guarantees:

import torch

# Adam: PyTorch's defaults are lr=1e-3, betas=(0.9, 0.999), eps=1e-8
opt = torch.optim.Adam(model.parameters(), lr=1e-3)

# AdamW: decoupled weight decay; the default weight_decay is 1e-2
opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=1e-2)

# SGD with momentum: PyTorch's SGD default is lr=1e-3 with no momentum, so set both
opt = torch.optim.SGD(model.parameters(), lr=1e-2, momentum=0.9)

What the evidence supports:

  • Adam and AdamW: 1e-3 is PyTorch’s default and matched the tuned results on our task. In our search the best value was 3e-3, and 3e-2 broke training. Try values spaced by a factor of about three around 1e-3 (3e-4, 1e-3, 3e-3), which is the spacing our search used.
  • SGD with momentum: there is no universal default. In our search the best rate was 0.03, and rates of 0.001 and 0.003 trained too slowly. Search at least a factor-of-ten range on a log scale, because the stable window is narrower than Adam’s (see the race).
  • Plain SGD: needs the most tuning. At 0.01 it underfit; the best rate we tried was 0.3.
  • Weight decay: with Adam, prefer AdamW to adding an L2 term to the loss. Adam Optimizer Explained covers why.
  • Learning-rate schedules (warmup, cosine decay) often matter as much as the optimizer. A later article in this series covers momentum and learning-rate schedules.

When SGD wins, and when Adam wins

SGD with momentum is a good choice when:

  • you are training an image classifier and have time to tune the learning rate and its schedule;
  • the last bit of accuracy matters more than getting a first result quickly (the published arguments above point this way, as a tendency);
  • memory is tight, since it stores fewer states than Adam.

Adam or AdamW is a good choice when:

  • you need a fast baseline with little tuning time (our untuned results above);
  • you are training transformers, which were introduced with Adam (Vaswani et al., 2017) and are usually trained with Adam-family optimizers;
  • gradients are sparse or very uneven across parameters, where per-parameter scaling helps (the ravine race shows the mechanism);
  • you want weight decay done correctly (AdamW).

Neither is a safe bet when you have not tuned the learning rate. In both our experiments the learning rate changed the outcome far more than the choice between SGD and Adam did.

Decision flowchart

START
 │
 ├─ Is memory very tight (huge model)? ───────────────► Yes: SGD (with momentum)
 │
 ├─ Do you have time to tune lr and schedule? ─┬─ No ──► Adam / AdamW, lr 1e-3 first
 │                                              │
 │                                              └─ Yes ─► What is the model?
 │                                                          ├─ Transformer / language model ► AdamW
 │                                                          ├─ CNN / image classifier ──────► SGD + momentum,
 │                                                          │                                  compare with AdamW
 │                                                          └─ Small MLP / tabular ─────────► Either; tune lr,
 │                                                                                             expect a tie
 └─ Unsure? Run both with a log-spaced lr search on a validation split.

This agrees with the decision table at the top, and with both experiments: Adam won the race with no tuning advantage, SGD with momentum needed more care, and on the PyTorch task the tuned optimizers tied. If you are choosing between SGD and Adam for a new project, start with the table, then confirm with a short learning-rate search.

FAQ

Which is better, SGD or Adam?

Neither wins everywhere. In our PyTorch run all four optimizers tied on test accuracy once tuned, and Adam was stronger untuned. SGD with momentum is often preferred for image classification when you can tune, and Adam for fast baselines and transformers.

Why is Adam used for transformers?

Transformers were introduced and trained with Adam (Vaswani et al., 2017), and Adam-family optimizers are the common choice. Adaptive scaling copes with parameters whose gradients differ widely in size.

Does Adam generalize worse than SGD?

Some studies report that it can, and others show the gap depends on regularization details and parametrization. Treat it as a tendency to test on your task, not a rule.

Is SGD with momentum the same as Adam?

No. Both use a running average of gradients, but Adam also divides each step by a running average of squared gradients, giving every parameter its own effective learning rate.

What learning rate should I start with?

For Adam and AdamW, 1e-3 (PyTorch’s default) is the usual first try. For SGD with momentum there is no safe default, so search on a log scale.

Should I use Adam or AdamW?

Prefer AdamW if you use weight decay. It applies decay separately from the gradient step, which is what Loshchilov and Hutter proposed.

Sources

  • Kingma, D. P. and Ba, J. (2015). “Adam: A Method for Stochastic Optimization.” ICLR 2015.
  • Loshchilov, I. and Hutter, F. (2019). “Decoupled Weight Decay Regularization.” ICLR 2019.
  • Wilson, A. C., Roelofs, R., Stern, M., Srebro, N. and Recht, B. (2017). “The Marginal Value of Adaptive Gradient Methods in Machine Learning.” NeurIPS 2017.
  • Keskar, N. S., Mudigere, D., Nocedal, J., Smelyanskiy, M. and Tang, P. T. P. (2017). “On Large-Batch Training for Deep Learning: Generalization Gap and Sharp Minima.” ICLR 2017.
  • Dinh, L., Pascanu, R., Bengio, S. and Bengio, Y. (2017). “Sharp Minima Can Generalize For Deep Nets.” ICML 2017.
  • Vaswani, A. et al. (2017). “Attention Is All You Need.” NeurIPS 2017.
  • PyTorch documentation: torch.optim.SGD, torch.optim.Adam, torch.optim.AdamW.
Scroll to Top