SafeZone AI Learn
Learn/ Mathematical Foundations/ Optimization · lesson 4 of 7

Stochastic gradient descent

Minibatch gradients as noisy estimators: the bias–variance of a gradient, the noise ball that a constant learning rate cannot escape, the schedules that shrink it — and why the noise is sometimes doing you a favour.

Full gradient descent needs the gradient of the loss over the entire dataset at every step — an O(n)O(n) sweep per update. Modern datasets made that absurd, and the fix changed the character of the algorithm: estimate the gradient from a random minibatch, and accept that every step is now a draw from a distribution. This lesson treats SGD as what it is — a stochastic process — because that is the only frame in which its behaviour (fast early, noisy late, schedule-dependent forever) makes sense.

The estimator

The training loss is a finite sum, f(x)=1ni=1nfi(x)f(x) = \frac{1}{n} \sum_{i=1}^n f_i(x), one term per example. Sampling a minibatch BB of size bb uniformly and averaging gives the minibatch gradient

gB(x)  =  1biBfi(x),g_B(x) \;=\; \frac{1}{b} \sum_{i \in B} \nabla f_i(x),

which is unbiasedE[gB(x)]=f(x)\mathbb{E}[g_B(x)] = \nabla f(x) — with covariance shrinking linearly in the batch size:

Cov ⁣[gB(x)]  =  Σ(x)b(sampling with replacement),\operatorname{Cov}\!\big[g_B(x)\big] \;=\; \frac{\Sigma(x)}{b} \qquad\text{(sampling with replacement),}

where Σ(x)\Sigma(x) is the covariance of a single-example gradient. Two consequences before any dynamics: the direction is right on average, and averaging four times more examples only halves the noise — standard-error scaling, σ/b\sigma/\sqrt{b}. Batch size buys noise reduction at a steep, sublinear exchange rate.

The update is otherwise unchanged:

xt+1=xtηtgBt(xt)  =  xtηtf(xt)  +  ηtξt,E[ξt]=0.x_{t+1} = x_t - \eta_t\, g_{B_t}(x_t) \;=\; x_t - \eta_t \nabla f(x_t) \;+\; \eta_t\,\xi_t, \qquad \mathbb{E}[\xi_t] = 0 .

That decomposition — gradient step plus zero-mean kick scaled by the learning rate — is the whole algorithm. Everything below is about the tug-of-war between the two terms.

idx = rng.permutation(n)                    # each epoch: shuffle, then slice
for s in range(0, n, b):
    batch = idx[s : s + b]
    x -= lr(t) * grad(x, batch)             # unbiased, noisy, cheap
    t += 1

The noise ball: what a constant learning rate converges to

Far from the optimum, the true gradient dwarfs the noise and SGD behaves like slightly drunk gradient descent — early progress is nearly as fast, at 1/b1/b-th the cost per step. Near the optimum the gradient vanishes but the noise does not, and the two terms balance. For a μ\mu-strongly convex, LL-smooth loss with (bounded) gradient-noise variance σ2/b\sigma^2/b, constant-η\eta SGD satisfies, in the limit,

E[f(xt)f]    t    Θ ⁣(ηLσ2μb)\mathbb{E}\big[f(x_t) - f^\star\big] \;\xrightarrow{\;t\to\infty\;}\; \Theta\!\Big( \frac{\eta L \sigma^2}{\mu\, b} \Big)

— it does not converge. It reaches a stationary distribution: a fuzzy cloud around the minimum, the noise ball, whose radius scales with η\eta and σ2/b\sigma^2/b. On the loss curve this is unmistakable: a fast drop, then a plateau that no amount of further training lowers. The plateau is not a bug, a bad init, or a local minimum — it is the equilibrium radius of a stochastic process, and the only levers that lower it are the ones in the formula: smaller η\eta, bigger bb, or less noise.

Run it, then let it sit: the iterate orbits the minimum in a cloud whose radius you control. Halve the learning rate — the cloud tightens and the crawl slows. Raise the batch size from 8 to 64 — same effect, bought with compute instead of speed. Switch the schedule to η/t\eta/\sqrt{t} and the ball itself shrinks over time: that is the schedule doing precisely its theoretical job. On the two-wells surface, turn σ up and watch the iterate occasionally kick out of the shallow well entirely — remember that sight when you reach the non-convex lesson.

Schedules: how to shrink the ball

If a constant η\eta ends in a ball of radius η\propto \eta, the classical move is to decay it. The Robbins–Monro conditions (1951 — SGD is older than the transistor) say the schedule must satisfy

t=1ηt=andt=1ηt2<\sum_{t=1}^{\infty} \eta_t = \infty \qquad\text{and}\qquad \sum_{t=1}^{\infty} \eta_t^2 < \infty

— enough total step to travel anywhere, but square-summable so the accumulated noise is finite. ηt=η0/t\eta_t = \eta_0 / t qualifies; ηt=η0/t\eta_t = \eta_0/\sqrt{t} fails the second condition but achieves the optimal O(1/t)O(1/\sqrt{t}) convex rate with averaging, and is what practice actually approximates. The realities of deep learning added an engineering layer on top:

ScheduleShapeWhen it earns its keep
Step decay÷10 at fixed epochsclassic vision training; crude but effective
Cosinesmooth decay to ~0the modern default; no thresholds to tune
Warmup → decayramp up, then decaylarge-batch and transformer training, where a full-size η\eta at step 0 diverges
Constant + late averagingflat, then average iteratestheory-optimal for convex SGD (Polyak–Ruppert averaging)

The unifying logic is exactly the noise ball: large η\eta early to cross the landscape while gradients dominate; small η\eta late to shrink the equilibrium cloud once noise dominates. Every schedule is a policy for spending that budget.

Batch size is not a free parameter

The variance formula tempts a simple story — bigger batch, less noise, better — but the exchange rates matter:

  • Compute per update grows linearly in bb, while noise shrinks only as 1/b1/\sqrt{b}. Past a problem-dependent critical size, extra examples per batch stop buying wall-clock progress (Shallue et al. call this the end of “perfect scaling”).
  • The linear-scaling rule — when you multiply bb by kk, multiply η\eta by kk too (Goyal et al., training ImageNet at b=8192b = 8192) — falls straight out of the update: kk small noisy steps ≈ one kk-times-larger, k\sqrt{k}-less-noisy step, provided the gradient does not change much across them. It breaks near the stability ceiling 2/L2/L from the previous lesson, which is why large-batch recipes need warmup.
  • The noise is not purely adversarial. Small-batch SGD reliably finds solutions that generalize slightly better in many settings (Keskar et al.); one mechanism is that the noise ball cannot fit inside sharp, narrow minima, so the process preferentially settles in wide, flat basins. The full flat-vs-sharp story — and its caveats — is picked up in the non-convex landscapes lesson, but the operational summary stands: the noise is a regularizer you were given for free, and “reduce it to zero” is not automatically the goal.

A reproducibility note practitioners learn the hard way

SGD’s result is a random variable: it depends on the shuffling seed, and on GPUs even “identical” runs differ through non-deterministic kernels and float addition order. Report loss curves across seeds, not a single lucky run — variance across seeds is often the honest error bar on every number in your results table.

Exercises

Work these before the next lesson

  1. Prove the unbiasedness E[gB]=f\mathbb{E}[g_B] = \nabla f and the Σ/b\Sigma/b covariance for sampling with replacement. What changes without replacement, and why does the distinction vanish for bnb \ll n?
    Solution

    Worked solutions are part of Premiumunlock all of them for £5/month →

  2. 4 more exercises — each with a worked solution — are part of Premium. Unlock everything for £5/month →

References

  • H. Robbins & S. Monro, “A Stochastic Approximation Method”, Ann. Math. Stat. 1951 — the original, still readable.
  • L. Bottou, F. Curtis, J. Nocedal, “Optimization Methods for Large-Scale Machine Learning”, SIAM Review 2018 — the definitive modern survey; §4 covers the noise-ball analysis quoted here.
  • P. Goyal et al., “Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour”, 2017 — the linear-scaling rule and warmup.
  • N. S. Keskar et al., “On Large-Batch Training for Deep Learning: Generalization Gap and Sharp Minima”, ICLR 2017.
  • C. Shallue et al., “Measuring the Effects of Data Parallelism on Neural Network Training”, JMLR 2019 — the critical-batch-size measurements.