Stochastic Gradient Descent
When the objective is an average over a huge dataset, , computing the full gradient means touching every example once per step. Stochastic gradient descent (SGD) uses the gradient of one example, or a small mini-batch, instead. Each step is noisy, but cheap steps usually beat one exact one, which is why SGD and its variants train essentially every neural network. The deep-learning side (momentum, Adam, schedules) is covered in Math for Deep Learning: SGD and Mini-Batches; here we look at it as an optimization method.
The method
Pick a random index (or a batch ) and step along its gradient:
The stochastic gradient is unbiased: right on average. Its variance is what makes SGD different from gradient descent: with a constant step, the iterates do not converge to but keep jittering in a "noise ball" around it whose size is proportional to the step.
SGD versus full-batch gradient descent
import numpy as np
rng = np.random.default_rng(0)
n, d = 5000, 10
X = rng.normal(size=(n, d)); w_true = rng.normal(size=d)
y = (X @ w_true + 0.5 * rng.normal(size=n) > 0).astype(float)
def loss(w):
z = X @ w
return np.mean(np.log1p(np.exp(-np.abs(z))) + np.maximum(z, 0) - y * z)
def grad(w, idx):
p = 1 / (1 + np.exp(-(X[idx] @ w)))
return X[idx].T @ (p - y[idx]) / len(idx)
# budget: 20 passes over the data (100,000 example-gradients)
w_gd = np.zeros(d)
for _ in range(20):
w_gd -= 1.0 * grad(w_gd, np.arange(n))
w_sgd = np.zeros(d)
for epoch in range(20):
for idx in np.array_split(rng.permutation(n), n // 32): # mini-batches of about 32
w_sgd -= 0.1 * grad(w_sgd, idx)
print(f"full-batch GD, 20 steps: loss {loss(w_gd):.4f}")
print(f"mini-batch SGD, 20 epochs: loss {loss(w_sgd):.4f}")full-batch GD, 20 steps: loss 0.2449
mini-batch SGD, 20 epochs: loss 0.1603
Same number of example-gradients, very different results: SGD made about 3,100 updates while gradient descent made 20.
Why noise is tolerable
Write the expected progress of one step for an -smooth :
Far from the optimum the first term dominates and SGD makes progress like gradient descent. Near the optimum is small but the stochastic gradients are not, so the last term (the variance) wins and progress stalls unless shrinks. Larger batches divide the variance by the batch size , at times the cost per step.
import numpy as np
rng = np.random.default_rng(1)
n = 2000
X = rng.normal(size=(n, 5)); w_true = rng.normal(size=5); y = X @ w_true + rng.normal(size=n)
w_star = np.linalg.lstsq(X, y, rcond=None)[0]
for b in (1, 10, 100):
w = np.zeros(5); dists = []
for k in range(20000 // b * 5):
idx = rng.integers(n, size=b)
w -= 0.01 * X[idx].T @ (X[idx] @ w - y[idx]) / b
if k > 20000 // b * 4:
dists.append(np.linalg.norm(w - w_star))
print(f"batch {b:3d}: average distance to w* at the end {np.mean(dists):.4f}")batch 1: average distance to w* at the end 0.1530
batch 10: average distance to w* at the end 0.0439
batch 100: average distance to w* at the end 0.0110
With a constant step, the noise ball shrinks as the batch grows (roughly by ).
Sampling and epochs
In practice you shuffle the data once per epoch and walk through it in batches (sampling without replacement), which is slightly better than independent sampling. Other practical points: normalize features (the condition number still matters), and monitor a validation metric rather than the training loss.
In software
torch.optim.SGD,tf.keras.optimizers.SGD, scikit-learn'sSGDClassifier/SGDRegressor(which implement the schedules of the next lesson).- For convex models on data that fit in memory, full-batch L-BFGS or coordinate descent is often faster and needs no step tuning; SGD wins when data are huge or streaming.
Exercises
Exercise 1: Unbiased?
If is uniform on , show for .
Answer
.
Solution
Each index has probability , and the gradient is linear, so the expectation is the average of the gradients, which is the gradient of the average.
Exercise 2: Updates per epoch
A dataset has 1.2 million examples and the batch size is 256. How many SGD updates happen per epoch?
Answer
About 4688.
Solution
, so 4688 batches if the last partial batch is kept.
Exercise 3: Variance and batch size (code)
Estimate the variance of a single-example gradient and of a batch-16 gradient for least squares at .
Answer
The batch-16 variance is about 1/16 of the single-example variance.
Solution
import numpy as np
rng = np.random.default_rng(2)
X = rng.normal(size=(10000, 3)); y = X @ np.array([1.0, -1.0, 2.0]) + rng.normal(size=10000)
g = lambda idx: X[idx].T @ (X[idx] @ np.zeros(3) - y[idx]) / len(idx)
v1 = np.var([g(rng.integers(10000, size=1)) for _ in range(20000)], axis=0).sum()
v16 = np.var([g(rng.integers(10000, size=16)) for _ in range(20000)], axis=0).sum()
print(round(float(v1), 2), round(float(v16), 3), " ratio:", round(float(v1 / v16), 1))27.37 1.686 ratio: 16.2
The variance of a mean of independent samples is the single-sample variance divided by .
Test yourself
A stochastic gradient with uniform is…
- biased
- an unbiased estimate of
- always zero at the optimum
- exact
With a constant step size, SGD converges to…
- exactly
- a neighbourhood of whose size grows with the step
- infinity
- a random point anywhere
Increasing the mini-batch size from 1 to divides the gradient variance by…
- it does not change