Skip to content
mentoor

Topic 4 of 5 · 5 min read

SGD, momentum and Adam optimizers

Goal: Pick an optimizer and batch size for a training job and state how much extra memory AdamW's state needs.

An optimizer is the rule that turns gradients into weight updates: plain SGD uses the gradient directly, momentum smooths it, and Adam adapts the step per weight. For transformers the usual default is AdamW, and it costs memory you should plan for.

Check yourself · 1 of 3

What does Adam keep for every weight, besides the weight itself?

Choose one answer

Why it matters

The optimizer choice changes how fast the run converges, how sensitive it is to the learning rate, and how much GPU memory you need. An agent will happily write torch.optim.Adam(model.parameters()) without telling you it just added two copies of the model to memory.

The ladder

  • Stochastic gradient descent (SGD). Compute the gradient on a mini-batch (for example 32 to 4,096 examples), not the whole dataset, and step. The batch gradient is a noisy estimate of the true one, which is cheap and works well. Bigger batches give smoother gradients and fewer steps per epoch.
  • Momentum. Keep a running average of past gradients and step along it, as a ball rolls downhill. It damps zigzag across steep valleys and speeds up along consistent directions. Cost: one extra number per weight.
  • Adam. Keeps two running averages per weight: the mean of the gradient (the first moment, m) and the mean of its square (the second moment, v). The step is roughly m / sqrt(v), so weights with big, noisy gradients take smaller steps and weights with small gradients take relatively larger ones. This makes it forgiving about the learning rate. The original paper describes both moments.
  • AdamW. Adam with weight decay applied directly to the weights, separately from the gradient update. Plain L2 regularisation inside Adam interacts badly with the adaptive scaling; the AdamW paper decouples them. Typical settings: lr = 3e-4 for training, 1e-5 to 5e-5 for fine-tuning, weight_decay = 0.01 to 0.1.

The memory bill

Adam and AdamW store m and v for every parameter. In fp32 (4 bytes) a 7-billion-parameter model has 28 GB of weights, 28 GB for m and 28 GB for v, plus 28 GB of gradients. That is about 112 GB before activations. SGD with momentum needs one extra copy instead of two. This is why large runs shard optimizer state across GPUs, use 8-bit optimizers, or fine-tune with LoRA, where only a small set of weights has optimizer state.

import torch
opt = torch.optim.AdamW(model.parameters(), lr=3e-4,
                        weight_decay=0.01, betas=(0.9, 0.999))

Before and after

Weak: a team fine-tunes a 7B model with Adam on one 80 GB GPU and gets out-of-memory in the first step, then lowers the batch size, which does not help because the state alone is over 50 GB. Fixed: they count weights, gradients and optimizer state first (about 4 + 4 + 8 bytes per parameter in fp32), then pick LoRA or sharding.

What goes wrong

  • Adam for everything. Some vision models still reach better final accuracy with SGD plus momentum.
  • L2 penalty added to Adam instead of AdamW. Decay is distorted.
  • Ignoring state in the memory budget.

Examples

Counting the memory

A 1.5B-parameter model in fp32: weights 6 GB, gradients 6 GB, Adam m and v 12 GB. Total about 24 GB before activations. Training it on a 24 GB card fails; a 48 GB card works with a small batch.

Reviewing an optimizer line

The agent writes torch.optim.Adam(params, lr=1e-3, weight_decay=0.01). In Adam, that decay is an L2 term folded into the gradient. Replace it with torch.optim.AdamW so the decay is applied separately, and lower the rate to 3e-4 or less for a transformer.

Key points

  • SGD steps along a mini-batch gradient, which is a noisy but cheap estimate of the full gradient.
  • Momentum averages past gradients to damp zigzag, at the cost of one extra number per weight.
  • Adam keeps a mean (m) and a mean of squares (v) per weight and scales each step by m over sqrt(v).
  • AdamW applies weight decay directly to the weights and is the usual default for transformers.
  • Adam state is two extra copies of the parameters: about 56 GB on top of 28 GB of fp32 weights for a 7B model.

Common mistakes

  • Leaving optimizer state out of the GPU memory estimate.
  • Using Adam with L2 weight_decay when AdamW was meant.
  • Assuming a bigger batch always trains better; it means fewer updates per epoch.
  • Using a fine-tuning rate for from-scratch training, or the reverse.

Check yourself · 2 of 3

What is the difference between AdamW and Adam with an L2 penalty?

Choose one answer

Check yourself · 3 of 3

A model has 1 billion parameters in fp32 (4 bytes each). How much extra memory do Adam's m and v take?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic