---
layout: post
title: "Adam and AdamW Explained: How LLMs Update Their Weights"
date: 2026-06-14
tags: ["Training & Optimization", "From Scratch"]
category: "ai"
description: "How does the Adam optimizer work? Derive momentum, RMSprop and bias correction, see why AdamW decouples weight decay, and walk a numeric update by hand."
keywords: "adam optimizer explained, adamw vs adam, weight decay decoupled, adaptive learning rate, bias correction adam, train transformer optimizer, adam from scratch"
image: /assets/images/og-adam-optimizer.png
---

SGD with a fixed learning rate is the baseline everyone learns first, and it is almost never what I run for transformers. In my first month of GPT training I tuned learning rates by hand and watched the loss spike whenever a batch had odd gradients. Adam, and specifically AdamW, handles most of that for me.

This post is the optimizer companion to [cross-entropy loss](/blog/cross-entropy-loss-explained/). As in the [autograd](/blog/build-autograd-from-scratch/) post, I build the update rule from SGD upward, derive bias correction, show where AdamW differs from Adam, and run one scalar parameter through three timesteps with real numbers. The defaults match what I use in AL-1: `lr=3e-4`, `betas=(0.9, 0.999)`, `eps=1e-8`, `weight_decay=0.1`.

---

## Why isn't plain SGD enough?

Stochastic gradient descent:

$$
\theta_{t+1} = \theta_t - \eta \, g_t
$$

where $g_t = \nabla_\theta L$ at step $t$ and $\eta$ is the learning rate.

Two problems show up in deep networks:

1. **Different scales per parameter.** Embedding gradients and LayerNorm gradients can differ by orders of magnitude, so one global $\eta$ is too large for some parameters and too small for others.
2. **Noisy minibatches.** A single batch gradient is a rough estimate, so raw SGD jitters, especially early in training.

Momentum addresses the second problem and adaptive scaling addresses the first. Adam combines both.

```mermaid
flowchart TB
  SGD["SGD\nfixed η"] --> MOM["+ Momentum\nsmooth direction"]
  MOM --> RMS["+ RMSprop\nper-param scale"]
  RMS --> ADAM["Adam\nbias correction"]
  ADAM --> ADAMW["AdamW\ndecoupled WD"]
```

---

## What does momentum add?

Exponential moving average of gradients:

$$
m_t = \beta_1 m_{t-1} + (1 - \beta_1) g_t
$$

$$
\theta_{t+1} = \theta_t - \eta \, m_t
$$

With $\beta_1 = 0.9$, the update is a smoothed blend of recent gradients. It dampens oscillation across ravines and builds speed along directions where the gradient stays consistent.

Initialize $m_0 = 0$. At $t = 1$:

$$
m_1 = 0.1 \, g_1
$$

The first step uses only 10% of the actual gradient. This is the **cold start** problem, which Adam fixes with bias correction.

---

## What does RMSprop add?

Track a moving average of **squared** gradients:

$$
v_t = \beta_2 v_{t-1} + (1 - \beta_2) g_t^2
$$

(elementwise square)

Scale each parameter's update inversely:

$$
\theta_{t+1} = \theta_t - \eta \frac{m_t}{\sqrt{v_t} + \epsilon}
$$

Large historical $|g|$ gives a large $v$ and a smaller effective step. Small $v$ gives a bigger step. This is the per-parameter adaptive learning rate.

$\epsilon = 10^{-8}$ prevents division by zero. In float32 training I sometimes use $10^{-6}$; for my NumPy AL-1 build $10^{-8}$ is fine.

---

## How does Adam combine them?

**Adam** (Kingma & Ba): momentum on $g$, RMSprop on $g^2$, plus bias correction.

At step $t$ (1-indexed):

$$
m_t = \beta_1 m_{t-1} + (1 - \beta_1) g_t
$$

$$
v_t = \beta_2 v_{t-1} + (1 - \beta_2) g_t^2
$$

Bias correction:

$$
\hat{m}_t = \frac{m_t}{1 - \beta_1^t}
$$

$$
\hat{v}_t = \frac{v_t}{1 - \beta_2^t}
$$

Update:

$$
\theta_{t+1} = \theta_t - \eta \frac{\hat{m}_t}{\sqrt{\hat{v}_t} + \epsilon}
$$

Bias correction is needed because $m_t$ and $v_t$ both start at zero, so early values are systematically **underestimated**. Dividing by $1 - \beta^t$ scales the average back up to the true magnitude. At $t = 1$, $\beta_1 = 0.9$:

$$
\frac{1}{1 - 0.9} = 10
$$

The first-step gradient gets full weight instead of 10%.

At $t = 10$: $1 - 0.9^{10} \approx 0.651$, which is still a noticeable boost. By $t = 100$ the correction is negligible for $\beta_1$, but $\beta_2 = 0.999$ needs hundreds of steps to settle. $v_t$ warms up slowly because squared gradients are tiny early on.

I used a constant gradient of $0.5$. The curves are the raw $v_t$ for three values of $\beta_2$. Bias correction lifts each one to $\hat{v}_t = g^2 = 0.25$ at every $t$.

{% include fig.html src="adam-optimizer-explained/v-warmup.svg" alt="Raw v_t against step t for a constant gradient of 0.5, with beta 2 equal to 0.9, 0.99 and 0.999. The 0.9 curve reaches 0.25 within about 50 steps. The 0.999 curve is still below 0.07 at step 300. At t equals 1 the raw v is 0.00025." caption="The raw $v_t$ climbs toward $g^2 = 0.25$, and it climbs slowest for $\beta_2 = 0.999$." %}

---

## A numeric walk-through: one weight, three steps

Single parameter $\theta$, learning rate $\eta = 0.1$, $\beta_1 = 0.9$, $\beta_2 = 0.999$, $\epsilon = 10^{-8}$, no weight decay.

Start: $\theta_0 = 1.0$, $m_0 = 0$, $v_0 = 0$.

**Step 1:** $g_1 = 0.5$

$$
m_1 = 0.9(0) + 0.1(0.5) = 0.05
$$

$$
v_1 = 0.999(0) + 0.001(0.25) = 0.00025
$$

$$
\hat{m}_1 = \frac{0.05}{1 - 0.9} = 0.5
$$

$$
\hat{v}_1 = \frac{0.00025}{1 - 0.999} = 0.25
$$

$$
\Delta\theta = 0.1 \cdot \frac{0.5}{\sqrt{0.25} + 10^{-8}} = 0.1 \cdot \frac{0.5}{0.5} = 0.1
$$

$$
\theta_1 = 1.0 - 0.1 = 0.9
$$

Without bias correction I would have used $m_1 = 0.05$, a step of $0.01$, which is ten times too small on step one.

**Step 2:** $g_2 = -0.3$

$$
m_2 = 0.9(0.05) + 0.1(-0.3) = 0.045 - 0.03 = 0.015
$$

$$
v_2 = 0.999(0.00025) + 0.001(0.09) = 0.00024975 + 0.00009 = 0.00033975
$$

$$
\hat{m}_2 = \frac{0.015}{1 - 0.81} = \frac{0.015}{0.19} \approx 0.0789
$$

$$
\hat{v}_2 = \frac{0.00033975}{1 - 0.998001} \approx \frac{0.00033975}{0.001999} \approx 0.1700
$$

$$
\Delta\theta = 0.1 \cdot \frac{0.0789}{\sqrt{0.1700}} \approx 0.1 \cdot \frac{0.0789}{0.412} \approx 0.0191
$$

$$
\theta_2 \approx 0.9 - 0.0191 = 0.8809
$$

The gradient flipped sign, but $m$ is still positive, so momentum fights the flip for a step. That is the smoothing at work.

**Step 3:** $g_3 = 0.2$. I skip the digits here; the table below has them. The point is that $v_t$ grows when gradients are consistently large, which shrinks the effective step on noisy axes.

I computed all three updates. The gradients are $0.5$, $-0.3$ and $0.2$. Step 1 matches the numbers above.

{% include fig.html src="adam-optimizer-explained/three-steps.svg" alt="Two tables of the three Adam updates with gradients 0.5, minus 0.3 and 0.2. Step 1 gives m-hat 0.5, v-hat 0.25, a step of 0.1 and theta 0.9. Step 2 gives a step of 0.0191 and theta 0.8809. Step 3 gives a step of 0.0347 and theta 0.8461." caption="The weight moves from $\theta_0 = 1$ to $\theta_3 = 0.8461$ over the three steps." %}

---

## Adam vs AdamW: what actually changes?

**L2 regularization in Adam** (the old way): add $\lambda \theta$ to the gradient before the Adam update:

$$
g_t \leftarrow g_t + \lambda \theta_t
$$

Weight decay then goes through the adaptive scaling. A large $v_t$ shrinks the decay term along with the data gradient, so the regularization strength differs from parameter to parameter.

**AdamW** (Loshchilov & Hutter): decouple weight decay from the gradient-based update.

$$
\theta_t \leftarrow \theta_t - \eta \lambda \theta_t \quad \text{(weight decay)}
$$

$$
\theta_t \leftarrow \theta_t - \eta \frac{\hat{m}_t}{\sqrt{\hat{v}_t} + \epsilon} \quad \text{(Adam step)}
$$

In code, two lines in `step()`:

```python
if weight_decay != 0.0:
    p.data -= lr * weight_decay * p.data
p.data -= lr * m_hat / (np.sqrt(v_hat) + eps)
```

Transformers almost universally use AdamW: GPT-2, LLaMA and my AL-1 pretrain follow the same pattern. A typical value is `weight_decay=0.1` on weights, while bias vectors and LayerNorm scales usually get `weight_decay=0`.

I compared the two for one parameter as its typical gradient size grows. In the L2 version the decay passes through the division by $\sqrt{\hat{v}_t}$; in AdamW it does not. I approximate $\sqrt{\hat{v}_t}$ by the gradient scale $s$ and ignore $\epsilon$.

{% include fig.html src="adam-optimizer-explained/decay-vs-scale.svg" alt="Decay per step against gradient scale s, with learning rate 0.1, lambda 0.1 and theta 1. AdamW is flat at 0.01. Adam with L2 is 0.01 at s equals 1 and 0.04 at s equals 0.25." caption="AdamW always shrinks $\theta$ by $\eta\lambda\theta = 0.01$, while the L2 decay depends on $s$." %}

| | Adam (L2 in grad) | AdamW |
|---|---|---|
| Weight decay | Mixed into $g_t$ | Direct shrink on $\theta$ |
| Effect with large $v_t$ | Weaker regularization | Decay independent of $v_t$ |
| Default for LLMs | Legacy | Yes |

---

## Default hyperparameters and what they mean

| Hyperparam | Typical value | Role |
|---|---|---|
| `lr` | $3 \times 10^{-4}$ | Global step scale (GPT-style pretrain) |
| $\beta_1$ | 0.9 | Gradient momentum window ~10 steps |
| $\beta_2$ | 0.999 | Squared-gradient window ~1000 steps |
| $\epsilon$ | $10^{-8}$ | Floor on $\sqrt{v}$ |
| `weight_decay` | 0.1 | Decoupled L2 shrink per step |

Learning rate is the knob I still tune. Warmup and cosine decay come later in the AL-1 checklist. The optimizer does not depend on them: it uses whatever $\eta$ I pass each step.

$\beta_2 = 0.999$ means $v_t$ is a very slow average. Early training steps have tiny $\hat{v}_t$ after correction, so effective learning rates can be large until $v$ accumulates. This is one reason warmup helps: it keeps $\eta$ small early, while $v$ calibrates.

---

## From-scratch AdamW (minimal)

Matches my AL-1 `zyn/optim.py`:

```python
class AdamW:
    def __init__(self, params, lr=3e-4, betas=(0.9, 0.999), eps=1e-8, weight_decay=0.0):
        self.params = list(params)
        self.lr = lr
        self.beta1, self.beta2 = betas
        self.eps = eps
        self.weight_decay = weight_decay
        self.t = 0
        self.m = [np.zeros_like(p.data) for p in self.params]
        self.v = [np.zeros_like(p.data) for p in self.params]

    def zero_grad(self):
        for p in self.params:
            p.grad = np.zeros_like(p.data)

    def step(self):
        self.t += 1
        bc1 = 1.0 - self.beta1 ** self.t
        bc2 = 1.0 - self.beta2 ** self.t
        for i, p in enumerate(self.params):
            g = p.grad
            self.m[i] = self.beta1 * self.m[i] + (1.0 - self.beta1) * g
            self.v[i] = self.beta2 * self.v[i] + (1.0 - self.beta2) * (g * g)
            m_hat = self.m[i] / bc1
            v_hat = self.v[i] / bc2
            if self.weight_decay != 0.0:
                p.data -= self.lr * self.weight_decay * p.data
            p.data -= self.lr * m_hat / (np.sqrt(v_hat) + self.eps)
```
{: data-title="zyn/optim.py" data-lineno="true"}

I do not run gradcheck on the optimizer itself. Instead I overfit a tiny model on one batch: if cross-entropy and AdamW are wired correctly, the loss should drop monotonically for 50 steps.

---

## How does the full training step look?

```mermaid
sequenceDiagram
  participant Data
  participant Model
  participant Loss
  participant Autograd
  participant AdamW

  Data->>Model: batch (x, y)
  Model->>Loss: logits
  Loss->>Autograd: scalar L
  Autograd->>Model: ∂L/∂θ
  AdamW->>Model: θ ← θ − update
```

One step:

1. `optimizer.zero_grad()`
2. Forward → [cross-entropy](/blog/cross-entropy-loss-explained/) loss
3. `loss.backward()`
4. (Optional) clip global grad norm
5. `optimizer.step()`

I run [gradcheck on the loss](/blog/numerical-gradient-checking-explained/) once and sanity-check the optimizer by overfitting. Only then do I point it at a real corpus.

---

## When AdamW is the wrong tool

The Adam family suits noisy, high-dimensional, non-stationary objectives, which describes language modeling. On some vision tasks it can generalize slightly worse than SGD with a carefully tuned schedule. For small convex problems, SGD with momentum is simpler and sufficient.

The memory cost is two extra full-sized buffers per parameter ($m$ and $v$). For a 124M-parameter GPT in float32 that is about $124\text{M} \times 2 \times 4$ bytes $\approx 1$ GB of optimizer state, on top of weights and activations. I accept that tradeoff.

---

## Mistakes I watch for

| Bug | What happens |
|---|---|
| Forgetting `zero_grad()` | Gradients accumulate across steps |
| Weight decay on biases/LayerNorm | Shrinks scales that should stay near 1 |
| Adam L2 instead of AdamW | Regularization fights adaptive scaling |
| LR too high without warmup | Loss spikes, $v_t$ never recovers |
| Bias correction off-by-one ($t$ starts at 0) | First hundred steps subtly wrong |

---

Adam looked like a bag of heuristics the first time I read the paper. Each piece solves a specific failure mode of SGD: momentum smooths the direction, RMSprop sets the scale, bias correction handles the cold start, and decoupled decay keeps regularization independent of $v_t$. AdamW is the version that works with weight decay when training billion-parameter models.

I now have autograd, gradcheck, cross-entropy and AdamW. The next items on my AL-1 checklist are gradient clipping, LR warmup, and a training loop that runs overnight without me watching the loss curve. The optimizer cannot rescue a wrong loss or a broken backward pass, but once those are solid, AdamW makes the update step uneventful.
