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 1.281.28 million images of ImageNet for 9090 epochs with minibatches of 256256 images takes 450,000450{,}000 updates (Goyal et al., 2017), whereas 450,000450{,}000 full-batch steps would require 450,000450{,}000 complete passes over the dataset—5,0005{,}000 times as much computation.

Instead, stochastic gradient descent (SGD) estimates the gradient from a single randomly sampled example or a small minibatch of bb examples (Section 2.1.2.3). This estimate is unbiased, and its variance decreases as 1/b1/b, but the sampling noise fundamentally alters the late-stage behavior of optimization: with a constant learning rate η\eta, 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 f(x)=1n∑i=1nfi(x)f(\mathbf{x}) = \frac{1}{n} \sum_{i=1}^n f_i(\mathbf{x}) over nn training examples, the exact gradient is the average of the per-example gradients:

∇f(x)=1n∑i=1n∇fi(x).(9.2.1)\nabla f(\mathbf{x}) = \frac{1}{n} \sum_{i = 1}^n \nabla f_i(\mathbf{x}). \tag{9.2.1}

Single-example SGD draws an index i∈{1,…,n}i \in \{1, \ldots, n\} uniformly at random at each step and updates

x←x−η∇fi(x).(9.2.2)\mathbf{x} \leftarrow \mathbf{x} - \eta \nabla f_i(\mathbf{x}). \tag{9.2.2}

Because Ei[∇fi(x)]=∇f(x)\mathbb{E}_i[\nabla f_i(\mathbf{x})] = \nabla f(\mathbf{x}), the stochastic gradient can be decomposed as ∇fi(x)=∇f(x)+ξ\nabla f_i(\mathbf{x}) = \nabla f(\mathbf{x}) + \boldsymbol{\xi}, where the gradient noise ξ\boldsymbol{\xi} has mean zero.

To see how ξ\boldsymbol{\xi} 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, 0

We then run 300300 steps of sgd_2d on the valley f(x)=0.1x12+2x22f(\mathbf{x}) = 0.1 x_1^2 + 2 x_2^2 (Section 9.1.1) at η=0.1\eta = 0.1 from (−5,−2)(-5, -2):

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 ∼100\sim 100 steps, the deterministic gradient dominates and the iterate approaches the origin. Once near the origin, ∥∇f(x)∥\|\nabla f(\mathbf{x})\| becomes small while the noise amplitude remains constant, trapping the iterate in an elongated cloud stretched along the flat axis x1x_1.

9.2.1.2 The Noise Ball#

We can compute the dimensions of this cloud analytically. Along an eigenvector with curvature λ>0\lambda > 0 and independent zero-mean gradient noise ξt\xi_t of variance σ2\sigma^2, a single SGD step evolves according to

xt+1=xt−η (λxt+ξt)=(1−ηλ) xt−η ξt.(9.2.3)x_{t+1} = x_t - \eta\, (\lambda x_t + \xi_t) = (1 - \eta\lambda)\, x_t - \eta\, \xi_t. \tag{9.2.3}

Squaring both sides and taking expectations (using E[xtξt]=0\mathbb{E}[x_t \xi_t] = 0) gives the second-moment recursion

E[xt+12]=(1−ηλ)2 E[xt2]+η2σ2.(9.2.4)\mathbb{E}\big[x_{t+1}^2\big] = (1 - \eta\lambda)^2\, \mathbb{E}\big[x_t^2\big] + \eta^2 \sigma^2. \tag{9.2.4}

For any stable step size 0<η<2/λ0 \lt \eta \lt 2/\lambda, the mean E[xt]\mathbb{E}[x_t] decays to zero and the second moment converges to the stationary variance where deterministic contraction balances noise injection, E[x∞2]=(1−ηλ)2E[x∞2]+η2σ2\mathbb{E}[x_\infty^2] = (1 - \eta\lambda)^2 \mathbb{E}[x_\infty^2] + \eta^2 \sigma^2:

E[x∞2]=η σ2λ (2−ηλ)≈η σ22λfor ηλ≪1.(9.2.5)\mathbb{E}\big[x_\infty^2\big] = \frac{\eta\, \sigma^2}{\lambda\, (2 - \eta\lambda)} \approx \frac{\eta\, \sigma^2}{2\lambda} \quad \textrm{for } \eta\lambda \ll 1. \tag{9.2.5}

Equation (9.2.5) characterizes the noise ball (Section 23.4.1 derives the full finite-time trajectory):

  1. Stability ceiling preserved: As η→2/λ\eta \to 2/\lambda, the denominator (2−ηλ)→0(2 - \eta\lambda) \to 0 and the variance diverges.
  2. Inverse curvature scaling: The stationary variance is inversely proportional to curvature λ\lambda. On the valley at η=0.1\eta = 0.1 with σ2=1\sigma^2 = 1, the stationary variance is 0.1/(0.2×1.98)≈0.25250.1 / (0.2 \times 1.98) \approx 0.2525 along the flat coordinate x1x_1 (std≈0.50\text{std} \approx 0.50) and 0.1/(4×1.6)≈0.01560.1 / (4 \times 1.6) \approx 0.0156 along the steep coordinate x2x_2 (std≈0.125\text{std} \approx 0.125). Flat directions suffer twice: they converge slowly during the transient phase and fluctuate widely at steady state.
  3. Linear step-size scaling: For ηλ≪1\eta\lambda \ll 1, halving the learning rate η\eta halves the stationary variance along every direction, as confirmed by simulating 10,00010{,}000 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 η\eta shrinks the noise ball ∝η\propto \eta but slows down initial convergence by reducing the per-step contraction rate ηλ\eta\lambda. Eliminating the noise floor requires decaying the learning rate ηt\eta_t 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

∑t=1∞ηt=∞and∑t=1∞ηt2<∞.(9.2.6)\sum_{t=1}^{\infty} \eta_t = \infty \qquad \textrm{and} \qquad \sum_{t=1}^{\infty} \eta_t^2 \lt \infty. \tag{9.2.6}

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 ∝∑tηt2\propto \sum_t \eta_t^2 remains finite. Polynomial schedules such as ηt=c/(t+t0)\eta_t = c / (t + t_0) with c>1/(2λmin⁡)c > 1/(2\lambda_{\min}) satisfy both conditions and reduce the expected squared error at rate E[∥xt−x⋆∥2]=O(1/t)\mathbb{E}[\|\mathbf{x}_t - \mathbf{x}^\star\|^2] = O(1/t) (Section 23.4.2; Exercise 2). On a fixed training budget of TT steps, practical deep learning replaces asymptotic 1/t1/t 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 Bt\mathcal{B}_t of bb examples:

gt=1b∑i∈Bt∇fi(xt).(9.2.7)\mathbf{g}_t = \frac{1}{b} \sum_{i \in \mathcal{B}_t} \nabla f_i(\mathbf{x}_t). \tag{9.2.7}

Let Σ(x)=Ei[(∇fi(x)−∇f(x))(∇fi(x)−∇f(x))⊤]\boldsymbol{\Sigma}(\mathbf{x}) = \mathbb{E}_i\big[(\nabla f_i(\mathbf{x}) - \nabla f(\mathbf{x}))(\nabla f_i(\mathbf{x}) - \nabla f(\mathbf{x}))^\top\big] denote the per-example gradient covariance matrix, whose trace tr⁡Σ=Ei∥∇fi(x)−∇f(x)∥2\operatorname{tr}\boldsymbol{\Sigma} = \mathbb{E}_i\|\nabla f_i(\mathbf{x}) - \nabla f(\mathbf{x})\|^2 is the total per-example gradient variance. For bb examples drawn independently with replacement, averaging divides the covariance by bb:

E∥gt−∇f(xt)∥2=tr⁡Σb.(9.2.8)\mathbb{E} \big\|\mathbf{g}_t - \nabla f(\mathbf{x}_t)\big\|^2 = \frac{\operatorname{tr} \boldsymbol{\Sigma}}{b}. \tag{9.2.8}

Substituting σ2←σ2/b\sigma^2 \leftarrow \sigma^2 / b into (9.2.5) gives the minibatch stationary variance along curvature λ\lambda:

E[x∞2]=η σ2b λ (2−ηλ)≈ηb⋅σ22λfor ηλ≪1.(9.2.9)\mathbb{E}\big[x_\infty^2\big] = \frac{\eta\, \sigma^2}{b\,\lambda\, (2 - \eta\lambda)} \approx \frac{\eta}{b} \cdot \frac{\sigma^2}{2\lambda} \quad \textrm{for } \eta\lambda \ll 1. \tag{9.2.9}

In the small-step regime ηλ≪1\eta\lambda \ll 1, the learning rate and batch size govern the stationary noise ball solely through their ratio η/b\eta / b: doubling the batch size bb has the same effect on the noise floor as halving the learning rate η\eta.

9.2.2.2 The Excess Loss on Data#

How much does fluctuation inside the noise ball raise the training loss above its minimum f(x⋆)f(\mathbf{x}^\star)? Along the kk-th eigenvector of the Hessian H\mathbf{H} (with eigenvalue λk\lambda_k and per-example gradient variance σk2\sigma_k^2), a stationary displacement of variance vk≈ησk22λkbv_k \approx \frac{\eta \sigma_k^2}{2 \lambda_k b} contributes 12λkvk\frac{1}{2}\lambda_k v_k to the expected quadratic loss:

12λk(η σk22λkb)=η σk24b.(9.2.10)\frac{1}{2} \lambda_k \left(\frac{\eta\, \sigma_k^2}{2 \lambda_k b}\right) = \frac{\eta\, \sigma_k^2}{4b}. \tag{9.2.10}

Notice that the curvature λk\lambda_k cancels: flat directions fluctuate across a wider radius (∝1/λk\propto 1/\lambda_k), but a unit displacement along a flat direction raises the loss less (∝λk\propto \lambda_k). Summing across all dd orthogonal eigenvectors (∑k=1dσk2=tr⁡Σ\sum_{k=1}^d \sigma_k^2 = \operatorname{tr}\boldsymbol{\Sigma}) yields the stationary excess loss:

E[f(x∞)]−f(x⋆)≈ηtr⁡Σ(x⋆)4b.(9.2.11)\mathbb{E}\big[f(\mathbf{x}_\infty)\big] - f(\mathbf{x}^\star) \approx \frac{\eta \operatorname{tr} \boldsymbol{\Sigma}(\mathbf{x}^\star)}{4b}. \tag{9.2.11}

We test (9.2.11) on the NASA airfoil self-noise regression dataset (n=1,500n = 1{,}500 wind-tunnel measurements with 55 standardized features and 11 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]-1

For linear regression with squared loss (representing the bias as a 66th weight on a constant feature), we compute the exact Hessian H=1nX⊤X\mathbf{H} = \frac{1}{n}\mathbf{X}^\top\mathbf{X}, the closed-form minimizer w⋆\mathbf{w}^\star, the largest curvature L=λmax⁡(H)≈2.10L = \lambda_{\max}(\mathbf{H}) \approx 2.10, and the per-example gradient variance tr⁡Σ(w⋆)≈3.24\operatorname{tr}\boldsymbol{\Sigma}(\mathbf{w}^\star) \approx 3.24:

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 12(w−w⋆)⊤H(w−w⋆)\frac{1}{2}(\mathbf{w} - \mathbf{w}^\star)^\top \mathbf{H} (\mathbf{w} - \mathbf{w}^\star):

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 w⋆\mathbf{w}^\star with batch size b=10b = 10, we average excess_loss over the third epoch (150150 steps) at η∈{0.05,0.025}\eta \in \{0.05, 0.025\} and compare with ηtr⁡Σ/(4b)\eta\operatorname{tr}\boldsymbol{\Sigma}/(4b):

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 b=10b = 10, the measured excess losses (about 0.0040.004 at η=0.05\eta = 0.05 and 0.0020.002 at η=0.025\eta = 0.025) closely match the prediction ηtr⁡Σ/(4b)\eta\operatorname{tr}\boldsymbol{\Sigma}/(4b). Notice what happens in the interpolating regime, where a model has enough capacity to fit every training example exactly so that ∇fi(x⋆)=0\nabla f_i(\mathbf{x}^\star) = \mathbf{0} for all ii: in that limit, tr⁡Σ(x⋆)=0\operatorname{tr}\boldsymbol{\Sigma}(\mathbf{x}^\star) = 0, the noise ball vanishes as the iterate approaches x⋆\mathbf{x}^\star, 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 tr⁡Σ(x⋆)>0\operatorname{tr}\boldsymbol{\Sigma}(\mathbf{x}^\star) > 0.

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 bb. Sampling bb distinct examples without replacement from a finite population of size nn introduces a negative correlation between per-example gradient errors (since ∑i=1n(∇fi(x)−∇f(x))=0\sum_{i=1}^n (\nabla f_i(\mathbf{x}) - \nabla f(\mathbf{x})) = \mathbf{0}), multiplying the minibatch gradient variance (9.2.8) by the finite-population correction factor (Exercise 3):

E∥gt−∇f(xt)∥2=tr⁡Σb⋅n−bn−1.(9.2.12)\mathbb{E} \big\|\mathbf{g}_t - \nabla f(\mathbf{x}_t)\big\|^2 = \frac{\operatorname{tr} \boldsymbol{\Sigma}}{b} \cdot \frac{n - b}{n - 1}. \tag{9.2.12}

When b≪nb \ll n (1010 out of 1,5001{,}500), this factor is nearly unity (0.9940.994); when b=nb = n, the variance vanishes as required for full-batch gradient descent. Across a full epoch, random reshuffling also forces the minibatch gradient errors over the n/bn/b 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 ηλ≪1\eta\lambda \ll 1 and η/b\eta / b is held constant, a single step on a minibatch of size bb with learning rate η\eta contracts the expected error by (1−ηλ)(1 - \eta\lambda) and lands in the same noise ball as bb single-example steps of learning rate η/b\eta / b, since (1−ηλ/b)b≈1−ηλ(1 - \eta\lambda / b)^b \approx 1 - \eta\lambda. Counted purely in per-example gradient evaluations, increasing bb 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 bb, and vector processors (CPUs and GPUs) evaluate bb 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 w=0\mathbf{w} = \mathbf{0} 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, seconds

We now execute train_sgd across b∈{1,10,100}b \in \{1, 10, 100\} at fixed ratio η/b=0.005\eta / b = 0.005, alongside full-batch gradient descent (b=1,500b = 1{,}500 at η=0.9<2/L≈0.95\eta = 0.9 \lt 2/L \approx 0.95):

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 (b×updatesb \times \text{updates}) 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 b=100b = 100 examples takes roughly the same wall-clock time as an update on b=1b = 1, making the b=100b = 100 epoch nearly 50–100×50\text{--}100\times faster while tracking the exact same loss curve per example processed. Notice also where linear scaling η∝b\eta \propto b breaks down: holding η/b=0.005\eta / b = 0.005 pushes the learning rate at b=100b = 100 to η=0.5\eta = 0.5, where ηL=0.5×2.10=1.05\eta L = 0.5 \times 2.10 = 1.05 is no longer small compared to 22 (inflating the denominator (2−ηλ)−1(2 - \eta\lambda)^{-1} in (9.2.5)), and any batch size beyond b≈190b \approx 190 violates the stability ceiling η<2/L≈0.95\eta \lt 2/L \approx 0.95. We analyze this critical batch size transition systematically in Section 9.8.

9.2.3 Summary#

Minibatch SGD estimates the gradient from bb examples, reducing the sampling variance to tr⁡(Σ)/b\operatorname{tr}(\boldsymbol{\Sigma})/b (times (n−b)/(n−1)(n-b)/(n-1) when sampling without replacement) while amortizing per-step dispatch and memory-bandwidth costs across the minibatch. Under a constant learning rate η\eta, iterates converge to a stationary noise ball whose coordinate variance along curvature λ\lambda is ησ2bλ(2−ηλ)≈ησ22λb\frac{\eta\sigma^2}{b\lambda(2 - \eta\lambda)} \approx \frac{\eta\sigma^2}{2\lambda b}, widest along the flattest directions. Summing quadratic loss contributions across all modes cancels λ\lambda, leaving an expected stationary excess loss of E[f(x∞)]−f(x⋆)≈ηtr⁡Σ(x⋆)4b\mathbb{E}[f(\mathbf{x}_\infty)] - f(\mathbf{x}^\star) \approx \frac{\eta\operatorname{tr}\boldsymbol{\Sigma}(\mathbf{x}^\star)}{4b} that vanishes only when the model interpolates every training example at the optimum. Whenever ηL≪1\eta L \ll 1, both transient progress per example and the stationary noise floor depend on η\eta and bb only through their ratio η/b\eta/b, until increasing bb with η∝b\eta \propto b approaches the deterministic curvature ceiling η<2/L\eta \lt 2/L.

9.2.4 Exercises#

  1. Noise as a random dataset. Show that sgd_2d on f(x)=0.1x12+2x22f(\mathbf{x}) = 0.1 x_1^2 + 2x_2^2 with unit-variance Gaussian gradient noise is equivalent to single-example SGD on f(x,w)=0.1(x1−w1)2+2(x2−w2)2f(\mathbf{x}, \mathbf{w}) = 0.1 (x_1 - w_1)^2 + 2 (x_2 - w_2)^2 with w∼N(0,C)\mathbf{w} \sim \mathcal{N}(\mathbf{0}, \mathbf{C}), and determine the covariance C\mathbf{C}.

  2. [code] The constant of a 1/t1/t schedule. ● For a 1D quadratic of curvature λ\lambda under gradient noise of variance σ2\sigma^2 and learning rate ηt=c/(t+t0)\eta_t = c / (t + t_0):

    1. Write the exact recursion for et=E[xt2]e_t = \mathbb{E}[x_t^2] and substitute the asymptotic ansatz et≈A/te_t \approx A/t to show that A=c2σ2/(2cλ−1)A = c^2 \sigma^2 / (2 c \lambda - 1) whenever c>1/(2λ)c > 1/(2\lambda). Which value of cc minimizes AA?
    2. Iterate the deterministic recursion for ete_t on λ=0.2,σ=1\lambda = 0.2, \sigma = 1 from e0=25e_0 = 25 with t0=20t_0 = 20 and c∈{1,2.5,5,10}c \in \{1, 2.5, 5, 10\} up to t=106t = 10^6, plotting t ett\,e_t versus tt on log–log axes, and explain why no single cc is simultaneously optimal for both λ1=0.2\lambda_1 = 0.2 and λ2=4\lambda_2 = 4.
  3. [code] The finite-population factor and reshuffling.

    1. Let ei=∇fi(x)−∇f(x)\mathbf{e}_i = \nabla f_i(\mathbf{x}) - \nabla f(\mathbf{x}). Using ∑i=1nei=0\sum_{i=1}^n \mathbf{e}_i = \mathbf{0}, show that Ei≠j[ei⊤ej]=−tr⁡Σ/(n−1)\mathbb{E}_{i \neq j}[\mathbf{e}_i^\top \mathbf{e}_j] = -\operatorname{tr}\boldsymbol{\Sigma}/(n - 1) and derive (9.2.12). Verify the formula empirically on the per-example gradients G of the airfoil dataset for b∈{10,100,500,1000}b \in \{10, 100, 500, 1000\} drawn with and without replacement.
    2. Draw n=100n = 100 vectors wi\mathbf{w}_i from the distribution of Exercise 1 and compare 20-epoch SGD trajectories sampled with replacement versus per-epoch reshuffling at η∈{0.1,0.01}\eta \in \{0.1, 0.01\}.
  4. [code] Gradient variance during training. ●

    1. On the airfoil linear model, compare tr⁡Σ\operatorname{tr}\boldsymbol{\Sigma} at w=0\mathbf{w} = \mathbf{0} versus w=w⋆\mathbf{w} = \mathbf{w}^\star.
    2. Train a two-layer ReLU MLP (6464 hidden units) on the airfoil data for 1010 epochs (b=10,η=0.05b = 10, \eta = 0.05) and compare tr⁡Σ\operatorname{tr}\boldsymbol{\Sigma} (broken down across W1, b1, W2, b2) at initialization versus after training.
  5. [code] Batch size and learning rate scaling. ● Fix η=0.05\eta = 0.05 at b=10b = 10 on the airfoil linear regression model and test b∈{1,10,100,1500}b \in \{1, 10, 100, 1500\} under both linear scaling (η∝b\eta \propto b) and square-root scaling (η∝b\eta \propto \sqrt{b}). Explain which configurations diverge using L=2.10L = 2.10, and compute the exact stationary excess loss across all 66 eigenvectors of H using (9.2.5) to explain why b=100,η=0.5b = 100, \eta = 0.5 has a slightly higher floor than b=10,η=0.05b = 10, \eta = 0.05.

Discussions