9.2 Stochastic and Minibatch Gradient Descent
In Section 9.1, every parameter update used the exact gradient of the objective, which requires evaluating the loss across the entire training set on every step. In deep learning, full-batch gradient descent is computationally prohibitive: training ResNet-50 on the million images of ImageNet for epochs with minibatches of images takes updates (Goyal et al., 2017), whereas full-batch steps would require complete passes over the dataset— times as much computation.
Instead, stochastic gradient descent (SGD) estimates the gradient from a single randomly sampled example or a small minibatch of examples (Section 2.1.2.3). This estimate is unbiased, and its variance decreases as , but the sampling noise fundamentally alters the late-stage behavior of optimization: with a constant learning rate , iterates do not converge to a point minimum but fluctuate inside a stationary noise ball.
In this section, we combine gradient noise with uneven curvature. Using the two-dimensional valley of Section 9.1.1, we derive the stationary variance of constant-step SGD along each curvature direction, test the resulting excess-loss prediction on a real regression dataset, examine how sampling without replacement and hardware parallelism shape minibatch selection, and motivate learning-rate decay (Section 9.7) and momentum (Section 9.4).
9.2.1 Stochastic Gradient Descent#
9.2.1.1 Sampled Gradients and the Valley#
For an empirical risk over training examples, the exact gradient is the average of the per-example gradients:
Single-example SGD draws an index uniformly at random at each step and updates
Because , the stochastic gradient can be decomposed as , where the gradient noise has mean zero.
To see how interacts with curvature, we first define sgd_2d to add independent zero-mean, unit-variance Gaussian noise to both gradient coordinates:
def sgd_2d(x1, x2, s1, s2, f_grad, eta, rng):
g1, g2 = f_grad(x1, x2)
n1, n2 = rng.normal(size=2) # Unit-variance gradient noise
return x1 - eta * (g1 + n1), x2 - eta * (g2 + n2), 0, 0We then run steps of sgd_2d on the valley (Section 9.1.1) at from :
rng = np.random.default_rng()
trace = d2l.train_2d(sgd_2d, d2l.valley_grad, steps=300, eta=0.1, rng=rng)
d2l.show_trace_2d(d2l.f_valley, trace)step 300, x1: -0.371201, x2: -0.077858
During the first steps, the deterministic gradient dominates and the iterate approaches the origin. Once near the origin, becomes small while the noise amplitude remains constant, trapping the iterate in an elongated cloud stretched along the flat axis .
9.2.1.2 The Noise Ball#
We can compute the dimensions of this cloud analytically. Along an eigenvector with curvature and independent zero-mean gradient noise of variance , a single SGD step evolves according to
Squaring both sides and taking expectations (using ) gives the second-moment recursion
For any stable step size , the mean decays to zero and the second moment converges to the stationary variance where deterministic contraction balances noise injection, :
Equation (9.2.5) characterizes the noise ball (Section 23.4.1 derives the full finite-time trajectory):
- Stability ceiling preserved: As , the denominator and the variance diverges.
- Inverse curvature scaling: The stationary variance is inversely proportional to curvature . On the valley at with , the stationary variance is along the flat coordinate () and along the steep coordinate (). Flat directions suffer twice: they converge slowly during the transient phase and fluctuate widely at steady state.
- Linear step-size scaling: For , halving the learning rate halves the stationary variance along every direction, as confirmed by simulating independent trajectories:
def noise_ball(eta, lam, num_runs=10000, num_steps=2000):
"""Variance of SGD iterates on sum(lam * x**2 / 2) with unit noise."""
rng = np.random.default_rng()
x = np.zeros((num_runs, len(lam)))
for _ in range(num_steps):
x = x - eta * (lam * x + rng.normal(size=x.shape))
return x.var(axis=0)
lam = np.array(d2l.VALLEY_CURVATURES) # Curvatures of the valley
for eta in (0.1, 0.05):
print(f'eta={eta}: measured {noise_ball(eta, lam).round(4)}, '
f'predicted {(eta / (lam * (2 - eta * lam))).round(4)}')eta=0.1: measured [0.2544 0.0157], predicted [0.2525 0.0156]
eta=0.05: measured [0.1275 0.007 ], predicted [0.1256 0.0069]
9.2.1.3 Decreasing Learning Rates#
Constant-step SGD faces a fundamental trade-off: a smaller learning rate shrinks the noise ball but slows down initial convergence by reducing the per-step contraction rate . Eliminating the noise floor requires decaying the learning rate over time. Robbins and Monro (1951) established that for smooth, strongly convex objectives with bounded gradient variance, SGD converges to the exact minimizer if the step sizes satisfy
The first condition ensures that the cumulative step budget is infinite so the iterate can reach the optimum from any initialization, while the second ensures that the cumulative injected noise variance remains finite. Polynomial schedules such as with satisfy both conditions and reduce the expected squared error at rate (Section 23.4.2; Exercise 2). On a fixed training budget of steps, practical deep learning replaces asymptotic schedules with cosine, linear, or warmup–stable–decay schedules (Section 9.7).
9.2.2 Minibatches#
9.2.2.1 Gradient Variance and Batch Size#
Instead of a single example, minibatch SGD averages the gradient over a random subset of examples:
Let denote the per-example gradient covariance matrix, whose trace is the total per-example gradient variance. For examples drawn independently with replacement, averaging divides the covariance by :
Substituting into (9.2.5) gives the minibatch stationary variance along curvature :
In the small-step regime , the learning rate and batch size govern the stationary noise ball solely through their ratio : doubling the batch size has the same effect on the noise floor as halving the learning rate .
9.2.2.2 The Excess Loss on Data#
How much does fluctuation inside the noise ball raise the training loss above its minimum ? Along the -th eigenvector of the Hessian (with eigenvalue and per-example gradient variance ), a stationary displacement of variance contributes to the expected quadratic loss:
Notice that the curvature cancels: flat directions fluctuate across a wider radius (), but a unit displacement along a flat direction raises the loss less (). Summing across all orthogonal eigenvectors () yields the stationary excess loss:
We test (9.2.11) on the NASA airfoil self-noise regression dataset ( wind-tunnel measurements with standardized features and standardized sound-pressure target):
d2l.DATA_HUB['airfoil'] = (d2l.DATA_URL + 'airfoil_self_noise.dat',
'76e5be1548fd8222e5074cf0faae75edff8cf93f')
def get_airfoil(batch_size=10, n=1500):
"""Load the standardized airfoil self-noise data as minibatches."""
data = np.genfromtxt(d2l.download('airfoil'),
dtype=np.float32, delimiter='\t')
data = torch.from_numpy((data - data.mean(axis=0)) / data.std(axis=0))
dataset = torch.utils.data.TensorDataset(
*(t.to(d2l.try_gpu()) for t in (data[:n, :-1], data[:n, -1])))
sampler = torch.utils.data.BatchSampler( # Whole minibatches of indices
torch.utils.data.RandomSampler(dataset), batch_size, drop_last=False)
data_iter = torch.utils.data.DataLoader(dataset, sampler=sampler,
batch_size=None)
return data_iter, data.shape[1]-1For linear regression with squared loss (representing the bias as a th weight on a constant feature), we compute the exact Hessian , the closed-form minimizer , the largest curvature , and the per-example gradient variance :
data_iter, num_features = get_airfoil(batch_size=1500)
X, y = map(d2l.numpy, next(iter(data_iter))) # All 1,500 examples
X = np.hstack([X, np.ones((len(X), 1), np.float32)]) # Bias as a 6th weight
H = X.T @ X / len(X) # Hessian of the loss
w_star = np.linalg.lstsq(X, y)[0] # The minimizer, in closed form
G = X * (X @ w_star - y)[:, None] # Per-example gradients at w_star
tr_Sigma = (G ** 2).sum(axis=1).mean()
print(f'L = {np.linalg.eigvalsh(H).max():.2f}, tr Sigma = {tr_Sigma:.2f}')L = 2.10, tr Sigma = 3.24
To measure the empirical excess loss against this prediction, sgd_runs simulates num_runs=400 vectorized minibatch SGD trajectories sampled with replacement, and excess_loss evaluates :
def sgd_runs(X, y, w, eta, b, num_steps, rng, num_runs=400):
"""Run minibatch SGD on the squared loss num_runs times from w, drawing
examples with replacement; return every iterate, (steps, runs, d)."""
W, trace = np.tile(w, (num_runs, 1)), []
for idx in rng.integers(0, len(X), (num_steps, num_runs, b)):
r = np.einsum('rbd,rd->rb', X[idx], W) - y[idx] # Residuals
W = W - eta / b * np.einsum('rbd,rb->rd', X[idx], r)
trace.append(W)
return np.array(trace)
def excess_loss(W, w_star, H):
"""f(w) - f(w_star) of the quadratic loss, for every w in the last axis."""
D = W - w_star
return 0.5 * np.einsum('...d,de,...e->...', D, H, D)Starting at with batch size , we average excess_loss over the third epoch ( steps) at and compare with :
rng = np.random.default_rng()
for eta in (0.05, 0.025): # b = 10, three epochs of 150 steps from w_star
trace = sgd_runs(X, y, w_star, eta, 10, 450, rng)
measured = excess_loss(trace[-150:], w_star, H).mean() # The last epoch
print(f'eta={eta}: excess loss {measured:.4f}, '
f'predicted {eta * tr_Sigma / (4 * 10):.4f}')eta=0.05: excess loss 0.0042, predicted 0.0041
eta=0.025: excess loss 0.0021, predicted 0.0020
At , the measured excess losses (about at and at ) closely match the prediction . Notice what happens in the interpolating regime, where a model has enough capacity to fit every training example exactly so that for all : in that limit, , the noise ball vanishes as the iterate approaches , and constant-step SGD converges geometrically to the exact minimizer. Overparameterized classifiers trained for many epochs approach this interpolating regime, whereas large language models trained for a single pass over massive corpora remain in the noise-limited regime where .
9.2.2.3 Sampling without Replacement#
In practice, data loaders do not sample minibatches independently with replacement; instead, they randomly permute the dataset at the start of each epoch and partition it into disjoint minibatches of size . Sampling distinct examples without replacement from a finite population of size introduces a negative correlation between per-example gradient errors (since ), multiplying the minibatch gradient variance (9.2.8) by the finite-population correction factor (Exercise 3):
When ( out of ), this factor is nearly unity (); when , the variance vanishes as required for full-batch gradient descent. Across a full epoch, random reshuffling also forces the minibatch gradient errors over the steps of the epoch to cancel to first order, yielding a smaller stationary error than sampling with replacement at small learning rates (Mishchenko et al., 2020).
9.2.2.4 Batch Size and Hardware Throughput#
When and is held constant, a single step on a minibatch of size with learning rate contracts the expected error by and lands in the same noise ball as single-example steps of learning rate , since . Counted purely in per-example gradient evaluations, increasing within this linear regime neither speeds up nor slows down learning.
What makes minibatches essential is hardware amortization. Every parameter update incurs fixed Python dispatch and kernel-launch overhead independent of , and vector processors (CPUs and GPUs) evaluate examples in parallel while reading the model weights from memory only once (Chapter 13). To benchmark both wall-clock time per epoch and loss versus examples processed on the airfoil dataset, train_sgd runs minibatch SGD on linear regression from and returns the full-dataset loss after every update alongside the seconds per epoch:
def train_sgd(lr, batch_size, num_epochs=2):
"""Minibatch SGD on linear regression from w = 0; return the loss after
every update and the seconds per epoch."""
data_iter, num_features = get_airfoil(batch_size)
X, y = (torch.cat(t) for t in zip(*data_iter)) # The whole dataset
w = torch.zeros(num_features + 1, device=X.device, requires_grad=True)
loss = lambda X, y: ((X @ w[:-1] + w[-1] - y) ** 2).mean() / 2
loss(X, y).backward() # Warm-up; the first update clears the gradient
ws = []
def epoch():
for X_b, y_b in data_iter:
w.grad = None
loss(X_b, y_b).backward()
with torch.no_grad():
w.sub_(lr * w.grad)
ws.append(w.detach().clone())
seconds = d2l.Benchmark(epoch, warmup=0, repeats=num_epochs).time
W = torch.stack(ws) # The weights after every update, (updates, 6)
losses = ((X @ W[:, :-1].T + W[:, -1] - y[:, None]) ** 2).mean(0) / 2
return losses, secondsWe now execute train_sgd across at fixed ratio , alongside full-batch gradient descent ( at ):
runs = {}
for b, lr, num_epochs in ((1500, 0.9, 10), (1, 0.005, 2), (10, 0.05, 2),
(100, 0.5, 2)): # lr / b = 0.005 for SGD
runs[b], seconds = train_sgd(lr, b, num_epochs)
updates = 1500 // b
print(f'b={b:4d}: {updates:4d} updates/epoch, {seconds:.3f} s/epoch '
f'({1000 * seconds / updates:.1f} ms/update), '
f'last-epoch loss {float(runs[b][-updates:].mean()):.3f}')b=1500: 1 updates/epoch, 0.003 s/epoch (2.7 ms/update), last-epoch loss 0.242
b= 1: 1500 updates/epoch, 1.825 s/epoch (1.2 ms/update), last-epoch loss 0.245
b= 10: 150 updates/epoch, 0.191 s/epoch (1.3 ms/update), last-epoch loss 0.245
b= 100: 15 updates/epoch, 0.023 s/epoch (1.5 ms/update), last-epoch loss 0.249
Plotting the training loss against total examples processed () overlays the sample efficiency of all four batch sizes:
d2l.plot([b * np.arange(1, len(losses) + 1) for b, losses in runs.items()],
[d2l.numpy(losses) for losses in runs.values()],
'examples processed', 'loss', legend=[f'b = {b}' for b in runs],
xscale='log')An update on examples takes roughly the same wall-clock time as an update on , making the epoch nearly faster while tracking the exact same loss curve per example processed. Notice also where linear scaling breaks down: holding pushes the learning rate at to , where is no longer small compared to (inflating the denominator in (9.2.5)), and any batch size beyond violates the stability ceiling . We analyze this critical batch size transition systematically in Section 9.8.
9.2.3 Summary#
Minibatch SGD estimates the gradient from examples, reducing the sampling variance to (times when sampling without replacement) while amortizing per-step dispatch and memory-bandwidth costs across the minibatch. Under a constant learning rate , iterates converge to a stationary noise ball whose coordinate variance along curvature is , widest along the flattest directions. Summing quadratic loss contributions across all modes cancels , leaving an expected stationary excess loss of that vanishes only when the model interpolates every training example at the optimum. Whenever , both transient progress per example and the stationary noise floor depend on and only through their ratio , until increasing with approaches the deterministic curvature ceiling .
9.2.4 Exercises#
-
Noise as a random dataset. Show that
sgd_2don with unit-variance Gaussian gradient noise is equivalent to single-example SGD on with , and determine the covariance . -
[code] The constant of a schedule. ● For a 1D quadratic of curvature under gradient noise of variance and learning rate :
- Write the exact recursion for and substitute the asymptotic ansatz to show that whenever . Which value of minimizes ?
- Iterate the deterministic recursion for on from with and up to , plotting versus on log–log axes, and explain why no single is simultaneously optimal for both and .
-
[code] The finite-population factor and reshuffling.
- Let . Using , show that and derive (9.2.12). Verify the formula empirically on the per-example gradients
Gof the airfoil dataset for drawn with and without replacement. - Draw vectors from the distribution of Exercise 1 and compare 20-epoch SGD trajectories sampled with replacement versus per-epoch reshuffling at .
- Let . Using , show that and derive (9.2.12). Verify the formula empirically on the per-example gradients
-
[code] Gradient variance during training. ●
- On the airfoil linear model, compare at versus .
- Train a two-layer ReLU MLP ( hidden units) on the airfoil data for epochs () and compare (broken down across
W1,b1,W2,b2) at initialization versus after training.
-
[code] Batch size and learning rate scaling. ● Fix at on the airfoil linear regression model and test under both linear scaling () and square-root scaling (). Explain which configurations diverge using , and compute the exact stationary excess loss across all eigenvectors of
Husing (9.2.5) to explain why has a slightly higher floor than .