# SGD vs Adam

> How SGD and Adam take their learning steps, why Adam is a good first try, and when SGD still wins, explained for your AI interview.

**In short:** SGD moves every weight by one learning rate times its gradient. Adam gives each weight its own step size, based on the history of its gradients, so it usually needs little tuning, but SGD can still generalise better.

AI and LLM interview question Q416, Classic ML and deep-learning basics. Intermediate, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/sgd-vs-adam

## Say it in 30 seconds

SGD and Adam both learn by nudging each weight to lower the error. SGD uses one learning rate, times the gradient, for every weight. Adam gives each weight its own step size, based on the recent history of its gradients. Adam typically needs little tuning, so it's my usual first try. But a 2017 study found adaptive methods like Adam generalised worse than SGD in its tests, so I'd test both before I ship.

## Say it in 2 minutes

SGD and Adam both train a model by nudging each weight in the direction that lowers the error. The gradient says which way and how hard. The real difference is the step size. SGD uses one learning rate, multiplied by each gradient, for every weight. Adam gives each weight its own step size, based on running averages of that weight's past gradients.

The practical trade-off is tuning. Adam's authors say its settings typically need little tuning, which makes it a sensible first choice for a new model. Both methods still have a learning rate that matters, so tune it for whichever you use. Then check the result on data the model hasn't seen.

Scale is where the difference shows. If one input is a transaction amount in rupees and another is a ratio between 0 and 1, a single step size has to be safe for the big one, so the small one barely moves. In my made-up run, SGD left the ratio weight at 0.053 of its target after 300 steps, while Adam reached both targets.

Adam doesn't always finish best. A 2017 study found adaptive methods generalised worse than SGD in its tests. The AdamW paper later showed that fixing how weight decay is applied substantially improves Adam's generalisation. So I'd start with Adam, then test SGD with momentum before shipping.

## What are SGD and Adam, in plain words?

Training a model means changing its weights, the numbers it learns, so its error gets smaller. The gradient tells you, for each weight, which way to move it and how hard. An optimiser is the rule that turns those gradients into actual changes.

SGD, short for stochastic gradient descent, is the simplest rule. It works on a small random batch of examples at each step, so each step is quick. PyTorch, the open-source library, describes it as "Implements stochastic gradient descent (optionally with momentum)."

Picture a hospital pharmacy setting drug doses for twelve wards. One dose rule for every ward is simple, but a ward of frail patients and a ward of tough cases need different steps. Adam is like a pharmacist who keeps a record for each ward and adjusts its step to match what has happened there.

The same problem shows up in AI. A bank's fraud model might take a transaction amount in rupees, which can run to tens of thousands, and a ratio between 0 and 1. One step size can't suit both inputs.

- **Gradient:** How much, and which way, one weight should change to reduce the error.
- **Learning rate:** How big each update's step is. Too big and training overshoots; too small and it crawls.
- **Momentum:** A share of the previous step, added to the next one, so the path stops zig-zagging.
- **Adaptive:** Changes each weight's step size on its own, using the history of that weight's gradients.
- **Generalise:** Doing well on new data, not only on the examples it trained on.

## How does SGD take a step?

1. **Pick a small batch:** Take a random handful of training examples, so each step is quick.
2. **Work out the gradient:** For each weight, find the direction and size that would lower the error on that batch.
3. **Move every weight by one rule:** New weight equals old weight minus the learning rate times its gradient. Momentum, if switched on, adds a share of the last step.

Because the learning rate is shared, one step size has to work for every weight. That keeps SGD simple, and it is also its weak spot when weights are on very different scales, as the example below shows.

## How does Adam take a step?

Adam keeps two running averages for every weight. The first is of its gradients, so it knows the usual direction. The second is of its squared gradients, so it knows how big they have been. Adam divides the first by the square root of the second, then multiplies by the learning rate. Because of that division, each weight moves about one learning rate per step, whatever the size of its gradients. A step shrinks when a weight's gradients keep changing sign, because the running average then cancels out.

*Diagram, Two ways to set each weight's step: Both methods start from the same gradient. They differ in whether every weight shares one step size or gets its own. The difference matters most when the weights live on very different scales.*
1. SGD takes the gradient and applies one learning rate to every weight.
2. Adam takes the same gradient and scales it by that weight's own history.
3. With one size for all, the big-scale weight sets the pace, so the small one barely moves.
4. Each weight gets a step of its own size, so both reach the target.

The Adam paper, by Kingma and Ba, describes the method in its abstract:

> "based on adaptive estimates of lower-order moments" (Adam paper (Kingma and Ba))
>
> "The hyper-parameters have intuitive interpretations and typically require little tuning." (Adam paper (Kingma and Ba))

PyTorch's Adam page describes its beta settings as "coefficients used for computing running averages of gradient and its square". The paper was published at ICLR 2015, in San Diego.

## What happens when weights live on very different scales?

Here is a made-up fraud score with two weights. One reads an amount in rupees and is very sensitive, the other reads a ratio and is much less so. Both start at zero and should reach 1.0. The code runs 300 steps of each method.

```python
# A made-up fraud score with two weights on very different scales:
# one reads a transaction amount in rupees (size 10000), one a ratio (size 1).
import math
SIZE = [10000.0, 1.0]
TARGET = [1.0, 1.0]
def loss(w):
    return sum(s * (x - t) ** 2 for s, x, t in zip(SIZE, w, TARGET))
def grad(w):
    return [2 * s * (x - t) for s, x, t in zip(SIZE, w, TARGET)]
def sgd(lr=0.00009, steps=300):
    w = [0.0, 0.0]
    for _ in range(steps):
        w = [x - lr * g for x, g in zip(w, grad(w))]
    return w
def adam(lr=0.01, steps=300, b1=0.9, b2=0.999, eps=1e-8):
    w, m, v = [0.0, 0.0], [0.0, 0.0], [0.0, 0.0]
    for t in range(1, steps + 1):
        g = grad(w)
        m = [b1 * a + (1 - b1) * b for a, b in zip(m, g)]
        v = [b2 * a + (1 - b2) * b * b for a, b in zip(v, g)]
        w = [x - lr * (a / (1 - b1 ** t)) / (math.sqrt(b / (1 - b2 ** t)) + eps)
             for x, a, b in zip(w, m, v)]
    return w
for name, w in [("SGD ", sgd()), ("Adam", adam())]:
    print(name, [round(x, 3) for x in w], "loss", round(loss(w), 3))
```

Output:

```text
SGD  [1.0, 0.053] loss 0.898
Adam [1.0, 1.0] loss 0.0
```

SGD's shared step has to stay small enough that the big weight doesn't overshoot. So in this run the ratio weight reaches only 0.053 of its target. Adam moves each weight by about one learning rate per step. With a learning rate of 0.01, it reaches both targets. That rate is ten times PyTorch's default of 0.001, which PyTorch gives as "learning rate (default: 1e-3)". At the default, Adam is only at about 0.28 after 300 steps, so it still needs a sensible learning rate. Real models have many weights, and their inputs often differ in scale. A common first fix is to rescale the inputs to a similar range, so one learning rate suits every weight. Adaptive methods like Adam help when that is not enough.

> **Tip:** When asked how you'd pick an optimiser, name the scale problem first. It shows the interviewer you understand why Adam exists and what problem it solves.

## When does SGD still win?

Adam's paper says it "compares favorably to other stochastic optimization methods", and its settings typically need little tuning, which is why it is a good first try. But good training scores don't prove the model works well on new data. Wilson and colleagues tested this in 2017, and their paper was submitted that May. They reported:

> "the solutions found by adaptive methods generalize worse (often significantly worse) than SGD, even when these solutions have better training performance" (Wilson and colleagues, 2017)
>
> "substantially improves Adam's generalization performance" (AdamW paper)

The fix that AdamW introduced concerns weight decay, a penalty that keeps weights small. In Adam, that penalty gets mixed into the adaptive step. The AdamW paper proposes a simple change: separate the penalty from the adaptive step, so it works the way the original weight decay was meant to. PyTorch's Adam page adds that with its decoupled_weight_decay flag set, "if True, this optimizer is equivalent to AdamW".

So neither method always wins. It depends on the model, the data and your tuning budget.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] SGD: one learning rate times the gradient, optionally with momentum.
- [ ] Adam: a step size per weight, from running averages of its gradients.
- [ ] Why Adam is a good first try: it typically needs little tuning.
- [ ] SGD's edge: a 2017 study found adaptive methods generalised worse than SGD in its tests.
- [ ] Why scale matters: one step size can't suit weights on very different scales.
- [ ] An honest close: it depends on the model, the data and the tuning budget.

**Common traps**

- Trap: "Adam is always better, so use it by default." Better: Adam's paper says it typically needs little tuning, but a 2017 study found SGD generalised better in its tests. Test both.
- Trap: "Adam has no learning rate, it sets its own." Better: Adam still has a learning rate you set. It adapts each weight's step, but it doesn't remove that setting.
- Trap: "SGD is old, so nobody uses it now." Better: SGD with momentum is still a strong option. The AdamW paper's fix let Adam compete with it on image classification.

## Can you spot the problem?

**Spot the problem:** A colleague's made-up fraud model trains with one SGD learning rate. After 300 steps the ratio weight has barely moved. Which is the likely cause?

A. The dataset has too many rows, so the model stops learning after step ten.
B. One shared step size is set for the big weight, so the ratio weight barely moves.
C. The learning rate is too high, so the big-scale weight keeps overshooting.
D. The batches are too small, so every gradient comes out as exactly zero.

**Answer:** B. With one step size for every weight, the big-scale weight sets the pace, and a small-scale weight can crawl. Per-weight step sizes, as in Adam, close that gap.

**Quick check:** A team must ship a new model in two weeks and has little time for tuning. What should they try first?

A. Plain SGD with no momentum, and never test anything else
B. Adam first, then compare with SGD with momentum before shipping
C. A very large learning rate, with no checks
D. Train for one step only, then ship the first weights it produces

**Answer:** B. Adam typically needs little tuning, so it's a good first try. Adaptive methods can generalise worse on some models, so compare against SGD with momentum before you commit.

## Can you answer these from memory?

**Flash cards**

- **What is SGD in one line?** Each weight moves by one learning rate times its gradient, optionally with momentum.
- **What does Adam add?** A step size per weight, from running averages of its gradients and squared gradients.
- **Does Adam need tuning?** Its authors say its settings typically need little tuning. You still set a learning rate.
- **What did the 2017 study find?** Adaptive methods' solutions often generalised worse than SGD, even with better training scores.
- **What is AdamW?** Adam with its weight decay separated from the adaptive step.
- **Which one first?** Adam, since it typically needs little tuning. Test SGD with momentum before you ship a model.

## Likely follow-up questions

- Q415 What is gradient descent? https://designervenkat.online/interview/ai/what-is-gradient-descent
- Q417 What does the learning rate do? https://designervenkat.online/interview/ai/what-does-the-learning-rate-do
- Q418 What is backpropagation? https://designervenkat.online/interview/ai/what-is-backpropagation
- Q414 L1, L2 and dropout regularisation? https://designervenkat.online/interview/ai/l1-l2-and-dropout-regularisation
- Q419 MSE vs cross-entropy loss? https://designervenkat.online/interview/ai/mse-vs-cross-entropy-loss
