TExcelTAD
Home › Optimization › Stochastic Gradient Descent

Stochastic Gradient Descent

When the objective is an average over a huge dataset, f(w)=1n∑i=1nfi(w)f(\mathbf{w}) = \frac{1}{n}\sum_{i=1}^n f_i(\mathbf{w}), 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 nn 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 iki_k (or a batch BkB_k) and step along its gradient:

wk+1=wk−tk∇fik(wk),E[∇fik(w)]=∇f(w)\mathbf{w}_{k+1} = \mathbf{w}_k - t_k\nabla f_{i_k}(\mathbf{w}_k), \qquad \mathbb{E}\left[\nabla f_{i_k}(\mathbf{w})\right] = \nabla f(\mathbf{w})

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 w∗\mathbf{w}^* but keep jittering in a "noise ball" around it whose size is proportional to the step.

SGD versus full-batch gradient descent

python · try it yourself
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 LL-smooth ff:

E[f(wk+1)]≤f(wk)−t∥∇f(wk)∥2+Lt22E∥∇fik(wk)∥2\mathbb{E}[f(\mathbf{w}_{k+1})] \le f(\mathbf{w}_k) - t\lVert \nabla f(\mathbf{w}_k) \rVert^2 + \frac{Lt^2}{2}\mathbb{E}\lVert \nabla f_{i_k}(\mathbf{w}_k) \rVert^2

Far from the optimum the first term dominates and SGD makes progress like gradient descent. Near the optimum ∇f\nabla f is small but the stochastic gradients are not, so the last term (the variance) wins and progress stalls unless tt shrinks. Larger batches divide the variance by the batch size bb, at bb times the cost per step.

python · try it yourself
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 b\sqrt{b}).

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's SGDClassifier / 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 ii is uniform on {1,…,n}\{1, \dots, n\}, show E[∇fi(w)]=∇f(w)\mathbb{E}[\nabla f_i(\mathbf{w})] = \nabla f(\mathbf{w}) for f=1n∑ifif = \frac{1}{n}\sum_if_i.

Answer

E[∇fi]=∑i1n∇fi=∇f\mathbb{E}[\nabla f_i] = \sum_i\frac{1}{n}\nabla f_i = \nabla f.

Solution

Each index has probability 1/n1/n, 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

1,200,000/256=4687.51{,}200{,}000 / 256 = 4687.5, 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 w=0\mathbf{w} = 0.

Answer

The batch-16 variance is about 1/16 of the single-example variance.

Solution
python · try it yourself
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 bb independent samples is the single-sample variance divided by bb.

Test yourself

A stochastic gradient ∇fi(w)\nabla f_{i}(\mathbf{w}) with uniform ii is…

  1. biased
  2. an unbiased estimate of ∇f(w)\nabla f(\mathbf{w})
  3. always zero at the optimum
  4. exact

With a constant step size, SGD converges to…

  1. exactly w∗\mathbf{w}^*
  2. a neighbourhood of w∗\mathbf{w}^* whose size grows with the step
  3. infinity
  4. a random point anywhere

Increasing the mini-batch size from 1 to bb divides the gradient variance by…

  1. bb
  2. b\sqrt{b}
  3. b2b^2
  4. it does not change