AI State of the Art
Fundamentals/Machine Learning: The Basics/25 min
Section 11

Modern Optimizers: Adam, AdamW, LAMB

Listen as a podcast β†’

Introduction: Why a Universal Optimizer Isn't Enough

With classic SGD (Stochastic Gradient Descent), all the weights in the network move with the same learning rate, the same step size. When you think about it, that makes no sense.

In a neural network, some weights are called on constantly and receive large gradients at every training step. Others receive tiny gradients, because they are tied to rare features. Think of a word embedding, the bundle of numbers attached to each word of the vocabulary: "the" turns up in almost every sentence, so its weights get frequent, sizeable corrections, whereas "stethoscope" almost never turns up, so its weights get rare, faint ones.

Imposing the same step size on these two families is absurd. A step large enough to move the rare weights makes the frequent weights explode. A step small enough to keep the frequent weights stable leaves the rare ones motionless.

Adaptive optimizers solve this dilemma: each weight gets its own step size, computed automatically from the history of its own gradients.

Adam: The Revolutionary Optimizer

Adam: A Method for Stochastic Optimization

The central idea of Adam: instead of using the raw gradient from a single step to update a weight, Adam builds an overview from recent history. For each weight in the network, it maintains two exponential memories that summarize what happened during previous steps.

Comparison of GD vs Adam optimization paths
Both runs start from the same point, top right, in an error landscape whose floor is at the centre. The blue plain-descent track shuttles up and down and wastes an enormous amount of effort; the orange Adam track heads almost straight for the middle.Source : Vizuara

Memory 1: Momentum (m)

It's the exponential moving average of past gradients:

mt=Ξ²1β‹…mtβˆ’1+(1βˆ’Ξ²1)β‹…gtm_t = \beta_1 \cdot m_{t-1} + (1 - \beta_1) \cdot g_t

Symbol by symbol: tt numbers the training steps; gtg_t is this weight's gradient at step tt; mtm_t the updated memory and mtβˆ’1m_{t-1} the previous one; Ξ²1\beta_1 ("beta one") a number between 0 and 1. The two coefficients Ξ²1\beta_1 and (1βˆ’Ξ²1)(1-\beta_1) always add to 1, which is what keeps mm an average rather than something that drifts in magnitude.

In one sentence: the new memory is 90% of the old one, plus the current gradient for the remaining 10%. Every gradient enters, then fades out gradually.

Concretely, m accumulates momentum in a direction. If the gradients have been pointing in the same direction for several steps, m becomes large in that direction and the weight accelerates. If the gradients oscillate (positive, negative, positive...), m stays close to zero and the weight barely moves. It's the same principle as a ball rolling down a hill: it picks up speed on smooth descents and hesitates in chaotic zones.

Memory 2: Volatility (v)

It's the exponential moving average of the squares of the gradients:

vt=Ξ²2β‹…vtβˆ’1+(1βˆ’Ξ²2)β‹…gt2v_t = \beta_2 \cdot v_{t-1} + (1 - \beta_2) \cdot g_t^2

Same construction, one difference: gt2g_t^2 instead of gtg_t, the gradient is squared before entering the average. Squaring destroys the sign.

By taking the square, we measure the amplitude of gradients, regardless of their direction. If v is large for a given weight, it means that weight receives high-amplitude gradients, possibly erratic. It's in a "turbulent" zone of the loss surface and deserves cautious treatment. If v is small, the weight receives weak and steady gradients: it's a calm zone where we can move faster.

The Update

ΞΈt=ΞΈtβˆ’1βˆ’Ξ·β‹…mtvt+Ο΅\theta_t = \theta_{t-1} - \eta \cdot \frac{m_t}{\sqrt{v_t} + \epsilon}

Symbol by symbol: ΞΈ\theta ("theta") is the parameter being corrected; Ξ·\eta ("eta") the base learning rate; mtm_t and vtv_t the two memories above; vt\sqrt{v_t} the square root of the second, which brings the squared quantity back to the scale of an ordinary gradient; and Ο΅\epsilon ("epsilon") a tiny number, around 10βˆ’810^{-8}, present only so that nothing ever gets divided by zero should vtv_t be nil.

In one sentence: step in the average direction of the recent gradients, but divided by their typical size. That division is the heart of the design: it cancels out the scale of the gradient, so the effective step no longer depends on how large this particular weight's gradients happen to be.

The key intuition:

A weight that usually receives large gradients (large v) is divided by a large number: it advances cautiously, because it's in a chaotic zone of the loss surface where large steps risk overshooting the optimum.

A weight that usually receives small gradients (small v) is divided by a small number: it can advance faster, because it's in a flat zone where you need to push harder to make progress.

This is what makes Adam so much more robust than SGD: it automatically calibrates the learning speed for each weight individually, without you having to find a single learning rate that works for the entire model at once.

Adam's magic numbers

Ξ²1=0.9\beta_1 = 0.9 (memory of the momentum) Ξ²2=0.999\beta_2 = 0.999 (memory of the magnitude) Learning rate Ξ·\eta = 0.001 or 0.0001 as a rule

These defaults work remarkably well. Ξ²1\beta_1 at 0.9 means momentum keeps 90% of its value at each step: its memory spans about ten steps. Ξ²2\beta_2 at 0.999 keeps 99.9%: its memory spans about a thousand steps, so the estimated magnitude is far smoother and slower to react. In practice you almost never touch either number.

Adam's Trap: Weight Decay

L2 regularization, also called weight decay, is a classic technique against overfitting, covered in detail in Regularization. The idea: add to the loss a penalty pushing all weights to stay small.

Ltotal=L+Ξ»βˆ‘ΞΈ2\mathcal{L}_{\text{total}} = \mathcal{L} + \lambda \sum \theta^2

Symbol by symbol: L\mathcal{L} is the ordinary loss, the one measuring prediction errors; βˆ‘ΞΈ2\sum \theta^2 is the sum of the squares of every parameter in the model, that is, a measure of "how big they are altogether"; and Ξ»\lambda ("lambda") is the weight given to that second concern, typically 0.01. In one sentence: the model must both predict well and keep its parameters small, and lambda says which of the two matters more.

With SGD, this works perfectly. Differentiating λθ2\lambda \theta^2 with respect to θ\theta gives 2λθ2\lambda\theta, that is where the factor 2 comes from, nothing more than the derivative of a square. That term is added to the loss gradient, and the update pulls each weight toward zero all the harder the bigger it already is.

With Adam, there's a subtle but devastating problem. The gradient of the penalty goes through the same adaptive machinery as everything else: it gets divided by vt\sqrt{v_t}. But the most active weights are exactly the ones with a large vtv_t, so the division crushes the penalty precisely where it was most needed. The network "thinks" it's being regularized, but in reality, the most important weights are barely affected by the penalty. You think you're regularizing, but you're barely doing anything.

AdamW: The Simple Fix

Decoupled Weight Decay Regularization

AdamW decouples weight decay from the rest. Instead of routing the penalty through the gradient (and therefore through the division) you apply it separately, after the Adam step:

ΞΈt=ΞΈtβˆ’1βˆ’Ξ·β‹…mtvtβˆ’Ξ»β‹…ΞΈtβˆ’1\theta_t = \theta_{t-1} - \eta \cdot \frac{m_t}{\sqrt{v_t}} - \lambda \cdot \theta_{t-1}

Same symbols as before. What changed is where Ξ»β‹…ΞΈtβˆ’1\lambda \cdot \theta_{t-1} sits: outside the fraction, so it never goes through the division by vt\sqrt{v_t}. In one sentence: take the Adam step, then separately shave every weight by a small percentage of its own value.

The upshot: the penalty now bites with equal force on every weight, which is what we wanted all along.

AdamW is now the standard

It is the default optimizer for transformers, for large language models (LLMs), and for most of today's deep learning. If you remember only one name, remember this one. Typical weight decay: 0.01 to 0.1.

Performance comparison of Adam and AdamW optimizers
Each square tests one pairing of learning rate and regularization strength, with blue marking the best results. With Adam, on the left, the workable zone is a thin diagonal band: tuning one forces you to retune the other. With AdamW, on the right, it opens into a broad blob, so the two settings become independent again.Source : IPRally

LAMB: For Massive Distributed Training

Industrial training spread over thousands of graphics processing units (GPUs) uses enormous batches: 8,000, 16,000, 32,000 examples handled together.

Problem: with Adam, past a certain threshold, enlarging the batch degrades the final model quality, even when the learning rate is readjusted. It is counter-intuitive, and it is the starting point of the paper below.

Large Batch Optimization for Deep Learning: Training BERT in 76 minutes (You et al., 2019)

LAMB (short for Layer-wise Adaptive Moments optimizer for Batch training) sets the step scale layer by layer:

ΞΈt=ΞΈtβˆ’1βˆ’Ξ·β‹…βˆ₯ΞΈtβˆ’1βˆ₯βˆ₯utβˆ₯β‹…ut\theta_t = \theta_{t-1} - \eta \cdot \frac{\|\theta_{t-1}\|}{\|u_t\|} \cdot u_t

Symbol by symbol: utu_t is the correction Adam would have applied to this layer (the fraction mt/vtm_t / \sqrt{v_t}); the double bars βˆ₯β‹…βˆ₯\|\cdot\| denote the norm, the overall length of a bundle of numbers, the same notion as the length of an arrow, extended to thousands of dimensions (see norms and distances). So βˆ₯ΞΈtβˆ’1βˆ₯\|\theta_{t-1}\| measures how big the layer's weights currently are, and βˆ₯utβˆ₯\|u_t\| how big the proposed correction is.

In one sentence: keep the direction Adam suggests, but rescale the step so it always amounts to the same percentage of the layer's own size. A layer with large weights gets a large correction, a layer with small weights a small one. Without this, once batches get huge, no single value of Ξ·\eta can suit every layer at once.

Result reported in the paper: BERT (Bidirectional Encoder Representations from Transformers) training time drops from 3 days to 76 minutes, by pushing the batch size to the memory limit of a single TPU v3 pod, a rack of Google's specialized Tensor Processing Units. One pod, not thousands of independent machines.

LAMB is not for you

LAMB is built for very large-scale distributed training. If you train on one to four graphics cards with batches of 32 to 512, it brings you nothing: AdamW will do better.

Quick Comparison Table

OptimizerWhen to useAdvantagePitfall
SGD + momentumClassic vision (ResNet)Sometimes generalizes betterVery sensitive to the learning rate
AdamRapid prototypingConverges fast, little tuningWeight decay is inoperative
AdamWNearly every case (transformers, LLM)Everything works wellVery slightly slower than Adam
LAMBVery large-scale distributed trainingHolds up at giant batch sizesVery hard to tune

The Importance of Learning Rate Scheduling

Regardless of the optimizer, you should vary the learning rate during training.

The most common strategy today is warmup followed by cosine decay:

PhaseEpochsLearning rate
Warmup0-10Gradually increases from 0 to 0.001
Cosine decay10-100Gradually decreases following a cosine curve to ~0

Why warm up? At the very start, Adam's two memories mm and vv start from zero: they have accumulated nothing, so the values they report mean nothing. Ramping the rate up slowly gives those memories time to fill before you dare take large steps. Without that precaution the first few steps can throw the weights anywhere, and the model never recovers.

Why decay? At the end of training, the model is close to a good optimum. Steps that are too large would make it oscillate around this optimum without ever converging. Gradually reducing the learning rate allows for fine-tuning the last adjustments. It's a technical detail that seems minor, but it almost always improves the final model quality.

Practical Details

Memory

Adam keeps two extra numbers (mm and vv) for every weight. For a 7-billion-parameter model, at 4 bytes per number (the usual 32-bit format), the arithmetic is right here:

ComponentCalculationMemory
Weights7Γ—109Γ—47 \times 10^9 \times 4 bytes28 GB
mm (momentum)7Γ—109Γ—47 \times 10^9 \times 4 bytes28 GB
vv (magnitude)7Γ—109Γ—47 \times 10^9 \times 4 bytes28 GB
Total84 GB (instead of 28 GB)

That's 3 times more memory than simply storing the weights. For very large models, this is a real problem: the optimizer consumes more memory than the model itself. Variants such as Adafactor (used by Google for the T5 model) shrink this footprint by keeping only compressed summaries of mm and vv instead of the full tables. But for training quality, AdamW remains the reference.

Practical Summary

For nearly every project:

  • Use AdamW
  • Initial learning rate: 0.001 or 0.0001
  • Weight decay: 0.01-0.1
  • Learning rate schedule: linear warmup + cosine decay
  • Batch size: 32-256 (adjust based on your GPU memory)

This is a robust configuration that gives excellent results in the vast majority of cases. You'll rarely beat this recipe by changing optimizers: the time spent experimenting with other configurations would almost always be better invested in data quality or model architecture.

Check your understanding0 / 5

1. In Adam's update, the momentum m gets divided by the square root of v, the typical gradient magnitude. What is that division for?

2. Why does classic L2 regularization, which works perfectly with SGD, become almost inoperative with Adam?

3. What exactly does AdamW change compared with Adam?

4. Why start training with a very small learning rate that ramps up gradually (the warmup phase)?

5. Training a 7-billion-parameter model with Adam takes about 84 GB for the weights plus optimizer, instead of 28 GB for the weights alone. Why?