Beyond "SGD is noisy"
The gradient-descent lesson introduced SGD, mini-batches, momentum and the Robbins–Monro conditions. This lesson quantifies them: how large the noise floor of constant-step SGD is, exactly how a schedule can fail, why averaging is so effective, what momentum and Adam do and do not fix, and how to choose a batch size.
Objective: predict the noise floor from the step size, batch size and gradient variance; choose a schedule that converges at the optimal rate; explain Adam's update and bias correction; and run a fair comparison.
Setup
Minimise , -strongly convex and -smooth, using a stochastic gradient with
where is the covariance of a single-example gradient and the batch size (sampling with replacement; without replacement from examples multiply by ). The key point: at the optimum but , because individual do not vanish.
Constant step: linear convergence to a noise floor
Near , write and . The update is with noise covariance . The mean of shrinks like , at the deterministic rate. The covariance settles where , which for small is
For least squares with homoscedastic noise of variance , the per-example gradient at the optimum is , so and the solution is . The expected excess loss is :
The floor is proportional to : halve the step or double the batch and it halves. Its scale is set by the noise and the total curvature, not by the condition number. For general strongly convex problems the same structure holds up to constants: error , with the gradient variance at the optimum.
Decaying steps, and how can fail
To get past the floor, must go to zero, but slowly enough to keep moving: and . The standard schedule is , which for strongly convex gives , provided . If is too small the method is far slower than : on the deterministic part of the error after steps is
so the squared error decays like , and with the noise term also decays slower than . Underestimating the curvature is therefore costly, and is rarely known. Two practical consequences:
- Constant then decay. Run a constant step while far away (fast linear progress), then decay once the loss plateaus ("step decay", or with a large offset ).
- Polyak–Ruppert averaging. Run a larger step, with or even constant for least squares, and report the average . The average achieves the asymptotically optimal covariance , the same as the best possible estimator from samples (the sandwich covariance of M-estimation), without knowing . Averaging cancels the oscillation around ; it lags when the iterates are still drifting, which is why one averages only the tail.
For convex but not strongly convex problems, with averaging gives , which is optimal for that class.
Mini-batch size
A batch of costs example-gradients and cuts the variance by . Two regimes:
- Noise-dominated (small ): doubling and doubling keeps and the floor fixed while halving the number of steps per epoch, so progress per example is unchanged and wall-clock time falls on parallel hardware. This is the "linear scaling rule".
- Curvature-dominated (large ): the step is capped by stability, , whatever the batch. Past that point, larger batches cost more examples for the same progress.
The crossover is roughly the gradient noise scale : the batch at which the noise in the gradient is comparable to its signal. It grows as training approaches the optimum (the signal shrinks), which is one argument for increasing the batch size over training instead of decaying the step.
Worked example
a step size that is too timid
Minimise (so ) from , ignoring noise, with . How far has moved after steps for and for ? What about ?
Show solutionHide solution
Each step multiplies by .
- (): , against the approximation . A million steps remove only three-quarters of the initial error.
- (): the product is (approximation ).
- (): the first factor is , so the first step lands exactly on the optimum. (With noise, makes the running average of the noisy targets, the optimal estimator; this is the "SGD for a mean" example from the gradient-descent lesson.)
The rule is not a technicality: a schedule scaled for the wrong curvature can look converged while it is stuck.
Momentum and Adam with noisy gradients
Momentum , accumulates gradients with weights summing to , so in a steady regime it behaves like SGD with effective step . Its benefit, the acceleration, is about the deterministic bias term. It does not reduce the noise floor at a given effective step: the noise is averaged over about steps but each step is times larger. Accelerated methods are also known to amplify gradient noise, so in the noise-dominated phase momentum mostly helps by smoothing direction, and its gain over tuned SGD is modest.
Adam keeps exponential averages of the gradient and of its elementwise square, corrects their start-up bias, and divides:
with defaults , , .
- Bias correction. With and a stationary gradient distribution, ; dividing by removes the shrinkage towards zero in early steps, and likewise for .
- Scale invariance. Multiplying the loss by a constant leaves the update unchanged (apart from ). Each coordinate moves by roughly times a signal-to-noise ratio , so is a step in parameter units and coordinates with tiny gradients (badly scaled features) are not starved. This diagonal preconditioning is the main reason Adam is robust to scaling.
- Limitations. Adam is not guaranteed to converge even on convex problems with fixed hyperparameters (the AMSGrad counterexamples), it still needs a decaying to reach the optimum, and L2 regularisation inside Adam is not weight decay (use AdamW). On well-conditioned convex problems, tuned SGD with averaging is usually as good.
Worked example
Adam's first step
At a parameter has gradient (any nonzero value). With the default and negligible , what is Adam's first step, with and without bias correction?
Show solutionHide solution
and .
With correction: and , so the step is . Every coordinate moves by exactly on the first step, whatever its gradient's scale: a gradient of and one of produce the same move.
Without correction: , a first step times too large. Because is much closer to 1 than , the uncorrected denominator is far more biased towards zero than the numerator, and early steps overshoot. The ratio decays to 1 only over roughly steps.
A runnable comparison on least squares
Ten features with scales from 1 down to 0.1 (), , noise . Every method gets the same budget: 20 passes' worth of single-example gradients. "Iterate" is the typical excess loss of the iterate over the last 5% of steps (the noise floor); "averaged" is the excess loss of the Polyak–Ruppert average of the second half.
import numpy as np
rng = np.random.default_rng(0)
n, p, sigma = 5_000, 10, 0.5
X = rng.standard_normal((n, p)) * np.logspace(0, -1, p) # feature scales 1 ... 0.1
y = X @ rng.standard_normal(p) + sigma * rng.standard_normal(n)
H = X.T @ X / n # Hessian of f(b) = |y - Xb|^2 / 2n
beta_hat = np.linalg.solve(H, X.T @ y / n)
def excess(b): # f(b) - f(beta_hat), exact for a quadratic
d = b - beta_hat
return 0.5 * d @ H @ d
eig = np.linalg.eigvalsh(H)
print(f"L = {eig[-1]:.3f}, m = {eig[0]:.4f}, kappa = {eig[-1] / eig[0]:.0f}, tr H = {eig.sum():.3f}")
def run(method, batch, lr, epochs=20, seed=1):
"""Same budget for every method: 20 passes' worth of per-example gradients."""
rng = np.random.default_rng(seed)
b, v, s, avg = np.zeros(p), np.zeros(p), np.zeros(p), np.zeros(p)
steps = epochs * n // batch
late = []
for t in range(1, steps + 1):
j = np.arange(n) if batch == n else rng.integers(0, n, batch)
g = X[j].T @ (X[j] @ b - y[j]) / batch # unbiased estimate of the full gradient
if method == "sgd":
b -= lr * g
elif method == "sgd 1/k":
b -= lr / (1 + t / 5_000) * g # eta_k ~ 1/k in the tail
elif method == "momentum":
v = 0.9 * v + g
b -= lr * v
elif method == "adam":
v = 0.9 * v + 0.1 * g
s = 0.999 * s + 0.001 * g * g
b -= lr * (v / (1 - 0.9**t)) / (np.sqrt(s / (1 - 0.999**t)) + 1e-8)
if t > steps // 2: # Polyak-Ruppert average of the second half
avg += (b - avg) / (t - steps // 2)
if t > steps - steps // 20: # typical excess over the last 5% of steps
late.append(excess(b))
return np.mean(late), excess(avg)
runs = [("gd", n, 1.0), ("sgd", 1, 0.05), ("sgd", 1, 0.2), ("sgd 1/k", 1, 0.2),
("sgd", 32, 0.5), ("momentum", 32, 0.05), ("adam", 32, 0.01)]
for method, batch, lr in runs:
last, averaged = run("sgd" if method == "gd" else method, batch, lr)
print(f"{method:<9} B={batch:<5} lr={lr:<5} iterate {last:.1e} averaged {averaged:.1e}")
L = 1.006, m = 0.0101, kappa = 99, tr H = 2.487
gd B=5000 lr=1.0 iterate 4.4e-03 averaged 6.6e-03
sgd B=1 lr=0.05 iterate 9.3e-03 averaged 2.4e-05
sgd B=1 lr=0.2 iterate 5.2e-02 averaged 3.2e-05
sgd 1/k B=1 lr=0.2 iterate 1.6e-03 averaged 2.1e-05
sgd B=32 lr=0.5 iterate 3.3e-03 averaged 2.2e-05
momentum B=32 lr=0.05 iterate 2.4e-03 averaged 1.9e-05
adam B=32 lr=0.01 iterate 8.1e-04 averaged 1.8e-05
Reading the table:
- Full-batch GD gets only 20 steps for the same budget; with the slow directions have barely moved ( of their error remains), and averaging its iterates only adds lag.
- Noise floor matches theory. The formula predicts for , (observed ) and for , (observed ). Quadrupling at multiplies the floor by about 5.6, a little more than 4 because the small-step approximation is starting to strain (some single examples have ).
- Decay helps the last iterate ( versus from the same start), but averaging dominates everything: every stochastic method's average lands near , one to three orders of magnitude below its own iterates.
- Momentum with , has effective step , the same as the , SGD run, and lands on essentially the same floor (the formula gives for both).
- Adam's low floor here comes from its small and per-coordinate scaling of the badly scaled features, not from any reduction in gradient noise. With equal care in tuning and averaging, the methods end up close: the gradient noise, not the optimiser, sets the limit.
Knowledge check
Which step-size schedule satisfies both Robbins–Monro conditions (sum of steps infinite, sum of squared steps finite)?
Knowledge check
Constant-step SGD on least squares sits at an excess-loss noise floor of 0.004 with learning rate 0.1 and batch size 8. Roughly what floor do you expect with learning rate 0.2 and batch size 32 (assuming both are in the stable, small-step regime)?
Knowledge check
A parameter's first gradient is 0.003 and another's is 250. With Adam (bias-corrected, default betas, tiny epsilon) and learning rate 0.001, how large are their first updates?
Knowledge check
You switch from SGD with learning rate 0.5 to heavy-ball momentum with β = 0.9 and learning rate 0.05, same batch size. What happens to the noise floor in the noise-dominated regime?
Key takeaways
- Constant-step SGD converges linearly to a noise floor; for least squares the floor is , proportional to step over batch size.
- gives only if ; too small a gives . Polyak–Ruppert averaging of a larger-step run reaches the optimal covariance without knowing .
- Mini-batches: scale the step with the batch while noise dominates; beyond the gradient noise scale, the curvature limit binds and larger batches waste examples.
- Momentum's gain is in the bias term; at equal effective step it has the same noise floor. Adam is a bias-corrected, per-coordinate normalised step of size about , robust to scaling but still needing decay and not guaranteed to converge.
Practice problems
Finished reading?
Answer the 4 knowledge checks to complete this lesson (0 done).