TExcelTAD
Home › Math for Machine Learning › Stochastic Gradient Descent

Stochastic Gradient Descent

The training loss is an average over NN examples, and its gradient is an average of NN per-example gradients. When NN is a million, computing the exact gradient for every step is wasteful. Stochastic gradient descent (SGD) estimates it from a small random mini-batch: each step is noisy, but cheap, and on average points the right way.

Unbiased gradient estimates

For L(θ)=1N∑n=1Nℓn(θ)L(\boldsymbol{\theta}) = \frac{1}{N}\sum_{n=1}^{N} \ell_n(\boldsymbol{\theta}), pick a random batch BB of size bb and use

gB=1b∑n∈B∇ℓn(θ),E[gB]=∇L(θ)\mathbf{g}_B = \frac{1}{b}\sum_{n \in B} \nabla\ell_n(\boldsymbol{\theta}), \qquad \mathbb{E}[\mathbf{g}_B] = \nabla L(\boldsymbol{\theta})

The estimate is unbiased, and its variance falls like 1/b1/b (Expectation and Variance). A batch of 64 costs 64/N64/N of a full gradient but is often almost as useful early in training, when all examples agree on the rough direction.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
N = 10000
X = np.column_stack([np.ones(N), rng.normal(size=N)])
y = X @ np.array([2.0, -1.0]) + rng.normal(size=N)
theta = np.array([0.0, 0.0])
full = -2 / N * X.T @ (y - X @ theta)
for b in (1, 16, 256):
    grads = []
    for _ in range(2000):
        idx = rng.integers(0, N, size=b)
        grads.append(-2 / b * X[idx].T @ (y[idx] - X[idx] @ theta))
    grads = np.array(grads)
    print(f"batch {b:3d}: mean {np.round(grads.mean(axis=0), 2)}, std {np.round(grads.std(axis=0), 3)}")
print("full gradient:", np.round(full, 2))
batch   1: mean [-4.05  2.09], std [2.842 5.295]
batch  16: mean [-4.    2.02], std [0.734 1.402]
batch 256: mean [-4.  2.], std [0.18  0.337]
full gradient: [-3.99  2.  ]

The SGD loop and its learning rate

python · try it yourself
import numpy as np

rng = np.random.default_rng(1)
N = 5000
X = np.column_stack([np.ones(N), rng.normal(size=(N, 2))])
y = X @ np.array([0.5, 2.0, -1.0]) + 0.3 * rng.normal(size=N)
theta_star = np.linalg.solve(X.T @ X, X.T @ y)

def sgd(lr_schedule, epochs=5, b=32):
    theta = np.zeros(3); step = 0
    for _ in range(epochs):
        perm = rng.permutation(N)                    # shuffle once per epoch
        for start in range(0, N, b):
            idx = perm[start:start + b]
            g = -2 / len(idx) * X[idx].T @ (y[idx] - X[idx] @ theta)
            theta -= lr_schedule(step) * g; step += 1
    return np.linalg.norm(theta - theta_star)

print(f"constant lr 0.05:          distance to optimum {sgd(lambda t: 0.05):.2e}")
print(f"constant lr 0.005:         distance to optimum {sgd(lambda t: 0.005):.2e}")
print(f"decaying 0.05/(1+t/100):   distance to optimum {sgd(lambda t: 0.05 / (1 + t / 100)):.2e}")
constant lr 0.05:          distance to optimum 1.47e-02
constant lr 0.005:         distance to optimum 1.49e-03
decaying 0.05/(1+t/100):   distance to optimum 3.60e-03

With a constant learning rate, SGD does not settle at the optimum: it keeps bouncing in a "noise ball" whose size grows with the learning rate. Decaying the learning rate shrinks the ball. (The small constant rate ends even closer here, but it would have needed ten times as many steps to cover the same distance early on; a decaying schedule gets the fast start and the small ball.) The classic convergence conditions (Robbins-Monro) are ∑tγt=∞\sum_t \gamma_t = \infty and ∑tγt2<∞\sum_t \gamma_t^2 < \infty, satisfied by γt∝1/t\gamma_t \propto 1/t.

Epochs, shuffling and batch size

  • An epoch is one pass over the data. Shuffling each epoch keeps batches representative.
  • Larger batches give less noisy gradients and better hardware use, but each example is seen fewer times per unit of compute. A common heuristic scales the learning rate linearly with the batch size (with a warm-up).
  • Gradient noise is not all bad: it helps escape saddle points and sharp minima, which is one explanation of why SGD-trained networks generalize well.

In software

  • PyTorch's DataLoader(shuffle=True, batch_size=...) produces the mini-batches; the optimizer only ever sees gB\mathbf{g}_B.
  • scikit-learn's SGDRegressor and SGDClassifier implement SGD with learning_rate="invscaling" and other schedules.
  • Deep learning adds momentum and adaptive scaling on top of SGD (Momentum and Nesterov).

Go further: Batch, Stochastic and Mini-Batch Gradient Descent measures the gradient noise and shows how to choose the batch size in practice.

Exercises

Exercise 1: Variance and batch size

A single-example gradient component has standard deviation 2. What is the standard deviation with a batch of 100?

Answer

0.2.

Solution

The mean of 100 independent estimates has standard deviation 2/100=0.22/\sqrt{100} = 0.2. Halving the noise again would take 400 examples.

Exercise 2: Steps per epoch

A dataset has 50,000 examples and the batch size is 128. How many SGD steps make one epoch?

Answer

391 (390 full batches plus one of 80).

Solution

50 000/128=390.62550\,000 / 128 = 390.625, so 390 full batches and a final partial batch of 50 000−390⋅128=8050\,000 - 390 \cdot 128 = 80 examples.

Exercise 3: Robbins-Monro (code)

Which schedules satisfy ∑γt=∞\sum \gamma_t = \infty and ∑γt2<∞\sum \gamma_t^2 < \infty: (a) γt=0.1\gamma_t = 0.1, (b) γt=1/t\gamma_t = 1/t, (c) γt=1/t2\gamma_t = 1/t^2? Look at partial sums up to 10610^6.

Answer

Only (b).

Solution

(a) has ∑γt2=∞\sum \gamma_t^2 = \infty; (c) has ∑γt<∞\sum \gamma_t < \infty, so it stops moving too early; (b) has a harmonic sum that diverges (slowly) and squares that converge to π2/6\pi^2/6.

python · try it yourself
import numpy as np
t = np.arange(1, 10**6 + 1, dtype=float)
for name, g in (("0.1", np.full_like(t, 0.1)), ("1/t", 1 / t), ("1/t^2", 1 / t**2)):
    print(f"{name:6s} sum {g.sum():12.2f}   sum of squares {np.sum(g**2):12.4f}")
0.1    sum    100000.00   sum of squares   10000.0000
1/t    sum        14.39   sum of squares       1.6449
1/t^2  sum         1.64   sum of squares       1.0823

Test yourself

A mini-batch gradient is…

  1. a biased estimate of the full gradient
  2. an unbiased but noisy estimate of the full gradient
  3. exactly the full gradient
  4. the second derivative

With a constant learning rate, SGD on a convex problem typically…

  1. converges exactly
  2. hovers in a noise ball around the optimum
  3. diverges
  4. stops after one epoch

Doubling the batch size divides the gradient noise's standard deviation by…

  1. 2
  2. 2\sqrt{2}
  3. 4
  4. it does not change