Stochastic Gradient Descent
The training loss is an average over examples, and its gradient is an average of per-example gradients. When 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 , pick a random batch of size and use
The estimate is unbiased, and its variance falls like (Expectation and Variance). A batch of 64 costs of a full gradient but is often almost as useful early in training, when all examples agree on the rough direction.
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
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 and , satisfied by .
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 . - scikit-learn's
SGDRegressorandSGDClassifierimplement SGD withlearning_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 . 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
, so 390 full batches and a final partial batch of examples.
Exercise 3: Robbins-Monro (code)
Which schedules satisfy and : (a) , (b) , (c) ? Look at partial sums up to .
Answer
Only (b).
Solution
(a) has ; (c) has , so it stops moving too early; (b) has a harmonic sum that diverges (slowly) and squares that converge to .
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…
- a biased estimate of the full gradient
- an unbiased but noisy estimate of the full gradient
- exactly the full gradient
- the second derivative
With a constant learning rate, SGD on a convex problem typically…
- converges exactly
- hovers in a noise ball around the optimum
- diverges
- stops after one epoch
Doubling the batch size divides the gradient noise's standard deviation by…
- 2
- 4
- it does not change