InferenceAIAll articles

From Gradient Descent to Adam: Build Every Optimiser in NumPy

By InferenceAI Editorial · 11 min read · intermediate · Updated

Write gradient descent, momentum, RMSProp and Adam from scratch, see what each one fixes, and finally understand Adam's bias correction.

Every deep learning framework hides its optimiser behind one line: optimizer.step(). That's convenient, but it also means many people train models for years without knowing what that line does. Then an interviewer asks "why does Adam need bias correction?" and the room goes quiet.

The good news is that the core optimisers are short. Each one is a few lines of NumPy, and each new one fixes a specific problem with the previous one. In this post we'll build them in order, gradient descent → momentum → RMSProp → Adam, and run every one so you can see it work.

The setup: a problem with a known answer

To see what an optimiser does, start with a function where we already know the answer:

f(w) = (w − 3)², minimum at w = 3, gradient f′(w) = 2(w − 3)

python
import numpy as np

def f(w):
    return (w - 3.0) ** 2

def df(w):
    return 2.0 * (w - 3.0)

Every optimiser below starts at w = 0 and should end near 3.

1. Plain gradient descent

The gradient points uphill. Take a small step the other way:

w ← w − η · ∇f(w)

python
w = 0.0
lr = 0.1
for step in range(50):
    w -= lr * df(w)

print(round(w, 6))   # 2.999957

That's all of it. The learning rate η (lr) is the most important hyperparameter you'll tune:

  • Too small and training crawls.
  • Too large and you overshoot the minimum. For this function, any lr > 1.0 makes w bounce further away on every step and diverge.

Plain gradient descent has two weaknesses on real loss surfaces. It zig-zags in narrow valleys, where the gradient mostly points across the valley instead of along it. And it uses one learning rate for every parameter, even when some parameters get huge gradients and others get tiny ones.

2. Momentum: remember where you were going

Picture a ball rolling downhill. It doesn't stop and change direction at every bump; it builds up speed. Momentum keeps a running velocity that adds up past gradients:

v ← β·v + ∇f(w)
w ← w − η·v

python
w, v, beta = 0.0, 0.0, 0.9
for step in range(200):
    v = beta * v + df(w)
    w -= 0.05 * v

print(round(w, 6))   # 2.999996

With β = 0.9, the velocity is a decaying sum of recent gradients in which roughly the last ten steps matter most. Zig-zag components cancel out (left, right, left, right) while consistent directions add up. In narrow valleys that's a big speed-up.

Note: momentum can overshoot and oscillate before settling, much like a real ball rolling past the bottom of a bowl. That's normal, and it's why momentum is usually paired with a slightly smaller learning rate.

3. RMSProp: a learning rate per parameter

Momentum fixes direction but not scale. If one weight's gradients are always about 100 and another's about 0.01, a single learning rate can't suit both.

RMSProp keeps a running average of squared gradients for each parameter and divides by its square root:

s ← ρ·s + (1 − ρ)·g²
w ← w − η · g / (√s + ε)

python
w, s = 0.0, 0.0
lr, rho, eps = 0.1, 0.9, 1e-8
for step in range(200):
    g = df(w)
    s = rho * s + (1 - rho) * g * g
    w -= lr * g / (np.sqrt(s) + eps)

print(round(w, 4))   # 3.0

Dividing by √s normalises the step size. Parameters with large gradients take smaller steps; parameters with small gradients take relatively bigger ones. The tiny ε (epsilon) only prevents division by zero.

One side effect: because each step is roughly lr × sign(gradient), RMSProp with a fixed learning rate tends to hover within about lr of the minimum instead of settling exactly. In practice, learning-rate schedules take care of this.

4. Adam: momentum + RMSProp + one clever fix

Adam combines the two ideas. It keeps a momentum-style average of gradients (m, the first moment) and an RMSProp-style average of squared gradients (v, the second moment):

m ← β₁·m + (1 − β₁)·g
v ← β₂·v + (1 − β₂)·g²

Then it fixes a subtle problem. Both m and v start at zero, so for the first few steps they're biased towards zero. With β₂ = 0.999, after one step v is only 0.001 · g², a thousand times too small. Adam corrects for this:

m̂ = m / (1 − β₁ᵗ), v̂ = v / (1 − β₂ᵗ)
w ← w − η · m̂ / (√v̂ + ε)

As t grows, β₁ᵗ and β₂ᵗ go to zero and the correction fades out. That's the answer to the interview question: bias correction undoes the zero-initialisation of the moment estimates, which otherwise makes the first steps the wrong size.

Here it is as a small, reusable class:

python
class Adam:
    def __init__(self, lr=0.001, beta1=0.9, beta2=0.999, eps=1e-8):
        self.lr, self.beta1, self.beta2, self.eps = lr, beta1, beta2, eps
        self.m = None
        self.v = None
        self.t = 0

    def step(self, params, grads):
        if self.m is None:
            self.m = np.zeros_like(params)
            self.v = np.zeros_like(params)
        self.t += 1
        self.m = self.beta1 * self.m + (1 - self.beta1) * grads
        self.v = self.beta2 * self.v + (1 - self.beta2) * grads ** 2
        m_hat = self.m / (1 - self.beta1 ** self.t)
        v_hat = self.v / (1 - self.beta2 ** self.t)
        return params - self.lr * m_hat / (np.sqrt(v_hat) + self.eps)

Putting Adam to work: linear regression from scratch

A one-variable function is a toy. Let's fit a real model: linear regression with three weights, using the gradient of mean squared error.

python
rng = np.random.default_rng(0)
X = rng.normal(size=(200, 3))
true_w = np.array([2.0, -1.0, 0.5])
y = X @ true_w + 0.1 * rng.normal(size=200)

w = np.zeros(3)
opt = Adam(lr=0.05)
for step in range(500):
    grad = 2 * X.T @ (X @ w - y) / len(y)   # d(MSE)/dw
    w = opt.step(w, grad)

print(np.round(w, 2))   # [ 1.99 -1.01  0.51]

It recovers the true weights [2, -1, 0.5] up to the noise we added. Same optimiser, no changes, now working on a vector of parameters, because every operation in step is element-wise.

Which one should you use?

OptimiserRemembers directionPer-parameter step sizeTypical use
SGDNoNoSimple baselines, convex problems
SGD + momentumYesNoCNNs for vision, often generalises very well
RMSPropNoYesRecurrent networks, reinforcement learning
Adam / AdamWYesYesTransformers, LLMs, most default setups

A practical note: for modern transformers you'll almost always see AdamW. It applies weight decay directly to the weights instead of folding it into the gradient, which works better with Adam's per-parameter scaling. The update loop is the same as above plus one line: params -= lr * weight_decay * params.

Common mistakes

  1. Forgetting to increment t before bias correction. At t = 0, 1 − β⁰ is zero and you divide by zero.
  2. Sharing state between parameter groups. Each parameter tensor needs its own m and v.
  3. Using Adam's default lr = 0.001 everywhere. It's a starting point, not a law. Transformers usually also need warm-up.
  4. Thinking Adam removes the need to tune. It makes training more forgiving, but the learning rate still matters most.

Key takeaways

  • Gradient descent steps against the gradient; the learning rate controls everything.
  • Momentum smooths the direction; RMSProp normalises the scale per parameter.
  • Adam does both, and bias correction fixes the zero-initialised moments early in training.
  • Each optimiser is a few lines of NumPy. Write them once and optimizer.step() stops being a black box.

Want to practise? Close this page and rewrite the Adam class from memory, then check it against the linear-regression example above. If the weights come out as [1.99, -1.01, 0.51], your bias correction is right. When you're ready for more, the problem set has graded ML implementation problems.

Frequently asked questions

What is the difference between SGD and Adam?

SGD updates every parameter with the same learning rate times the gradient. Adam keeps running averages of the gradient and of the squared gradient for each parameter, which adds momentum and an adaptive per-parameter step size.

Why does Adam need bias correction?

Adam initialises its moment estimates at zero, so for the first steps they are biased towards zero and the update size is wrong. Dividing by (1 - beta to the power t) corrects this, and the correction fades as training continues.

What is the difference between Adam and AdamW?

AdamW applies weight decay directly to the weights instead of adding it to the gradient. This decoupling works better with Adam's adaptive step sizes and is the standard choice for training transformers.

#optimizers#adam#gradient-descent#numpy

Sources and further reading

Practise what you just read

Solve hands-on AI and ML coding problems in your browser, with instant feedback on every test case.

Browse problems