Simple Algorithm
Machine Learning · Descent · 22 min

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 1/B1/B 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 ησ2/μ\eta\sigma^2/\mu, 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:

F(θ)=1n∑i=1nfi(θ),fi(θ)=ℓ(hθ(xi),yi),∇F=1n∑i=1n∇fi.F(\boldsymbol\theta)=\frac1n\sum_{i=1}^nf_i(\boldsymbol\theta),\qquad f_i(\boldsymbol\theta)=\ell\big(h_{\boldsymbol\theta}(\mathbf x_i),y_i\big),\qquad\nabla F=\frac1n\sum_{i=1}^n\nabla f_i.

One exact gradient costs nn per-example gradients. Stochastic gradient descent uses a random mini-batch B\mathcal B of size BB instead: gB(θ)=1B∑i∈B∇fi(θ)\mathbf g_{\mathcal B}(\boldsymbol\theta)=\frac1B\sum_{i\in\mathcal B}\nabla f_i(\boldsymbol\theta) and θt+1=θt−ηt gBt(θt)\boldsymbol\theta_{t+1}=\boldsymbol\theta_t-\eta_t\,\mathbf g_{\mathcal B_t}(\boldsymbol\theta_t). If every example is equally likely to be in the batch, the expectation is right: E[gB(θ)]=∇F(θ)\E\big[\mathbf g_{\mathcal B}(\boldsymbol\theta)\big]=\nabla F(\boldsymbol\theta).

DerivationHow noisy is a mini-batch gradient?
  1. Σ(θ)=1n∑i=1n(∇fi(θ)−∇F(θ))(∇fi(θ)−∇F(θ))⊤\Sigma(\boldsymbol\theta)=\frac1n\sum_{i=1}^n\big(\nabla f_i(\boldsymbol\theta)-\nabla F(\boldsymbol\theta)\big)\big(\nabla f_i(\boldsymbol\theta)-\nabla F(\boldsymbol\theta)\big)^\top

    Measure the spread of the per-example gradients around their mean with the gradient-noise covariance:

  2. Cov⁡[gB]=Σ(θ)B,E∥gB−∇F∥2=tr⁡Σ(θ)B\Cov\big[\mathbf g_{\mathcal B}\big]=\frac{\Sigma(\boldsymbol\theta)}B,\qquad\E\norm{\mathbf g_{\mathcal B}-\nabla F}^2=\frac{\operatorname{tr}\Sigma(\boldsymbol\theta)}B

    With BB independent draws (with replacement), the batch gradient is an average of BB i.i.d. terms with covariance Σ\Sigma, so its covariance is divided by BB:

  3. Cov⁡[gB]=n−Bn−1⋅Σ(θ)B\Cov\big[\mathbf g_{\mathcal B}\big]=\frac{n-B}{n-1}\cdot\frac{\Sigma(\boldsymbol\theta)}B

    Drawing BB distinct examples (without replacement), the usual practice, adds the finite-population correction of survey sampling, which vanishes at B=nB=n:

  4. Either way the noise's standard deviation falls like 1/B1/\sqrt B, while the cost of a step grows like BB. Quadrupling the batch halves the noise and quadruples the work.

The algorithm and its cost

python
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 w

An epoch is one pass through the shuffled data in ⌈n/B⌉\lceil n/B\rceil steps. Each step costs O(Bd)\order{Bd} for a linear model, independent of nn; a whole epoch costs about the same arithmetic as one full gradient.

Per epoch, then, gradient descent moves once and SGD with B=1B=1 moves nn times. Far from the optimum, the per-example gradients largely agree, and nn rough steps make enormously more progress than one exact step. Near the optimum they disagree (at the minimizer of FF 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.

Check your understanding

A linear model has d=100d=100 features and n=106n=10^6 training examples. Compare one epoch of SGD with B=1B=1 to one step of full gradient descent.

  1. The SGD epoch costs about 10610^6 times more arithmetic
  2. They cost about the same arithmetic, but SGD updates the parameters 10610^6 times instead of once
  3. The SGD epoch is cheaper because each step uses one example
  4. They are identical: SGD with B=1B=1 is gradient descent
Show the answer

B. They cost about the same arithmetic, but SGD updates the parameters 10610^6 times instead of once

Both touch every example once, about nd=108nd=10^8 multiply-adds. The difference is what is done with that work: one exact step, or 10610^6 noisy steps, each using the newest parameters.

Constant steps: the noise ball

Assume FF is LL-smooth and μ\mu-strongly convex with minimum F⋆F^\star, and the stochastic gradients are unbiased with bounded variance: E[gt∣θt]=∇F(θt)\E[\mathbf g_t\mid\boldsymbol\theta_t]=\nabla F(\boldsymbol\theta_t) and E[∥gt−∇F(θt)∥2∣θt]≤σ2\E\big[\norm{\mathbf g_t-\nabla F(\boldsymbol\theta_t)}^2\mid\boldsymbol\theta_t\big]\le\sigma^2. (For mini-batches, σ2\sigma^2 is the single-example bound divided by BB.)

DerivationProof
  1. F(θt+1)≤F(θt)−η ∇F(θt)⊤gt+Lη22∥gt∥2F(\boldsymbol\theta_{t+1})\le F(\boldsymbol\theta_t)-\eta\,\nabla F(\boldsymbol\theta_t)^\top\mathbf g_t+\frac{L\eta^2}2\norm{\mathbf g_t}^2

    Apply the quadratic upper bound of LL-smoothness to the step −ηgt-\eta\mathbf g_t:

  2. E[F(θt+1)∣θt]≤F(θt)−η(1−Lη2)∥∇F(θt)∥2+Lη2σ22\E\big[F(\boldsymbol\theta_{t+1})\mid\boldsymbol\theta_t\big]\le F(\boldsymbol\theta_t)-\eta\Big(1-\frac{L\eta}2\Big)\norm{\nabla F(\boldsymbol\theta_t)}^2+\frac{L\eta^2\sigma^2}2

    Take the expectation given θt\boldsymbol\theta_t. Unbiasedness handles the middle term, and the second moment is the squared mean plus the variance, E∥gt∥2≤∥∇F∥2+σ2\E\norm{\mathbf g_t}^2\le\norm{\nabla F}^2+\sigma^2:

  3. EF(θt+1)−F⋆≤(1−ημ)(EF(θt)−F⋆)+Lη2σ22\E F(\boldsymbol\theta_{t+1})-F^\star\le(1-\eta\mu)\big(\E F(\boldsymbol\theta_t)-F^\star\big)+\frac{L\eta^2\sigma^2}2

    With η≤1/L\eta\le1/L the bracket is at least 12\tfrac12. Strong convexity implies ∥∇F∥2≥2μ(F−F⋆)\norm{\nabla F}^2\ge2\mu(F-F^\star) (the Polyak–Łojasiewicz inequality). Subtract F⋆F^\star and take full expectations:

  4. EF(θt)−F⋆≤(1−ημ)t(F(θ0)−F⋆)+Lη2σ22⋅1ημ\E F(\boldsymbol\theta_t)-F^\star\le(1-\eta\mu)^t\big(F(\boldsymbol\theta_0)-F^\star\big)+\frac{L\eta^2\sigma^2}2\cdot\frac1{\eta\mu}

    Unroll the recursion and bound the geometric series ∑k(1−ημ)k≤1/(ημ)\sum_k(1-\eta\mu)^k\le1/(\eta\mu). ■\blacksquare

The trade-off is explicit. The floor ηLσ2/(2μ)\eta L\sigma^2/(2\mu) is proportional to η\eta and to the gradient variance σ2\sigma^2, so halving the step halves the floor, but it also halves ημ\eta\mu and doubles the time it takes to get there. Because σ2\sigma^2 scales like 1/B1/B, the floor scales like η/B\eta/B: the ratio that the Convergence lesson Batch Size, Learning Rate & Noise builds on.

Predict before you look

Constant-step SGD has reached its noise floor. You keep η\eta fixed and raise the batch size from 1 to 16 (sampling with replacement). By what factor does the floor term ηLσ2/(2μ)\eta L\sigma^2/(2\mu) shrink?

Show the answer

16 ×

σ2\sigma^2 is the variance of the batch gradient, which is the single-example variance divided by BB. So the floor shrinks 16-fold, while each step costs 16 times more. The typical distance to the optimum shrinks only by 16=4\sqrt{16}=4, 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:

∑tηt=∞and∑tηt2<∞.\sum_{t}\eta_t=\infty\qquad\text{and}\qquad\sum_t\eta_t^2<\infty.

The recursion above shows why. The contraction ∏t(1−ηtμ)\prod_t(1-\eta_t\mu) reaches zero only if ∑tηt=∞\sum_t\eta_t=\infty (the steps must be able to travel any distance), and the noise injected at each step, proportional to ηt2σ2\eta_t^2\sigma^2, must die out. ∑tηt2<∞\sum_t\eta_t^2<\infty is the classical way to guarantee that, and the proof of almost-sure convergence uses it; convergence in expectation needs only ηt→0\eta_t\to0 besides the first condition. Steps ηt=c/(μt)\eta_t=c/(\mu t) satisfy both conditions, and with a large enough constant cc they give EF(θt)−F⋆=O(1/t)\E F(\boldsymbol\theta_t)-F^\star=\order{1/t} on smooth, strongly convex problems (with too small a cc the rate collapses); steps ∝1/t\propto1/\sqrt t 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.

ScheduleFormNotes
Constantηt=η\eta_t=\etafast at first, then a noise floor ∝η\propto\eta; often followed by a final decay
1/t1/tηt=η0/(1+t/t0)\eta_t=\eta_0/(1+t/t_0)Robbins–Monro; optimal rate for strongly convex problems, but very sensitive to η0\eta_0 (see Convergence of SGD)
1/t1/\sqrt t plus averagingηt=η0/1+t/t0\eta_t=\eta_0/\sqrt{1+t/t_0}, report θˉt\bar{\boldsymbol\theta}_trobust; optimal for general convex problems
Step decaydivide η\eta by 10 at a few fixed epochsa long-standing default for image classifiers; each drop lowers the plateau
Cosineηt=ηmin⁡+12(η0−ηmin⁡)(1+cos⁡πtT)\eta_t=\eta_{\min}+\tfrac12(\eta_0-\eta_{\min})\big(1+\cos\frac{\pi t}T\big)smooth decay to ηmin⁡\eta_{\min} over a fixed budget TT
Warmupramp η\eta up linearly over the first stepsavoids instability early in training, standard for large batches and transformers
Practical schedules work with a fixed budget of steps rather than an infinite horizon, so they need not satisfy the Robbins–Monro conditions literally: step decay that halves forever has a finite total ∑ηt\sum\eta_t.
Check your understanding

Which step-size sequence satisfies both Robbins–Monro conditions?

  1. ηt=0.01\eta_t=0.01 for all tt
  2. ηt=1/(t+1)2\eta_t=1/(t+1)^2
  3. ηt=1/(t+1)\eta_t=1/(t+1)
  4. ηt=1/t+1\eta_t=1/\sqrt{t+1}
Show the answer

C. ηt=1/(t+1)\eta_t=1/(t+1)

∑1/(t+1)\sum1/(t+1) diverges (the harmonic series), while ∑1/(t+1)2=π2/6\sum1/(t+1)^2=\pi^2/6 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 σ2\sigma^2: 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 θ⋆\boldsymbol\theta^\star minimizes every fif_i at once and every ∇fi(θ⋆)=0\nabla f_i(\boldsymbol\theta^\star)=\mathbf 0. The gradient noise then shrinks as the iterates approach θ⋆\boldsymbol\theta^\star, 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 ∇F\nabla F, with covariance Σ(θ)/B\Sigma(\boldsymbol\theta)/B (times n−Bn−1\frac{n-B}{n-1} without replacement): noise falls like 1/B1/\sqrt B while cost grows like BB.
  • An SGD step costs O(Bd)\order{Bd} whatever nn is; an epoch costs about one full gradient but makes n/Bn/B updates, which is why SGD wins early and at scale.
  • With constant η≤1/L\eta\le1/L on a smooth, strongly convex objective, EF(θt)−F⋆≤(1−ημ)tΔ0+ηLσ2/(2μ)\E F(\boldsymbol\theta_t)-F^\star\le(1-\eta\mu)^t\Delta_0+\eta L\sigma^2/(2\mu): linear progress down to a floor proportional to η/B\eta/B.
  • Convergence needs decaying steps with ∑ηt=∞\sum\eta_t=\infty and ∑ηt2<∞\sum\eta_t^2<\infty (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.

Question 1

You increase the mini-batch size from 64 to 256 (sampling with replacement). What happens to the standard deviation of the gradient noise?

  1. It halves
  2. It falls by a factor of 4
  3. It is unchanged, because the gradient is unbiased either way
  4. It doubles, because more examples add more noise
Show the answer

A. It halves

The covariance is Σ/B\Sigma/B, so the standard deviation scales like 1/B1/\sqrt B: four times the batch, half the noise, four times the cost per step.

Question 2

Constant-step SGD on a smooth, strongly convex problem obeys EF(θt)−F⋆≤(1−ημ)tΔ0+ηLσ2/(2μ)\E F(\boldsymbol\theta_t)-F^\star\le(1-\eta\mu)^t\Delta_0+\eta L\sigma^2/(2\mu). What does halving η\eta do?

  1. Halves the floor and makes the transient twice as fast
  2. Halves the floor, but the transient takes about twice as many steps
  3. Leaves the floor unchanged and slows the transient
  4. 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 η\eta, and the transient decays like (1−ημ)t≈e−ημt(1-\eta\mu)^t\approx e^{-\eta\mu t}, whose time constant 1/(ημ)1/(\eta\mu) doubles. That tension is why schedules start large and shrink.

Question 3

Why can a single pass of SGD over fresh examples be analyzed as minimizing the population risk R(θ)R(\boldsymbol\theta) rather than the training loss?

  1. Because SGD's noise acts as a regularizer
  2. Because a fresh example's loss gradient is an unbiased estimate of ∇R(θ)\nabla R(\boldsymbol\theta) at the current parameters
  3. Because the training loss and the risk have the same minimizer
  4. 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 ∇R(θ)\nabla R(\boldsymbol\theta) at the current parameters

An example drawn from the data distribution and not used before is independent of θt\boldsymbol\theta_t, so E[∇ℓ(hθt(x),y)∣θt]=∇R(θt)\E[\nabla\ell(h_{\boldsymbol\theta_t}(\mathbf x),y)\mid\boldsymbol\theta_t]=\nabla R(\boldsymbol\theta_t). Every stochastic-approximation guarantee then applies directly to RR.

Question 4

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?

  1. Raise the learning rate
  2. Shuffle less often
  3. Decay the learning rate (or raise the batch size)
  4. 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 ∝ησ2\propto\eta\sigma^2. Decaying η\eta shrinks it directly; a larger batch shrinks σ2\sigma^2.

Go deeper

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.