Defines Adam's first- and second-moment estimates, their bias correction and the adaptive step (ICLR 2015). Section 2.1 discusses the step-size bound, the signal-to-noise ratio and invariance to gradient scale.
Adam Optimizer
Adam combines momentum, a running average of gradients, with a per-parameter step size scaled by a running average of squared gradients.
Intuition
The idea in plain words, before the symbols.
Training is noisy: mini-batch gradients bounce around from step to step, and different parameters can have gradients of very different sizes. A single learning rate can then be too large for some parameters and too small for others.
Adam (Kingma and Ba, 2015) keeps two running averages for every parameter:
- , an average of recent gradients. This is momentum: it smooths out noise from individual mini-batches and keeps the direction that recent gradients agree on.
- , an average of recent squared gradients. This estimates the gradient's second raw moment , which Kingma and Ba also call the uncentered variance. Because , it measures how large the gradient typically is, mean and spread together; it is not a measure of uncertainty on its own.
Each step moves by , times the learning rate. Dividing by removes the gradient's scale: multiply every gradient by a constant and both and grow by , so the step is unchanged. When recent gradients are nearly equal, is close to and the step is close to the learning rate. When they keep flipping sign, averages toward zero while does not, and the step shrinks. Kingma and Ba describe the ratio as a signal-to-noise ratio.
Study prompts for this section: Intuition
Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.
Mathematics
Definitions, assumptions and the derivation.
Let count updates from the starting parameters , and let be the (stochastic) gradient for update , taken at the parameters before it.
Adam keeps exponential moving averages:
Because and start at zero, Adam uses bias correction:
Update rule:
The division is elementwise, so Adam acts like a diagonal preconditioner: a coordinate with large recent gradients gets a smaller effective learning rate , and one with small gradients a larger one. The step is that rate times , so large gradients do not mean small steps: when a coordinate's gradient stays about the same from step to step, is close to and the coordinate moves by about , whatever that gradient's size. A single large gradient is different: it keeps high for many steps and shrinks the steps that follow. Bias correction matters most early in training because the moving averages are initialized at zero. The small is not a learning signal; it prevents division by zero and can affect stability when gradients are tiny.
Typical defaults: , , .
What bias correction divides out
Unrolling the first recurrence from shows exactly what the correction removes:
The weights on past gradients add up to , not to one, so early in training is an average shrunk towards zero. Dividing by makes the weights sum to one, and the same holds for with . Kingma and Ba (2015, Section 3) derive the correction as removing this initialization bias in expectation, assuming the gradient distribution changes slowly; it does not make every corrected value an unbiased estimate when the gradients drift.
Two steps by hand
Take two coordinates with , , , , , and gradients and . The numbers are chosen so that every value in the two steps is a fraction. Coordinate by coordinate:
At both coordinates move by exactly , although one gradient is four times the other: the first corrected step is . Without the two corrections the first ratio would be , too large by the factor . With the usual and that factor is about at the first step, and it fades slowly: for a constant gradient the uncorrected step is times the corrected one, still about after steps. At coordinate 1's gradient changes sign. Its first average partly cancels and its step shrinks to , while its second average, built from squares, stays at . Coordinate 2's gradients agree, and it keeps moving by .
Rescaling one coordinate
Multiply one coordinate's whole gradient history by a constant and keep everything else fixed. The recurrences are linear in and in , so for that coordinate
When and this is exactly the old ratio: with in the example above, both steps are unchanged. Each condition matters. With the ratio becomes instead of : nearly the same while is small next to both and , but very different when the rescaled gradients become as small as . With the step keeps its size and reverses its direction. With and it is . In floating-point arithmetic the cancellation is exact only up to rounding: in double precision the second-step ratio of the rescaled coordinate is before rescaling and after, one unit apart in the last place. This is the invariance to gradient scale that Kingma and Ba (2015, Section 2.1) note; it describes the update rule, not whether Adam trains a given model well.
Study prompts for this section: Mathematics
Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.
Code
The same calculation as runnable code, in the notation of the derivation.
import torch
alpha = 0.1
beta1, beta2 = 0.9, 0.999
eps = 1e-8
theta = torch.tensor([3.0], requires_grad=True)
m = torch.zeros_like(theta)
v = torch.zeros_like(theta)
for t in range(1, 51):
loss = (theta ** 2).sum()
loss.backward()
g = theta.grad.detach()
m = beta1 * m + (1 - beta1) * g
v = beta2 * v + (1 - beta2) * (g * g)
mhat = m / (1 - beta1 ** t)
vhat = v / (1 - beta2 ** t)
theta = (theta - alpha * mhat / (vhat.sqrt() + eps)).detach().requires_grad_(True)
if t in [1, 5, 10, 50]:
print(t, "theta=", theta.item(), "loss=", loss.item())
The second block repeats the two steps worked by hand above in exact fractions, using only Python's standard library. It checks each step, the ratio without bias correction and the unchanged steps after rescaling, then computes the rescaled ratio again in ordinary floating point, where it differs in the last place.
from fractions import Fraction as F
from math import isqrt, sqrt
B1, B2, ALPHA = F(1, 2), F(7, 8), F(1, 10)
def exact_root(value):
"""Square root of a fraction that is a perfect square, as every value here is."""
root = F(isqrt(value.numerator), isqrt(value.denominator))
assert root * root == value
return root
def adam_coordinate(gradients):
"""One coordinate of Adam with epsilon = 0: the update treats coordinates separately."""
m = v = theta = F(0)
steps = []
for t, g in enumerate(map(F, gradients), start=1):
m = B1 * m + (1 - B1) * g
v = B2 * v + (1 - B2) * g * g
m_hat, v_hat = m / (1 - B1**t), v / (1 - B2**t)
step = -ALPHA * m_hat / exact_root(v_hat)
theta += step
steps.append({"m_hat": m_hat, "v_hat": v_hat, "step": step, "theta": theta})
return steps
first = adam_coordinate([2, -2]) # coordinate 1: its gradient changes sign
second = adam_coordinate([-8, -8]) # coordinate 2: its gradients agree
assert [s["step"] for s in first] == [F(-1, 10), F(1, 30)]
assert [s["step"] for s in second] == [F(1, 10), F(1, 10)]
assert (first[1]["m_hat"], first[1]["v_hat"]) == (F(-2, 3), F(4))
# Without bias correction the first ratio is m_1 / sqrt(v_1) = 1 / sqrt(1/2) = sqrt(2).
m_1, v_1 = (1 - B1) * 2, (1 - B2) * 2**2
assert abs(m_1 / sqrt(v_1) - sqrt(2)) < 1e-15
# Multiplying coordinate 1's gradients by c = 10 leaves every step unchanged.
assert [s["step"] for s in adam_coordinate([20, -20])] == [s["step"] for s in first]
def float_ratio(gradients):
"""The same coordinate in ordinary double-precision arithmetic: the last ratio."""
m = v = 0.0
for t, g in enumerate(gradients, start=1):
m = 0.5 * m + 0.5 * g
v = 0.875 * v + 0.125 * g * g
ratio = (m / (1 - 0.5**t)) / sqrt(v / (1 - 0.875**t))
return ratio
print("coordinate 1 steps:", [str(s["step"]) for s in first])
print("coordinate 2 steps:", [str(s["step"]) for s in second])
print("second ratio, before and after c = 10:", float_ratio([2.0, -2.0]), float_ratio([20.0, -20.0]))
Study prompts for this section: Code
Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.
Demo
Change an input, predict the result, and see which quantities respond.
Explore Adam Optimizer
Observation guide
Optional and ungraded. Opening a guide saves nothing.
Choose what to inspect in Adam Optimizer, then open its guide.
The first code block and the demo are two different examples of the same per-coordinate update rule; they are not the same run. That code optimizes one parameter with , starting at with . The demo races SGD, SGD with momentum and Adam on the two-parameter Rosenbrock loss , whose minimum is at . All three start at , use the exact gradient with no mini-batch noise, and share one . SGD updates ; the momentum runner reuses as , then .
What carries over between the two examples is the first step. At , bias correction gives and , so each coordinate changes by : a step of size about whatever the scale of , as long as . In that code, , so and goes from to about ; the first printed line pairs that updated with the loss computed before the update. In the demo at , . Adam's update is about , to about , while SGD and momentum both take to . The demo also adds inside its bias-correction denominators, which changes this first Adam step by a relative amount of about at . With AdamW on, the demo also subtracts with : decoupled weight decay, applied outside the adaptive step (Loshchilov and Hutter, 2019). For Adam this differs from adding an penalty to the loss, whose gradient would also be divided by .
Before the race, predict which optimizer has the lowest loss after 60 updates. A loss that is no longer a finite number is reported as diverged and cannot win, and equal lowest losses are reported as a tie. The result describes this one deterministic run, not a general ranking of optimizers; other scenarios in the demo change the order.
Study prompts for this section: Demo
Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.
Practice
Work out two exact steps, see what bias correction changes, then scale one coordinate's gradients by 10 and predict again.
Concept: Adam Optimizer
What is the smallest example of Adam Optimizer you can work through by hand, and what does it show?
DetailsOptimization
Reference id
concept:optimization/adamAfter the first pass
Go deeper
Optional material for a second reading. Sources are always shown; the other panels open from their headings or from these links, and closing one keeps what you wrote or revealed.What to look for in each sectionChoose a section and what you expect to see in it, then read short advice.
Section by section
Choose what to look for in each section
Adam combines momentum, a running average of gradients, with a per-parameter step size scaled by a running average of squared gradients.

Start with the picture, metaphor, or geometric mechanism.
Choose what you expect to see in this section of Adam Optimizer.
Questions to ask of the pictureChoose a part of the picture and what you expect, then read short advice.
Looking at the picture
Questions to ask of the picture
Adam combines momentum, a running average of gradients, with a per-parameter step size scaled by a running average of squared gradients.
Which part of the picture should you look at first?
Pick the part of the picture you expect to explain Adam Optimizer.
Sources
References for this page
A reference shows where an idea comes from; it does not vouch for every step on this page.Shows that L2 regularization and weight decay differ for Adam and proposes AdamW, which applies weight decay separately from the adaptive gradient step (ICLR 2019).
Textbook treatment of momentum (Section 8.3.2) and of Adam among adaptive learning-rate methods (Section 8.5.3).
What each claim rests on2 claims, each with its sources, where it appears on this page, and its caveats.
Claims and sources
Adam combines momentum, a running average of gradients, with a per-parameter step size scaled by a running average of squared gradients.
The checks were made by this site, not by an independent reviewer.
Kingma and Ba's Algorithm 1 initializes m0 and v0 to zero, updates biased first-moment and second raw-moment estimates from gt and gt^2, computes bias-corrected estimates, and updates parameters with alpha*m...
This checks Adam's original adaptive-moment update mechanics, not convergence guarantees, AdamW decoupled weight decay, AMSGrad, optimizer generalization debates, sparse-gradient variants, or framework-speci...
Checked Kingma and Ba Algorithm 1 plus sections 2 and 3: the paper initializes m0 and v0 as zero vectors, updates biased first and second raw moment estimates from gt and gt^2, divides by 1-beta1^t and 1-beta2^t for bias correction, states vector operations are element-wise, and updates theta with alpha*mhat/(sqrt(vhat)+epsilon). Scope is original Adam update mechanics only.
Kingma and Ba (Section 2.1) note that rescaling the gradients by a factor c scales mhat by c and vhat by c squared, which cancel in the step. The page's two-step example shows the cancellation in exact fract...
Exact only for c > 0, epsilon = 0 and the whole gradient history; with epsilon > 0 the step can change, a lot once the scaled gradients are as small as epsilon; a negative c reverses it, and floating-point r...
Read Kingma and Ba Section 2.1, 'Adam's update rule' (with epsilon = 0 the effective step is invariant to the scale of the gradients: rescaling g by a factor c scales mhat by c and vhat by c squared, which cancel), and Section 3 (the bias-correction derivation, exact when the second moment is stationary). Recomputed the page's two-step example and the c = 10 rescaling in exact fractions and in double precision.
Explain it without the pageWrite your own explanation before asking for feedback. Your draft and any hints stay while this page is open.
Practice · Adam Optimizer
Try the idea in your own words
Adam combines momentum, a running average of gradients, with a per-parameter step size scaled by a running average of squared gradients.
Concept · Selected for practice
Adam Optimizer
What it rests on: Sources: Adam: A Method for Stochastic Optimization; Decoupled Weight Decay Regularization; Deep Learning
Context and links
Optimization
Explain the mechanism
For Adam Optimizer: What is the smallest example of Adam Optimizer you can work through by hand, and what does it show? Explain your answer, including what changes, why, and which assumption matters.
A rough first thought is enough. Your draft stays when you change tasks.
Your draft stays on this page and is cleared when you leave or reload.
A little help · Explain
Open one hint at a time. These are suggestions, not your answer or a grade.
0 of 3 hints shown for this question.
Clearing your answer keeps this help record. Outside help is your own report; this page cannot check it.
Where am I stuck? (optional)
Take your draft to a feedback conversation
No AI feedback runs here. You can copy a prompt to use elsewhere; nothing is sent automatically. Review the text before sharing, and leave out private information.
Write an attempt before copying a feedback prompt.
A draft, or an AI reply to it, is not a test of what you have learned. To check that, try a different case later without help.
Ask about this pagePick one item on this page and copy a prompt about it into an AI assistant you already use. Notes you write here stay in this browser.
assert root * root == valueYour question
Choose what your question is about
Pick the idea, equation, source, code, claim, misconception or demo state you want to ask about. The prompt you copy includes it, so the answer can stay on that item.Open the draft below to save one note and next action in this browser.
Adam Optimizer
What is the smallest example of Adam Optimizer you can work through by hand, and what does it show?
Fixed prompts generated from this item. They are not comments from people or independent reviews.
The 3 cited sources must support this exact item, not just the surrounding topic.
Connect the definition to one equation, piece of code or demo before widening the discussion.
Change one input, then check that the same relationship holds in the mathematics, the code and the demo.
You can state the mechanism in your own words
Local action draftNo local draft saved yetOpen when you are ready to write one next action
This draft stays in this browser and is attached to this item only.
- What the 3 cited sources say about this exact item
- The definition, its prerequisites, and a contrasting concept
- The equation or code that makes the concept concrete
- One demo state that shows what stays the same as the inputs change
- You can state the mechanism in your own words
- You can name the prerequisite that would clear up the confusion
- You can predict how the result changes when one input changes
Reference id
concept/concept-notebook/optimization/adam
concept:optimization/adam