Estimate a full gradient
An empirical loss is the average of example losses. Its gradient is the mean of the per-example gradients at a fixed parameter vector. If a mini-batch contains independently and uniformly drawn indices with replacement, its mean gradient is unbiased. Independence gives covariance where is the covariance of a single draw. Sampling a uniformly chosen subset of fixed size without replacement also gives an unbiased mean, but the covariance uses a finite-population correction.
For scalar per-example gradients and the full gradient is With one uniform draw the expected update gradient is still although neither draw returns that value. The single-draw variance is For four independent draws, the variance of their average is
When training for next-token loss, choose the unit whose average defines the objective. For example, sample scored tokens uniformly for a token-weighted estimate. Sampling documents uniformly and averaging their losses equally estimates the mean document loss. Within a document, token gradients can be correlated, so the independent-draw variance calculation requires care.
Track gradient moments
Adam keeps two exponential moving averages, initialised at zero. For gradient its first moment is and its raw second moment is Squaring and all divisions below are coordinatewise. For use and to correct for zero initialisation. The update subtracts for a positive The denominator adapts the scale of the step in each coordinate.
Adding to the loss adds to its gradient. Decoupled weight decay instead subtracts directly alongside the parameter update. In plain gradient descent these operations agree. In Adam, adding the penalty to the gradient changes the moment estimates and their scaling, while direct decay leaves the moments based on the data gradient.
At the first step, the bias-corrected first and second moments are and for any allowed moment coefficients. Use two coordinates to compare update signs.
from math import sqrt
rate, eps = 0.1, 1e-8
for gradient in (2.0, -6.0):
first = 0.1 * gradient / (1 - 0.9)
second = 0.001 * gradient**2 / (1 - 0.999)
update = -rate * first / (sqrt(second) + eps)
print(f"{update:.3f}")-0.100
0.100Exercises
A batch has equally weighted gradients of and Find the update gradient.
Show solution✓ Checked
Their mean is
Find and for and
Show solution✓ Checked
and
With zero data gradient and zero moment history, find the parameter after a decoupled decay step starting at with and
Show solution✓ Checked
Multiplying by gives