Stochastic Gradient Descent
Learning from mini-batches: cheap, noisy steps that work.
When the loss is an average over millions of examples, an exact gradient is a luxury. Stochastic gradient descent replaces it with the gradient of a small random batch: unbiased, cheap and noisy. This lesson derives that noise, proves what a constant learning rate can and cannot achieve, and turns the result into the schedules and recipes practitioners use.
What you’ll learn
- Show that mini-batch gradients are unbiased for the gradient of the empirical risk, and compute their covariance, including the scaling and the finite-population correction.
- Implement mini-batch SGD with epochs and reshuffling, and compare its cost per step and per epoch with gradient descent.
- Prove that constant-step SGD on a smooth, strongly convex objective converges linearly to a noise floor proportional to , and explain why decaying steps are needed to converge.
- Choose learning-rate schedules and batch sizes with the standard recipes, and recognize when SGD has no noise floor at all.
Finite sums and unbiased gradients
Training minimizes the empirical risk, an average of per-example losses:
One exact gradient costs per-example gradients. Stochastic gradient descent uses a random mini-batch of size instead: and . If every example is equally likely to be in the batch, the expectation is right: .
Measure the spread of the per-example gradients around their mean with the gradient-noise covariance:
With independent draws (with replacement), the batch gradient is an average of i.i.d. terms with covariance , so its covariance is divided by :
Drawing distinct examples (without replacement), the usual practice, adds the finite-population correction of survey sampling, which vanishes at :
Either way the noise's standard deviation falls like , while the cost of a step grows like . Quadrupling the batch halves the noise and quadruples the work.
The algorithm and its cost
import numpy as np
def sgd_least_squares(X, y, batch_size=32, lr=0.01, epochs=20, seed=0):
"""Mini-batch SGD on (1/2n)||Xw - y||^2, reshuffling the data every epoch."""
rng = np.random.default_rng(seed)
n, d = X.shape
w = np.zeros(d)
for epoch in range(epochs):
perm = rng.permutation(n) # each epoch: sample without replacement
for start in range(0, n, batch_size):
idx = perm[start:start + batch_size]
Xb, yb = X[idx], y[idx]
grad = Xb.T @ (Xb @ w - yb) / len(idx) # estimate of the full gradient
w -= lr * grad
return wAn epoch is one pass through the shuffled data in steps. Each step costs for a linear model, independent of ; a whole epoch costs about the same arithmetic as one full gradient.
Per epoch, then, gradient descent moves once and SGD with moves times. Far from the optimum, the per-example gradients largely agree, and rough steps make enormously more progress than one exact step. Near the optimum they disagree (at the minimizer of they average to zero without vanishing individually), and the noise takes over.
Bottou & Bousquet (2008) turned this into an argument about learning rather than optimization. When data are plentiful and computation is the bottleneck, there is no point in optimizing the training loss far below the statistical error that a finite sample incurs anyway. In that large-scale regime, they argued, stochastic gradient methods, which are poor optimization algorithms, can be the better learning algorithms.
A linear model has features and training examples. Compare one epoch of SGD with to one step of full gradient descent.
- The SGD epoch costs about times more arithmetic
- They cost about the same arithmetic, but SGD updates the parameters times instead of once
- The SGD epoch is cheaper because each step uses one example
- They are identical: SGD with is gradient descent
Show the answer
B. They cost about the same arithmetic, but SGD updates the parameters times instead of once
Both touch every example once, about multiply-adds. The difference is what is done with that work: one exact step, or noisy steps, each using the newest parameters.
Constant steps: the noise ball
Assume is -smooth and -strongly convex with minimum , and the stochastic gradients are unbiased with bounded variance: and . (For mini-batches, is the single-example bound divided by .)
Apply the quadratic upper bound of -smoothness to the step :
Take the expectation given . Unbiasedness handles the middle term, and the second moment is the squared mean plus the variance, :
With the bracket is at least . Strong convexity implies (the Polyak–Łojasiewicz inequality). Subtract and take full expectations:
Unroll the recursion and bound the geometric series .
The trade-off is explicit. The floor is proportional to and to the gradient variance , so halving the step halves the floor, but it also halves and doubles the time it takes to get there. Because scales like , the floor scales like : the ratio that the Convergence lesson Batch Size, Learning Rate & Noise builds on.
Constant-step SGD has reached its noise floor. You keep fixed and raise the batch size from 1 to 16 (sampling with replacement). By what factor does the floor term shrink?
Show the answer
16 ×
is the variance of the batch gradient, which is the single-example variance divided by . So the floor shrinks 16-fold, while each step costs 16 times more. The typical distance to the optimum shrinks only by , since the loss gap is quadratic in the distance.
Decaying steps and schedules
To converge rather than hover, the step must shrink. Robbins & Monro (1951) gave the classic conditions for their stochastic approximation method:
The recursion above shows why. The contraction reaches zero only if (the steps must be able to travel any distance), and the noise injected at each step, proportional to , must die out. is the classical way to guarantee that, and the proof of almost-sure convergence uses it; convergence in expectation needs only besides the first condition. Steps satisfy both conditions, and with a large enough constant they give on smooth, strongly convex problems (with too small a the rate collapses); steps violate the second condition and converge more slowly, but combined with iterate averaging they are more robust. The Robbins–Monro theory is developed in Convergence of SGD.
| Schedule | Form | Notes |
|---|---|---|
| Constant | fast at first, then a noise floor ; often followed by a final decay | |
| Robbins–Monro; optimal rate for strongly convex problems, but very sensitive to (see Convergence of SGD) | ||
| plus averaging | , report | robust; optimal for general convex problems |
| Step decay | divide by 10 at a few fixed epochs | a long-standing default for image classifiers; each drop lowers the plateau |
| Cosine | smooth decay to over a fixed budget | |
| Warmup | ramp up linearly over the first steps | avoids instability early in training, standard for large batches and transformers |
Which step-size sequence satisfies both Robbins–Monro conditions?
- for all
Show the answer
C.
diverges (the harmonic series), while is finite. The steps can travel arbitrarily far, but the total injected noise stays bounded.
When the noise vanishes, and what comes next
The noise floor came from : gradient noise that does not vanish at the optimum. Two situations remove it:
- Interpolation. Modern overparameterized models can often fit every training example exactly (interpolation), so a single minimizes every at once and every . The gradient noise then shrinks as the iterates approach , and constant-step SGD can converge linearly with no floor at all.
- Finite sums with memory. For a fixed training set, the noise can be cancelled by comparing each sampled gradient with a stored one at a reference point. This variance reduction gives linear convergence for strongly convex finite sums at roughly the per-step cost of SGD.
Key takeaways
- A uniformly sampled mini-batch gradient is unbiased for , with covariance (times without replacement): noise falls like while cost grows like .
- An SGD step costs whatever is; an epoch costs about one full gradient but makes updates, which is why SGD wins early and at scale.
- With constant on a smooth, strongly convex objective, : linear progress down to a floor proportional to .
- Convergence needs decaying steps with and (Robbins–Monro); practical schedules (step, cosine, warmup) work on a fixed budget.
- The floor disappears under interpolation, and for finite sums variance reduction removes it.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
You increase the mini-batch size from 64 to 256 (sampling with replacement). What happens to the standard deviation of the gradient noise?
- It halves
- It falls by a factor of 4
- It is unchanged, because the gradient is unbiased either way
- It doubles, because more examples add more noise
Show the answer
A. It halves
The covariance is , so the standard deviation scales like : four times the batch, half the noise, four times the cost per step.
Constant-step SGD on a smooth, strongly convex problem obeys . What does halving do?
- Halves the floor and makes the transient twice as fast
- Halves the floor, but the transient takes about twice as many steps
- Leaves the floor unchanged and slows the transient
- Removes the floor entirely
Show the answer
B. Halves the floor, but the transient takes about twice as many steps
The floor is proportional to , and the transient decays like , whose time constant doubles. That tension is why schedules start large and shrink.
Why can a single pass of SGD over fresh examples be analyzed as minimizing the population risk rather than the training loss?
- Because SGD's noise acts as a regularizer
- Because a fresh example's loss gradient is an unbiased estimate of at the current parameters
- Because the training loss and the risk have the same minimizer
- Because mini-batches are larger than the training set
Show the answer
B. Because a fresh example's loss gradient is an unbiased estimate of at the current parameters
An example drawn from the data distribution and not used before is independent of , so . Every stochastic-approximation guarantee then applies directly to .
Your SGD training loss plateaus well above the best value you have seen from full-batch runs. Which change is most likely to lower the plateau?
- Raise the learning rate
- Shuffle less often
- Decay the learning rate (or raise the batch size)
- Use a smaller batch with the same learning rate
Show the answer
C. Decay the learning rate (or raise the batch size)
A plateau above the optimum is the signature of the noise floor . Decaying shrinks it directly; a larger batch shrinks .
Go deeper
- Convergence of SGD · Robbins–Monro conditions, step-size schedules and averaging.
- Variance Reduction: SVRG & SAGA · Linear convergence for finite sums by correcting the noise.
- Batch Size, Learning Rate & Noise · Linear scaling, large-batch training and the noise of SGD.
Further reading
- H. Robbins & S. Monro, "A stochastic approximation method," Annals of Mathematical Statistics 22(3), 400–407 (1951).
- L. Bottou & O. Bousquet, "The tradeoffs of large scale learning," Advances in Neural Information Processing Systems 20, 161–168 (2008).
- L. Bottou, F. E. Curtis & J. Nocedal, "Optimization methods for large-scale machine learning," SIAM Review 60(2), 223–311 (2018).
- I. Goodfellow, Y. Bengio & A. Courville, Deep Learning (MIT Press, 2016), section 8.3.