Type at least 2 letters. Enter opens the first result, Esc closes.

    Optimization · Lesson 5 · Momentum and noise

    Stochastic gradient descent, the noise ball and batch size

    Intermediate 75 min 4 interactive figures 3 videos Colab notebook

    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 BB independent samples has variance σ2/B\sigma^2/B (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 η\eta and the batch size BB. 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 a1,…,ana_1, \dots, a_n with mean aˉ\bar a and variance σ2=1n∑i(ai−aˉ)2\sigma^2 = \frac1n\sum_i (a_i - \bar a)^2. The loss

    f(x)=1n∑i=1n12(x−ai)2f(x) = \frac1n\sum_{i=1}^n \tfrac12 (x - a_i)^2

    has derivative f′(x)=x−aˉf'(x) = x - \bar a, so its minimizer is x⋆=aˉx^\star = \bar a. One random example ii gives the stochastic gradient g=x−aig = x - a_i. Its average over ii is x−aˉ=f′(x)x - \bar a = f'(x): the stochastic gradient is right on average.

    Now look at the step direction −g=ai−x-g = a_i - x of each example. If xx is to the right of all data points, every ai−xa_i - x is negative: every example says "move left", like the full gradient. If xx 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).

    Interactive figure: loading…

    Drag the blue point xx from the right into the shaded region. Each arrow is the step direction of one example: blue if it agrees with the full step −f′(x)-f'(x) (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 xx: it moves fast at first, then jumps around x⋆x^\star inside the dashed band x⋆±ησ2/(2−η)x^\star \pm \sqrt{\eta\sigma^2/(2-\eta)} (derived in section 3).

    Two facts from this picture are the core of the lesson:

    1. The noise does not shrink near x⋆x^\star. The variance of g=x−aig = x - a_i is σ2\sigma^2 at every xx. What shrinks is the signal ∣f′(x)∣=∣x−aˉ∣|f'(x)| = |x - \bar a|.
    2. So with a fixed step, SGD cannot settle at x⋆x^\star. It reaches a noise ball around x⋆x^\star and stays there.

    The noise ball in two dimensions #

    Now take f(x)=12(x12+10x22)f(x) = \tfrac12(x_1^2 + 10x_2^2), so μ=1\mu = 1, L=10L = 10 and x⋆=0x^\star = 0. We add Gaussian noise to the exact gradient: g=∇f(x)+ξg = \nabla f(x) + \xi with ξ∼N(0,I/B)\xi \sim \mathcal N(0, I/B). This is the noisy quadratic: a model of a minibatch gradient with batch size BB.

    Interactive figure: loading…

    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 η\eta and the batch BB and watch the cloud size: it scales like η/B\eta/B. The yellow dashed circle has the radius of the bound ησ2/(μB)\sqrt{\eta\sigma^2/(\mu B)}; the dotted dark circle has the radius m∞\sqrt{m_\infty}, where m∞m_\infty is the exact floor. Then choose decaying: the cloud keeps shrinking.

    Quick check

    SGD runs with a constant step and the loss has stopped falling. You halve the step. What happens?

    Quick check

    In the 1D mean example the data lie in [−0.8,3.6][-0.8, 3.6] and the current point is x=5x = 5. What fraction of the single-example steps ai−xa_i - x point toward x⋆x^\star?

    3. Definitions and main results #

    Stochastic gradients and minibatches #

    Training minimizes the empirical risk, an average over the nn training examples:

    f(x)=1n∑i=1nfi(x),f(x) = \frac1n \sum_{i=1}^n f_i(x),

    where fif_i is the loss on example ii and xx are the parameters (in a neural network, θ\theta). SGD is

    xk+1=xk−ηk gk,x_{k+1} = x_k - \eta_k\, g_k ,

    where gkg_k is a stochastic gradient: a random vector computed from a few examples. We assume two properties. Write Ek\mathbb E_k for the expectation given xkx_k (only the new random sample is random).

    • Unbiased: Ek[gk]=∇f(xk)\mathbb E_k[g_k] = \nabla f(x_k).
    • Bounded variance: Ek∥gk−∇f(xk)∥2≤σ2\mathbb E_k\|g_k - \nabla f(x_k)\|^2 \le \sigma^2.

    A minibatch gradient averages BB example gradients, g=1B∑j=1B∇fij(x)g = \frac1B\sum_{j=1}^B \nabla f_{i_j}(x), with indices i1,…,iBi_1, \dots, i_B drawn independently and uniformly. One full pass over the data is an epoch.

    Proposition (minibatch mean and variance). If one example gradient has mean ∇f(x)\nabla f(x) and variance σ2\sigma^2, the minibatch gradient has mean ∇f(x)\nabla f(x) and variance σ2/B\sigma^2/B.

    Proof.

    1. Write δj=∇fij(x)−∇f(x)\delta_j = \nabla f_{i_j}(x) - \nabla f(x). Each δj\delta_j has mean 0 and E∥δj∥2=σ2\mathbb E\|\delta_j\|^2 = \sigma^2, and they are independent.
    2. Mean: E[g]=1B∑jE[∇fij(x)]=∇f(x)\mathbb E[g] = \frac1B\sum_j \mathbb E[\nabla f_{i_j}(x)] = \nabla f(x).
    3. Variance: E∥g−∇f(x)∥2=1B2 E∥∑jδj∥2=1B2∑j,lE[δj⊤δl]\mathbb E\|g - \nabla f(x)\|^2 = \frac{1}{B^2}\,\mathbb E\big\|\sum_j \delta_j\big\|^2 = \frac{1}{B^2}\sum_{j,l}\mathbb E[\delta_j^\top\delta_l].
    4. For j≠lj \ne l, independence gives E[δj⊤δl]=E[δj]⊤E[δl]=0\mathbb E[\delta_j^\top\delta_l] = \mathbb E[\delta_j]^\top\mathbb E[\delta_l] = 0. Only the BB terms with j=lj = l remain: 1B2⋅Bσ2=σ2/B\frac{1}{B^2}\cdot B\sigma^2 = \sigma^2/B. ■\blacksquare

    In practice, batches are often drawn without replacement. Then the variance is n−BB(n−1)σ2\frac{n - B}{B(n - 1)}\sigma^2: almost σ2/B\sigma^2/B when B≪nB \ll n, and 00 at B=nB = n, where the minibatch is the whole dataset (Garrigos and Gower, Lemma 6.5).

    Quick check

    One example gradient has variance σ2=4\sigma^2 = 4 (summed over coordinates). What is the variance of the mean of a minibatch of B=16B = 16 independent examples?

    The exact noise ball in one dimension #

    Go back to the mean example with a constant step η∈(0,2)\eta \in (0, 2). SGD is xk+1=xk−η(xk−aik)=(1−η)xk+ηaikx_{k+1} = x_k - \eta(x_k - a_{i_k}) = (1 - \eta)x_k + \eta a_{i_k}. Subtract x⋆=aˉx^\star = \bar a:

    ek+1=(1−η) ek+η (aik−aˉ),ek=xk−x⋆.e_{k+1} = (1 - \eta)\,e_k + \eta\,(a_{i_k} - \bar a), \qquad e_k = x_k - x^\star .
    1. The new noise aik−aˉa_{i_k} - \bar a has mean 0 and variance σ2\sigma^2, and it is independent of eke_k.
    2. Square and take expectations. The cross term has mean 0, so Eek+12=(1−η)2 Eek2+η2σ2\mathbb E e_{k+1}^2 = (1 - \eta)^2\,\mathbb E e_k^2 + \eta^2\sigma^2.
    3. This recursion has the fixed point m=(1−η)2m+η2σ2m = (1-\eta)^2 m + \eta^2\sigma^2, that is m=η2σ21−(1−η)2=η2σ2η(2−η)m = \dfrac{\eta^2\sigma^2}{1 - (1 - \eta)^2} = \dfrac{\eta^2\sigma^2}{\eta(2 - \eta)}.
    4. Since (1−η)2<1(1 - \eta)^2 < 1, Eek2\mathbb E e_k^2 converges to this fixed point:
    Eek2  ⟶  η σ22−η.\mathbb E e_k^2 \;\longrightarrow\; \frac{\eta\,\sigma^2}{2 - \eta} .

    The error does not go to zero. It settles at a level proportional to η\eta (for small η\eta).

    A decaying step reaches x⋆x^\star. Take ηk=1/(k+1)\eta_k = 1/(k + 1) for k=0,1,…k = 0, 1, \dots Then x1=ai0x_1 = a_{i_0} (whatever x0x_0 is), x2=12(ai0+ai1)x_2 = \tfrac12(a_{i_0} + a_{i_1}), and in general xkx_k is the average of the first kk samples. Its variance is σ2/k\sigma^2/k. So Eek2=σ2/k\mathbb E e_k^2 = \sigma^2/k: the error goes to zero, at the rate O(1/k)O(1/k). This rate cannot be improved in general: with kk samples of Gaussian data, no estimator of the mean has a smaller error than σ2/k\sigma^2/k, and for strongly convex problems no method that sees kk noisy gradients can guarantee better than order 1/k1/k (Agarwal et al. 2012).

    Theorem 1 (SGD with a constant step converges to a noise ball) #

    Setting. ff is μ\mu-strongly convex and LL-smooth with minimizer x⋆x^\star (lesson 02). The stochastic gradients are unbiased with variance at most σ2\sigma^2. The step is constant, 0<η≤1/L0 < \eta \le 1/L. Then

    E∥ek∥2  ≤  (1−ημ)k ∥e0∥2+ησ2μ.\mathbb E\|e_k\|^2 \;\le\; (1 - \eta\mu)^k\,\|e_0\|^2 + \frac{\eta\sigma^2}{\mu} .

    With minibatches of size BB, replace σ2\sigma^2 by σ2/B\sigma^2/B.

    Why this is true. Each step contracts the squared error like gradient descent, by a factor 1−ημ1 - \eta\mu, and adds fresh noise of size η2σ2\eta^2\sigma^2. With a squared error mm, the two balance when ημ m≈η2σ2\eta\mu\, m \approx \eta^2\sigma^2, that is at m≈ησ2/μm \approx \eta\sigma^2/\mu.

    Proof.

    1. Expand the square: ∥ek+1∥2=∥ek−ηgk∥2=∥ek∥2−2η gk⊤ek+η2∥gk∥2\|e_{k+1}\|^2 = \|e_k - \eta g_k\|^2 = \|e_k\|^2 - 2\eta\, g_k^\top e_k + \eta^2\|g_k\|^2.
    2. Take Ek\mathbb E_k. Unbiasedness gives Ek[gk⊤ek]=∇f(xk)⊤ek\mathbb E_k[g_k^\top e_k] = \nabla f(x_k)^\top e_k. Split gkg_k into mean plus noise; the cross term has mean 0, so Ek∥gk∥2=∥∇f(xk)∥2+Ek∥gk−∇f(xk)∥2≤∥∇f(xk)∥2+σ2\mathbb E_k\|g_k\|^2 = \|\nabla f(x_k)\|^2 + \mathbb E_k\|g_k - \nabla f(x_k)\|^2 \le \|\nabla f(x_k)\|^2 + \sigma^2.
    3. Strong convexity between xkx_k and x⋆x^\star: f⋆≥f(xk)+∇f(xk)⊤(x⋆−xk)+μ2∥ek∥2f^\star \ge f(x_k) + \nabla f(x_k)^\top(x^\star - x_k) + \tfrac\mu2\|e_k\|^2. Rearranged: ∇f(xk)⊤ek≥f(xk)−f⋆+μ2∥ek∥2\nabla f(x_k)^\top e_k \ge f(x_k) - f^\star + \tfrac\mu2\|e_k\|^2.
    4. Smoothness: the descent lemma at the point xk−∇f(xk)/Lx_k - \nabla f(x_k)/L gives f⋆≤f(xk)−∥∇f(xk)∥2/(2L)f^\star \le f(x_k) - \|\nabla f(x_k)\|^2/(2L), so ∥∇f(xk)∥2≤2L (f(xk)−f⋆)\|\nabla f(x_k)\|^2 \le 2L\,(f(x_k) - f^\star).
    5. Put 2, 3 and 4 into 1:
    Ek∥ek+1∥2≤(1−ημ)∥ek∥2−2η (1−ηL) (f(xk)−f⋆)+η2σ2.\mathbb E_k\|e_{k+1}\|^2 \le (1 - \eta\mu)\|e_k\|^2 - 2\eta\,(1 - \eta L)\,(f(x_k) - f^\star) + \eta^2\sigma^2 .

    For η≤1/L\eta \le 1/L the middle term is ≤0\le 0. Drop it.

    1. Take full expectations and unroll the recursion mk+1≤(1−ημ)mk+η2σ2m_{k+1} \le (1 - \eta\mu)m_k + \eta^2\sigma^2, with mk=E∥ek∥2m_k = \mathbb E\|e_k\|^2. The geometric sum ∑j≥0(1−ημ)j\sum_{j \ge 0}(1 - \eta\mu)^j is at most 1/(ημ)1/(\eta\mu):
    E∥ek∥2≤(1−ημ)k∥e0∥2+η2σ2∑j=0k−1(1−ημ)j≤(1−ημ)k∥e0∥2+ησ2μ.  ■\mathbb E\|e_k\|^2 \le (1 - \eta\mu)^k\|e_0\|^2 + \eta^2\sigma^2\sum_{j=0}^{k-1}(1 - \eta\mu)^j \le (1 - \eta\mu)^k\|e_0\|^2 + \frac{\eta\sigma^2}{\mu}. \;\blacksquare

    With σ=0\sigma = 0 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 η\eta. The second term is the floor.

    • Halving η\eta halves the floor, but the transient becomes about twice as slow.
    • Doubling BB 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 η\eta behaves like single-example SGD with step η/B\eta/B (Bottou, Curtis and Nocedal §4.2).

    Robbins–Monro conditions #

    To reach x⋆x^\star itself, the step must go to zero, but not too fast (Robbins and Monro 1951):

    ∑k=0∞ηk=∞,∑k=0∞ηk2<∞.\sum_{k=0}^{\infty} \eta_k = \infty, \qquad \sum_{k=0}^{\infty} \eta_k^2 < \infty .
    • The first condition lets the iterates travel any distance. If ∑ηk\sum\eta_k were finite, the total distance would be bounded, and SGD could stop before reaching x⋆x^\star.
    • The second condition keeps the total injected noise ∑kηk2σ2\sum_k \eta_k^2\sigma^2 finite.

    ηk=c/(k+1)\eta_k = c/(k + 1) satisfies both: ∑1/k\sum 1/k diverges and ∑1/k2=π2/6\sum 1/k^2 = \pi^2/6. In general c/kac/k^a satisfies both exactly when 1/2<a≤11/2 < a \le 1.

    Quick check

    Is ηk=1/(k+1)2\eta_k = 1/(k+1)^2 a valid Robbins–Monro step-size sequence?

    Theorem 2 (the O(1/k)O(1/k) rate with a decaying step) #

    Take the setting of Theorem 1 and ηk=c/(k0+k)\eta_k = c/(k_0 + k) with cμ>1c\mu > 1 and η0=c/k0≤1/L\eta_0 = c/k_0 \le 1/L. Then

    E∥ek∥2≤νk0+k,ν=max⁡(c2σ2cμ−1,  k0∥e0∥2).\mathbb E\|e_k\|^2 \le \frac{\nu}{k_0 + k}, \qquad \nu = \max\Big(\frac{c^2\sigma^2}{c\mu - 1},\; k_0\|e_0\|^2\Big).

    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 ηk≤1/L\eta_k \le 1/L. With mk=E∥ek∥2m_k = \mathbb E\|e_k\|^2 it gives mk+1≤(1−ηkμ)mk+ηk2σ2m_{k+1} \le (1 - \eta_k\mu)m_k + \eta_k^2\sigma^2. Write k^=k0+k\hat k = k_0 + k, so ηk=c/k^\eta_k = c/\hat k.

    1. Base case: m0=∥e0∥2≤ν/k0m_0 = \|e_0\|^2 \le \nu/k_0, because ν≥k0∥e0∥2\nu \ge k_0\|e_0\|^2.
    2. Induction step: assume mk≤ν/k^m_k \le \nu/\hat k. Since 1−ηkμ≥01 - \eta_k\mu \ge 0,
    mk+1≤(1−cμk^)νk^+c2σ2k^2=(k^−1) νk^2−(cμ−1) ν−c2σ2k^2.m_{k+1} \le \Big(1 - \frac{c\mu}{\hat k}\Big)\frac{\nu}{\hat k} + \frac{c^2\sigma^2}{\hat k^2} = \frac{(\hat k - 1)\,\nu}{\hat k^2} - \frac{(c\mu - 1)\,\nu - c^2\sigma^2}{\hat k^2} .
    1. The second fraction is ≥0\ge 0 because ν≥c2σ2/(cμ−1)\nu \ge c^2\sigma^2/(c\mu - 1). Drop it.
    2. (k^−1)(k^+1)=k^2−1≤k^2(\hat k - 1)(\hat k + 1) = \hat k^2 - 1 \le \hat k^2, so k^−1k^2≤1k^+1\dfrac{\hat k - 1}{\hat k^2} \le \dfrac{1}{\hat k + 1}. Hence mk+1≤ν/(k^+1)m_{k+1} \le \nu/(\hat k + 1). ■\blacksquare

    The condition cμ>1c\mu > 1 matters. Even without noise, ηk=c/k\eta_k = c/k on f(x)=μ2x2f(x) = \tfrac\mu2 x^2 gives ek=e0∏j=1k(1−cμ/j)e_k = e_0\prod_{j=1}^{k}(1 - c\mu/j), and ek2e_k^2 decays like k−2cμk^{-2c\mu}. If cμ<1/2c\mu < 1/2 this is slower than 1/k1/k. 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 cc, multiply the learning rate by cc.

    Why. Compare cc small steps with one large step over the same cBcB examples:

    • cc steps of size η\eta move by η (gk+gk+1+⋯+gk+c−1)\eta\,(g_k + g_{k+1} + \dots + g_{k+c-1}), each gg a mean over BB examples;
    • one step of size cηc\eta with a batch of cBcB examples moves by cη⋅1c(gk+⋯+gk+c−1)c\eta\cdot\frac1c(g_k + \dots + g_{k+c-1}) if the gradients are computed at the same point.

    The two agree when the gradient changes little during the cc small steps. In Theorem 1, the floor depends only on η/B\eta/B, which the rule keeps fixed. And cc contractions (1−ημ)c(1 - \eta\mu)^c match one contraction 1−cημ1 - c\eta\mu to first order.

    When it fails.

    1. When cηc\eta reaches the curvature limit: gradient descent is unstable for steps above 2/L2/L (lesson 01), whatever the noise.
    2. 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).
    3. When BB 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 GG be the true gradient, HH the Hessian and Σ\Sigma the covariance matrix of the per-example gradients. A step x−ε gx - \varepsilon\, g with a batch of size BB changes the loss, to second order and in expectation, by

    E[Δf]=−ε∥G∥2+12ε2(G⊤HG+tr⁡(HΣ)B).\mathbb E[\Delta f] = -\varepsilon\|G\|^2 + \tfrac12\varepsilon^2\Big(G^\top HG + \frac{\operatorname{tr}(H\Sigma)}{B}\Big).

    Minimize over ε\varepsilon (a parabola in ε\varepsilon):

    εopt(B)=εmax⁡1+Bnoise/B,Δfopt(B)=Δfmax⁡1+Bnoise/B,Bnoise=tr⁡(HΣ)G⊤HG.\varepsilon_{\text{opt}}(B) = \frac{\varepsilon_{\max}}{1 + B_{\text{noise}}/B}, \qquad \Delta f_{\text{opt}}(B) = \frac{\Delta f_{\max}}{1 + B_{\text{noise}}/B}, \qquad B_{\text{noise}} = \frac{\operatorname{tr}(H\Sigma)}{G^\top HG} .

    Here εmax⁡=∥G∥2/G⊤HG\varepsilon_{\max} = \|G\|^2/G^\top HG and Δfmax⁡=12∥G∥4/G⊤HG\Delta f_{\max} = \tfrac12\|G\|^4/G^\top HG are the best step and the best decrease with the exact gradient. BnoiseB_{\text{noise}} is the gradient noise scale. If HH is a multiple of the identity, it becomes the simple noise scale

    Bsimple=tr⁡Σ∥G∥2:B_{\text{simple}} = \frac{\operatorname{tr}\Sigma}{\|G\|^2}:

    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.

    • B≪BnoiseB \ll B_{\text{noise}}: εopt\varepsilon_{\text{opt}} and the progress per step grow linearly with BB. This is the linear scaling regime: doubling BB halves the number of steps, for the same number of examples.
    • B≫BnoiseB \gg B_{\text{noise}}: the progress per step saturates at Δfmax⁡\Delta f_{\max}. Extra examples are wasted.

    Over a whole training run, the number of steps SS and the number of examples EE needed to reach a target loss follow

    (SSmin⁡−1)(EEmin⁡−1)=1.\Big(\frac{S}{S_{\min}} - 1\Big)\Big(\frac{E}{E_{\min}} - 1\Big) = 1 .

    The critical batch size Bcrit=Emin⁡/Smin⁡B_{\text{crit}} = E_{\min}/S_{\min} is the batch size where training takes twice the minimum number of steps and twice the minimum number of examples. McCandlish et al. find Bcrit≈BnoiseB_{\text{crit}} \approx B_{\text{noise}}. As the loss falls, ∥G∥\|G\| shrinks and BnoiseB_{\text{noise}} grows: a large batch is more useful late in training than early.

    Interactive figure: loading…

    Move the batch size BB and watch the two costs. The blue curve is the number of steps S/Smin⁡=1+Bnoise/BS/S_{\min} = 1 + B_{\text{noise}}/B; the violet curve is the number of examples E/Emin⁡=1+B/BnoiseE/E_{\min} = 1 + B/B_{\text{noise}}. Below BnoiseB_{\text{noise}} (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 BnoiseB_{\text{noise}}: the whole picture slides along the axis.

    Quick check

    Training works well on 8 GPUs with learning rate η\eta. You move to 64 GPUs, so the global batch grows 8 times. What should you do?

    GD or SGD per unit of computation #

    Count example gradients (one ∇fi\nabla f_i is one unit of work) for a finite sum of nn terms, to reach E∥ek∥2≤ε\mathbb E\|e_k\|^2 \le \varepsilon:

    • GD: nn per step. With η=1/L\eta = 1/L and σ=0\sigma = 0, Theorem 1 gives ∥ek∥2≤(1−1/κ)k∥e0∥2≤e−k/κ∥e0∥2\|e_k\|^2 \le (1 - 1/\kappa)^k\|e_0\|^2 \le e^{-k/\kappa}\|e_0\|^2, so about κln⁡(∥e0∥2/ε)\kappa\ln(\|e_0\|^2/\varepsilon) steps: about nκln⁡(1/ε)n\kappa\ln(1/\varepsilon) in total.
    • SGD with ηk=c/(k0+k)\eta_k = c/(k_0 + k): one per step and about ν/ε\nu/\varepsilon steps (Theorem 2). This does not depend on nn.

    GD wins for high accuracy on a small dataset. SGD wins when nn is large. In learning, the accuracy only needs to reach the statistical error, about ε∼1/n\varepsilon \sim 1/n. Then GD costs about nκln⁡nn\kappa\ln n and SGD about νn\nu n: 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.

    Interactive figure: loading…

    Count work, not steps. Least squares with d=5d = 5 and κ≈11\kappa \approx 11. 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 nn 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 ησ2/μ\eta\sigma^2/\mu is proportional to η\eta. But the contraction factor 1−ημ1 - \eta\mu 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 8η8\eta reaches the curvature limit (about 2/L2/L), or when the global batch is far above BcritB_{\text{crit}}: then more GPUs cost more but hardly reduce the number of steps.

    4. Worked example #

    Problem. f(x)=12(x12+10x22)f(x) = \tfrac12(x_1^2 + 10x_2^2), so μ=1\mu = 1, L=10L = 10, x⋆=0x^\star = 0. Start at x0=(1,1)x_0 = (1, 1), so ∥e0∥2=2\|e_0\|^2 = 2. The stochastic gradient is g=∇f(x)+ξg = \nabla f(x) + \xi with ξ∼N(0,I2/B)\xi \sim \mathcal N(0, I_2/B). One example has variance σ2=tr⁡I2=2\sigma^2 = \operatorname{tr} I_2 = 2.

    (a) The exact floor. The coordinates do not interact. For a coordinate with curvature λ\lambda, the error follows ek+1=(1−ηλ)ek−ηξke_{k+1} = (1 - \eta\lambda)e_k - \eta\xi_k with Var⁡ξk=1/B\operatorname{Var}\xi_k = 1/B. As in the 1D derivation of section 3:

    Ee2  →  η2/B1−(1−ηλ)2=ηBλ (2−ηλ).\mathbb E e^2 \;\to\; \frac{\eta^2/B}{1 - (1 - \eta\lambda)^2} = \frac{\eta}{B\lambda\,(2 - \eta\lambda)} .

    For η=0.05\eta = 0.05, B=1B = 1: the flat coordinate (λ=1\lambda = 1) gives 0.05/(1⋅1.95)=0.02560.05/(1 \cdot 1.95) = 0.0256; the steep one (λ=10\lambda = 10) gives 0.05/(10⋅1.5)=0.00330.05/(10 \cdot 1.5) = 0.0033. The sum is 0.02900.0290.

    η\eta BB exact floor bound ησ2/(μB)\eta\sigma^2/(\mu B)
    0.05 1 0.0256+0.0033=0.02900.0256 + 0.0033 = 0.0290 0.1
    0.025 1 0.0127+0.0014=0.01410.0127 + 0.0014 = 0.0141 0.05
    0.05 4 0.0290/4=0.00720.0290/4 = 0.0072 0.025

    The bound is about 3.5 times too large here, because it uses only μ\mu (the flattest direction) for all the noise. But it scales correctly: proportional to η\eta and to 1/B1/B. The transient factor (1−ημ)k=0.95k(1 - \eta\mu)^k = 0.95^k shrinks by 10310^3 after ln⁡103/(−ln⁡0.95)≈135\ln 10^3/(-\ln 0.95) \approx 135 steps.

    (b) Robbins–Monro steps. Take ηk=2/(20+k)\eta_k = 2/(20 + k): c=2c = 2, k0=20k_0 = 20, cμ=2>1c\mu = 2 > 1 and η0=0.1=1/L\eta_0 = 0.1 = 1/L. Then

    ν=max⁡(c2σ2cμ−1,  k0∥e0∥2)=max⁡(4⋅21,  20⋅2)=40,\nu = \max\Big(\frac{c^2\sigma^2}{c\mu - 1},\; k_0\|e_0\|^2\Big) = \max\Big(\frac{4 \cdot 2}{1},\; 20 \cdot 2\Big) = 40,

    and Theorem 2 gives E∥ek∥2≤40/(20+k)\mathbb E\|e_k\|^2 \le 40/(20 + k): 0.0390.039 at k=1000k = 1000 and 0.00400.0040 at k=104k = 10^4. The exact value, from the second-moment recursion of each coordinate, is about 1.44/(20+k)1.44/(20 + k): 0.00140.0014 and 0.000140.00014. The bound is loose in the constant but has the right 1/k1/k shape. For comparison, the constant step η=0.05\eta = 0.05 stays at 0.0290.029 forever.

    (c) Linear scaling. Keep η/B=0.0125\eta/B = 0.0125 and spend E=4000E = 4000 examples, so S=E/BS = E/B steps (exact second moments):

    (η,B)(\eta, B) (0.0125, 1) (0.025, 2) (0.05, 4) (0.1, 8) (0.2, 16)
    steps SS 4000 2000 1000 500 250
    E∥eS∥2\mathbb E\|e_S\|^2 0.0070 0.0070 0.0072 0.0078 1.63

    Up to B=8B = 8, the same number of examples gives almost the same error in 8 times fewer steps. At B=16B = 16 the step 0.2=2/L0.2 = 2/L sits at the stability limit of the steep coordinate: ∣1−0.2⋅10∣=1|1 - 0.2 \cdot 10| = 1. That coordinate no longer contracts, the noise accumulates, and the error grows to 1.631.63.

    (d) Noise scale. Here H=diag⁡(1,10)H = \operatorname{diag}(1, 10) and the per-example covariance is Σ=I\Sigma = I. At a point where G=(1,1)G = (1, 1): Bnoise=tr⁡(HΣ)/G⊤HG=11/11=1B_{\text{noise}} = \operatorname{tr}(H\Sigma)/G^\top HG = 11/11 = 1 and Bsimple=tr⁡Σ/∥G∥2=2/2=1B_{\text{simple}} = \operatorname{tr}\Sigma/\|G\|^2 = 2/2 = 1. Closer to the minimum, at G=(0.1,0.1)G = (0.1, 0.1): 11/0.11=10011/0.11 = 100 and 2/0.02=1002/0.02 = 100. 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 n=106n = 10^6 examples with the same noise, and we want E∥e∥2≤10−4\mathbb E\|e\|^2 \le 10^{-4}. For GD with η=1/L=0.1\eta = 1/L = 0.1, Theorem 1 with σ=0\sigma = 0 gives ∥ek∥2≤0.9k∥e0∥2\|e_k\|^2 \le 0.9^k\|e_0\|^2, so it needs ln⁡(2⋅104)/(−ln⁡0.9)≈94\ln(2 \cdot 10^4)/(-\ln 0.9) \approx 94 steps of 10610^6 example gradients: about 9.4⋅1079.4 \cdot 10^7. SGD with the steps of (b) needs, by the bound, 40/10−4=4⋅10540/10^{-4} = 4 \cdot 10^5 example gradients (with the exact constant 1.441.44, about 1.4⋅1041.4 \cdot 10^4).

    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 E∥gB∥2=∥G∥2+tr⁡(Σ)/B\mathbb E\|g_B\|^2 = \|G\|^2 + \operatorname{tr}(\Sigma)/B, the squared norms at a small and a large batch give unbiased estimates of ∥G∥2\|G\|^2 and tr⁡Σ\operatorname{tr}\Sigma. 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 BB. The linear scaling rule with warmup keeps the loss curve per example roughly unchanged while BB stays below BcritB_{\text{crit}}. Kaplan et al. (2020) fit BcritB_{\text{crit}} 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 tt and a Gaussian noise, so σ2\sigma^2 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 η\eta the error stops at a floor proportional to ησ2/B\eta\sigma^2/B. Decay η\eta or grow BB to go lower.
    • "Unbiased means it converges." An unbiased gradient is right on average, but the iterates still jump around x⋆x^\star unless the step goes to zero.
    • Decaying the step badly. c/k2c/k^2 stops before x⋆x^\star (the total travel is finite). c/kc/k with cμ<1/2c\mu < 1/2 decays slower than 1/k1/k, even without noise.
    • Comparing per iteration instead of per example. An SGD step costs BB example gradients; a GD step costs nn.
    • Scaling the learning rate with BB without limit. Linear scaling holds only for B≲BnoiseB \lesssim B_{\text{noise}} and η\eta below the curvature limit, and it needs warmup.
    • Forgetting that the noise scale changes. BnoiseB_{\text{noise}} grows as the loss falls, so a batch that is too large early can be the right size late.

    8. Check yourself #

    1. In the 1D mean example with σ2=1\sigma^2 = 1 and η=0.1\eta = 0.1, what is the exact noise floor, and what does Theorem 1 give?
      AnswerExact: ησ2/(2−η)=0.1/1.9≈0.053\eta\sigma^2/(2 - \eta) = 0.1/1.9 \approx 0.053. Theorem 1: ησ2/μ=0.1\eta\sigma^2/\mu = 0.1 (here μ=L=1\mu = L = 1).
    2. Do ηk=(k+1)−0.7\eta_k = (k+1)^{-0.7} and ηk=(k+1)−0.4\eta_k = (k+1)^{-0.4} satisfy the Robbins–Monro conditions?
      Answer(k+1)−0.7(k+1)^{-0.7}: yes, ∑k−0.7=∞\sum k^{-0.7} = \infty and ∑k−1.4<∞\sum k^{-1.4} < \infty. (k+1)−0.4(k+1)^{-0.4}: no, ∑k−0.8=∞\sum k^{-0.8} = \infty, so the second condition fails. In general c/kac/k^a works exactly for 1/2<a≤11/2 < a \le 1.
    3. Where does the proof of Theorem 1 use η≤1/L\eta \le 1/L?
      AnswerIn step 5. Smoothness turns the η2∥∇f∥2\eta^2\|\nabla f\|^2 term into at most 2η2L(f−f⋆)2\eta^2L(f - f^\star), and η≤1/L\eta \le 1/L makes −2η(1−ηL)(f−f⋆)≤0-2\eta(1 - \eta L)(f - f^\star) \le 0, so the term can be dropped.
    4. 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?
      Answer0.1⋅2048/256=0.80.1 \cdot 2048/256 = 0.8. It breaks if 0.80.8 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.
    5. At some point in training Bsimple≈50B_{\text{simple}} \approx 50, and your batch is 4096. What does the noise-scale model predict?
      AnswerTake Bnoise≈50B_{\text{noise}} \approx 50. Then Δfopt=Δfmax⁡/(1+50/4096)≈0.988 Δfmax⁡\Delta f_{\text{opt}} = \Delta f_{\max}/(1 + 50/4096) \approx 0.988\,\Delta f_{\max}; with half the batch it is about 0.976 Δfmax⁡0.976\,\Delta f_{\max}. Almost the same progress per step for half the compute: most examples are wasted (until BnoiseB_{\text{noise}} grows later in training).
    6. n=104n = 10^4 examples, κ=10\kappa = 10, and you need ε=10−10\varepsilon = 10^{-10} (a high-accuracy fit). GD or SGD?
      AnswerGD (or conjugate gradients, L-BFGS): about nκln⁡(1/ε)=104⋅10⋅23≈2.3⋅106n\kappa\ln(1/\varepsilon) = 10^4 \cdot 10 \cdot 23 \approx 2.3 \cdot 10^6 example gradients. SGD needs about ν/ε\nu/\varepsilon, of order 1010ν10^{10}\nu.
    Recall cardsAnswer in your head first, then reveal. Add the cards to your review deck to see them again just before you would forget.
    1. What does "unbiased stochastic gradient" mean?

    2. What is the variance of the mean of BB independent example gradients with variance σ2\sigma^2?

    3. State the noise-ball bound for SGD with a constant step.

    4. Why does SGD with a constant step not converge to x⋆x^\star?

    5. In 1D mean estimation, what is the exact noise floor of SGD with step η\eta?

    6. State the Robbins–Monro conditions and say why each one is needed.

    7. What is the linear scaling rule, and when does it fail?

    8. What is the simple noise scale, and what does it predict?

    9. Per example gradient, why does SGD beat GD on a large dataset?

    Open the review →

    9. Interview angle #

    • "Why does SGD not converge with a constant learning rate?" — The gradient noise does not vanish at x⋆x^\star, so the error settles at about ησ2/(μB)\eta\sigma^2/(\mu B). 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 B≪BnoiseB \ll B_{\text{noise}} and the step stays below the curvature limit, with warmup. Beyond BcritB_{\text{crit}} larger batches mostly waste compute.
    • "SGD is O(1/k)O(1/k) and GD is linear. Why use SGD?" — A step costs BB instead of nn example gradients. To statistical accuracy ε∼1/n\varepsilon \sim 1/n, SGD needs O(n)O(n) example gradients, GD O(nκlog⁡n)O(n\kappa\log n).
    • "What is the gradient noise scale, and how do you measure it?" — Bsimple=tr⁡Σ/∥G∥2B_{\text{simple}} = \operatorname{tr}\Sigma/\|G\|^2, 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:

    1. Simulate SGD for 1D mean estimation and compare the measured noise floor with ησ2/(2−η)\eta\sigma^2/(2 - \eta).
    2. Write minibatch SGD for least squares; compare a constant step with a decaying step c/(k0+k)c/(k_0 + k).
    3. Measure the variance of minibatch gradients against BB for logistic regression on the scikit-learn digits dataset, and estimate the simple noise scale.
    4. 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 #

    Why SGD makes fast progress far from the minimum and slows down near it (the region of confusion).
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    A gentle picture of SGD and minibatches on a small regression problem.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    How minibatches and epochs are organized in practice.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play