Stochastic gradient descent, the noise ball and batch size
Before this lesson: the linear rate of gradient descent (lesson 03), the descent lemma and strong convexity (lesson 02), expectation and variance (probability and statistics track, lesson 02), and the fact that the mean of independent samples has variance (probability and statistics track, lesson 06). Time: about 75 minutes, plus the notebook.
Why this matters #
Every large model is trained with stochastic gradients. Two numbers then shape training: the learning rate and the batch size . This lesson explains four things you see in practice. The loss stops falling at a constant learning rate, and it drops again when you decay the learning rate. A larger global batch in data-parallel training (DDP, FSDP) needs a larger learning rate. Adding more GPUs stops reducing the number of steps at some point. And SGD, with a slower rate per step than gradient descent, still wins on large datasets. Adam (lesson 06) and the schedules of lesson 07 build on these facts.
1. Predict first #
2. The picture #
All examples agree far away, and disagree near the minimum #
Take the simplest problem: estimate a mean. The data are numbers with mean and variance . The loss
has derivative , so its minimizer is . One random example gives the stochastic gradient . Its average over is : the stochastic gradient is right on average.
Now look at the step direction of each example. If is to the right of all data points, every is negative: every example says "move left", like the full gradient. If is inside the data range, some examples say "left" and others "right". This interval is the region of confusion (Bertsekas' example, in Bottou, Curtis and Nocedal §3.3).
Drag the blue point from the right into the shaded region. Each arrow is the step direction of one example: blue if it agrees with the full step (thick dark arrow), magenta if it points the other way. Outside the data range all arrows agree. Inside, they disagree, and the full step becomes short. The chart below runs SGD with one random example per step from the current : it moves fast at first, then jumps around inside the dashed band (derived in section 3).
Two facts from this picture are the core of the lesson:
- The noise does not shrink near . The variance of is at every . What shrinks is the signal .
- So with a fixed step, SGD cannot settle at . It reaches a noise ball around and stays there.
The noise ball in two dimensions #
Now take , so , and . We add Gaussian noise to the exact gradient: with . This is the noisy quadratic: a model of a minibatch gradient with batch size .
Many SGD runs from one start. Each faint blue line is one SGD run; the dark line is gradient descent with the same step. Press Play. The runs first follow gradient descent, then stop in a cloud: the noise ball. Change the step and the batch and watch the cloud size: it scales like . The yellow dashed circle has the radius of the bound ; the dotted dark circle has the radius , where is the exact floor. Then choose decaying: the cloud keeps shrinking.
SGD runs with a constant step and the loss has stopped falling. You halve the step. What happens?
The floor is proportional to : each step injects noise of size , and the pull back to is proportional to . But the contraction factor per step is ; with half the step it is closer to 1, so the transient takes about twice as many steps. The noise is still there; only a step that keeps shrinking reaches the minimum.
In the 1D mean example the data lie in and the current point is . What fraction of the single-example steps point toward ?
Every , so every is negative, like . Outside the data range SGD moves like gradient descent. Only inside the range (the region of confusion) do the examples disagree.
3. Definitions and main results #
Stochastic gradients and minibatches #
Training minimizes the empirical risk, an average over the training examples:
where is the loss on example and are the parameters (in a neural network, ). SGD is
where is a stochastic gradient: a random vector computed from a few examples. We assume two properties. Write for the expectation given (only the new random sample is random).
- Unbiased: .
- Bounded variance: .
A minibatch gradient averages example gradients, , with indices drawn independently and uniformly. One full pass over the data is an epoch.
Proposition (minibatch mean and variance). If one example gradient has mean and variance , the minibatch gradient has mean and variance .
Proof.
- Write . Each has mean 0 and , and they are independent.
- Mean: .
- Variance: .
- For , independence gives . Only the terms with remain: .
In practice, batches are often drawn without replacement. Then the variance is : almost when , and at , where the minibatch is the whole dataset (Garrigos and Gower, Lemma 6.5).
One example gradient has variance (summed over coordinates). What is the variance of the mean of a minibatch of independent examples?
The variance of a mean of independent terms is . The standard deviation is : four times more examples are needed to halve the noise. would be the mistake of dividing by twice.
The exact noise ball in one dimension #
Go back to the mean example with a constant step . SGD is . Subtract :
- The new noise has mean 0 and variance , and it is independent of .
- Square and take expectations. The cross term has mean 0, so .
- This recursion has the fixed point , that is .
- Since , converges to this fixed point:
The error does not go to zero. It settles at a level proportional to (for small ).
A decaying step reaches . Take for Then (whatever is), , and in general is the average of the first samples. Its variance is . So : the error goes to zero, at the rate . This rate cannot be improved in general: with samples of Gaussian data, no estimator of the mean has a smaller error than , and for strongly convex problems no method that sees noisy gradients can guarantee better than order (Agarwal et al. 2012).
Theorem 1 (SGD with a constant step converges to a noise ball) #
Setting. is -strongly convex and -smooth with minimizer (lesson 02). The stochastic gradients are unbiased with variance at most . The step is constant, . Then
With minibatches of size , replace by .
Why this is true. Each step contracts the squared error like gradient descent, by a factor , and adds fresh noise of size . With a squared error , the two balance when , that is at .
Proof.
- Expand the square: .
- Take . Unbiasedness gives . Split into mean plus noise; the cross term has mean 0, so .
- Strong convexity between and : . Rearranged: .
- Smoothness: the descent lemma at the point gives , so .
- Put 2, 3 and 4 into 1:
For the middle term is . Drop it.
- Take full expectations and unroll the recursion , with . The geometric sum is at most :
With this is the linear rate of gradient descent in distance (lesson 03).
Reading the bound. The first term is the transient: it shrinks like gradient descent with step . The second term is the floor.
- Halving halves the floor, but the transient becomes about twice as slow.
- Doubling halves the floor in the same number of steps, but each step costs twice as many example gradients.
- Per example gradient, the two options cost about the same: minibatch SGD with step behaves like single-example SGD with step (Bottou, Curtis and Nocedal §4.2).
Robbins–Monro conditions #
To reach itself, the step must go to zero, but not too fast (Robbins and Monro 1951):
- The first condition lets the iterates travel any distance. If were finite, the total distance would be bounded, and SGD could stop before reaching .
- The second condition keeps the total injected noise finite.
satisfies both: diverges and . In general satisfies both exactly when .
Is a valid Robbins–Monro step-size sequence?
. The total distance SGD can travel is then bounded by about times the gradient size, so from a far start it stalls. The second condition holds, but both are needed. A larger batch does not change this.
Theorem 2 (the rate with a decaying step) #
Take the setting of Theorem 1 and with and . Then
This is a variant of Theorem 4.7 of Bottou, Curtis and Nocedal, written for the distance.
Proof by induction
Step 5 of Theorem 1 holds for every step . With it gives . Write , so .
- Base case: , because .
- Induction step: assume . Since ,
- The second fraction is because . Drop it.
- , so . Hence .
The condition matters. Even without noise, on gives , and decays like . If this is slower than . A step that decays too early is as bad as no decay.
Batch size: the linear scaling rule #
Linear scaling rule (Goyal et al. 2017, §2.1): when you multiply the batch size by , multiply the learning rate by .
Why. Compare small steps with one large step over the same examples:
- steps of size move by , each a mean over examples;
- one step of size with a batch of examples moves by if the gradients are computed at the same point.
The two agree when the gradient changes little during the small steps. In Theorem 1, the floor depends only on , which the rule keeps fixed. And contractions match one contraction to first order.
When it fails.
- When reaches the curvature limit: gradient descent is unstable for steps above (lesson 01), whatever the noise.
- Early in training, where the gradient changes fast. Goyal et al. needed a gradual warmup (5 epochs) to train ResNet-50 with batch 8192 (lesson 07).
- When is far above the critical batch size (next).
The gradient noise scale and the critical batch size #
McCandlish et al. (2018) ask: for which batch size does a larger batch stop helping? Let be the true gradient, the Hessian and the covariance matrix of the per-example gradients. A step with a batch of size changes the loss, to second order and in expectation, by
Minimize over (a parabola in ):
Here and are the best step and the best decrease with the exact gradient. is the gradient noise scale. If is a multiple of the identity, it becomes the simple noise scale
the total gradient variance divided by the squared gradient norm. It is the batch size at which noise and signal in one step have about the same size.
- : and the progress per step grow linearly with . This is the linear scaling regime: doubling halves the number of steps, for the same number of examples.
- : the progress per step saturates at . Extra examples are wasted.
Over a whole training run, the number of steps and the number of examples needed to reach a target loss follow
The critical batch size is the batch size where training takes twice the minimum number of steps and twice the minimum number of examples. McCandlish et al. find . As the loss falls, shrinks and grows: a large batch is more useful late in training than early.
Move the batch size and watch the two costs. The blue curve is the number of steps ; the violet curve is the number of examples . Below (yellow line) the steps fall almost like the dashed line of perfect linear scaling, at almost no extra cost in examples. Above it, the steps flatten and the examples grow. Change : the whole picture slides along the axis.
Training works well on 8 GPUs with learning rate . You move to 64 GPUs, so the global batch grows 8 times. What should you do?
The linear scaling rule keeps fixed, so 8 times fewer steps cover the same examples with the same noise floor. It fails when the larger step becomes unstable (), early in training without warmup, and when , where extra examples bring little progress. The rule is sometimes used with Adam, but it is not the rule derived here.
GD or SGD per unit of computation #
Count example gradients (one is one unit of work) for a finite sum of terms, to reach :
- GD: per step. With and , Theorem 1 gives , so about steps: about in total.
- SGD with : one per step and about steps (Theorem 2). This does not depend on .
GD wins for high accuracy on a small dataset. SGD wins when is large. In learning, the accuracy only needs to reach the statistical error, about . Then GD costs about and SGD about : a fixed number of passes over the data (Bottou, Curtis and Nocedal §4.4). Redundant data widen the gap: copy the dataset 10 times, and a GD step costs 10 times more, while SGD does not change.
Count work, not steps. Least squares with and . The x-axis is the number of example gradients. Gradient descent (dark, one dot per pass) needs a full pass for one step; minibatch SGD makes progress after a few hundred examples, then stops at its noise floor. Switch from 10,000 to 100,000: the GD curve moves right by a factor of 10, the SGD curve does not move. Choose decaying to see SGD go below its floor, slowly. The yellow line marks one pass.
Answers to section 1. (1) The level halves: the floor is proportional to . But the contraction factor moves closer to 1, so reaching the floor takes about twice as many steps. This is why decaying the learning rate makes the loss drop. (2) Multiply the learning rate by 8, with a warmup. This stops working when reaches the curvature limit (about ), or when the global batch is far above : then more GPUs cost more but hardly reduce the number of steps.
4. Worked example #
Problem. , so , , . Start at , so . The stochastic gradient is with . One example has variance .
(a) The exact floor. The coordinates do not interact. For a coordinate with curvature , the error follows with . As in the 1D derivation of section 3:
For , : the flat coordinate () gives ; the steep one () gives . The sum is .
| exact floor | bound | ||
|---|---|---|---|
| 0.05 | 1 | 0.1 | |
| 0.025 | 1 | 0.05 | |
| 0.05 | 4 | 0.025 |
The bound is about 3.5 times too large here, because it uses only (the flattest direction) for all the noise. But it scales correctly: proportional to and to . The transient factor shrinks by after steps.
(b) Robbins–Monro steps. Take : , , and . Then
and Theorem 2 gives : at and at . The exact value, from the second-moment recursion of each coordinate, is about : and . The bound is loose in the constant but has the right shape. For comparison, the constant step stays at forever.
(c) Linear scaling. Keep and spend examples, so steps (exact second moments):
| (0.0125, 1) | (0.025, 2) | (0.05, 4) | (0.1, 8) | (0.2, 16) | |
|---|---|---|---|---|---|
| steps | 4000 | 2000 | 1000 | 500 | 250 |
| 0.0070 | 0.0070 | 0.0072 | 0.0078 | 1.63 |
Up to , the same number of examples gives almost the same error in 8 times fewer steps. At the step sits at the stability limit of the steep coordinate: . That coordinate no longer contracts, the noise accumulates, and the error grows to .
(d) Noise scale. Here and the per-example covariance is . At a point where : and . Closer to the minimum, at : and . Far from the minimum a batch of 1 is already enough; near it, batches up to about 100 still pay off.
(e) Cost. Suppose this were a finite sum of examples with the same noise, and we want . For GD with , Theorem 1 with gives , so it needs steps of example gradients: about . SGD with the steps of (b) needs, by the bound, example gradients (with the exact constant , about ).
5. In code #
NumPy checks the floors of the worked example with 20,000 independent SGD runs, then measures minibatch noise on a least-squares problem and estimates the simple noise scale. The estimate uses two batch sizes: since , the squared norms at a small and a large batch give unbiased estimates of and . In data-parallel training the small batch is the per-GPU batch and the large one is the global batch after the all-reduce, so the estimate is almost free (McCandlish et al., Appendix A.1).
import numpy as np
# 1) Noise ball on f(x) = (x1^2 + 10 x2^2)/2 with gradient noise N(0, I/B).
# R independent SGD runs at once (one row per run).
rng = np.random.default_rng(0)
lam = np.array([1.0, 10.0])
R, K = 20_000, 2_000
def floor(eta, B):
x = np.ones((R, 2)) # x0 = (1, 1) in every run
for _ in range(K):
g = lam * x + rng.standard_normal((R, 2)) / np.sqrt(B) # unbiased, variance 2/B
x -= eta * g
return (x ** 2).sum(1).mean()
for eta, B in [(0.05, 1), (0.025, 1), (0.05, 4)]:
exact = (eta / (B * lam * (2 - eta * lam))).sum()
print(eta, B, round(floor(eta, B), 4), round(exact, 4), eta * 2 / B)
# 0.05 1 0.0288 0.029 0.1 <- simulated, exact, bound eta sigma^2 / (mu B)
# 0.025 1 0.0141 0.0141 0.05
# 0.05 4 0.0072 0.0072 0.025
# 2) Minibatch noise is tr(Sigma)/B, and the simple noise scale grows near the minimum.
rng = np.random.default_rng(0)
n, d = 10_000, 5
X = rng.standard_normal((n, d))
y = X @ rng.standard_normal(d) + 0.5 * rng.standard_normal(n)
w_hat = np.linalg.lstsq(X, y, rcond=None)[0] # minimizer of ||Xw - y||^2 / (2n)
def stats(w):
per_example = X * (X @ w - y)[:, None] # gradient of each term, shape (n, d)
G = per_example.mean(0) # full gradient
tr_sigma = ((per_example - G) ** 2).sum(1).mean() # trace of the per-example covariance
return per_example, G, tr_sigma
def batch_grads(per_example, B, draws=20_000): # minibatch gradients, with replacement
return per_example[rng.integers(0, n, size=(draws, B))].mean(1)
per_example, G, tr_sigma = stats(np.zeros(d))
for B in [1, 8, 64]:
var = ((batch_grads(per_example, B) - G) ** 2).sum(1).mean() # E|G_B - G|^2
print(B, round(var * B / tr_sigma, 2)) # about 1: the variance is tr(Sigma)/B
# 1 0.98
# 8 1.0
# 64 1.0
for w in [np.zeros(d), w_hat + 0.05]: # far from and near the minimizer
per_example, G, tr_sigma = stats(w)
b_s, b_b = 8, 64
g_s = (batch_grads(per_example, b_s) ** 2).sum(1).mean() # E|G_Bsmall|^2
g_b = (batch_grads(per_example, b_b) ** 2).sum(1).mean() # E|G_Bbig|^2
G2 = (b_b * g_b - b_s * g_s) / (b_b - b_s) # estimates |G|^2
S = (g_s - g_b) / (1 / b_s - 1 / b_b) # estimates tr(Sigma)
print(round(S / G2, 1), round(tr_sigma / (G @ G), 1)) # estimated vs exact B_simple
# 6.5 6.3
# 100.1 103.2
The noise scale grows from about 6 far from the minimizer to about 100 near it, as in part (d).
6. Where it shows up #
- Training large models. In DDP or FSDP the global batch is (per-GPU batch) × (number of GPUs) × (gradient-accumulation steps). Scaling out raises . The linear scaling rule with warmup keeps the loss curve per example roughly unchanged while stays below . Kaplan et al. (2020) fit as a power law in the loss for language models and used it to choose batch sizes. The noise-scale estimate of section 5 costs almost nothing in a DDP run.
- Learning-rate decay. Step decay, cosine decay and the cooldown of warmup–stable–decay (WSD) schedules all shrink the noise ball at the end of training (lesson 07).
- ML for science. A physics-informed loss is a Monte Carlo estimate of an integral over collocation points; resampling them every step makes the gradient stochastic, with a variance that falls like one over the number of points. In diffusion and flow-matching training each loss term also samples a time and a Gaussian noise, so includes these sources too. For small full-batch problems (an inverse problem with a few thousand residuals), deterministic methods with linear rates win (quasi-Newton and Gauss–Newton methods, lesson 10).
7. Common mistakes #
- Reading the plateau as convergence. At a constant the error stops at a floor proportional to . Decay or grow to go lower.
- "Unbiased means it converges." An unbiased gradient is right on average, but the iterates still jump around unless the step goes to zero.
- Decaying the step badly. stops before (the total travel is finite). with decays slower than , even without noise.
- Comparing per iteration instead of per example. An SGD step costs example gradients; a GD step costs .
- Scaling the learning rate with without limit. Linear scaling holds only for and below the curvature limit, and it needs warmup.
- Forgetting that the noise scale changes. grows as the loss falls, so a batch that is too large early can be the right size late.
8. Check yourself #
- In the 1D mean example with and , what is the exact noise floor, and
what does Theorem 1 give?
Answer
Exact: . Theorem 1: (here ). - Do and satisfy the Robbins–Monro conditions?
Answer
: yes, and . : no, , so the second condition fails. In general works exactly for . - Where does the proof of Theorem 1 use ?
Answer
In step 5. Smoothness turns the term into at most , and makes , so the term can be dropped. - Batch 256 with learning rate 0.1 works well. You move to batch 2048. What learning rate does the
linear scaling rule give, and what can break it?
Answer
. It breaks if exceeds the curvature (stability) limit, early in training without warmup, or if 2048 is far above the critical batch size, where the extra examples give little progress. - At some point in training , and your batch is 4096. What does the
noise-scale model predict?
Answer
Take . Then ; with half the batch it is about . Almost the same progress per step for half the compute: most examples are wasted (until grows later in training). - examples, , and you need (a high-accuracy fit). GD or SGD?
Answer
GD (or conjugate gradients, L-BFGS): about example gradients. SGD needs about , of order .
What does "unbiased stochastic gradient" mean?
Its expectation, given the current point, is the true gradient: .
What is the variance of the mean of independent example gradients with variance ?
. The cross terms vanish because the errors are independent with mean zero.
State the noise-ball bound for SGD with a constant step.
For -strongly convex, -smooth and : (with for minibatches).
Why does SGD with a constant step not converge to ?
The gradient noise does not vanish at , while the pull towards does. Each step adds noise of size , so the error settles at a level proportional to .
In 1D mean estimation, what is the exact noise floor of SGD with step ?
, from .
State the Robbins–Monro conditions and say why each one is needed.
(the iterates can travel any distance) and (the total injected noise stays finite).
What is the linear scaling rule, and when does it fail?
Multiply the learning rate by when the batch grows by . It fails above the curvature limit, early in training without warmup, and for .
What is the simple noise scale, and what does it predict?
. It estimates the critical batch size: below it, a larger batch saves steps almost for free; above it, extra examples are mostly wasted.
Per example gradient, why does SGD beat GD on a large dataset?
A GD step costs example gradients; SGD's cost to a fixed accuracy (about ) does not depend on .
9. Interview angle #
- "Why does SGD not converge with a constant learning rate?" — The gradient noise does not vanish at , so the error settles at about . Decay the learning rate or grow the batch to go lower.
- "You double the batch size. What do you do with the learning rate?" — Double it while and the step stays below the curvature limit, with warmup. Beyond larger batches mostly waste compute.
- "SGD is and GD is linear. Why use SGD?" — A step costs instead of example gradients. To statistical accuracy , SGD needs example gradients, GD .
- "What is the gradient noise scale, and how do you measure it?" — , the batch size at which noise and signal in one step are about equal. Estimate it from the squared gradient norms at two batch sizes, for example per GPU and after the all-reduce.
10. Practice #
The notebook for this lesson runs in Colab. It has four exercises, each with a check cell and a folded solution:
- Simulate SGD for 1D mean estimation and compare the measured noise floor with .
- Write minibatch SGD for least squares; compare a constant step with a decaying step .
- Measure the variance of minibatch gradients against for logistic regression on the scikit-learn digits dataset, and estimate the simple noise scale.
- Find the number of steps to a target error against the batch size, with the linear scaling rule, and find the batch size where linear scaling breaks.
11. Watch and read #
- Bottou, Curtis and Nocedal, Optimization Methods for Large-Scale Machine Learning (SIAM Review, 2018): §3.3 (why SGD, the region of confusion), §4.2 (Theorems 4.6 and 4.7) and §4.4 (work complexity).
- Garrigos and Gower, Handbook of Convergence Theorems for (Stochastic) Gradient Methods: §5 (SGD theorems) and Lemma 6.5 (minibatch variance).
- McCandlish, Kaplan, Amodei et al., An Empirical Model of Large-Batch Training: §2 (the noise scale and the critical batch size) and Appendix A.1 (the estimator of section 5).
- Goyal et al., Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour: §2 (the linear scaling rule and gradual warmup).
- Robbins and Monro, A Stochastic Approximation Method (Annals of Mathematical Statistics, 1951): the original step-size conditions.
- Agarwal, Bartlett, Ravikumar and Wainwright, Information-theoretic lower bounds on the oracle complexity of stochastic convex optimization (IEEE Transactions on Information Theory, 2012): why no method beats the order with noisy gradients.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.